diff --git a/lib/python3.11/site-packages/_yaml/__init__.py b/lib/python3.11/site-packages/_yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694 --- /dev/null +++ b/lib/python3.11/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/lib/python3.11/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7268fc536cde46f355b1e45dd2a7a027b6ee59d4 Binary files /dev/null and b/lib/python3.11/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/einops-0.8.2.dist-info/INSTALLER b/lib/python3.11/site-packages/einops-0.8.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/lib/python3.11/site-packages/einops-0.8.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/lib/python3.11/site-packages/einops-0.8.2.dist-info/METADATA b/lib/python3.11/site-packages/einops-0.8.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cb156e638fb958fedd1323631c6d5dddc0936b32 --- /dev/null +++ b/lib/python3.11/site-packages/einops-0.8.2.dist-info/METADATA @@ -0,0 +1,394 @@ +Metadata-Version: 2.4 +Name: einops +Version: 0.8.2 +Summary: A new flavour of deep learning operations +Project-URL: Homepage, https://github.com/arogozhnikov/einops +Author: Alex Rogozhnikov +License: MIT +License-File: LICENSE +Keywords: deep learning,einops,machine learning,neural networks,scientific computations,tensor manipulation +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Requires-Python: >=3.9 +Description-Content-Type: text/markdown + + + + + + +https://user-images.githubusercontent.com/6318811/177030658-66f0eb5d-e136-44d8-99c9-86ae298ead5b.mp4 + + + + +# einops +[![Run tests](https://github.com/arogozhnikov/einops/actions/workflows/run_tests.yml/badge.svg)](https://github.com/arogozhnikov/einops/actions/workflows/run_tests.yml) +[![PyPI version](https://badge.fury.io/py/einops.svg)](https://badge.fury.io/py/einops) +[![Documentation](https://img.shields.io/badge/documentation-link-blue.svg)](https://einops.rocks/) +![Supported python versions](https://raw.githubusercontent.com/arogozhnikov/einops/main/docs/resources/python_badge.svg) + + +Flexible and powerful tensor operations for readable and reliable code.
+Supports numpy, pytorch, tensorflow, jax, and [others](#supported-frameworks). + +## Recent updates: + +- 0.8.0: tinygrad backend added, small fixes +- 0.7.0: no-hassle `torch.compile`, support of [array api standard](https://data-apis.org/array-api/latest/API_specification/index.html) and more +- 10'000🎉: github reports that more than 10k project use einops +- einops 0.6.1: paddle backend added +- einops 0.6 introduces [packing and unpacking](https://github.com/arogozhnikov/einops/blob/main/docs/4-pack-and-unpack.ipynb) +- einops 0.5: einsum is now a part of einops +- [Einops paper](https://openreview.net/pdf?id=oapKSVM2bcj) is accepted for oral presentation at ICLR 2022 (yes, it worth reading). + Talk recordings are [available](https://iclr.cc/virtual/2022/oral/6603) + + +
+Previous updates +- flax and oneflow backend added +- torch.jit.script is supported for pytorch layers +- powerful EinMix added to einops. [Einmix tutorial notebook](https://github.com/arogozhnikov/einops/blob/main/docs/3-einmix-layer.ipynb) +
+ + + + +## Tweets + +> In case you need convincing arguments for setting aside time to learn about einsum and einops... +[Tim Rocktäschel](https://twitter.com/_rockt/status/1230818967205425152) + +> Writing better code with PyTorch and einops 👌 +[Andrej Karpathy](https://twitter.com/karpathy/status/1290826075916779520) + +> Slowly but surely, einops is seeping in to every nook and cranny of my code. If you find yourself shuffling around bazillion dimensional tensors, this might change your life +[Nasim Rahaman](https://twitter.com/nasim_rahaman/status/1216022614755463169) + +[More testimonials](https://einops.rocks/pages/testimonials/) + + +## Contents + +- [Installation](#Installation) +- [Documentation](https://einops.rocks/) +- [Tutorial](#Tutorials) +- [API micro-reference](#API) +- [Why use einops](#Why-use-einops-notation) +- [Supported frameworks](#Supported-frameworks) +- [Citing](#Citing) +- [Repository](https://github.com/arogozhnikov/einops) and [discussions](https://github.com/arogozhnikov/einops/discussions) + +## Installation + +Plain and simple: +```bash +pip install einops +``` + +(`uv pip install einops` works as well) + +## Tutorials + +Tutorials are the most convenient way to see `einops` in action + +- part 1: [einops fundamentals](https://github.com/arogozhnikov/einops/blob/main/docs/1-einops-basics.ipynb) +- part 2: [einops for deep learning](https://github.com/arogozhnikov/einops/blob/main/docs/2-einops-for-deep-learning.ipynb) +- part 3: [packing and unpacking](https://github.com/arogozhnikov/einops/blob/main/docs/4-pack-and-unpack.ipynb) +- part 4: [improve pytorch code with einops](http://einops.rocks/pytorch-examples.html) + +Kapil Sachdeva recorded a small [intro to einops](https://www.youtube.com/watch?v=xGy75Pjsqzo). + +## API + +`einops` has a minimalistic yet powerful API. + +Three core operations provided ([einops tutorial](https://github.com/arogozhnikov/einops/blob/main/docs/) +shows those cover stacking, reshape, transposition, squeeze/unsqueeze, repeat, tile, concatenate, view and numerous reductions) + +```python +from einops import rearrange, reduce, repeat +# rearrange elements according to the pattern +output_tensor = rearrange(input_tensor, 't b c -> b c t') +# combine rearrangement and reduction +output_tensor = reduce(input_tensor, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2) +# copy along a new axis +output_tensor = repeat(input_tensor, 'h w -> h w c', c=3) +``` + +Later additions to the family are `pack` and `unpack` functions (better than stack/split/concatenate): + +```python +from einops import pack, unpack +# pack and unpack allow reversibly 'packing' multiple tensors into one. +# Packed tensors may be of different dimensionality: +packed, ps = pack([class_token_bc, image_tokens_bhwc, text_tokens_btc], 'b * c') +class_emb_bc, image_emb_bhwc, text_emb_btc = unpack(transformer(packed), ps, 'b * c') +``` + +Finally, einops provides einsum with a support of multi-lettered names: + +```python +from einops import einsum, pack, unpack +# einsum is like ... einsum, generic and flexible dot-product +# but 1) axes can be multi-lettered 2) pattern goes last 3) works with multiple frameworks +C = einsum(A, B, 'b t1 head c, b t2 head c -> b head t1 t2') +``` + +### EinMix + +`EinMix` is a generic linear layer, perfect for MLP Mixers and similar architectures. + +### Layers + +Einops provides layers (`einops` keeps a separate version for each framework) that reflect corresponding functions + +```python +from einops.layers.torch import Rearrange, Reduce +from einops.layers.tensorflow import Rearrange, Reduce +from einops.layers.flax import Rearrange, Reduce +from einops.layers.paddle import Rearrange, Reduce +``` + +
+Example of using layers within a pytorch model +Example given for pytorch, but code in other frameworks is almost identical + +```python +from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU +from einops.layers.torch import Rearrange + +model = Sequential( + ..., + Conv2d(6, 16, kernel_size=5), + MaxPool2d(kernel_size=2), + # flattening without need to write forward + Rearrange('b c h w -> b (c h w)'), + Linear(16*5*5, 120), + ReLU(), + Linear(120, 10), +) +``` + +No more flatten needed! + +Additionally, torch layers as those are script-able and compile-able. +Operations [are torch.compile-able](https://github.com/arogozhnikov/einops/wiki/Using-torch.compile-with-einops), + but not script-able due to limitations of torch.jit.script. +
+ + + + +## Naming + +`einops` stands for Einstein-Inspired Notation for operations +(though "Einstein operations" is more attractive and easier to remember). + +Notation was loosely inspired by Einstein summation (in particular by `numpy.einsum` operation). + +## Why use `einops` notation?! + + +### Semantic information (being verbose in expectations) + +```python +y = x.view(x.shape[0], -1) +y = rearrange(x, 'b c h w -> b (c h w)') +``` +While these two lines are doing the same job in *some* context, +the second one provides information about the input and output. +In other words, `einops` focuses on interface: *what is the input and output*, not *how* the output is computed. + +The next operation looks similar: + +```python +y = rearrange(x, 'time c h w -> time (c h w)') +``` +but it gives the reader a hint: +this is not an independent batch of images we are processing, +but rather a sequence (video). + +Semantic information makes the code easier to read and maintain. + +### Convenient checks + +Reconsider the same example: + +```python +y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19) +y = rearrange(x, 'b c h w -> b (c h w)') +``` +The second line checks that the input has four dimensions, +but you can also specify particular dimensions. +That's opposed to just writing comments about shapes since comments don't prevent mistakes, +not tested, and without code review tend to be outdated +```python +y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19) +y = rearrange(x, 'b c h w -> b (c h w)', c=256, h=19, w=19) +``` + +### Result is strictly determined + +Below we have at least two ways to define the depth-to-space operation +```python +# depth-to-space +rearrange(x, 'b c (h h2) (w w2) -> b (c h2 w2) h w', h2=2, w2=2) +rearrange(x, 'b c (h h2) (w w2) -> b (h2 w2 c) h w', h2=2, w2=2) +``` +There are at least four more ways to do it. Which one is used by the framework? + +These details are ignored, since *usually* it makes no difference, +but it can make a big difference (e.g. if you use grouped convolutions in the next stage), +and you'd like to specify this in your code. + + +### Uniformity + +```python +reduce(x, 'b c (x dx) -> b c x', 'max', dx=2) +reduce(x, 'b c (x dx) (y dy) -> b c x y', 'max', dx=2, dy=3) +reduce(x, 'b c (x dx) (y dy) (z dz) -> b c x y z', 'max', dx=2, dy=3, dz=4) +``` +These examples demonstrated that we don't use separate operations for 1d/2d/3d pooling, +those are all defined in a uniform way. + +Space-to-depth and depth-to space are defined in many frameworks but how about width-to-height? Here you go: + +```python +rearrange(x, 'b c h (w w2) -> b c (h w2) w', w2=2) +``` + + +### Framework independent behavior + +Even simple functions are defined differently by different frameworks + +```python +y = x.flatten() # or flatten(x) +``` + +Suppose `x`'s shape was `(3, 4, 5)`, then `y` has shape ... + +- numpy, pytorch, cupy, chainer, jax: `(60,)` +- keras, tensorflow.layers, gluon: `(3, 20)` + +`einops` works the same way in all frameworks. + + +### Independence of framework terminology + +Example: `tile` vs `repeat` causes lots of confusion. To copy image along width: +```python +np.tile(image, (1, 2)) # in numpy +image.repeat(1, 2) # pytorch's repeat ~ numpy's tile +``` + +With einops you don't need to decipher which axis was repeated: +```python +repeat(image, 'h w -> h (tile w)', tile=2) # in numpy +repeat(image, 'h w -> h (tile w)', tile=2) # in pytorch +repeat(image, 'h w -> h (tile w)', tile=2) # in tf +repeat(image, 'h w -> h (tile w)', tile=2) # in jax +repeat(image, 'h w -> h (tile w)', tile=2) # in cupy +... (etc.) +``` + +[Testimonials](https://einops.rocks/pages/testimonials/) provide users' perspective on the same question. + + +## Supported frameworks + +Einops works with ... + +- [numpy](http://www.numpy.org/) +- [pytorch](https://pytorch.org/) +- [tensorflow](https://www.tensorflow.org/) +- [jax](https://github.com/google/jax) +- [cupy](https://github.com/cupy/cupy) +- [flax](https://github.com/google/flax) (community) +- [paddle](https://github.com/PaddlePaddle/Paddle) (community) +- [oneflow](https://github.com/Oneflow-Inc/oneflow) (community) +- [tinygrad](https://github.com/tinygrad/tinygrad) (community) +- [pytensor](https://github.com/pymc-devs/pytensor) (community) + + + +```python +from einops import rearrange +=> from einops.array_api import rearrange +``` + +But actually it is even better: einops can be used with *any* framework that supports +[Python array API standard](https://data-apis.org/array-api/latest/API_specification/index.html), +to name a few: + +- numpy >= 2.0 +- [MLX](https://github.com/ml-explore/mlx) # yes, einops works with apple's framework +- [pydata/sparse](https://github.com/pydata/sparse) >= 0.15 # and works with sparse tensors +- [cubed](https://github.com/cubed-dev/cubed) # and with distributed tensors too +- [quantco/ndonnx](https://github.com/Quantco/ndonnx) +- jax +- cupy +- dask is supported via [array-api-compat](https://github.com/data-apis/array-api-compat) + + +## Development + +Devcontainer is provided, this environment can be used locally, or on your server, +or within github codespaces. +To start with devcontainers in vs code, clone repo, and click 'Reopen in Devcontainer'. + +Starting from einops 0.8.1, einops distributes tests as a part of package. + +```bash +# pip install einops pytest +python -m einops.tests.run_tests numpy pytorch jax --pip-install +``` + +`numpy pytorch jax` is an _example_, any subset of testable frameworks can be provided. +Every framework is tested against numpy, so it is a requirement for tests. + +Specifying `--pip-install` will install requirements in current virtualenv, +and should be omitted if dependencies are installed locally. + +To build/test docs: + +```bash +hatch run docs:serve # Serving on http://localhost:8000/ +``` + + +## Citing einops + +Please use the following bibtex record + +```text +@inproceedings{ + rogozhnikov2022einops, + title={Einops: Clear and Reliable Tensor Manipulations with Einstein-like Notation}, + author={Alex Rogozhnikov}, + booktitle={International Conference on Learning Representations}, + year={2022}, + url={https://openreview.net/forum?id=oapKSVM2bcj} +} +``` + + +## Supported python versions + +`einops` works with python 3.9 or later. diff --git a/lib/python3.11/site-packages/einops-0.8.2.dist-info/RECORD b/lib/python3.11/site-packages/einops-0.8.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6f9a3ddf019f053b2af45f93238bab2b62f80fa6 --- /dev/null +++ b/lib/python3.11/site-packages/einops-0.8.2.dist-info/RECORD @@ -0,0 +1,58 @@ +einops-0.8.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +einops-0.8.2.dist-info/METADATA,sha256=C9ZdsENoikT0opYIwculIcky9_928ji72GlEHhUBJlM,13724 +einops-0.8.2.dist-info/RECORD,, +einops-0.8.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +einops-0.8.2.dist-info/licenses/LICENSE,sha256=MNmENkKW9R_67K1LAe4SfpUlDFBokY1LZvyWIGcj5DQ,1073 +einops/__init__.py,sha256=MwPcYWGHKsJE0Uxlhf7YMv_Sf6vu9W9Y98hy1mRM6zk,438 +einops/__pycache__/__init__.cpython-311.pyc,, +einops/__pycache__/_backends.cpython-311.pyc,, +einops/__pycache__/_torch_specific.cpython-311.pyc,, +einops/__pycache__/array_api.cpython-311.pyc,, +einops/__pycache__/einops.cpython-311.pyc,, +einops/__pycache__/packing.cpython-311.pyc,, +einops/__pycache__/parsing.cpython-311.pyc,, +einops/_backends.py,sha256=v4snGd66fVWeK0M8e3lNJ9j7_qmd8RMRyJVUTQB5slc,22528 +einops/_torch_specific.py,sha256=QXgLFLDIgDa_Iqtv5gcucEeD3LHALYHJhaXRKgC5f4A,4329 +einops/array_api.py,sha256=7mQ-4yhlWtqmtvcTZyI-pmDOSDbk3qpSCExl4-Vm1-o,5236 +einops/einops.py,sha256=vmx5IWde_ePuzrPDLZZVw_-0Qsare1k8YRRaKt5ZL-8,38079 +einops/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +einops/experimental/__pycache__/__init__.cpython-311.pyc,, +einops/experimental/__pycache__/indexing.cpython-311.pyc,, +einops/experimental/indexing.py,sha256=yFFflW3-kV6_5PPJU7_jOJsJBCWCWlE4dGlu9gwSPXo,121 +einops/layers/__init__.py,sha256=jijwEY07Yr3rBx8N5zwZ-5qfbl-KX2BcRDK8NJFDaWA,3705 +einops/layers/__pycache__/__init__.cpython-311.pyc,, +einops/layers/__pycache__/_einmix.cpython-311.pyc,, +einops/layers/__pycache__/flax.cpython-311.pyc,, +einops/layers/__pycache__/keras.cpython-311.pyc,, +einops/layers/__pycache__/oneflow.cpython-311.pyc,, +einops/layers/__pycache__/paddle.cpython-311.pyc,, +einops/layers/__pycache__/tensorflow.cpython-311.pyc,, +einops/layers/__pycache__/torch.cpython-311.pyc,, +einops/layers/_einmix.py,sha256=MQr6rymfMw-nzFmhvaLCcee0o7Ai8a1lmluxndWDAjU,11075 +einops/layers/flax.py,sha256=Hk7L31wR2BHL63950-0hy3ivw4rc8NkgGW9jn1AKs-8,2518 +einops/layers/keras.py,sha256=jxD9ZgYLWsKMkCIwojbBNSrY6c1pfXYhE2AMZa0pNXA,217 +einops/layers/oneflow.py,sha256=djcKEZRJrWvxTuSsO4jJVZojieKiDPdUpP4SOpg_zTM,1864 +einops/layers/paddle.py,sha256=YCHffUB4ha7wG-xEOeR9XcTPl48Kr57k_nBEx-J6FVA,1907 +einops/layers/tensorflow.py,sha256=MjGApMbkb_gwAdGya7uGfPZ7olyETsRzbwymfJHii9E,3322 +einops/layers/torch.py,sha256=BV-PzjoijGU9RGea1HCFuIMx4yccicz767M0jJDIH6U,2405 +einops/packing.py,sha256=EZeGLgMRD78hB-0e80ubXvWHukh0_O_wJCf0Hbbdylo,7660 +einops/parsing.py,sha256=vNPYcAs54-KLX1RtbkypGpsSpujzVkj_dQkZlUinLYw,6805 +einops/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +einops/tests/__init__.py,sha256=CpSdrOGBSspTwuG6cAsYMGAwkTq0VuIBrehM7K-SYwU,3531 +einops/tests/__pycache__/__init__.cpython-311.pyc,, +einops/tests/__pycache__/run_tests.cpython-311.pyc,, +einops/tests/__pycache__/test_einsum.cpython-311.pyc,, +einops/tests/__pycache__/test_examples.cpython-311.pyc,, +einops/tests/__pycache__/test_layers.cpython-311.pyc,, +einops/tests/__pycache__/test_ops.cpython-311.pyc,, +einops/tests/__pycache__/test_other.cpython-311.pyc,, +einops/tests/__pycache__/test_packing.cpython-311.pyc,, +einops/tests/__pycache__/test_parsing.cpython-311.pyc,, +einops/tests/run_tests.py,sha256=efJ2apHPOw1BKNIv5qZSNjHpgjSv0rJ4v9hbPbE7yNE,3072 +einops/tests/test_einsum.py,sha256=Nycwg4a-4_Vz7l5f7mj2KIQ7QVs8P2SQIy1rnDcMOG8,11022 +einops/tests/test_examples.py,sha256=6VVkHgov6hpEyoUGbMzFvRfoWTdP1Wr8RPji7G4pPlw,11510 +einops/tests/test_layers.py,sha256=m8RqmBojvVMgr_ET6mhcGpbfYPasg60jUYux7ZlXhSM,18667 +einops/tests/test_ops.py,sha256=4nxEGJWrmEG6cctYHGYuVVdEs5nUN9ziH7ukQYar44M,26884 +einops/tests/test_other.py,sha256=vkWSJr7sn-COewksivTPaLe-GAmzLt7IEZF9TMnt360,13521 +einops/tests/test_packing.py,sha256=AIBNiy8RftTj8dLv1AdNijkTXfrjCOTSw43fuD6Pfjc,10408 +einops/tests/test_parsing.py,sha256=-YAJeJlhDb3U6xYIDRrtm6p4MSNWogeH6l3-np1wUCA,4389 diff --git a/lib/python3.11/site-packages/einops-0.8.2.dist-info/WHEEL b/lib/python3.11/site-packages/einops-0.8.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/lib/python3.11/site-packages/einops-0.8.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/lib/python3.11/site-packages/einops-0.8.2.dist-info/licenses/LICENSE b/lib/python3.11/site-packages/einops-0.8.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3a654e906619009358eb2cfe80609bd12b43fa7f --- /dev/null +++ b/lib/python3.11/site-packages/einops-0.8.2.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Alex Rogozhnikov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/python3.11/site-packages/einops/__pycache__/packing.cpython-311.pyc b/lib/python3.11/site-packages/einops/__pycache__/packing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd265109d573be76d715f5ed1cc5a8548a30c441 Binary files /dev/null and b/lib/python3.11/site-packages/einops/__pycache__/packing.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/einops/__pycache__/parsing.cpython-311.pyc b/lib/python3.11/site-packages/einops/__pycache__/parsing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3b4148f438527bf6c48b0d5471e974672e4852e Binary files /dev/null and b/lib/python3.11/site-packages/einops/__pycache__/parsing.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/SKILL.md b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..48cfdabb87941fdce350f3d84b8e51f08b51eab9 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/SKILL.md @@ -0,0 +1,436 @@ +--- +name: fastapi +description: FastAPI best practices and conventions. Use when working with FastAPI APIs and Pydantic models for them. Keeps FastAPI code clean and up to date with the latest features and patterns, updated with new versions. Write new code or refactor and update old code. +--- + +# FastAPI + +Official FastAPI skill to write code with best practices, keeping up to date with new versions and features. + +## Use the `fastapi` CLI + +Run the development server on localhost with reload: + +```bash +fastapi dev +``` + + +Run the production server: + +```bash +fastapi run +``` + +### Add an entrypoint in `pyproject.toml` + +FastAPI CLI will read the entrypoint in `pyproject.toml` to know where the FastAPI app is declared. + +```toml +[tool.fastapi] +entrypoint = "my_app.main:app" +``` + +### Use `fastapi` with a path + +When adding the entrypoint to `pyproject.toml` is not possible, or the user explicitly asks not to, or it's running an independent small app, you can pass the app file path to the `fastapi` command: + +```bash +fastapi dev my_app/main.py +``` + +Prefer to set the entrypoint in `pyproject.toml` when possible. + +## Use `Annotated` + +Always prefer the `Annotated` style for parameter and dependency declarations. + +It keeps the function signatures working in other contexts, respects the types, allows reusability. + +### In Parameter Declarations + +Use `Annotated` for parameter declarations, including `Path`, `Query`, `Header`, etc.: + +```python +from typing import Annotated + +from fastapi import FastAPI, Path, Query + +app = FastAPI() + + +@app.get("/items/{item_id}") +async def read_item( + item_id: Annotated[int, Path(ge=1, description="The item ID")], + q: Annotated[str | None, Query(max_length=50)] = None, +): + return {"message": "Hello World"} +``` + +instead of: + +```python +# DO NOT DO THIS +@app.get("/items/{item_id}") +async def read_item( + item_id: int = Path(ge=1, description="The item ID"), + q: str | None = Query(default=None, max_length=50), +): + return {"message": "Hello World"} +``` + +### For Dependencies + +Use `Annotated` for dependencies with `Depends()`. + +Unless asked not to, create a new type alias for the dependency to allow re-using it. + +```python +from typing import Annotated + +from fastapi import Depends, FastAPI + +app = FastAPI() + + +def get_current_user(): + return {"username": "johndoe"} + + +CurrentUserDep = Annotated[dict, Depends(get_current_user)] + + +@app.get("/items/") +async def read_item(current_user: CurrentUserDep): + return {"message": "Hello World"} +``` + +instead of: + +```python +# DO NOT DO THIS +@app.get("/items/") +async def read_item(current_user: dict = Depends(get_current_user)): + return {"message": "Hello World"} +``` + +## Do not use Ellipsis for *path operations* or Pydantic models + +Do not use `...` as a default value for required parameters, it's not needed and not recommended. + +Do this, without Ellipsis (`...`): + +```python +from typing import Annotated + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + + +class Item(BaseModel): + name: str + description: str | None = None + price: float = Field(gt=0) + + +app = FastAPI() + + +@app.post("/items/") +async def create_item(item: Item, project_id: Annotated[int, Query()]): ... +``` + +instead of this: + +```python +# DO NOT DO THIS +class Item(BaseModel): + name: str = ... + description: str | None = None + price: float = Field(..., gt=0) + + +app = FastAPI() + + +@app.post("/items/") +async def create_item(item: Item, project_id: Annotated[int, Query(...)]): ... +``` + +## Return Type or Response Model + +When possible, include a return type. It will be used to validate, filter, document, and serialize the response. + +```python +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + + +@app.get("/items/me") +async def get_item() -> Item: + return Item(name="Plumbus", description="All-purpose home device") +``` + +**Important**: Return types or response models are what filter data ensuring no sensitive information is exposed. And they are used to serialize data with Pydantic (in Rust), this is the main idea that can increase response performance. + +The return type doesn't have to be a Pydantic model, it could be a different type, like a list of integers, or a dict, etc. + +### When to use `response_model` instead + +If the return type is not the same as the type that you want to use to validate, filter, or serialize, use the `response_model` parameter on the decorator instead. + +```python +from typing import Any + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + + +@app.get("/items/me", response_model=Item) +async def get_item() -> Any: + return {"name": "Foo", "description": "A very nice Item"} +``` + +This can be particularly useful when filtering data to expose only the public fields and avoid exposing sensitive information. + +```python +from typing import Any + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class InternalItem(BaseModel): + name: str + description: str | None = None + secret_key: str + + +class Item(BaseModel): + name: str + description: str | None = None + + +@app.get("/items/me", response_model=Item) +async def get_item() -> Any: + item = InternalItem( + name="Foo", description="A very nice Item", secret_key="supersecret" + ) + return item +``` + +## Performance + +Do not use `ORJSONResponse` or `UJSONResponse`, they are deprecated. + +Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side. + +## Including Routers + +When declaring routers, prefer to add router level parameters like prefix, tags, etc. to the router itself, instead of in `include_router()`. + +Do this: + +```python +from fastapi import APIRouter, FastAPI + +app = FastAPI() + +router = APIRouter(prefix="/items", tags=["items"]) + + +@router.get("/") +async def list_items(): + return [] + + +# In main.py +app.include_router(router) +``` + +instead of this: + +```python +# DO NOT DO THIS +from fastapi import APIRouter, FastAPI + +app = FastAPI() + +router = APIRouter() + + +@router.get("/") +async def list_items(): + return [] + + +# In main.py +app.include_router(router, prefix="/items", tags=["items"]) +``` + +There could be exceptions, but try to follow this convention. + +Apply shared dependencies at the router level via `dependencies=[Depends(...)]`. + +## Dependency Injection + +See [the dependency injection reference](references/dependencies.md) for detailed patterns including `yield` with `scope`, and class dependencies. + +Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup (with `yield`), or is shared across endpoints. + +Apply shared dependencies at the router level via `dependencies=[Depends(...)]`. + +## Async vs Sync *path operations* + +Use `async` *path operations* only when fully certain that the logic called inside is compatible with async and await (it's called with `await`) or that doesn't block. + +```python +from fastapi import FastAPI + +app = FastAPI() + + +# Use async def when calling async code +@app.get("/async-items/") +async def read_async_items(): + data = await some_async_library.fetch_items() + return data + + +# Use plain def when calling blocking/sync code or when in doubt +@app.get("/items/") +def read_items(): + data = some_blocking_library.fetch_items() + return data +``` + +In case of doubt, or by default, use regular `def` functions, those will be run in a threadpool so they don't block the event loop. + +The same rules apply to dependencies. + +Make sure blocking code is not run inside of `async` functions. The logic will work, but will damage the performance heavily. + +When needing to mix blocking and async code, see Asyncer in [the other tools reference](references/other-tools.md). + +## Streaming (JSON Lines, SSE, bytes) + +See [the streaming reference](references/streaming.md) for JSON Lines, Server-Sent Events (`EventSourceResponse`, `ServerSentEvent`), and byte streaming (`StreamingResponse`) patterns. + +## Tooling + +See [the other tools reference](references/other-tools.md) for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc. + +## Other Libraries + +See [the other tools reference](references/other-tools.md) for details on other libraries: + +* Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio. +* SQLModel for working with SQL databases, prefer it over SQLAlchemy. +* HTTPX for interacting with HTTP (other APIs), prefer it over Requests. + +## Do not use Pydantic RootModels + +Do not use Pydantic `RootModel`, instead use regular type annotations with `Annotated` and Pydantic validation utilities. + +For example, for a list with validations you could do: + +```python +from typing import Annotated + +from fastapi import Body, FastAPI +from pydantic import Field + +app = FastAPI() + + +@app.post("/items/") +async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]): + return items +``` + +instead of: + +```python +# DO NOT DO THIS +from typing import Annotated + +from fastapi import FastAPI +from pydantic import Field, RootModel + +app = FastAPI() + + +class ItemList(RootModel[Annotated[list[int], Field(min_length=1)]]): + pass + + +@app.post("/items/") +async def create_items(items: ItemList): + return items + +``` + +FastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so that types can work as normally and there's no need for the custom logic and types in RootModels. + +## Use one HTTP operation per function + +Don't mix HTTP operations in a single function, having one function per HTTP operation helps separate concerns and organize the code. + +Do this: + +```python +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + + +@app.get("/items/") +async def list_items(): + return [] + + +@app.post("/items/") +async def create_item(item: Item): + return item +``` + +instead of this: + +```python +# DO NOT DO THIS +from fastapi import FastAPI, Request +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + + +@app.api_route("/items/", methods=["GET", "POST"]) +async def handle_items(request: Request): + if request.method == "GET": + return [] +``` diff --git a/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md new file mode 100644 index 0000000000000000000000000000000000000000..ca709096e62aa1051a51695519cbb9f45b75646f --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md @@ -0,0 +1,142 @@ +# Dependency Injection + +Use dependencies when: + +* They can't be declared in Pydantic validation and require additional logic +* The logic depends on external resources or could block in any other way +* Other dependencies need their results (it's a sub-dependency) +* The logic can be shared by multiple endpoints to do things like error early, authentication, etc. +* They need to handle cleanup (e.g., DB sessions, file handles), using dependencies with `yield` +* Their logic needs input data from the request, like headers, query parameters, etc. + +## Dependencies with `yield` and `scope` + +When using dependencies with `yield`, they can have a `scope` that defines when the exit code is run. + +Use the default scope `"request"` to run the exit code after the response is sent back. + +```python +from typing import Annotated + +from fastapi import Depends, FastAPI + +app = FastAPI() + + +def get_db(): + db = DBSession() + try: + yield db + finally: + db.close() + + +DBDep = Annotated[DBSession, Depends(get_db)] + + +@app.get("/items/") +async def read_items(db: DBDep): + return db.query(Item).all() +``` + +Use the scope `"function"` when they should run the exit code after the response data is generated but before the response is sent back to the client. + +```python +from typing import Annotated + +from fastapi import Depends, FastAPI + +app = FastAPI() + + +def get_username(): + try: + yield "Rick" + finally: + print("Cleanup up before response is sent") + +UserNameDep = Annotated[str, Depends(get_username, scope="function")] + +@app.get("/users/me") +def get_user_me(username: UserNameDep): + return username +``` + +## Class Dependencies + +Avoid creating class dependencies when possible. + +If a class is needed, instead create a regular function dependency that returns a class instance. + +Do this: + +```python +from dataclasses import dataclass +from typing import Annotated + +from fastapi import Depends, FastAPI + +app = FastAPI() + + +@dataclass +class DatabasePaginator: + offset: int = 0 + limit: int = 100 + q: str | None = None + + def get_page(self) -> dict: + # Simulate a page of data + return { + "offset": self.offset, + "limit": self.limit, + "q": self.q, + "items": [], + } + + +def get_db_paginator( + offset: int = 0, limit: int = 100, q: str | None = None +) -> DatabasePaginator: + return DatabasePaginator(offset=offset, limit=limit, q=q) + + +PaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)] + + +@app.get("/items/") +async def read_items(paginator: PaginatorDep): + return paginator.get_page() +``` + +instead of this: + +```python +# DO NOT DO THIS +from typing import Annotated + +from fastapi import Depends, FastAPI + +app = FastAPI() + + +class DatabasePaginator: + def __init__(self, offset: int = 0, limit: int = 100, q: str | None = None): + self.offset = offset + self.limit = limit + self.q = q + + def get_page(self) -> dict: + # Simulate a page of data + return { + "offset": self.offset, + "limit": self.limit, + "q": self.q, + "items": [], + } + + +@app.get("/items/") +async def read_items(paginator: Annotated[DatabasePaginator, Depends()]): + return paginator.get_page() +``` diff --git a/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md new file mode 100644 index 0000000000000000000000000000000000000000..58b19d09669f8a548cf90ed8598af311ac3029d4 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md @@ -0,0 +1,76 @@ +# Other Tools + +## uv + +If uv is available, use it to manage dependencies. + +## Ruff + +If Ruff is available, use it to lint and format the code. Consider enabling the FastAPI rules. + +## ty + +If ty is available, use it to check types. + +## Asyncer + +When needing to run blocking code inside of async functions, or async code inside of blocking functions, suggest using Asyncer. + +Prefer it over AnyIO or asyncio. + +Install: + +```bash +uv add asyncer +``` + +Run blocking sync code inside of async with `asyncify()`: + +```python +from asyncer import asyncify +from fastapi import FastAPI + +app = FastAPI() + + +def do_blocking_work(name: str) -> str: + # Some blocking I/O operation + return f"Hello {name}" + + +@app.get("/items/") +async def read_items(): + result = await asyncify(do_blocking_work)(name="World") + return {"message": result} +``` + +And run async code inside of blocking sync code with `syncify()`: + +```python +from asyncer import syncify +from fastapi import FastAPI + +app = FastAPI() + + +async def do_async_work(name: str) -> str: + return f"Hello {name}" + + +@app.get("/items/") +def read_items(): + result = syncify(do_async_work)(name="World") + return {"message": result} +``` + +## SQLModel for SQL databases + +When working with SQL databases, prefer using SQLModel as it is integrated with Pydantic and will allow declaring data validation with the same models. + +Prefer it over SQLAlchemy. + +## HTTPX + +Use HTTPX for handling HTTP communication (e.g. with other APIs). It support sync and async usage. + +Prefer it over Requests. diff --git a/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md new file mode 100644 index 0000000000000000000000000000000000000000..0832eedcb92b747444e4fcc406c845ed51fa21bd --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md @@ -0,0 +1,105 @@ +# Streaming + +## Stream JSON Lines + +To stream JSON Lines, declare the return type and use `yield` to return the data. + +```python +@app.get("/items/stream") +async def stream_items() -> AsyncIterable[Item]: + for item in items: + yield item +``` + +## Server-Sent Events (SSE) + +To stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint. + +Plain objects are automatically JSON-serialized as `data:` fields, declare the return type so the serialization is done by Pydantic: + +```python +from collections.abc import AsyncIterable + +from fastapi import FastAPI +from fastapi.sse import EventSourceResponse +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + + +@app.get("/items/stream", response_class=EventSourceResponse) +async def stream_items() -> AsyncIterable[Item]: + yield Item(name="Plumbus", price=32.99) + yield Item(name="Portal Gun", price=999.99) +``` + +For full control over SSE fields (`event`, `id`, `retry`, `comment`), yield `ServerSentEvent` instances: + +```python +from collections.abc import AsyncIterable + +from fastapi import FastAPI +from fastapi.sse import EventSourceResponse, ServerSentEvent + +app = FastAPI() + + +@app.get("/events", response_class=EventSourceResponse) +async def stream_events() -> AsyncIterable[ServerSentEvent]: + yield ServerSentEvent(data={"status": "started"}, event="status", id="1") + yield ServerSentEvent(data={"progress": 50}, event="progress", id="2") +``` + +Use `raw_data` instead of `data` to send pre-formatted strings without JSON encoding: + +```python +yield ServerSentEvent(raw_data="plain text line", event="log") +``` + +## Stream bytes + +To stream bytes, declare a `response_class=` of `StreamingResponse` or a sub-class, and use `yield` to return the data. + +```python +from fastapi import FastAPI +from fastapi.responses import StreamingResponse +from app.utils import read_image + +app = FastAPI() + + +class PNGStreamingResponse(StreamingResponse): + media_type = "image/png" + +@app.get("/image", response_class=PNGStreamingResponse) +def stream_image_no_async_no_annotation(): + with read_image() as image_file: + yield from image_file +``` + +prefer this over returning a `StreamingResponse` directly: + +```python +# DO NOT DO THIS + +import anyio +from fastapi import FastAPI +from fastapi.responses import StreamingResponse +from app.utils import read_image + +app = FastAPI() + + +class PNGStreamingResponse(StreamingResponse): + media_type = "image/png" + + +@app.get("/") +async def main(): + return PNGStreamingResponse(read_image()) +``` diff --git a/lib/python3.11/site-packages/fastapi/__init__.py b/lib/python3.11/site-packages/fastapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38e74723220bf8cf8224967fb60219f580b2dcf4 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/__init__.py @@ -0,0 +1,25 @@ +"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" + +__version__ = "0.136.3" + +from starlette import status as status + +from .applications import FastAPI as FastAPI +from .background import BackgroundTasks as BackgroundTasks +from .datastructures import UploadFile as UploadFile +from .exceptions import HTTPException as HTTPException +from .exceptions import WebSocketException as WebSocketException +from .param_functions import Body as Body +from .param_functions import Cookie as Cookie +from .param_functions import Depends as Depends +from .param_functions import File as File +from .param_functions import Form as Form +from .param_functions import Header as Header +from .param_functions import Path as Path +from .param_functions import Query as Query +from .param_functions import Security as Security +from .requests import Request as Request +from .responses import Response as Response +from .routing import APIRouter as APIRouter +from .websockets import WebSocket as WebSocket +from .websockets import WebSocketDisconnect as WebSocketDisconnect diff --git a/lib/python3.11/site-packages/fastapi/__main__.py b/lib/python3.11/site-packages/fastapi/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc36465f5f40701bf333de8811d76d3484f211e6 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/__main__.py @@ -0,0 +1,3 @@ +from fastapi.cli import main + +main() diff --git a/lib/python3.11/site-packages/fastapi/_compat/__init__.py b/lib/python3.11/site-packages/fastapi/_compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4581c38c88ede0d70f9c40a67fbc9ee79529cffd --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/_compat/__init__.py @@ -0,0 +1,40 @@ +from .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE +from .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1 +from .shared import field_annotation_is_scalar as field_annotation_is_scalar +from .shared import ( + field_annotation_is_scalar_sequence as field_annotation_is_scalar_sequence, +) +from .shared import field_annotation_is_sequence as field_annotation_is_sequence +from .shared import ( + is_bytes_or_nonable_bytes_annotation as is_bytes_or_nonable_bytes_annotation, +) +from .shared import is_bytes_sequence_annotation as is_bytes_sequence_annotation +from .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance +from .shared import ( + is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_uploadfile_annotation, +) +from .shared import ( + is_uploadfile_sequence_annotation as is_uploadfile_sequence_annotation, +) +from .shared import lenient_issubclass as lenient_issubclass +from .shared import sequence_types as sequence_types +from .shared import value_is_sequence as value_is_sequence +from .v2 import ModelField as ModelField +from .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError +from .v2 import RequiredParam as RequiredParam +from .v2 import Undefined as Undefined +from .v2 import Url as Url +from .v2 import copy_field_info as copy_field_info +from .v2 import create_body_model as create_body_model +from .v2 import evaluate_forwardref as evaluate_forwardref +from .v2 import get_cached_model_fields as get_cached_model_fields +from .v2 import get_definitions as get_definitions +from .v2 import get_flat_models_from_fields as get_flat_models_from_fields +from .v2 import get_missing_field_error as get_missing_field_error +from .v2 import get_model_name_map as get_model_name_map +from .v2 import get_schema_from_model_field as get_schema_from_model_field +from .v2 import is_scalar_field as is_scalar_field +from .v2 import serialize_sequence_value as serialize_sequence_value +from .v2 import ( + with_info_plain_validator_function as with_info_plain_validator_function, +) diff --git a/lib/python3.11/site-packages/fastapi/_compat/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/fastapi/_compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a51a0424a53a87c80ee42af1e7b3a0c5ba1bcb31 Binary files /dev/null and b/lib/python3.11/site-packages/fastapi/_compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/_compat/__pycache__/shared.cpython-311.pyc b/lib/python3.11/site-packages/fastapi/_compat/__pycache__/shared.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eef795261faa1b103976678e9df025904ea8c06 Binary files /dev/null and b/lib/python3.11/site-packages/fastapi/_compat/__pycache__/shared.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/_compat/__pycache__/v2.cpython-311.pyc b/lib/python3.11/site-packages/fastapi/_compat/__pycache__/v2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94994059743e40bda223671395653db8621b01d8 Binary files /dev/null and b/lib/python3.11/site-packages/fastapi/_compat/__pycache__/v2.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/_compat/shared.py b/lib/python3.11/site-packages/fastapi/_compat/shared.py new file mode 100644 index 0000000000000000000000000000000000000000..bd38c553442dfb145dd8c73145c242ec3311aedc --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/_compat/shared.py @@ -0,0 +1,214 @@ +import types +import typing +import warnings +from collections import deque +from collections.abc import Mapping, Sequence +from dataclasses import is_dataclass +from typing import ( + Annotated, + Any, + TypeGuard, + TypeVar, + Union, + get_args, + get_origin, +) + +from fastapi.types import UnionType +from pydantic import BaseModel +from pydantic.version import VERSION as PYDANTIC_VERSION +from starlette.datastructures import UploadFile + +_T = TypeVar("_T") + +# Copy from Pydantic: pydantic/_internal/_typing_extra.py +WithArgsTypes: tuple[Any, ...] = ( + typing._GenericAlias, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute] + types.GenericAlias, + types.UnionType, +) # pyright: ignore[reportAttributeAccessIssue] + +PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) + + +sequence_annotation_to_type = { + Sequence: list, + list: list, + tuple: tuple, + set: set, + frozenset: frozenset, + deque: deque, +} + +sequence_types: tuple[type[Any], ...] = tuple(sequence_annotation_to_type.keys()) + + +# Copy of Pydantic: pydantic/_internal/_utils.py with added TypeGuard +def lenient_issubclass( + cls: Any, class_or_tuple: type[_T] | tuple[type[_T], ...] | None +) -> TypeGuard[type[_T]]: + try: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + except TypeError: # pragma: no cover + if isinstance(cls, WithArgsTypes): + return False + raise # pragma: no cover + + +def _annotation_is_sequence(annotation: type[Any] | None) -> bool: + if lenient_issubclass(annotation, (str, bytes)): + return False + return lenient_issubclass(annotation, sequence_types) + + +def field_annotation_is_sequence(annotation: type[Any] | None) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if field_annotation_is_sequence(arg): + return True + return False + return _annotation_is_sequence(annotation) or _annotation_is_sequence( + get_origin(annotation) + ) + + +def value_is_sequence(value: Any) -> bool: + return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) + + +def _annotation_is_complex(annotation: type[Any] | None) -> bool: + return ( + lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile)) + or _annotation_is_sequence(annotation) + or is_dataclass(annotation) + ) + + +def field_annotation_is_complex(annotation: type[Any] | None) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + return any(field_annotation_is_complex(arg) for arg in get_args(annotation)) + + if origin is Annotated: + return field_annotation_is_complex(get_args(annotation)[0]) + + return ( + _annotation_is_complex(annotation) + or _annotation_is_complex(origin) + or hasattr(origin, "__pydantic_core_schema__") + or hasattr(origin, "__get_pydantic_core_schema__") + ) + + +def field_annotation_is_scalar(annotation: Any) -> bool: + # handle Ellipsis here to make tuple[int, ...] work nicely + return annotation is Ellipsis or not field_annotation_is_complex(annotation) + + +def field_annotation_is_scalar_sequence(annotation: type[Any] | None) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one_scalar_sequence = False + for arg in get_args(annotation): + if field_annotation_is_scalar_sequence(arg): + at_least_one_scalar_sequence = True + continue + elif not field_annotation_is_scalar(arg): + return False + return at_least_one_scalar_sequence + return field_annotation_is_sequence(annotation) and all( + field_annotation_is_scalar(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, bytes): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, bytes): + return True + return False + + +def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool: + if lenient_issubclass(annotation, UploadFile): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if lenient_issubclass(arg, UploadFile): + return True + return False + + +def is_bytes_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_bytes_sequence_annotation(arg): + at_least_one = True + continue + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_bytes_or_nonable_bytes_annotation(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_uploadfile_sequence_annotation(annotation: Any) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + at_least_one = False + for arg in get_args(annotation): + if is_uploadfile_sequence_annotation(arg): + at_least_one = True + continue + return at_least_one + return field_annotation_is_sequence(annotation) and all( + is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) + for sub_annotation in get_args(annotation) + ) + + +def is_pydantic_v1_model_instance(obj: Any) -> bool: + # TODO: remove this function once the required version of Pydantic fully + # removes pydantic.v1 + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + from pydantic import v1 + except ImportError: # pragma: no cover + return False + return isinstance(obj, v1.BaseModel) + + +def is_pydantic_v1_model_class(cls: Any) -> bool: + # TODO: remove this function once the required version of Pydantic fully + # removes pydantic.v1 + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + from pydantic import v1 + except ImportError: # pragma: no cover + return False + return lenient_issubclass(cls, v1.BaseModel) + + +def annotation_is_pydantic_v1(annotation: Any) -> bool: + if is_pydantic_v1_model_class(annotation): + return True + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if is_pydantic_v1_model_class(arg): + return True + if field_annotation_is_sequence(annotation): + for sub_annotation in get_args(annotation): + if annotation_is_pydantic_v1(sub_annotation): + return True + return False diff --git a/lib/python3.11/site-packages/fastapi/_compat/v2.py b/lib/python3.11/site-packages/fastapi/_compat/v2.py new file mode 100644 index 0000000000000000000000000000000000000000..7be686d8655a9e7720ff0d751f82283cac20db98 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/_compat/v2.py @@ -0,0 +1,493 @@ +import re +import warnings +from collections.abc import Sequence +from copy import copy +from dataclasses import dataclass, is_dataclass +from enum import Enum +from functools import lru_cache +from typing import ( + Annotated, + Any, + Literal, + Union, + cast, + get_args, + get_origin, +) + +from fastapi._compat import lenient_issubclass, shared +from fastapi.openapi.constants import REF_TEMPLATE +from fastapi.types import IncEx, ModelNameMap, UnionType +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model +from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError +from pydantic import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation +from pydantic import ValidationError as ValidationError +from pydantic._internal import _typing_extra as _pydantic_typing_extra +from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] + GetJsonSchemaHandler as GetJsonSchemaHandler, +) +from pydantic.fields import FieldInfo as FieldInfo +from pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema +from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue +from pydantic_core import CoreSchema as CoreSchema +from pydantic_core import PydanticUndefined +from pydantic_core import Url as Url +from pydantic_core.core_schema import ( + with_info_plain_validator_function as with_info_plain_validator_function, +) + +RequiredParam = PydanticUndefined +Undefined = PydanticUndefined + + +def evaluate_forwardref( + value: Any, + globalns: dict[str, Any] | None = None, + localns: dict[str, Any] | None = None, +) -> Any: + # eval_type_lenient has been deprecated since Pydantic v2.10.0b1 (PR #10530) + try_eval_type = getattr(_pydantic_typing_extra, "try_eval_type", None) + if try_eval_type is not None: + return try_eval_type(value, globalns, localns)[0] + return _pydantic_typing_extra.eval_type_lenient( # ty: ignore[deprecated] + value, globalns, localns + ) + + +class GenerateJsonSchema(_GenerateJsonSchema): + # TODO: remove when this is merged (or equivalent): https://github.com/pydantic/pydantic/pull/12841 + # and dropping support for any version of Pydantic before that one (so, in a very long time) + def bytes_schema(self, schema: CoreSchema) -> JsonSchemaValue: + json_schema = {"type": "string", "contentMediaType": "application/octet-stream"} + bytes_mode = ( + self._config.ser_json_bytes + if self.mode == "serialization" + else self._config.val_json_bytes + ) + if bytes_mode == "base64": + json_schema["contentEncoding"] = "base64" + self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes) + return json_schema + + +# TODO: remove when dropping support for Pydantic < v2.12.3 +_Attrs = { + "default": ..., + "default_factory": None, + "alias": None, + "alias_priority": None, + "validation_alias": None, + "serialization_alias": None, + "title": None, + "field_title_generator": None, + "description": None, + "examples": None, + "exclude": None, + "exclude_if": None, + "discriminator": None, + "deprecated": None, + "json_schema_extra": None, + "frozen": None, + "validate_default": None, + "repr": True, + "init": None, + "init_var": None, + "kw_only": None, +} + + +# TODO: remove when dropping support for Pydantic < v2.12.3 +def asdict(field_info: FieldInfo) -> dict[str, Any]: + attributes = {} + for attr in _Attrs: + value = getattr(field_info, attr, Undefined) + if value is not Undefined: + attributes[attr] = value + return { + "annotation": field_info.annotation, + "metadata": field_info.metadata, + "attributes": attributes, + } + + +@dataclass +class ModelField: + field_info: FieldInfo + name: str + mode: Literal["validation", "serialization"] = "validation" + config: ConfigDict | None = None + + @property + def alias(self) -> str: + a = self.field_info.alias + return a if a is not None else self.name + + @property + def validation_alias(self) -> str | None: + va = self.field_info.validation_alias + if isinstance(va, str) and va: + return va + return None + + @property + def serialization_alias(self) -> str | None: + sa = self.field_info.serialization_alias + return sa or None + + @property + def default(self) -> Any: + return self.get_default() + + def __post_init__(self) -> None: + with warnings.catch_warnings(): + # Pydantic >= 2.12.0 warns about field specific metadata that is unused + # (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we + # end up building the type adapter from a model field annotation so we + # need to ignore the warning: + if shared.PYDANTIC_VERSION_MINOR_TUPLE >= (2, 12): + from pydantic.warnings import UnsupportedFieldAttributeWarning + + warnings.simplefilter( + "ignore", category=UnsupportedFieldAttributeWarning + ) + # TODO: remove after setting the min Pydantic to v2.12.3 + # that adds asdict(), and use self.field_info.asdict() instead + field_dict = asdict(self.field_info) + annotated_args = ( + field_dict["annotation"], + *field_dict["metadata"], + # this FieldInfo needs to be created again so that it doesn't include + # the old field info metadata and only the rest of the attributes + Field(**field_dict["attributes"]), + ) + self._type_adapter: TypeAdapter[Any] = TypeAdapter( + Annotated[annotated_args], # ty: ignore[invalid-type-form] + config=self.config, + ) + + def get_default(self) -> Any: + if self.field_info.is_required(): + return Undefined + return self.field_info.get_default(call_default_factory=True) + + def validate( + self, + value: Any, + values: dict[str, Any] = {}, # noqa: B006 + *, + loc: tuple[int | str, ...] = (), + ) -> tuple[Any, list[dict[str, Any]]]: + try: + return ( + self._type_adapter.validate_python(value, from_attributes=True), + [], + ) + except ValidationError as exc: + return None, _regenerate_error_with_loc( + errors=exc.errors(include_url=False), loc_prefix=loc + ) + + def serialize( + self, + value: Any, + *, + mode: Literal["json", "python"] = "json", + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Any: + # What calls this code passes a value that already called + # self._type_adapter.validate_python(value) + return self._type_adapter.dump_python( + value, + mode=mode, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + def serialize_json( + self, + value: Any, + *, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> bytes: + # What calls this code passes a value that already called + # self._type_adapter.validate_python(value) + # This uses Pydantic's dump_json() which serializes directly to JSON + # bytes in one pass (via Rust), avoiding the intermediate Python dict + # step of dump_python(mode="json") + json.dumps(). + return self._type_adapter.dump_json( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + def __hash__(self) -> int: + # Each ModelField is unique for our purposes, to allow making a dict from + # ModelField to its JSON Schema. + return id(self) + + +def _has_computed_fields(field: ModelField) -> bool: + computed_fields = field._type_adapter.core_schema.get("schema", {}).get( + "computed_fields", [] + ) + return len(computed_fields) > 0 + + +def get_schema_from_model_field( + *, + field: ModelField, + model_name_map: ModelNameMap, + field_mapping: dict[ + tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue + ], + separate_input_output_schemas: bool = True, +) -> dict[str, Any]: + override_mode: Literal["validation"] | None = ( + None + if (separate_input_output_schemas or _has_computed_fields(field)) + else "validation" + ) + field_alias = ( + (field.validation_alias or field.alias) + if field.mode == "validation" + else (field.serialization_alias or field.alias) + ) + + # This expects that GenerateJsonSchema was already used to generate the definitions + json_schema = field_mapping[(field, override_mode or field.mode)] + if "$ref" not in json_schema: + # TODO remove when deprecating Pydantic v1 + # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 + json_schema["title"] = field.field_info.title or field_alias.title().replace( + "_", " " + ) + return json_schema + + +def get_definitions( + *, + fields: Sequence[ModelField], + model_name_map: ModelNameMap, + separate_input_output_schemas: bool = True, +) -> tuple[ + dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], + dict[str, dict[str, Any]], +]: + schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) + validation_fields = [field for field in fields if field.mode == "validation"] + serialization_fields = [field for field in fields if field.mode == "serialization"] + flat_validation_models = get_flat_models_from_fields( + validation_fields, known_models=set() + ) + flat_serialization_models = get_flat_models_from_fields( + serialization_fields, known_models=set() + ) + flat_validation_model_fields = [ + ModelField( + field_info=FieldInfo(annotation=model), + name=model.__name__, + mode="validation", + ) + for model in flat_validation_models + ] + flat_serialization_model_fields = [ + ModelField( + field_info=FieldInfo(annotation=model), + name=model.__name__, + mode="serialization", + ) + for model in flat_serialization_models + ] + flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields + input_types = {f.field_info.annotation for f in fields} + unique_flat_model_fields = { + f for f in flat_model_fields if f.field_info.annotation not in input_types + } + inputs = [ + ( + field, + ( + field.mode + if (separate_input_output_schemas or _has_computed_fields(field)) + else "validation" + ), + field._type_adapter.core_schema, + ) + for field in list(fields) + list(unique_flat_model_fields) + ] + field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs) + for item_def in cast(dict[str, dict[str, Any]], definitions).values(): + if "description" in item_def: + item_description = cast(str, item_def["description"]).split("\f")[0] + item_def["description"] = item_description + # definitions: dict[DefsRef, dict[str, Any]] + # but mypy complains about general str in other places that are not declared as + # DefsRef, although DefsRef is just str: + # DefsRef = NewType('DefsRef', str) + # So, a cast to simplify the types here + return field_mapping, cast(dict[str, dict[str, Any]], definitions) + + +def is_scalar_field(field: ModelField) -> bool: + from fastapi import params + + return shared.field_annotation_is_scalar( + field.field_info.annotation + ) and not isinstance(field.field_info, params.Body) + + +def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: + cls = type(field_info) + merged_field_info = cls.from_annotation(annotation) + new_field_info = copy(field_info) + new_field_info.metadata = merged_field_info.metadata + new_field_info.annotation = merged_field_info.annotation + return new_field_info + + +def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: + origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation + if origin_type is Union or origin_type is UnionType: # Handle optional sequences + union_args = get_args(field.field_info.annotation) + for union_arg in union_args: + if union_arg is type(None): + continue + origin_type = get_origin(union_arg) or union_arg + break + assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index] # ty: ignore[invalid-return-type] + + +def get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]: + error = ValidationError.from_exception_data( + "Field required", [{"type": "missing", "loc": loc, "input": {}}] + ).errors(include_url=False)[0] + error["input"] = None + return error # type: ignore[return-value] # ty: ignore[invalid-return-type] + + +def create_body_model( + *, fields: Sequence[ModelField], model_name: str +) -> type[BaseModel]: + field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} + BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] # ty: ignore[no-matching-overload] + return BodyModel + + +def get_model_fields(model: type[BaseModel]) -> list[ModelField]: + model_fields: list[ModelField] = [] + for name, field_info in model.model_fields.items(): + type_ = field_info.annotation + if lenient_issubclass(type_, (BaseModel, dict)) or is_dataclass(type_): + model_config = None + else: + model_config = model.model_config + model_fields.append( + ModelField( + field_info=field_info, + name=name, + config=model_config, + ) + ) + return model_fields + + +@lru_cache +def get_cached_model_fields(model: type[BaseModel]) -> list[ModelField]: + return get_model_fields(model) + + +# Duplicate of several schema functions from Pydantic v1 to make them compatible with +# Pydantic v2 and allow mixing the models + +TypeModelOrEnum = type["BaseModel"] | type[Enum] +TypeModelSet = set[TypeModelOrEnum] + + +def normalize_name(name: str) -> str: + return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name) + + +def get_model_name_map(unique_models: TypeModelSet) -> dict[TypeModelOrEnum, str]: + name_model_map = {} + for model in unique_models: + model_name = normalize_name(model.__name__) + name_model_map[model_name] = model + return {v: k for k, v in name_model_map.items()} + + +def get_flat_models_from_model( + model: type["BaseModel"], known_models: TypeModelSet | None = None +) -> TypeModelSet: + known_models = known_models or set() + fields = get_model_fields(model) + get_flat_models_from_fields(fields, known_models=known_models) + return known_models + + +def get_flat_models_from_annotation( + annotation: Any, known_models: TypeModelSet +) -> TypeModelSet: + origin = get_origin(annotation) + if origin is not None: + for arg in get_args(annotation): + if lenient_issubclass(arg, (BaseModel, Enum)): + if arg not in known_models: + known_models.add(arg) # type: ignore[arg-type] + if lenient_issubclass(arg, BaseModel): + get_flat_models_from_model(arg, known_models=known_models) + else: + get_flat_models_from_annotation(arg, known_models=known_models) + return known_models + + +def get_flat_models_from_field( + field: ModelField, known_models: TypeModelSet +) -> TypeModelSet: + field_type = field.field_info.annotation + if lenient_issubclass(field_type, BaseModel): + if field_type in known_models: + return known_models + known_models.add(field_type) + get_flat_models_from_model(field_type, known_models=known_models) + elif lenient_issubclass(field_type, Enum): + known_models.add(field_type) + else: + get_flat_models_from_annotation(field_type, known_models=known_models) + return known_models + + +def get_flat_models_from_fields( + fields: Sequence[ModelField], known_models: TypeModelSet +) -> TypeModelSet: + for field in fields: + get_flat_models_from_field(field, known_models=known_models) + return known_models + + +def _regenerate_error_with_loc( + *, errors: Sequence[Any], loc_prefix: tuple[str | int, ...] +) -> list[dict[str, Any]]: + updated_loc_errors: list[Any] = [ + {**err, "loc": loc_prefix + err.get("loc", ())} for err in errors + ] + + return updated_loc_errors diff --git a/lib/python3.11/site-packages/fastapi/applications.py b/lib/python3.11/site-packages/fastapi/applications.py new file mode 100644 index 0000000000000000000000000000000000000000..faac6853faf19d8887172f7fa9b69c2d5c515c40 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/applications.py @@ -0,0 +1,4691 @@ +from collections.abc import Awaitable, Callable, Coroutine, Sequence +from enum import Enum +from typing import Annotated, Any, TypeVar + +from annotated_doc import Doc +from fastapi import routing +from fastapi.datastructures import Default, DefaultPlaceholder +from fastapi.exception_handlers import ( + http_exception_handler, + request_validation_exception_handler, + websocket_request_validation_exception_handler, +) +from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError +from fastapi.logger import logger +from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware +from fastapi.openapi.docs import ( + get_redoc_html, + get_swagger_ui_html, + get_swagger_ui_oauth2_redirect_html, +) +from fastapi.openapi.utils import get_openapi +from fastapi.params import Depends +from fastapi.types import DecoratedCallable, IncEx +from fastapi.utils import generate_unique_id +from starlette.applications import Starlette +from starlette.datastructures import State +from starlette.exceptions import HTTPException +from starlette.middleware import Middleware +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.middleware.errors import ServerErrorMiddleware +from starlette.middleware.exceptions import ExceptionMiddleware +from starlette.requests import Request +from starlette.responses import HTMLResponse, JSONResponse, Response +from starlette.routing import BaseRoute +from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send +from typing_extensions import deprecated + +AppType = TypeVar("AppType", bound="FastAPI") + + +class FastAPI(Starlette): + """ + `FastAPI` app class, the main entrypoint to use FastAPI. + + Read more in the + [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/). + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + ``` + """ + + def __init__( + self: AppType, + *, + debug: Annotated[ + bool, + Doc( + """ + Boolean indicating if debug tracebacks should be returned on server + errors. + + Read more in the + [Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application). + """ + ), + ] = False, + routes: Annotated[ + list[BaseRoute] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Starlette and supported for compatibility. + + --- + + A list of routes to serve incoming HTTP and WebSocket requests. + """ + ), + deprecated( + """ + You normally wouldn't use this parameter with FastAPI, it is inherited + from Starlette and supported for compatibility. + + In FastAPI, you normally would use the *path operation methods*, + like `app.get()`, `app.post()`, etc. + """ + ), + ] = None, + title: Annotated[ + str, + Doc( + """ + The title of the API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(title="ChimichangApp") + ``` + """ + ), + ] = "FastAPI", + summary: Annotated[ + str | None, + Doc( + """ + A short summary of the API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(summary="Deadpond's favorite app. Nuff said.") + ``` + """ + ), + ] = None, + description: Annotated[ + str, + Doc( + ''' + A description of the API. Supports Markdown (using + [CommonMark syntax](https://commonmark.org/)). + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI( + description=""" + ChimichangApp API helps you do awesome stuff. 🚀 + + ## Items + + You can **read items**. + + ## Users + + You will be able to: + + * **Create users** (_not implemented_). + * **Read users** (_not implemented_). + + """ + ) + ``` + ''' + ), + ] = "", + version: Annotated[ + str, + Doc( + """ + The version of the API. + + **Note** This is the version of your application, not the version of + the OpenAPI specification nor the version of FastAPI being used. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(version="0.0.1") + ``` + """ + ), + ] = "0.1.0", + openapi_url: Annotated[ + str | None, + Doc( + """ + The URL where the OpenAPI schema will be served from. + + If you set it to `None`, no OpenAPI schema will be served publicly, and + the default automatic endpoints `/docs` and `/redoc` will also be + disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(openapi_url="/api/v1/openapi.json") + ``` + """ + ), + ] = "/openapi.json", + openapi_tags: Annotated[ + list[dict[str, Any]] | None, + Doc( + """ + A list of tags used by OpenAPI, these are the same `tags` you can set + in the *path operations*, like: + + * `@app.get("/users/", tags=["users"])` + * `@app.get("/items/", tags=["items"])` + + The order of the tags can be used to specify the order shown in + tools like Swagger UI, used in the automatic path `/docs`. + + It's not required to specify all the tags used. + + The tags that are not declared MAY be organized randomly or based + on the tools' logic. Each tag name in the list MUST be unique. + + The value of each item is a `dict` containing: + + * `name`: The name of the tag. + * `description`: A short description of the tag. + [CommonMark syntax](https://commonmark.org/) MAY be used for rich + text representation. + * `externalDocs`: Additional external documentation for this tag. If + provided, it would contain a `dict` with: + * `description`: A short description of the target documentation. + [CommonMark syntax](https://commonmark.org/) MAY be used for + rich text representation. + * `url`: The URL for the target documentation. Value MUST be in + the form of a URL. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags). + + **Example** + + ```python + from fastapi import FastAPI + + tags_metadata = [ + { + "name": "users", + "description": "Operations with users. The **login** logic is also here.", + }, + { + "name": "items", + "description": "Manage items. So _fancy_ they have their own docs.", + "externalDocs": { + "description": "Items external docs", + "url": "https://fastapi.tiangolo.com/", + }, + }, + ] + + app = FastAPI(openapi_tags=tags_metadata) + ``` + """ + ), + ] = None, + servers: Annotated[ + list[dict[str, str | Any]] | None, + Doc( + """ + A `list` of `dict`s with connectivity information to a target server. + + You would use it, for example, if your application is served from + different domains and you want to use the same Swagger UI in the + browser to interact with each of them (instead of having multiple + browser tabs open). Or if you want to leave fixed the possible URLs. + + If the servers `list` is not provided, or is an empty `list`, the + `servers` property in the generated OpenAPI will be: + + * a `dict` with a `url` value of the application's mounting point + (`root_path`) if it's different from `/`. + * otherwise, the `servers` property will be omitted from the OpenAPI + schema. + + Each item in the `list` is a `dict` containing: + + * `url`: A URL to the target host. This URL supports Server Variables + and MAY be relative, to indicate that the host location is relative + to the location where the OpenAPI document is being served. Variable + substitutions will be made when a variable is named in `{`brackets`}`. + * `description`: An optional string describing the host designated by + the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for + rich text representation. + * `variables`: A `dict` between a variable name and its value. The value + is used for substitution in the server's URL template. + + Read more in the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI( + servers=[ + {"url": "https://stag.example.com", "description": "Staging environment"}, + {"url": "https://prod.example.com", "description": "Production environment"}, + ] + ) + ``` + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of global dependencies, they will be applied to each + *path operation*, including in sub-routers. + + Read more about it in the + [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/). + + **Example** + + ```python + from fastapi import Depends, FastAPI + + from .dependencies import func_dep_1, func_dep_2 + + app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)]) + ``` + """ + ), + ] = None, + default_response_class: Annotated[ + type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + + **Example** + + ```python + from fastapi import FastAPI + from fastapi.responses import ORJSONResponse + + app = FastAPI(default_response_class=ORJSONResponse) + ``` + """ + ), + ] = Default(JSONResponse), + redirect_slashes: Annotated[ + bool, + Doc( + """ + Whether to detect and redirect slashes in URLs when the client doesn't + use the same format. + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(redirect_slashes=True) # the default + + @app.get("/items/") + async def read_items(): + return [{"item_id": "Foo"}] + ``` + + With this app, if a client goes to `/items` (without a trailing slash), + they will be automatically redirected with an HTTP status code of 307 + to `/items/`. + """ + ), + ] = True, + docs_url: Annotated[ + str | None, + Doc( + """ + The path to the automatic interactive API documentation. + It is handled in the browser by Swagger UI. + + The default URL is `/docs`. You can disable it by setting it to `None`. + + If `openapi_url` is set to `None`, this will be automatically disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(docs_url="/documentation", redoc_url=None) + ``` + """ + ), + ] = "/docs", + redoc_url: Annotated[ + str | None, + Doc( + """ + The path to the alternative automatic interactive API documentation + provided by ReDoc. + + The default URL is `/redoc`. You can disable it by setting it to `None`. + + If `openapi_url` is set to `None`, this will be automatically disabled. + + Read more in the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(docs_url="/documentation", redoc_url="redocumentation") + ``` + """ + ), + ] = "/redoc", + swagger_ui_oauth2_redirect_url: Annotated[ + str | None, + Doc( + """ + The OAuth2 redirect endpoint for the Swagger UI. + + By default it is `/docs/oauth2-redirect`. + + This is only used if you use OAuth2 (with the "Authorize" button) + with Swagger UI. + """ + ), + ] = "/docs/oauth2-redirect", + swagger_ui_init_oauth: Annotated[ + dict[str, Any] | None, + Doc( + """ + OAuth2 configuration for the Swagger UI, by default shown at `/docs`. + + Read more about the available configuration options in the + [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). + """ + ), + ] = None, + middleware: Annotated[ + Sequence[Middleware] | None, + Doc( + """ + List of middleware to be added when creating the application. + + In FastAPI you would normally do this with `app.add_middleware()` + instead. + + Read more in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + """ + ), + ] = None, + exception_handlers: Annotated[ + dict[ + int | type[Exception], + Callable[[Request, Any], Coroutine[Any, Any, Response]], + ] + | None, + Doc( + """ + A dictionary with handlers for exceptions. + + In FastAPI, you would normally use the decorator + `@app.exception_handler()`. + + Read more in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + """ + ), + ] = None, + on_startup: Annotated[ + Sequence[Callable[[], Any]] | None, + Doc( + """ + A list of startup event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + on_shutdown: Annotated[ + Sequence[Callable[[], Any]] | None, + Doc( + """ + A list of shutdown event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + lifespan: Annotated[ + Lifespan[AppType] | None, + Doc( + """ + A `Lifespan` context manager handler. This replaces `startup` and + `shutdown` functions with a single context manager. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + terms_of_service: Annotated[ + str | None, + Doc( + """ + A URL to the Terms of Service for your API. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI(terms_of_service="http://example.com/terms/") + ``` + """ + ), + ] = None, + contact: Annotated[ + dict[str, str | Any] | None, + Doc( + """ + A dictionary with the contact information for the exposed API. + + It can contain several fields. + + * `name`: (`str`) The name of the contact person/organization. + * `url`: (`str`) A URL pointing to the contact information. MUST be in + the format of a URL. + * `email`: (`str`) The email address of the contact person/organization. + MUST be in the format of an email address. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI( + contact={ + "name": "Deadpoolio the Amazing", + "url": "http://x-force.example.com/contact/", + "email": "dp@x-force.example.com", + } + ) + ``` + """ + ), + ] = None, + license_info: Annotated[ + dict[str, str | Any] | None, + Doc( + """ + A dictionary with the license information for the exposed API. + + It can contain several fields. + + * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The + license name used for the API. + * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression + for the API. The `identifier` field is mutually exclusive of the `url` + field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. + * `url`: (`str`) A URL to the license used for the API. This MUST be + the format of a URL. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more at the + [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). + + **Example** + + ```python + app = FastAPI( + license_info={ + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html", + } + ) + ``` + """ + ), + ] = None, + openapi_prefix: Annotated[ + str, + Doc( + """ + A URL prefix for the OpenAPI URL. + """ + ), + deprecated( + """ + "openapi_prefix" has been deprecated in favor of "root_path", which + follows more closely the ASGI standard, is simpler, and more + automatic. + """ + ), + ] = "", + root_path: Annotated[ + str, + Doc( + """ + A path prefix handled by a proxy that is not seen by the application + but is seen by external clients, which affects things like Swagger UI. + + Read more about it at the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(root_path="/api/v1") + ``` + """ + ), + ] = "", + root_path_in_servers: Annotated[ + bool, + Doc( + """ + To disable automatically generating the URLs in the `servers` field + in the autogenerated OpenAPI using the `root_path`. + + Read more about it in the + [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path). + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI(root_path_in_servers=False) + ``` + """ + ), + ] = True, + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + OpenAPI callbacks that should apply to all *path operations*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + webhooks: Annotated[ + routing.APIRouter | None, + Doc( + """ + Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't + depend on specific *path operations*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0. + + Read more about it in the + [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark all *path operations* as deprecated. You probably don't need it, + but it's available. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) all the *path operations* in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + swagger_ui_parameters: Annotated[ + dict[str, Any] | None, + Doc( + """ + Parameters to configure Swagger UI, the autogenerated interactive API + documentation (by default at `/docs`). + + Read more about it in the + [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + separate_input_output_schemas: Annotated[ + bool, + Doc( + """ + Whether to generate separate OpenAPI schemas for request body and + response body when the results would be more precise. + + This is particularly useful when automatically generating clients. + + For example, if you have a model like: + + ```python + from pydantic import BaseModel + + class Item(BaseModel): + name: str + tags: list[str] = [] + ``` + + When `Item` is used for input, a request body, `tags` is not required, + the client doesn't have to provide it. + + But when using `Item` for output, for a response body, `tags` is always + available because it has a default value, even if it's just an empty + list. So, the client should be able to always expect it. + + In this case, there would be two different schemas, one for input and + another one for output. + + Read more about it in the + [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas) + """ + ), + ] = True, + openapi_external_docs: Annotated[ + dict[str, Any] | None, + Doc( + """ + This field allows you to provide additional external documentation links. + If provided, it must be a dictionary containing: + + * `description`: A brief description of the external documentation. + * `url`: The URL pointing to the external documentation. The value **MUST** + be a valid URL format. + + **Example**: + + ```python + from fastapi import FastAPI + + external_docs = { + "description": "Detailed API Reference", + "url": "https://example.com/api-docs", + } + + app = FastAPI(openapi_external_docs=external_docs) + ``` + """ + ), + ] = None, + strict_content_type: Annotated[ + bool, + Doc( + """ + Enable strict checking for request Content-Type headers. + + When `True` (the default), requests with a body that do not include + a `Content-Type` header will **not** be parsed as JSON. + + This prevents potential cross-site request forgery (CSRF) attacks + that exploit the browser's ability to send requests without a + Content-Type header, bypassing CORS preflight checks. In particular + applicable for apps that need to be run locally (in localhost). + + When `False`, requests without a `Content-Type` header will have + their body parsed as JSON, which maintains compatibility with + certain clients that don't send `Content-Type` headers. + + Read more about it in the + [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/). + """ + ), + ] = True, + **extra: Annotated[ + Any, + Doc( + """ + Extra keyword arguments to be stored in the app, not used by FastAPI + anywhere. + """ + ), + ], + ) -> None: + self.debug = debug + self.title = title + self.summary = summary + self.description = description + self.version = version + self.terms_of_service = terms_of_service + self.contact = contact + self.license_info = license_info + self.openapi_url = openapi_url + self.openapi_tags = openapi_tags + self.root_path_in_servers = root_path_in_servers + self.docs_url = docs_url + self.redoc_url = redoc_url + self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url + self.swagger_ui_init_oauth = swagger_ui_init_oauth + self.swagger_ui_parameters = swagger_ui_parameters + self.servers = servers or [] + self.separate_input_output_schemas = separate_input_output_schemas + self.openapi_external_docs = openapi_external_docs + self.extra = extra + self.openapi_version: Annotated[ + str, + Doc( + """ + The version string of OpenAPI. + + FastAPI will generate OpenAPI version 3.1.0, and will output that as + the OpenAPI version. But some tools, even though they might be + compatible with OpenAPI 3.1.0, might not recognize it as a valid. + + So you could override this value to trick those tools into using + the generated OpenAPI. Have in mind that this is a hack. But if you + avoid using features added in OpenAPI 3.1.0, it might work for your + use case. + + This is not passed as a parameter to the `FastAPI` class to avoid + giving the false idea that FastAPI would generate a different OpenAPI + schema. It is only available as an attribute. + + **Example** + + ```python + from fastapi import FastAPI + + app = FastAPI() + + app.openapi_version = "3.0.2" + ``` + """ + ), + ] = "3.1.0" + self.openapi_schema: dict[str, Any] | None = None + if self.openapi_url: + assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" + assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" + # TODO: remove when discarding the openapi_prefix parameter + if openapi_prefix: + logger.warning( + '"openapi_prefix" has been deprecated in favor of "root_path", which ' + "follows more closely the ASGI standard, is simpler, and more " + "automatic. Check the docs at " + "https://fastapi.tiangolo.com/advanced/sub-applications/" + ) + self.webhooks: Annotated[ + routing.APIRouter, + Doc( + """ + The `app.webhooks` attribute is an `APIRouter` with the *path + operations* that will be used just for documentation of webhooks. + + Read more about it in the + [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). + """ + ), + ] = webhooks or routing.APIRouter() + self.root_path = root_path or openapi_prefix + self.state: Annotated[ + State, + Doc( + """ + A state object for the application. This is the same object for the + entire application, it doesn't change from request to request. + + You normally wouldn't use this in FastAPI, for most of the cases you + would instead use FastAPI dependencies. + + This is simply inherited from Starlette. + + Read more about it in the + [Starlette docs for Applications](https://www.starlette.dev/applications/#storing-state-on-the-app-instance). + """ + ), + ] = State() + self.dependency_overrides: Annotated[ + dict[Callable[..., Any], Callable[..., Any]], + Doc( + """ + A dictionary with overrides for the dependencies. + + Each key is the original dependency callable, and the value is the + actual dependency that should be called. + + This is for testing, to replace expensive dependencies with testing + versions. + + Read more about it in the + [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/). + """ + ), + ] = {} + self.router: routing.APIRouter = routing.APIRouter( + routes=routes, + redirect_slashes=redirect_slashes, + dependency_overrides_provider=self, + on_startup=on_startup, + on_shutdown=on_shutdown, + lifespan=lifespan, + default_response_class=default_response_class, + dependencies=dependencies, + callbacks=callbacks, + deprecated=deprecated, + include_in_schema=include_in_schema, + responses=responses, + generate_unique_id_function=generate_unique_id_function, + strict_content_type=strict_content_type, + ) + self.exception_handlers: dict[ + Any, Callable[[Request, Any], Response | Awaitable[Response]] + ] = {} if exception_handlers is None else dict(exception_handlers) + self.exception_handlers.setdefault(HTTPException, http_exception_handler) + self.exception_handlers.setdefault( + RequestValidationError, request_validation_exception_handler + ) + + # Starlette still has incorrect type specification for the handlers + self.exception_handlers.setdefault( + WebSocketRequestValidationError, + websocket_request_validation_exception_handler, # type: ignore[arg-type] + ) # ty: ignore[no-matching-overload] + + self.user_middleware: list[Middleware] = ( + [] if middleware is None else list(middleware) + ) + self.middleware_stack: ASGIApp | None = None + self.setup() + + def build_middleware_stack(self) -> ASGIApp: + # Duplicate/override from Starlette to add AsyncExitStackMiddleware + # inside of ExceptionMiddleware, inside of custom user middlewares + debug = self.debug + error_handler = None + exception_handlers: dict[Any, ExceptionHandler] = {} + + for key, value in self.exception_handlers.items(): + if key in (500, Exception): + error_handler = value + else: + exception_handlers[key] = value + + middleware = ( + [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] + + self.user_middleware + + [ + Middleware( + ExceptionMiddleware, + handlers=exception_handlers, + debug=debug, + ), + # Add FastAPI-specific AsyncExitStackMiddleware for closing files. + # Before this was also used for closing dependencies with yield but + # those now have their own AsyncExitStack, to properly support + # streaming responses while keeping compatibility with the previous + # versions (as of writing 0.117.1) that allowed doing + # except HTTPException inside a dependency with yield. + # This needs to happen after user middlewares because those create a + # new contextvars context copy by using a new AnyIO task group. + # This AsyncExitStack preserves the context for contextvars, not + # strictly necessary for closing files but it was one of the original + # intentions. + # If the AsyncExitStack lived outside of the custom middlewares and + # contextvars were set, for example in a dependency with 'yield' + # in that internal contextvars context, the values would not be + # available in the outer context of the AsyncExitStack. + # By placing the middleware and the AsyncExitStack here, inside all + # user middlewares, the same context is used. + # This is currently not needed, only for closing files, but used to be + # important when dependencies with yield were closed here. + Middleware(AsyncExitStackMiddleware), + ] + ) + + app = self.router + for cls, args, kwargs in reversed(middleware): + app = cls(app, *args, **kwargs) + return app + + def openapi(self) -> dict[str, Any]: + """ + Generate the OpenAPI schema of the application. This is called by FastAPI + internally. + + The first time it is called it stores the result in the attribute + `app.openapi_schema`, and next times it is called, it just returns that same + result. To avoid the cost of generating the schema every time. + + If you need to modify the generated OpenAPI schema, you could modify it. + + Read more in the + [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/). + """ + if not self.openapi_schema: + self.openapi_schema = get_openapi( + title=self.title, + version=self.version, + openapi_version=self.openapi_version, + summary=self.summary, + description=self.description, + terms_of_service=self.terms_of_service, + contact=self.contact, + license_info=self.license_info, + routes=self.routes, + webhooks=self.webhooks.routes, + tags=self.openapi_tags, + servers=self.servers, + separate_input_output_schemas=self.separate_input_output_schemas, + external_docs=self.openapi_external_docs, + ) + return self.openapi_schema + + def setup(self) -> None: + if self.openapi_url: + + async def openapi(req: Request) -> JSONResponse: + root_path = req.scope.get("root_path", "").rstrip("/") + schema = self.openapi() + if root_path and self.root_path_in_servers: + server_urls = {s.get("url") for s in schema.get("servers", [])} + if root_path not in server_urls: + schema = dict(schema) + schema["servers"] = [{"url": root_path}] + schema.get( + "servers", [] + ) + return JSONResponse(schema) + + self.add_route(self.openapi_url, openapi, include_in_schema=False) + if self.openapi_url and self.docs_url: + + async def swagger_ui_html(req: Request) -> HTMLResponse: + root_path = req.scope.get("root_path", "").rstrip("/") + openapi_url = root_path + self.openapi_url + oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url + if oauth2_redirect_url: + oauth2_redirect_url = root_path + oauth2_redirect_url + return get_swagger_ui_html( + openapi_url=openapi_url, + title=f"{self.title} - Swagger UI", + oauth2_redirect_url=oauth2_redirect_url, + init_oauth=self.swagger_ui_init_oauth, + swagger_ui_parameters=self.swagger_ui_parameters, + ) + + self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False) + + if self.swagger_ui_oauth2_redirect_url: + + async def swagger_ui_redirect(req: Request) -> HTMLResponse: + return get_swagger_ui_oauth2_redirect_html() + + self.add_route( + self.swagger_ui_oauth2_redirect_url, + swagger_ui_redirect, + include_in_schema=False, + ) + if self.openapi_url and self.redoc_url: + + async def redoc_html(req: Request) -> HTMLResponse: + root_path = req.scope.get("root_path", "").rstrip("/") + openapi_url = root_path + self.openapi_url + return get_redoc_html( + openapi_url=openapi_url, title=f"{self.title} - ReDoc" + ) + + self.add_route(self.redoc_url, redoc_html, include_in_schema=False) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.root_path: + scope["root_path"] = self.root_path + await super().__call__(scope, receive, send) + + def add_api_route( + self, + path: str, + endpoint: Callable[..., Any], + *, + response_model: Any = Default(None), + status_code: int | None = None, + tags: list[str | Enum] | None = None, + dependencies: Sequence[Depends] | None = None, + summary: str | None = None, + description: str | None = None, + response_description: str = "Successful Response", + responses: dict[int | str, dict[str, Any]] | None = None, + deprecated: bool | None = None, + methods: list[str] | None = None, + operation_id: str | None = None, + response_model_include: IncEx | None = None, + response_model_exclude: IncEx | None = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), + name: str | None = None, + openapi_extra: dict[str, Any] | None = None, + generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( + generate_unique_id + ), + ) -> None: + self.router.add_api_route( + path, + endpoint=endpoint, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def api_route( + self, + path: str, + *, + response_model: Any = Default(None), + status_code: int | None = None, + tags: list[str | Enum] | None = None, + dependencies: Sequence[Depends] | None = None, + summary: str | None = None, + description: str | None = None, + response_description: str = "Successful Response", + responses: dict[int | str, dict[str, Any]] | None = None, + deprecated: bool | None = None, + methods: list[str] | None = None, + operation_id: str | None = None, + response_model_include: IncEx | None = None, + response_model_exclude: IncEx | None = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: type[Response] = Default(JSONResponse), + name: str | None = None, + openapi_extra: dict[str, Any] | None = None, + generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( + generate_unique_id + ), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.router.add_api_route( + path, + func, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + return func + + return decorator + + def add_api_websocket_route( + self, + path: str, + endpoint: Callable[..., Any], + name: str | None = None, + *, + dependencies: Sequence[Depends] | None = None, + ) -> None: + self.router.add_api_websocket_route( + path, + endpoint, + name=name, + dependencies=dependencies, + ) + + def websocket( + self, + path: Annotated[ + str, + Doc( + """ + WebSocket path. + """ + ), + ], + name: Annotated[ + str | None, + Doc( + """ + A name for the WebSocket. Only used internally. + """ + ), + ] = None, + *, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be used for this + WebSocket. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + """ + ), + ] = None, + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ```python + from fastapi import FastAPI, WebSocket + + app = FastAPI() + + @app.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_api_websocket_route( + path, + func, + name=name, + dependencies=dependencies, + ) + return func + + return decorator + + def include_router( + self, + router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")], + *, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + + **Example** + + ```python + from fastapi import Depends, FastAPI + + from .dependencies import get_token_header + from .internal import admin + + app = FastAPI() + + app.include_router( + admin.router, + dependencies=[Depends(get_token_header)], + ) + ``` + """ + ), + ] = None, + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark all the *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + **Example** + + ```python + from fastapi import FastAPI + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + deprecated=True, + ) + ``` + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include (or not) all the *path operations* in this router in the + generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + **Example** + + ```python + from fastapi import FastAPI + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + include_in_schema=False, + ) + ``` + """ + ), + ] = True, + default_response_class: Annotated[ + type[Response], + Doc( + """ + Default response class to be used for the *path operations* in this + router. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + + **Example** + + ```python + from fastapi import FastAPI + from fastapi.responses import ORJSONResponse + + from .internal import old_api + + app = FastAPI() + + app.include_router( + old_api.router, + default_response_class=ORJSONResponse, + ) + ``` + """ + ), + ] = Default(JSONResponse), + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> None: + """ + Include an `APIRouter` in the same app. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import FastAPI + + from .users import users_router + + app = FastAPI() + + app.include_router(users_router) + ``` + """ + self.router.include_router( + router, + prefix=prefix, + tags=tags, + dependencies=dependencies, + responses=responses, + deprecated=deprecated, + include_in_schema=include_in_schema, + default_response_class=default_response_class, + callbacks=callbacks, + generate_unique_id_function=generate_unique_id_function, + ) + + def get( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + ``` + """ + return self.router.get( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def put( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + ``` + """ + return self.router.put( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def post( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + ``` + """ + return self.router.post( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def delete( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + ``` + """ + return self.router.delete( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def options( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + ``` + """ + return self.router.options( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def head( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import FastAPI, Response + + app = FastAPI() + + @app.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + ``` + """ + return self.router.head( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def patch( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + ``` + """ + return self.router.patch( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def trace( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[routing.APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + ``` + """ + return self.router.trace( + path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def websocket_route( + self, path: str, name: str | None = None + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.router.add_websocket_route(path, func, name=name) + return func + + return decorator + + @deprecated( + """ + on_event is deprecated, use lifespan event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). + """ + ) + def on_event( + self, + event_type: Annotated[ + str, + Doc( + """ + The type of event. `startup` or `shutdown`. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the application. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ + return self.router.on_event(event_type) # ty: ignore[deprecated] + + def middleware( + self, + middleware_type: Annotated[ + str, + Doc( + """ + The type of middleware. Currently only supports `http`. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a middleware to the application. + + Read more about it in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + + ## Example + + ```python + import time + from typing import Awaitable, Callable + + from fastapi import FastAPI, Request, Response + + app = FastAPI() + + + @app.middleware("http") + async def add_process_time_header( + request: Request, call_next: Callable[[Request], Awaitable[Response]] + ) -> Response: + start_time = time.time() + response = await call_next(request) + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + return response + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_middleware(BaseHTTPMiddleware, dispatch=func) + return func + + return decorator + + def exception_handler( + self, + exc_class_or_status_code: Annotated[ + int | type[Exception], + Doc( + """ + The Exception class this would handle, or a status code. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an exception handler to the app. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, Request + from fastapi.responses import JSONResponse + + + class UnicornException(Exception): + def __init__(self, name: str): + self.name = name + + + app = FastAPI() + + + @app.exception_handler(UnicornException) + async def unicorn_exception_handler(request: Request, exc: UnicornException): + return JSONResponse( + status_code=418, + content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, + ) + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_exception_handler(exc_class_or_status_code, func) + return func + + return decorator diff --git a/lib/python3.11/site-packages/fastapi/background.py b/lib/python3.11/site-packages/fastapi/background.py new file mode 100644 index 0000000000000000000000000000000000000000..7677058c438105d599233d441e8e7de81225a697 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/background.py @@ -0,0 +1,61 @@ +from collections.abc import Callable +from typing import Annotated, Any + +from annotated_doc import Doc +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from typing_extensions import ParamSpec + +P = ParamSpec("P") + + +class BackgroundTasks(StarletteBackgroundTasks): + """ + A collection of background tasks that will be called after a response has been + sent to the client. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + + ## Example + + ```python + from fastapi import BackgroundTasks, FastAPI + + app = FastAPI() + + + def write_notification(email: str, message=""): + with open("log.txt", mode="w") as email_file: + content = f"notification for {email}: {message}" + email_file.write(content) + + + @app.post("/send-notification/{email}") + async def send_notification(email: str, background_tasks: BackgroundTasks): + background_tasks.add_task(write_notification, email, message="some notification") + return {"message": "Notification sent in the background"} + ``` + """ + + def add_task( + self, + func: Annotated[ + Callable[P, Any], + Doc( + """ + The function to call after the response is sent. + + It can be a regular `def` function or an `async def` function. + """ + ), + ], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + """ + Add a function to be called in the background after the response is sent. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + """ + return super().add_task(func, *args, **kwargs) diff --git a/lib/python3.11/site-packages/fastapi/cli.py b/lib/python3.11/site-packages/fastapi/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3301e9daf73b474162d712f4b87f54ccd97a16 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/cli.py @@ -0,0 +1,13 @@ +try: + from fastapi_cli.cli import main as cli_main + +except ImportError: # pragma: no cover + cli_main = None # type: ignore + + +def main() -> None: + if not cli_main: # type: ignore[truthy-function] + message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' + print(message) + raise RuntimeError(message) # noqa: B904 + cli_main() diff --git a/lib/python3.11/site-packages/fastapi/concurrency.py b/lib/python3.11/site-packages/fastapi/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..76a5a2eb128bc8c22d61d986ab2cdc434178dd24 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/concurrency.py @@ -0,0 +1,41 @@ +from collections.abc import AsyncGenerator +from contextlib import AbstractContextManager +from contextlib import asynccontextmanager as asynccontextmanager +from typing import TypeVar + +import anyio.to_thread +from anyio import CapacityLimiter +from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa +from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa +from starlette.concurrency import ( # noqa + run_until_first_complete as run_until_first_complete, +) + +_T = TypeVar("_T") + + +@asynccontextmanager +async def contextmanager_in_threadpool( + cm: AbstractContextManager[_T], +) -> AsyncGenerator[_T, None]: + # blocking __exit__ from running waiting on a free thread + # can create race conditions/deadlocks if the context manager itself + # has its own internal pool (e.g. a database connection pool) + # to avoid this we let __exit__ run without a capacity limit + # since we're creating a new limiter for each call, any non-zero limit + # works (1 is arbitrary) + exit_limiter = CapacityLimiter(1) + try: + yield await run_in_threadpool(cm.__enter__) + except Exception as e: + ok = bool( + await anyio.to_thread.run_sync( + cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter + ) + ) + if not ok: + raise e + else: + await anyio.to_thread.run_sync( + cm.__exit__, None, None, None, limiter=exit_limiter + ) diff --git a/lib/python3.11/site-packages/fastapi/datastructures.py b/lib/python3.11/site-packages/fastapi/datastructures.py new file mode 100644 index 0000000000000000000000000000000000000000..1da784cf0927ed55ec6abeb051d89a6ce1e90630 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/datastructures.py @@ -0,0 +1,186 @@ +from collections.abc import Callable, Mapping +from typing import ( + Annotated, + Any, + BinaryIO, + TypeVar, + cast, +) + +from annotated_doc import Doc +from pydantic import GetJsonSchemaHandler +from starlette.datastructures import URL as URL # noqa: F401 +from starlette.datastructures import Address as Address # noqa: F401 +from starlette.datastructures import FormData as FormData # noqa: F401 +from starlette.datastructures import Headers as Headers # noqa: F401 +from starlette.datastructures import QueryParams as QueryParams # noqa: F401 +from starlette.datastructures import State as State # noqa: F401 +from starlette.datastructures import UploadFile as StarletteUploadFile + + +class UploadFile(StarletteUploadFile): + """ + A file uploaded in a request. + + Define it as a *path operation function* (or dependency) parameter. + + If you are using a regular `def` function, you can use the `upload_file.file` + attribute to access the raw standard Python file (blocking, not async), useful and + needed for non-async code. + + Read more about it in the + [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import FastAPI, File, UploadFile + + app = FastAPI() + + + @app.post("/files/") + async def create_file(file: Annotated[bytes, File()]): + return {"file_size": len(file)} + + + @app.post("/uploadfile/") + async def create_upload_file(file: UploadFile): + return {"filename": file.filename} + ``` + """ + + file: Annotated[ + BinaryIO, + Doc("The standard Python file object (non-async)."), + ] + filename: Annotated[str | None, Doc("The original file name.")] + size: Annotated[int | None, Doc("The size of the file in bytes.")] + headers: Annotated[Headers, Doc("The headers of the request.")] + content_type: Annotated[ + str | None, Doc("The content type of the request, from the headers.") + ] + + async def write( + self, + data: Annotated[ + bytes, + Doc( + """ + The bytes to write to the file. + """ + ), + ], + ) -> None: + """ + Write some bytes to the file. + + You normally wouldn't use this from a file you read in a request. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().write(data) + + async def read( + self, + size: Annotated[ + int, + Doc( + """ + The number of bytes to read from the file. + """ + ), + ] = -1, + ) -> bytes: + """ + Read some bytes from the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().read(size) + + async def seek( + self, + offset: Annotated[ + int, + Doc( + """ + The position in bytes to seek to in the file. + """ + ), + ], + ) -> None: + """ + Move to a position in the file. + + Any next read or write will be done from that position. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().seek(offset) + + async def close(self) -> None: + """ + Close the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().close() + + @classmethod + def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": + if not isinstance(__input_value, StarletteUploadFile): + raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") + return cast(UploadFile, __input_value) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler + ) -> dict[str, Any]: + return {"type": "string", "contentMediaType": "application/octet-stream"} + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] + ) -> Mapping[str, Any]: + from ._compat.v2 import with_info_plain_validator_function + + return with_info_plain_validator_function(cls._validate) + + +class DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ + + def __init__(self, value: Any): + self.value = value + + def __bool__(self) -> bool: + return bool(self.value) + + def __eq__(self, o: object) -> bool: + return isinstance(o, DefaultPlaceholder) and o.value == self.value + + +DefaultType = TypeVar("DefaultType") + + +def Default(value: DefaultType) -> DefaultType: + """ + You shouldn't use this function directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ + return DefaultPlaceholder(value) # type: ignore + + +# Sentinel for "parameter not provided" in Param/FieldInfo. +# Typed as None to satisfy ty +_Unset = Default(None) diff --git a/lib/python3.11/site-packages/fastapi/dependencies/__init__.py b/lib/python3.11/site-packages/fastapi/dependencies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23b8cea162d6bd6bd27f96499c33da39336528c6 Binary files /dev/null and b/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/models.cpython-311.pyc b/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f31850a60d6c027f41d84fbefe34d1f3f58e4e3 Binary files /dev/null and b/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/models.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/utils.cpython-311.pyc b/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b1148f1b9f7356d845d98a79ee58c1eb86080ef Binary files /dev/null and b/lib/python3.11/site-packages/fastapi/dependencies/__pycache__/utils.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/fastapi/dependencies/models.py b/lib/python3.11/site-packages/fastapi/dependencies/models.py new file mode 100644 index 0000000000000000000000000000000000000000..25ffb0d2da81071cd220b8d7bccd79b5cb795a23 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/dependencies/models.py @@ -0,0 +1,193 @@ +import inspect +import sys +from collections.abc import Callable +from dataclasses import dataclass, field +from functools import cached_property, partial +from typing import Any, Literal + +from fastapi._compat import ModelField +from fastapi.security.base import SecurityBase +from fastapi.types import DependencyCacheKey + +if sys.version_info >= (3, 13): # pragma: no cover + from inspect import iscoroutinefunction +else: # pragma: no cover + from asyncio import iscoroutinefunction + + +def _unwrapped_call(call: Callable[..., Any] | None) -> Any: + if call is None: + return call # pragma: no cover + unwrapped = inspect.unwrap(_impartial(call)) + return unwrapped + + +def _impartial(func: Callable[..., Any]) -> Callable[..., Any]: + while isinstance(func, partial): + func = func.func + return func + + +@dataclass +class Dependant: + path_params: list[ModelField] = field(default_factory=list) + query_params: list[ModelField] = field(default_factory=list) + header_params: list[ModelField] = field(default_factory=list) + cookie_params: list[ModelField] = field(default_factory=list) + body_params: list[ModelField] = field(default_factory=list) + dependencies: list["Dependant"] = field(default_factory=list) + name: str | None = None + call: Callable[..., Any] | None = None + request_param_name: str | None = None + websocket_param_name: str | None = None + http_connection_param_name: str | None = None + response_param_name: str | None = None + background_tasks_param_name: str | None = None + security_scopes_param_name: str | None = None + own_oauth_scopes: list[str] | None = None + parent_oauth_scopes: list[str] | None = None + use_cache: bool = True + path: str | None = None + scope: Literal["function", "request"] | None = None + + @cached_property + def oauth_scopes(self) -> list[str]: + scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else [] + # This doesn't use a set to preserve order, just in case + for scope in self.own_oauth_scopes or []: + if scope not in scopes: + scopes.append(scope) + return scopes + + @cached_property + def cache_key(self) -> DependencyCacheKey: + scopes_for_cache = ( + tuple(sorted(set(self.oauth_scopes or []))) if self._uses_scopes else () + ) + return ( + self.call, + scopes_for_cache, + self.computed_scope or "", + ) + + @cached_property + def _uses_scopes(self) -> bool: + if self.own_oauth_scopes: + return True + if self.security_scopes_param_name is not None: + return True + if self._is_security_scheme: + return True + for sub_dep in self.dependencies: + if sub_dep._uses_scopes: + return True + return False + + @cached_property + def _is_security_scheme(self) -> bool: + if self.call is None: + return False # pragma: no cover + unwrapped = _unwrapped_call(self.call) + return isinstance(unwrapped, SecurityBase) + + # Mainly to get the type of SecurityBase, but it's the same self.call + @cached_property + def _security_scheme(self) -> SecurityBase: + unwrapped = _unwrapped_call(self.call) + assert isinstance(unwrapped, SecurityBase) + return unwrapped + + @cached_property + def _security_dependencies(self) -> list["Dependant"]: + security_deps = [dep for dep in self.dependencies if dep._is_security_scheme] + return security_deps + + @cached_property + def is_gen_callable(self) -> bool: + if self.call is None: + return False # pragma: no cover + if inspect.isgeneratorfunction( + _impartial(self.call) + ) or inspect.isgeneratorfunction(_unwrapped_call(self.call)): + return True + if inspect.isclass(_unwrapped_call(self.call)): + return False + dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004 + if dunder_call is None: + return False # pragma: no cover + if inspect.isgeneratorfunction( + _impartial(dunder_call) + ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)): + return True + dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004 + if dunder_unwrapped_call is None: + return False # pragma: no cover + if inspect.isgeneratorfunction( + _impartial(dunder_unwrapped_call) + ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)): + return True + return False + + @cached_property + def is_async_gen_callable(self) -> bool: + if self.call is None: + return False # pragma: no cover + if inspect.isasyncgenfunction( + _impartial(self.call) + ) or inspect.isasyncgenfunction(_unwrapped_call(self.call)): + return True + if inspect.isclass(_unwrapped_call(self.call)): + return False + dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004 + if dunder_call is None: + return False # pragma: no cover + if inspect.isasyncgenfunction( + _impartial(dunder_call) + ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_call)): + return True + dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004 + if dunder_unwrapped_call is None: + return False # pragma: no cover + if inspect.isasyncgenfunction( + _impartial(dunder_unwrapped_call) + ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_unwrapped_call)): + return True + return False + + @cached_property + def is_coroutine_callable(self) -> bool: + if self.call is None: + return False # pragma: no cover + if inspect.isroutine(_impartial(self.call)) and iscoroutinefunction( + _impartial(self.call) + ): + return True + if inspect.isroutine(_unwrapped_call(self.call)) and iscoroutinefunction( + _unwrapped_call(self.call) + ): + return True + if inspect.isclass(_unwrapped_call(self.call)): + return False + dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004 + if dunder_call is None: + return False # pragma: no cover + if iscoroutinefunction(_impartial(dunder_call)) or iscoroutinefunction( + _unwrapped_call(dunder_call) + ): + return True + dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004 + if dunder_unwrapped_call is None: + return False # pragma: no cover + if iscoroutinefunction( + _impartial(dunder_unwrapped_call) + ) or iscoroutinefunction(_unwrapped_call(dunder_unwrapped_call)): + return True + return False + + @cached_property + def computed_scope(self) -> str | None: + if self.scope: + return self.scope + if self.is_gen_callable or self.is_async_gen_callable: + return "request" + return None diff --git a/lib/python3.11/site-packages/fastapi/dependencies/utils.py b/lib/python3.11/site-packages/fastapi/dependencies/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..40dffba64bed832416a002df7e89d504b365e436 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/dependencies/utils.py @@ -0,0 +1,1061 @@ +import dataclasses +import inspect +import sys +from collections.abc import ( + AsyncGenerator, + AsyncIterable, + AsyncIterator, + Callable, + Generator, + Iterable, + Iterator, + Mapping, + Sequence, +) +from contextlib import AsyncExitStack, contextmanager +from copy import copy, deepcopy +from dataclasses import dataclass +from typing import ( + Annotated, + Any, + ForwardRef, + Literal, + Union, + cast, + get_args, + get_origin, +) + +from fastapi import params +from fastapi._compat import ( + ModelField, + RequiredParam, + Undefined, + copy_field_info, + create_body_model, + evaluate_forwardref, + field_annotation_is_scalar, + field_annotation_is_scalar_sequence, + field_annotation_is_sequence, + get_cached_model_fields, + get_missing_field_error, + is_bytes_or_nonable_bytes_annotation, + is_bytes_sequence_annotation, + is_scalar_field, + is_uploadfile_or_nonable_uploadfile_annotation, + is_uploadfile_sequence_annotation, + lenient_issubclass, + sequence_types, + serialize_sequence_value, + value_is_sequence, +) +from fastapi.background import BackgroundTasks +from fastapi.concurrency import ( + asynccontextmanager, + contextmanager_in_threadpool, +) +from fastapi.dependencies.models import Dependant +from fastapi.exceptions import DependencyScopeError +from fastapi.logger import logger +from fastapi.security.oauth2 import SecurityScopes +from fastapi.types import DependencyCacheKey +from fastapi.utils import create_model_field, get_path_param_names +from pydantic import BaseModel, Json +from pydantic.fields import FieldInfo +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from starlette.concurrency import run_in_threadpool +from starlette.datastructures import ( + FormData, + Headers, + ImmutableMultiDict, + QueryParams, + UploadFile, +) +from starlette.requests import HTTPConnection, Request +from starlette.responses import Response +from starlette.websockets import WebSocket +from typing_inspection.typing_objects import is_typealiastype + +multipart_not_installed_error = ( + 'Form data requires "python-multipart" to be installed. \n' + 'You can install "python-multipart" with: \n\n' + "pip install python-multipart\n" +) +multipart_incorrect_install_error = ( + 'Form data requires "python-multipart" to be installed. ' + 'It seems you installed "multipart" instead. \n' + 'You can remove "multipart" with: \n\n' + "pip uninstall multipart\n\n" + 'And then install "python-multipart" with: \n\n' + "pip install python-multipart\n" +) + + +def ensure_multipart_is_installed() -> None: + try: + from python_multipart import __version__ + + # Import an attribute that can be mocked/deleted in testing + assert __version__ > "0.0.12" + except (ImportError, AssertionError): + try: + # __version__ is available in both multiparts, and can be mocked + from multipart import ( # type: ignore[no-redef,import-untyped] + __version__, + ) + + assert __version__ + try: + # parse_options_header is only available in the right multipart + from multipart.multipart import ( # type: ignore[import-untyped] + parse_options_header, + ) + + assert parse_options_header + except ImportError: + logger.error(multipart_incorrect_install_error) + raise RuntimeError(multipart_incorrect_install_error) from None + except ImportError: + logger.error(multipart_not_installed_error) + raise RuntimeError(multipart_not_installed_error) from None + + +def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: + assert callable(depends.dependency), ( + "A parameter-less dependency must have a callable dependency" + ) + own_oauth_scopes: list[str] = [] + if isinstance(depends, params.Security) and depends.scopes: + own_oauth_scopes.extend(depends.scopes) + return get_dependant( + path=path, + call=depends.dependency, + scope=depends.scope, + own_oauth_scopes=own_oauth_scopes, + ) + + +def get_flat_dependant( + dependant: Dependant, + *, + skip_repeats: bool = False, + visited: list[DependencyCacheKey] | None = None, + parent_oauth_scopes: list[str] | None = None, +) -> Dependant: + if visited is None: + visited = [] + visited.append(dependant.cache_key) + use_parent_oauth_scopes = (parent_oauth_scopes or []) + ( + dependant.oauth_scopes or [] + ) + + flat_dependant = Dependant( + path_params=dependant.path_params.copy(), + query_params=dependant.query_params.copy(), + header_params=dependant.header_params.copy(), + cookie_params=dependant.cookie_params.copy(), + body_params=dependant.body_params.copy(), + name=dependant.name, + call=dependant.call, + request_param_name=dependant.request_param_name, + websocket_param_name=dependant.websocket_param_name, + http_connection_param_name=dependant.http_connection_param_name, + response_param_name=dependant.response_param_name, + background_tasks_param_name=dependant.background_tasks_param_name, + security_scopes_param_name=dependant.security_scopes_param_name, + own_oauth_scopes=dependant.own_oauth_scopes, + parent_oauth_scopes=use_parent_oauth_scopes, + use_cache=dependant.use_cache, + path=dependant.path, + scope=dependant.scope, + ) + for sub_dependant in dependant.dependencies: + if skip_repeats and sub_dependant.cache_key in visited: + continue + flat_sub = get_flat_dependant( + sub_dependant, + skip_repeats=skip_repeats, + visited=visited, + parent_oauth_scopes=flat_dependant.oauth_scopes, + ) + flat_dependant.dependencies.append(flat_sub) + flat_dependant.path_params.extend(flat_sub.path_params) + flat_dependant.query_params.extend(flat_sub.query_params) + flat_dependant.header_params.extend(flat_sub.header_params) + flat_dependant.cookie_params.extend(flat_sub.cookie_params) + flat_dependant.body_params.extend(flat_sub.body_params) + flat_dependant.dependencies.extend(flat_sub.dependencies) + + return flat_dependant + + +def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]: + if not fields: + return fields + first_field = fields[0] + if len(fields) == 1 and lenient_issubclass( + first_field.field_info.annotation, BaseModel + ): + fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) + return fields_to_extract + return fields + + +def get_flat_params(dependant: Dependant) -> list[ModelField]: + flat_dependant = get_flat_dependant(dependant, skip_repeats=True) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + return path_params + query_params + header_params + cookie_params + + +def _get_signature(call: Callable[..., Any]) -> inspect.Signature: + try: + signature = inspect.signature(call, eval_str=True) + except NameError: + # Handle type annotations with if TYPE_CHECKING, not used by FastAPI + # e.g. dependency return types + if sys.version_info >= (3, 14): + from annotationlib import Format + + signature = inspect.signature(call, annotation_format=Format.FORWARDREF) + else: + signature = inspect.signature(call) + return signature + + +def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: + signature = _get_signature(call) + unwrapped = inspect.unwrap(call) + globalns = getattr(unwrapped, "__globals__", {}) + typed_params = [ + inspect.Parameter( + name=param.name, + kind=param.kind, + default=param.default, + annotation=get_typed_annotation(param.annotation, globalns), + ) + for param in signature.parameters.values() + ] + typed_signature = inspect.Signature(typed_params) + return typed_signature + + +def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any: + if isinstance(annotation, str): + annotation = ForwardRef(annotation) + annotation = evaluate_forwardref(annotation, globalns, globalns) + if annotation is type(None): + return None + return annotation + + +def get_typed_return_annotation(call: Callable[..., Any]) -> Any: + signature = _get_signature(call) + unwrapped = inspect.unwrap(call) + annotation = signature.return_annotation + + if annotation is inspect.Signature.empty: + return None + + globalns = getattr(unwrapped, "__globals__", {}) + return get_typed_annotation(annotation, globalns) + + +_STREAM_ORIGINS = { + AsyncIterable, + AsyncIterator, + AsyncGenerator, + Iterable, + Iterator, + Generator, +} + + +def get_stream_item_type(annotation: Any) -> Any | None: + origin = get_origin(annotation) + if origin is not None and origin in _STREAM_ORIGINS: + type_args = get_args(annotation) + if type_args: + return type_args[0] + return Any + return None + + +def get_dependant( + *, + path: str, + call: Callable[..., Any], + name: str | None = None, + own_oauth_scopes: list[str] | None = None, + parent_oauth_scopes: list[str] | None = None, + use_cache: bool = True, + scope: Literal["function", "request"] | None = None, +) -> Dependant: + dependant = Dependant( + call=call, + name=name, + path=path, + use_cache=use_cache, + scope=scope, + own_oauth_scopes=own_oauth_scopes, + parent_oauth_scopes=parent_oauth_scopes, + ) + current_scopes = (parent_oauth_scopes or []) + (own_oauth_scopes or []) + path_param_names = get_path_param_names(path) + endpoint_signature = get_typed_signature(call) + signature_params = endpoint_signature.parameters + for param_name, param in signature_params.items(): + is_path_param = param_name in path_param_names + param_details = analyze_param( + param_name=param_name, + annotation=param.annotation, + value=param.default, + is_path_param=is_path_param, + ) + if param_details.depends is not None: + assert param_details.depends.dependency + if ( + (dependant.is_gen_callable or dependant.is_async_gen_callable) + and dependant.computed_scope == "request" + and param_details.depends.scope == "function" + ): + assert dependant.call + call_name = getattr(dependant.call, "__name__", "") + raise DependencyScopeError( + f'The dependency "{call_name}" has a scope of ' + '"request", it cannot depend on dependencies with scope "function".' + ) + sub_own_oauth_scopes: list[str] = [] + if isinstance(param_details.depends, params.Security): + if param_details.depends.scopes: + sub_own_oauth_scopes = list(param_details.depends.scopes) + sub_dependant = get_dependant( + path=path, + call=param_details.depends.dependency, + name=param_name, + own_oauth_scopes=sub_own_oauth_scopes, + parent_oauth_scopes=current_scopes, + use_cache=param_details.depends.use_cache, + scope=param_details.depends.scope, + ) + dependant.dependencies.append(sub_dependant) + continue + if add_non_field_param_to_dependency( + param_name=param_name, + type_annotation=param_details.type_annotation, + dependant=dependant, + ): + assert param_details.field is None, ( + f"Cannot specify multiple FastAPI annotations for {param_name!r}" + ) + continue + assert param_details.field is not None + if isinstance(param_details.field.field_info, params.Body): + dependant.body_params.append(param_details.field) + else: + add_param_to_fields(field=param_details.field, dependant=dependant) + return dependant + + +def add_non_field_param_to_dependency( + *, param_name: str, type_annotation: Any, dependant: Dependant +) -> bool | None: + if lenient_issubclass(type_annotation, Request): + dependant.request_param_name = param_name + return True + elif lenient_issubclass(type_annotation, WebSocket): + dependant.websocket_param_name = param_name + return True + elif lenient_issubclass(type_annotation, HTTPConnection): + dependant.http_connection_param_name = param_name + return True + elif lenient_issubclass(type_annotation, Response): + dependant.response_param_name = param_name + return True + elif lenient_issubclass(type_annotation, StarletteBackgroundTasks): + dependant.background_tasks_param_name = param_name + return True + elif lenient_issubclass(type_annotation, SecurityScopes): + dependant.security_scopes_param_name = param_name + return True + return None + + +@dataclass +class ParamDetails: + type_annotation: Any + depends: params.Depends | None + field: ModelField | None + + +def analyze_param( + *, + param_name: str, + annotation: Any, + value: Any, + is_path_param: bool, +) -> ParamDetails: + field_info = None + depends = None + type_annotation: Any = Any + use_annotation: Any = Any + if is_typealiastype(annotation): + # unpack in case PEP 695 type syntax is used + annotation = annotation.__value__ + if annotation is not inspect.Signature.empty: + use_annotation = annotation + type_annotation = annotation + # Extract Annotated info + if get_origin(use_annotation) is Annotated: + annotated_args = get_args(annotation) + type_annotation = annotated_args[0] + fastapi_annotations = [ + arg + for arg in annotated_args[1:] + if isinstance(arg, (FieldInfo, params.Depends)) + ] + fastapi_specific_annotations = [ + arg + for arg in fastapi_annotations + if isinstance( + arg, + ( + params.Param, + params.Body, + params.Depends, + ), + ) + ] + if fastapi_specific_annotations: + fastapi_annotation: FieldInfo | params.Depends | None = ( + fastapi_specific_annotations[-1] + ) + else: + fastapi_annotation = None + # Set default for Annotated FieldInfo + if isinstance(fastapi_annotation, FieldInfo): + # Copy `field_info` because we mutate `field_info.default` below. + field_info = copy_field_info( + field_info=fastapi_annotation, + annotation=use_annotation, + ) + assert ( + field_info.default == Undefined or field_info.default == RequiredParam + ), ( + f"`{field_info.__class__.__name__}` default value cannot be set in" + f" `Annotated` for {param_name!r}. Set the default value with `=` instead." + ) + if value is not inspect.Signature.empty: + assert not is_path_param, "Path parameters cannot have default values" + field_info.default = value + else: + field_info.default = RequiredParam + # Get Annotated Depends + elif isinstance(fastapi_annotation, params.Depends): + depends = fastapi_annotation + # Get Depends from default value + if isinstance(value, params.Depends): + assert depends is None, ( + "Cannot specify `Depends` in `Annotated` and default value" + f" together for {param_name!r}" + ) + assert field_info is None, ( + "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a" + f" default value together for {param_name!r}" + ) + depends = value + # Get FieldInfo from default value + elif isinstance(value, FieldInfo): + assert field_info is None, ( + "Cannot specify FastAPI annotations in `Annotated` and default value" + f" together for {param_name!r}" + ) + field_info = value + if isinstance(field_info, FieldInfo): + field_info.annotation = type_annotation + + # Get Depends from type annotation + if depends is not None and depends.dependency is None: + # Copy `depends` before mutating it + depends = copy(depends) + depends = dataclasses.replace(depends, dependency=type_annotation) + + # Handle non-param type annotations like Request + # Only apply special handling when there's no explicit Depends - if there's a Depends, + # the dependency will be called and its return value used instead of the special injection + if depends is None and lenient_issubclass( + type_annotation, + ( + Request, + WebSocket, + HTTPConnection, + Response, + StarletteBackgroundTasks, + SecurityScopes, + ), + ): + assert field_info is None, ( + f"Cannot specify FastAPI annotation for type {type_annotation!r}" + ) + # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value + elif field_info is None and depends is None: + default_value = value if value is not inspect.Signature.empty else RequiredParam + if is_path_param: + # We might check here that `default_value is RequiredParam`, but the fact is that the same + # parameter might sometimes be a path parameter and sometimes not. See + # `tests/test_infer_param_optionality.py` for an example. + field_info = params.Path(annotation=use_annotation) + elif is_uploadfile_or_nonable_uploadfile_annotation( + type_annotation + ) or is_uploadfile_sequence_annotation(type_annotation): + field_info = params.File(annotation=use_annotation, default=default_value) + elif not field_annotation_is_scalar(annotation=type_annotation): + field_info = params.Body(annotation=use_annotation, default=default_value) + else: + field_info = params.Query(annotation=use_annotation, default=default_value) + + field = None + # It's a field_info, not a dependency + if field_info is not None: + # Handle field_info.in_ + if is_path_param: + assert isinstance(field_info, params.Path), ( + f"Cannot use `{field_info.__class__.__name__}` for path param" + f" {param_name!r}" + ) + elif ( + isinstance(field_info, params.Param) + and getattr(field_info, "in_", None) is None + ): + field_info.in_ = params.ParamTypes.query + use_annotation_from_field_info = use_annotation + if isinstance(field_info, params.Form): + ensure_multipart_is_installed() + if not field_info.alias and getattr(field_info, "convert_underscores", None): + alias = param_name.replace("_", "-") + else: + alias = field_info.alias or param_name + field_info.alias = alias + field = create_model_field( + name=param_name, + type_=use_annotation_from_field_info, + default=field_info.default, + alias=alias, + field_info=field_info, + ) + if is_path_param: + assert is_scalar_field(field=field), ( + "Path params must be of one of the supported types" + ) + elif isinstance(field_info, params.Query): + assert ( + is_scalar_field(field) + or field_annotation_is_scalar_sequence(field.field_info.annotation) + or lenient_issubclass(field.field_info.annotation, BaseModel) + ), f"Query parameter {param_name!r} must be one of the supported types" + + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) + + +def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: + field_info = field.field_info + field_info_in = getattr(field_info, "in_", None) + if field_info_in == params.ParamTypes.path: + dependant.path_params.append(field) + elif field_info_in == params.ParamTypes.query: + dependant.query_params.append(field) + elif field_info_in == params.ParamTypes.header: + dependant.header_params.append(field) + else: + assert field_info_in == params.ParamTypes.cookie, ( + f"non-body parameters must be in path, query, header or cookie: {field.name}" + ) + dependant.cookie_params.append(field) + + +async def _solve_generator( + *, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any] +) -> Any: + assert dependant.call + if dependant.is_async_gen_callable: + cm = asynccontextmanager(dependant.call)(**sub_values) + elif dependant.is_gen_callable: + cm = contextmanager_in_threadpool(contextmanager(dependant.call)(**sub_values)) + return await stack.enter_async_context(cm) + + +@dataclass +class SolvedDependency: + values: dict[str, Any] + errors: list[Any] + background_tasks: StarletteBackgroundTasks | None + response: Response + dependency_cache: dict[DependencyCacheKey, Any] + + +async def solve_dependencies( + *, + request: Request | WebSocket, + dependant: Dependant, + body: dict[str, Any] | FormData | bytes | None = None, + background_tasks: StarletteBackgroundTasks | None = None, + response: Response | None = None, + dependency_overrides_provider: Any | None = None, + dependency_cache: dict[DependencyCacheKey, Any] | None = None, + # TODO: remove this parameter later, no longer used, not removing it yet as some + # people might be monkey patching this function (although that's not supported) + async_exit_stack: AsyncExitStack, + embed_body_fields: bool, +) -> SolvedDependency: + request_astack = request.scope.get("fastapi_inner_astack") + assert isinstance(request_astack, AsyncExitStack), ( + "fastapi_inner_astack not found in request scope" + ) + function_astack = request.scope.get("fastapi_function_astack") + assert isinstance(function_astack, AsyncExitStack), ( + "fastapi_function_astack not found in request scope" + ) + values: dict[str, Any] = {} + errors: list[Any] = [] + if response is None: + response = Response() + del response.headers["content-length"] + response.status_code = None # type: ignore + if dependency_cache is None: + dependency_cache = {} + for sub_dependant in dependant.dependencies: + sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) + call = sub_dependant.call + use_sub_dependant = sub_dependant + if ( + dependency_overrides_provider + and dependency_overrides_provider.dependency_overrides + ): + original_call = sub_dependant.call + call = getattr( + dependency_overrides_provider, "dependency_overrides", {} + ).get(original_call, original_call) + use_path: str = sub_dependant.path # type: ignore + use_sub_dependant = get_dependant( + path=use_path, + call=call, + name=sub_dependant.name, + parent_oauth_scopes=sub_dependant.oauth_scopes, + scope=sub_dependant.scope, + ) + + solved_result = await solve_dependencies( + request=request, + dependant=use_sub_dependant, + body=body, + background_tasks=background_tasks, + response=response, + dependency_overrides_provider=dependency_overrides_provider, + dependency_cache=dependency_cache, + async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, + ) + background_tasks = solved_result.background_tasks + if solved_result.errors: + errors.extend(solved_result.errors) + continue + if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: + solved = dependency_cache[sub_dependant.cache_key] + elif ( + use_sub_dependant.is_gen_callable or use_sub_dependant.is_async_gen_callable + ): + use_astack = request_astack + if sub_dependant.scope == "function": + use_astack = function_astack + solved = await _solve_generator( + dependant=use_sub_dependant, + stack=use_astack, + sub_values=solved_result.values, + ) + elif use_sub_dependant.is_coroutine_callable: + solved = await call(**solved_result.values) + else: + solved = await run_in_threadpool(call, **solved_result.values) + if sub_dependant.name is not None: + values[sub_dependant.name] = solved + if sub_dependant.cache_key not in dependency_cache: + dependency_cache[sub_dependant.cache_key] = solved + path_values, path_errors = request_params_to_args( + dependant.path_params, request.path_params + ) + query_values, query_errors = request_params_to_args( + dependant.query_params, request.query_params + ) + header_values, header_errors = request_params_to_args( + dependant.header_params, request.headers + ) + cookie_values, cookie_errors = request_params_to_args( + dependant.cookie_params, request.cookies + ) + values.update(path_values) + values.update(query_values) + values.update(header_values) + values.update(cookie_values) + errors += path_errors + query_errors + header_errors + cookie_errors + if dependant.body_params: + ( + body_values, + body_errors, + ) = await request_body_to_args( # body_params checked above + body_fields=dependant.body_params, + received_body=body, + embed_body_fields=embed_body_fields, + ) + values.update(body_values) + errors.extend(body_errors) + if dependant.http_connection_param_name: + values[dependant.http_connection_param_name] = request + if dependant.request_param_name and isinstance(request, Request): + values[dependant.request_param_name] = request + elif dependant.websocket_param_name and isinstance(request, WebSocket): + values[dependant.websocket_param_name] = request + if dependant.background_tasks_param_name: + if background_tasks is None: + background_tasks = BackgroundTasks() + values[dependant.background_tasks_param_name] = background_tasks + if dependant.response_param_name: + values[dependant.response_param_name] = response + if dependant.security_scopes_param_name: + values[dependant.security_scopes_param_name] = SecurityScopes( + scopes=dependant.oauth_scopes + ) + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) + + +def _validate_value_with_model_field( + *, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...] +) -> tuple[Any, list[Any]]: + if value is None: + if field.field_info.is_required(): + return None, [get_missing_field_error(loc=loc)] + else: + return deepcopy(field.default), [] + return field.validate(value, values, loc=loc) + + +def _is_json_field(field: ModelField) -> bool: + return any(type(item) is Json for item in field.field_info.metadata) + + +def _get_multidict_value( + field: ModelField, values: Mapping[str, Any], alias: str | None = None +) -> Any: + alias = alias or get_validation_alias(field) + if ( + (not _is_json_field(field)) + and field_annotation_is_sequence(field.field_info.annotation) + and isinstance(values, (ImmutableMultiDict, Headers)) + ): + value = values.getlist(alias) + else: + value = values.get(alias, None) + if ( + value is None + or ( + isinstance(field.field_info, params.Form) + and isinstance(value, str) # For type checks + and value == "" + ) + or ( + field_annotation_is_sequence(field.field_info.annotation) + and len(value) == 0 + ) + ): + if field.field_info.is_required(): + return + else: + return deepcopy(field.default) + return value + + +def request_params_to_args( + fields: Sequence[ModelField], + received_params: Mapping[str, Any] | QueryParams | Headers, +) -> tuple[dict[str, Any], list[Any]]: + values: dict[str, Any] = {} + errors: list[dict[str, Any]] = [] + + if not fields: + return values, errors + + first_field = fields[0] + fields_to_extract = fields + single_not_embedded_field = False + default_convert_underscores = True + if len(fields) == 1 and lenient_issubclass( + first_field.field_info.annotation, BaseModel + ): + fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) + single_not_embedded_field = True + # If headers are in a Pydantic model, the way to disable convert_underscores + # would be with Header(convert_underscores=False) at the Pydantic model level + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) + + params_to_process: dict[str, Any] = {} + + processed_keys = set() + + for field in fields_to_extract: + alias = None + if isinstance(received_params, Headers): + # Handle fields extracted from a Pydantic Model for a header, each field + # doesn't have a FieldInfo of type Header with the default convert_underscores=True + convert_underscores = getattr( + field.field_info, "convert_underscores", default_convert_underscores + ) + if convert_underscores: + alias = get_validation_alias(field) + if alias == field.name: + alias = alias.replace("_", "-") + value = _get_multidict_value(field, received_params, alias=alias) + if value is not None: + params_to_process[get_validation_alias(field)] = value + processed_keys.add(alias or get_validation_alias(field)) + # For headers with convert_underscores=True, mark both the converted + # header name and the original field alias as processed to avoid + # accepting the original alias as an extra header. + processed_keys.add(get_validation_alias(field)) + + for key in received_params.keys(): + if key not in processed_keys: + if isinstance(received_params, (ImmutableMultiDict, Headers)): + value = received_params.getlist(key) + if isinstance(value, list) and (len(value) == 1): + params_to_process[key] = value[0] + else: + params_to_process[key] = value + else: + params_to_process[key] = received_params.get(key) + + if single_not_embedded_field: + field_info = first_field.field_info + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) + loc: tuple[str, ...] = (field_info.in_.value,) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=params_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + + for field in fields: + value = _get_multidict_value(field, received_params) + field_info = field.field_info + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) + loc = (field_info.in_.value, get_validation_alias(field)) + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) + else: + values[field.name] = v_ + return values, errors + + +def is_union_of_base_models(field_type: Any) -> bool: + """Check if field type is a Union where all members are BaseModel subclasses.""" + from fastapi.types import UnionType + + origin = get_origin(field_type) + + # Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+) + if origin is not Union and origin is not UnionType: + return False + + union_args = get_args(field_type) + + for arg in union_args: + if not lenient_issubclass(arg, BaseModel): + return False + + return True + + +def _should_embed_body_fields(fields: list[ModelField]) -> bool: + if not fields: + return False + # More than one dependency could have the same field, it would show up as multiple + # fields but it's the same one, so count them by name + body_param_names_set = {field.name for field in fields} + # A top level field has to be a single field, not multiple + if len(body_param_names_set) > 1: + return True + first_field = fields[0] + # If it explicitly specifies it is embedded, it has to be embedded + if getattr(first_field.field_info, "embed", None): + return True + # If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level + # otherwise it has to be embedded, so that the key value pair can be extracted + if ( + isinstance(first_field.field_info, params.Form) + and not lenient_issubclass(first_field.field_info.annotation, BaseModel) + and not is_union_of_base_models(first_field.field_info.annotation) + ): + return True + return False + + +async def _extract_form_body( + body_fields: list[ModelField], + received_body: FormData, +) -> dict[str, Any]: + values = {} + + for field in body_fields: + value = _get_multidict_value(field, received_body) + field_info = field.field_info + if ( + isinstance(field_info, params.File) + and is_bytes_or_nonable_bytes_annotation(field.field_info.annotation) + and isinstance(value, UploadFile) + ): + value = await value.read() + elif ( + is_bytes_sequence_annotation(field.field_info.annotation) + and isinstance(field_info, params.File) + and value_is_sequence(value) + ): + # For types + assert isinstance(value, sequence_types) + results: list[bytes | str] = [] + for sub_value in value: + results.append(await sub_value.read()) + value = serialize_sequence_value(field=field, value=results) + if value is not None: + values[get_validation_alias(field)] = value + field_aliases = {get_validation_alias(field) for field in body_fields} + for key in received_body.keys(): + if key not in field_aliases: + param_values = received_body.getlist(key) + if len(param_values) == 1: + values[key] = param_values[0] + else: + values[key] = param_values + return values + + +async def request_body_to_args( + body_fields: list[ModelField], + received_body: dict[str, Any] | FormData | bytes | None, + embed_body_fields: bool, +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + values: dict[str, Any] = {} + errors: list[dict[str, Any]] = [] + assert body_fields, "request_body_to_args() should be called with fields" + single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields + first_field = body_fields[0] + body_to_process = received_body + + fields_to_extract: list[ModelField] = body_fields + + if ( + single_not_embedded_field + and lenient_issubclass(first_field.field_info.annotation, BaseModel) + and isinstance(received_body, FormData) + ): + fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) + + if isinstance(received_body, FormData): + body_to_process = await _extract_form_body(fields_to_extract, received_body) + + if single_not_embedded_field: + loc: tuple[str, ...] = ("body",) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=body_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + for field in body_fields: + loc = ("body", get_validation_alias(field)) + value: Any | None = None + if body_to_process is not None and not isinstance(body_to_process, bytes): + try: + value = body_to_process.get(get_validation_alias(field)) + # If the received body is a list, not a dict + except AttributeError: + errors.append(get_missing_field_error(loc)) + continue + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) + else: + values[field.name] = v_ + return values, errors + + +def get_body_field( + *, flat_dependant: Dependant, name: str, embed_body_fields: bool +) -> ModelField | None: + """ + Get a ModelField representing the request body for a path operation, combining + all body parameters into a single field if necessary. + + Used to check if it's form data (with `isinstance(body_field, params.Form)`) + or JSON and to generate the JSON Schema for a request body. + + This is **not** used to validate/parse the request body, that's done with each + individual body parameter. + """ + if not flat_dependant.body_params: + return None + first_param = flat_dependant.body_params[0] + if not embed_body_fields: + return first_param + model_name = "Body_" + name + BodyModel = create_body_model( + fields=flat_dependant.body_params, model_name=model_name + ) + required = any( + True for f in flat_dependant.body_params if f.field_info.is_required() + ) + BodyFieldInfo_kwargs: dict[str, Any] = { + "annotation": BodyModel, + "alias": "body", + } + if not required: + BodyFieldInfo_kwargs["default"] = None + if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): + BodyFieldInfo: type[params.Body] = params.File + elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): + BodyFieldInfo = params.Form + else: + BodyFieldInfo = params.Body + + body_param_media_types = [ + f.field_info.media_type + for f in flat_dependant.body_params + if isinstance(f.field_info, params.Body) + ] + if len(set(body_param_media_types)) == 1: + BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] + final_field = create_model_field( + name="body", + type_=BodyModel, + alias="body", + field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), + ) + return final_field + + +def get_validation_alias(field: ModelField) -> str: + va = getattr(field, "validation_alias", None) + return va or field.alias diff --git a/lib/python3.11/site-packages/fastapi/encoders.py b/lib/python3.11/site-packages/fastapi/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..c9f882d2bae15511d157c017102d478f01846e66 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/encoders.py @@ -0,0 +1,364 @@ +import dataclasses +import datetime +from collections import defaultdict, deque +from collections.abc import Callable +from decimal import Decimal +from enum import Enum +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) +from pathlib import Path, PurePath +from re import Pattern +from types import GeneratorType +from typing import Annotated, Any +from uuid import UUID + +from annotated_doc import Doc +from fastapi.exceptions import PydanticV1NotSupportedError +from fastapi.types import IncEx +from pydantic import BaseModel +from pydantic.networks import AnyUrl, NameEmail +from pydantic.types import SecretBytes, SecretStr +from pydantic_core import PydanticUndefinedType + +from ._compat import ( + Url, + is_pydantic_v1_model_instance, +) + +try: + # pydantic.color.Color is deprecated since v2.0b3, but supporting for bwd-compat + from pydantic.color import Color # ty: ignore[deprecated] +except ImportError: # pragma: no cover + + class Color: # type: ignore[no-redef] + pass + + +try: + # Supporting the new Color format for newer versions of Pydantic + from pydantic_extra_types.color import Color as PyExtraColor +except ImportError: # pragma: no cover + + class PyExtraColor: # type: ignore[no-redef] + pass + + +# Taken from Pydantic v1 as is +def isoformat(o: datetime.date | datetime.time) -> str: + return o.isoformat() + + +# Adapted from Pydantic v1 +# TODO: pv2 should this return strings instead? +def decimal_encoder(dec_value: Decimal) -> int | float: + """ + Encodes a Decimal as int if there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where an integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + + >>> decimal_encoder(Decimal("NaN")) + nan + """ + exponent = dec_value.as_tuple().exponent + if isinstance(exponent, int) and exponent >= 0: + return int(dec_value) + else: + return float(dec_value) + + +ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), + Color: str, + PyExtraColor: str, + datetime.date: isoformat, + datetime.datetime: isoformat, + datetime.time: isoformat, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: decimal_encoder, + Enum: lambda o: o.value, + frozenset: list, + deque: list, + GeneratorType: list, + IPv4Address: str, + IPv4Interface: str, + IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, + IPv6Network: str, + NameEmail: str, + Path: str, + Pattern: lambda o: o.pattern, + SecretBytes: str, + SecretStr: str, + set: list, + UUID: str, + Url: str, + AnyUrl: str, +} + + +def generate_encoders_by_class_tuples( + type_encoder_map: dict[Any, Callable[[Any], Any]], +) -> dict[Callable[[Any], Any], tuple[Any, ...]]: + encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict( + tuple + ) + for type_, encoder in type_encoder_map.items(): + encoders_by_class_tuples[encoder] += (type_,) + return encoders_by_class_tuples + + +encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) + + +def jsonable_encoder( + obj: Annotated[ + Any, + Doc( + """ + The input object to convert to JSON. + """ + ), + ], + include: Annotated[ + IncEx | None, + Doc( + """ + Pydantic's `include` parameter, passed to Pydantic models to set the + fields to include. + """ + ), + ] = None, + exclude: Annotated[ + IncEx | None, + Doc( + """ + Pydantic's `exclude` parameter, passed to Pydantic models to set the + fields to exclude. + """ + ), + ] = None, + by_alias: Annotated[ + bool, + Doc( + """ + Pydantic's `by_alias` parameter, passed to Pydantic models to define if + the output should use the alias names (when provided) or the Python + attribute names. In an API, if you set an alias, it's probably because you + want to use it in the result, so you probably want to leave this set to + `True`. + """ + ), + ] = True, + exclude_unset: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_unset` parameter, passed to Pydantic models to define + if it should exclude from the output the fields that were not explicitly + set (and that only had their default values). + """ + ), + ] = False, + exclude_defaults: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define + if it should exclude from the output the fields that had the same default + value, even when they were explicitly set. + """ + ), + ] = False, + exclude_none: Annotated[ + bool, + Doc( + """ + Pydantic's `exclude_none` parameter, passed to Pydantic models to define + if it should exclude from the output any fields that have a `None` value. + """ + ), + ] = False, + custom_encoder: Annotated[ + dict[Any, Callable[[Any], Any]] | None, + Doc( + """ + Pydantic's `custom_encoder` parameter, passed to Pydantic models to define + a custom encoder. + """ + ), + ] = None, + sqlalchemy_safe: Annotated[ + bool, + Doc( + """ + Exclude from the output any fields that start with the name `_sa`. + + This is mainly a hack for compatibility with SQLAlchemy objects, they + store internal SQLAlchemy-specific state in attributes named with `_sa`, + and those objects can't (and shouldn't be) serialized to JSON. + """ + ), + ] = True, +) -> Any: + """ + Convert any object to something that can be encoded in JSON. + + This is used internally by FastAPI to make sure anything you return can be + encoded as JSON before it is sent to the client. + + You can also use it yourself, for example to convert objects before saving them + in a database that supports only JSON. + + Read more about it in the + [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). + """ + custom_encoder = custom_encoder or {} + if custom_encoder: + if type(obj) in custom_encoder: + return custom_encoder[type(obj)](obj) + else: + for encoder_type, encoder_instance in custom_encoder.items(): + if isinstance(obj, encoder_type): + return encoder_instance(obj) + if include is not None and not isinstance(include, (set, dict)): + include = set(include) # type: ignore[assignment] # ty: ignore[invalid-assignment] + if exclude is not None and not isinstance(exclude, (set, dict)): + exclude = set(exclude) # type: ignore[assignment] # ty: ignore[invalid-assignment] + if isinstance(obj, BaseModel): + obj_dict = obj.model_dump( + mode="json", + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + ) + return jsonable_encoder( + obj_dict, + exclude_none=exclude_none, + exclude_defaults=exclude_defaults, + sqlalchemy_safe=sqlalchemy_safe, + ) + if dataclasses.is_dataclass(obj): + assert not isinstance(obj, type) + obj_dict = dataclasses.asdict(obj) + return jsonable_encoder( + obj_dict, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + if isinstance(obj, Enum): + return obj.value + if isinstance(obj, PurePath): + return str(obj) + if isinstance(obj, (str, int, float, type(None))): + return obj + if isinstance(obj, PydanticUndefinedType): + return None + if isinstance(obj, dict): + encoded_dict = {} + allowed_keys = set(obj.keys()) + if include is not None: + allowed_keys &= set(include) + if exclude is not None: + allowed_keys -= set(exclude) + for key, value in obj.items(): + if ( + ( + not sqlalchemy_safe + or (not isinstance(key, str)) + or (not key.startswith("_sa")) + ) + and (value is not None or not exclude_none) + and key in allowed_keys + ): + encoded_key = jsonable_encoder( + key, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + encoded_value = jsonable_encoder( + value, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + encoded_dict[encoded_key] = encoded_value + return encoded_dict + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): + encoded_list = [] + for item in obj: + encoded_list.append( + jsonable_encoder( + item, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) + ) + return encoded_list + + if type(obj) in ENCODERS_BY_TYPE: + return ENCODERS_BY_TYPE[type(obj)](obj) + for encoder, classes_tuple in encoders_by_class_tuples.items(): + if isinstance(obj, classes_tuple): + return encoder(obj) + if is_pydantic_v1_model_instance(obj): + raise PydanticV1NotSupportedError( + "pydantic.v1 models are no longer supported by FastAPI." + f" Please update the model {obj!r}." + ) + try: + data = dict(obj) + except Exception as e: + errors: list[Exception] = [] + errors.append(e) + try: + data = vars(obj) + except Exception as e: + errors.append(e) + raise ValueError(errors) from e + return jsonable_encoder( + data, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) diff --git a/lib/python3.11/site-packages/fastapi/exception_handlers.py b/lib/python3.11/site-packages/fastapi/exception_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..475dd7bdd9891a7595b6df5db97cd3840179c8fa --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/exception_handlers.py @@ -0,0 +1,34 @@ +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError +from fastapi.utils import is_body_allowed_for_status_code +from fastapi.websockets import WebSocket +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse, Response +from starlette.status import WS_1008_POLICY_VIOLATION + + +async def http_exception_handler(request: Request, exc: HTTPException) -> Response: + headers = getattr(exc, "headers", None) + if not is_body_allowed_for_status_code(exc.status_code): + return Response(status_code=exc.status_code, headers=headers) + return JSONResponse( + {"detail": exc.detail}, status_code=exc.status_code, headers=headers + ) + + +async def request_validation_exception_handler( + request: Request, exc: RequestValidationError +) -> JSONResponse: + return JSONResponse( + status_code=422, + content={"detail": jsonable_encoder(exc.errors())}, + ) + + +async def websocket_request_validation_exception_handler( + websocket: WebSocket, exc: WebSocketRequestValidationError +) -> None: + await websocket.close( + code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors()) + ) diff --git a/lib/python3.11/site-packages/fastapi/exceptions.py b/lib/python3.11/site-packages/fastapi/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d7065c52fe20220e12b7d20db4da7cbeadaf171a --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/exceptions.py @@ -0,0 +1,256 @@ +from collections.abc import Mapping, Sequence +from typing import Annotated, Any, TypedDict + +from annotated_doc import Doc +from pydantic import BaseModel, create_model +from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.exceptions import WebSocketException as StarletteWebSocketException + + +class EndpointContext(TypedDict, total=False): + function: str + path: str + file: str + line: int + + +class HTTPException(StarletteHTTPException): + """ + An HTTP exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, HTTPException + + app = FastAPI() + + items = {"foo": "The Foo Wrestlers"} + + + @app.get("/items/{item_id}") + async def read_item(item_id: str): + if item_id not in items: + raise HTTPException(status_code=404, detail="Item not found") + return {"item": items[item_id]} + ``` + """ + + def __init__( + self, + status_code: Annotated[ + int, + Doc( + """ + HTTP status code to send to the client. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) + """ + ), + ], + detail: Annotated[ + Any, + Doc( + """ + Any data to be sent to the client in the `detail` key of the JSON + response. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) + """ + ), + ] = None, + headers: Annotated[ + Mapping[str, str] | None, + Doc( + """ + Any headers to send to the client in the response. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) + + """ + ), + ] = None, + ) -> None: + super().__init__(status_code=status_code, detail=detail, headers=headers) + + +class WebSocketException(StarletteWebSocketException): + """ + A WebSocket exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import ( + Cookie, + FastAPI, + WebSocket, + WebSocketException, + status, + ) + + app = FastAPI() + + @app.websocket("/items/{item_id}/ws") + async def websocket_endpoint( + *, + websocket: WebSocket, + session: Annotated[str | None, Cookie()] = None, + item_id: str, + ): + if session is None: + raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Session cookie is: {session}") + await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") + ``` + """ + + def __init__( + self, + code: Annotated[ + int, + Doc( + """ + A closing code from the + [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). + """ + ), + ], + reason: Annotated[ + str | None, + Doc( + """ + The reason to close the WebSocket connection. + + It is UTF-8-encoded data. The interpretation of the reason is up to the + application, it is not specified by the WebSocket specification. + + It could contain text that could be human-readable or interpretable + by the client code, etc. + """ + ), + ] = None, + ) -> None: + super().__init__(code=code, reason=reason) + + +RequestErrorModel: type[BaseModel] = create_model("Request") +WebSocketErrorModel: type[BaseModel] = create_model("WebSocket") + + +class FastAPIError(RuntimeError): + """ + A generic, FastAPI-specific error. + """ + + +class DependencyScopeError(FastAPIError): + """ + A dependency declared that it depends on another dependency with an invalid + (narrower) scope. + """ + + +class ValidationException(Exception): + def __init__( + self, + errors: Sequence[Any], + *, + endpoint_ctx: EndpointContext | None = None, + ) -> None: + self._errors = errors + self.endpoint_ctx = endpoint_ctx + + ctx = endpoint_ctx or {} + self.endpoint_function = ctx.get("function") + self.endpoint_path = ctx.get("path") + self.endpoint_file = ctx.get("file") + self.endpoint_line = ctx.get("line") + + def errors(self) -> Sequence[Any]: + return self._errors + + def _format_endpoint_context(self) -> str: + if not (self.endpoint_file and self.endpoint_line and self.endpoint_function): + if self.endpoint_path: + return f"\n Endpoint: {self.endpoint_path}" + return "" + + context = f'\n File "{self.endpoint_file}", line {self.endpoint_line}, in {self.endpoint_function}' + if self.endpoint_path: + context += f"\n {self.endpoint_path}" + return context + + def __str__(self) -> str: + message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n" + for err in self._errors: + message += f" {err}\n" + message += self._format_endpoint_context() + return message.rstrip() + + +class RequestValidationError(ValidationException): + def __init__( + self, + errors: Sequence[Any], + *, + body: Any = None, + endpoint_ctx: EndpointContext | None = None, + ) -> None: + super().__init__(errors, endpoint_ctx=endpoint_ctx) + self.body = body + + +class WebSocketRequestValidationError(ValidationException): + def __init__( + self, + errors: Sequence[Any], + *, + endpoint_ctx: EndpointContext | None = None, + ) -> None: + super().__init__(errors, endpoint_ctx=endpoint_ctx) + + +class ResponseValidationError(ValidationException): + def __init__( + self, + errors: Sequence[Any], + *, + body: Any = None, + endpoint_ctx: EndpointContext | None = None, + ) -> None: + super().__init__(errors, endpoint_ctx=endpoint_ctx) + self.body = body + + +class PydanticV1NotSupportedError(FastAPIError): + """ + A pydantic.v1 model is used, which is no longer supported. + """ + + +class FastAPIDeprecationWarning(UserWarning): + """ + A custom deprecation warning as DeprecationWarning is ignored + Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries + """ diff --git a/lib/python3.11/site-packages/fastapi/logger.py b/lib/python3.11/site-packages/fastapi/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5b2c4ad5250b589aa0c8f8d1cc9125b91b10edb0 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/logger.py @@ -0,0 +1,3 @@ +import logging + +logger = logging.getLogger("fastapi") diff --git a/lib/python3.11/site-packages/fastapi/middleware/__init__.py b/lib/python3.11/site-packages/fastapi/middleware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..620296d5ad6ca2cc49eb5d0dc140bcbc3204e9b4 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/middleware/__init__.py @@ -0,0 +1 @@ +from starlette.middleware import Middleware as Middleware diff --git a/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py b/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce3f5a625548a00514f872d1653194bd3669a73 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py @@ -0,0 +1,18 @@ +from contextlib import AsyncExitStack + +from starlette.types import ASGIApp, Receive, Scope, Send + + +# Used mainly to close files after the request is done, dependencies are closed +# in their own AsyncExitStack +class AsyncExitStackMiddleware: + def __init__( + self, app: ASGIApp, context_name: str = "fastapi_middleware_astack" + ) -> None: + self.app = app + self.context_name = context_name + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + async with AsyncExitStack() as stack: + scope[self.context_name] = stack + await self.app(scope, receive, send) diff --git a/lib/python3.11/site-packages/fastapi/param_functions.py b/lib/python3.11/site-packages/fastapi/param_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..1856178fcb5c88a46899a7a490fbb0c26d314da1 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/param_functions.py @@ -0,0 +1,2460 @@ +from collections.abc import Callable, Sequence +from typing import Annotated, Any, Literal + +from annotated_doc import Doc +from fastapi import params +from fastapi._compat import Undefined +from fastapi.datastructures import _Unset +from fastapi.openapi.models import Example +from pydantic import AliasChoices, AliasPath +from typing_extensions import deprecated + + +def Path( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = ..., + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + + Read more about it in the + [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata) + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + """ + Declare a path parameter for a *path operation*. + + Read more about it in the + [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/). + + ```python + from typing import Annotated + + from fastapi import FastAPI, Path + + app = FastAPI() + + + @app.get("/items/{item_id}") + async def read_items( + item_id: Annotated[int, Path(title="The ID of the item to get")], + ): + return {"item_id": item_id} + ``` + """ + return params.Path( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Query( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value) + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters) + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata) + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata) + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + + Read more about it in the + [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters) + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Query( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Header( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + convert_underscores: Annotated[ + bool, + Doc( + """ + Automatically convert underscores to hyphens in the parameter field name. + + Read more about it in the + [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) + """ + ), + ] = True, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Header( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + convert_underscores=convert_underscores, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Cookie( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Cookie( + default=default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Body( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + embed: Annotated[ + bool | None, + Doc( + """ + When `embed` is `True`, the parameter will be expected in a JSON body as a + key instead of being the JSON body itself. + + This happens automatically when more than one `Body` parameter is declared. + + Read more about it in the + [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). + """ + ), + ] = None, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "application/json", + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Body( + default=default, + default_factory=default_factory, + embed=embed, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Form( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "application/x-www-form-urlencoded", + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.Form( + default=default, + default_factory=default_factory, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def File( # noqa: N802 + default: Annotated[ + Any, + Doc( + """ + Default value if the parameter field is not set. + """ + ), + ] = Undefined, + *, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + A callable to generate the default value. + + This doesn't affect `Path` parameters as the value is always required. + The parameter is available only for compatibility. + """ + ), + ] = _Unset, + media_type: Annotated[ + str, + Doc( + """ + The media type of this parameter field. Changing it would affect the + generated OpenAPI, but currently it doesn't affect the parsing of the data. + """ + ), + ] = "multipart/form-data", + alias: Annotated[ + str | None, + Doc( + """ + An alternative name for the parameter field. + + This will be used to extract the data and for the generated OpenAPI. + It is particularly useful when you can't use the name you want because it + is a Python reserved keyword or similar. + """ + ), + ] = None, + alias_priority: Annotated[ + int | None, + Doc( + """ + Priority of the alias. This affects whether an alias generator is used. + """ + ), + ] = _Unset, + validation_alias: Annotated[ + str | AliasPath | AliasChoices | None, + Doc( + """ + 'Whitelist' validation step. The parameter field will be the single one + allowed by the alias or set of aliases defined. + """ + ), + ] = None, + serialization_alias: Annotated[ + str | None, + Doc( + """ + 'Blacklist' validation step. The vanilla parameter field will be the + single one of the alias' or set of aliases' fields and all the other + fields will be ignored at serialization time. + """ + ), + ] = None, + title: Annotated[ + str | None, + Doc( + """ + Human-readable title. + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + Human-readable description. + """ + ), + ] = None, + gt: Annotated[ + float | None, + Doc( + """ + Greater than. If set, value must be greater than this. Only applicable to + numbers. + """ + ), + ] = None, + ge: Annotated[ + float | None, + Doc( + """ + Greater than or equal. If set, value must be greater than or equal to + this. Only applicable to numbers. + """ + ), + ] = None, + lt: Annotated[ + float | None, + Doc( + """ + Less than. If set, value must be less than this. Only applicable to numbers. + """ + ), + ] = None, + le: Annotated[ + float | None, + Doc( + """ + Less than or equal. If set, value must be less than or equal to this. + Only applicable to numbers. + """ + ), + ] = None, + min_length: Annotated[ + int | None, + Doc( + """ + Minimum length for strings. + """ + ), + ] = None, + max_length: Annotated[ + int | None, + Doc( + """ + Maximum length for strings. + """ + ), + ] = None, + pattern: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + ] = None, + regex: Annotated[ + str | None, + Doc( + """ + RegEx pattern for strings. + """ + ), + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: Annotated[ + str | None, + Doc( + """ + Parameter field name for discriminating the type in a tagged union. + """ + ), + ] = None, + strict: Annotated[ + bool | None, + Doc( + """ + If `True`, strict validation is applied to the field. + """ + ), + ] = _Unset, + multiple_of: Annotated[ + float | None, + Doc( + """ + Value must be a multiple of this. Only applicable to numbers. + """ + ), + ] = _Unset, + allow_inf_nan: Annotated[ + bool | None, + Doc( + """ + Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + """ + ), + ] = _Unset, + max_digits: Annotated[ + int | None, + Doc( + """ + Maximum number of digits allowed for decimal values. + """ + ), + ] = _Unset, + decimal_places: Annotated[ + int | None, + Doc( + """ + Maximum number of decimal places allowed for decimal values. + """ + ), + ] = _Unset, + examples: Annotated[ + list[Any] | None, + Doc( + """ + Example values for this field. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) + """ + ), + ] = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: Annotated[ + dict[str, Example] | None, + Doc( + """ + OpenAPI-specific examples. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Swagger UI (that provides the `/docs` interface) has better support for the + OpenAPI-specific examples than the JSON Schema `examples`, that's the main + use case for this. + + Read more about it in the + [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). + """ + ), + ] = None, + deprecated: Annotated[ + deprecated | str | bool | None, + Doc( + """ + Mark this parameter field as deprecated. + + It will affect the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) this parameter field in the generated OpenAPI. + You probably don't need it, but it's available. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + json_schema_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Any additional JSON schema data. + """ + ), + ] = None, + **extra: Annotated[ + Any, + Doc( + """ + Include extra fields used by the JSON Schema. + """ + ), + deprecated( + """ + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + """ + ), + ], +) -> Any: + return params.File( + default=default, + default_factory=default_factory, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + example=example, + examples=examples, + openapi_examples=openapi_examples, + deprecated=deprecated, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +def Depends( # noqa: N802 + dependency: Annotated[ + Callable[..., Any] | None, + Doc( + """ + A "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you, just pass the object + directly. + + Read more about it in the + [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) + """ + ), + ] = None, + *, + use_cache: Annotated[ + bool, + Doc( + """ + By default, after a dependency is called the first time in a request, if + the dependency is declared again for the rest of the request (for example + if the dependency is needed by several dependencies), the value will be + re-used for the rest of the request. + + Set `use_cache` to `False` to disable this behavior and ensure the + dependency is called again (if declared more than once) in the same request. + + Read more about it in the + [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times) + """ + ), + ] = True, + scope: Annotated[ + Literal["function", "request"] | None, + Doc( + """ + Mainly for dependencies with `yield`, define when the dependency function + should start (the code before `yield`) and when it should end (the code + after `yield`). + + * `"function"`: start the dependency before the *path operation function* + that handles the request, end the dependency after the *path operation + function* ends, but **before** the response is sent back to the client. + So, the dependency function will be executed **around** the *path operation + **function***. + * `"request"`: start the dependency before the *path operation function* + that handles the request (similar to when using `"function"`), but end + **after** the response is sent back to the client. So, the dependency + function will be executed **around** the **request** and response cycle. + + Read more about it in the + [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope) + """ + ), + ] = None, +) -> Any: + """ + Declare a FastAPI dependency. + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + + app = FastAPI() + + + async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): + return {"q": q, "skip": skip, "limit": limit} + + + @app.get("/items/") + async def read_items(commons: Annotated[dict, Depends(common_parameters)]): + return commons + ``` + """ + return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope) + + +def Security( # noqa: N802 + dependency: Annotated[ + Callable[..., Any] | None, + Doc( + """ + A "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you, just pass the object + directly. + + Read more about it in the + [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) + """ + ), + ] = None, + *, + scopes: Annotated[ + Sequence[str] | None, + Doc( + """ + OAuth2 scopes required for the *path operation* that uses this Security + dependency. + + The term "scope" comes from the OAuth2 specification, it seems to be + intentionally vague and interpretable. It normally refers to permissions, + in cases to roles. + + These scopes are integrated with OpenAPI (and the API docs at `/docs`). + So they are visible in the OpenAPI specification. + + Read more about it in the + [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/) + """ + ), + ] = None, + use_cache: Annotated[ + bool, + Doc( + """ + By default, after a dependency is called the first time in a request, if + the dependency is declared again for the rest of the request (for example + if the dependency is needed by several dependencies), the value will be + re-used for the rest of the request. + + Set `use_cache` to `False` to disable this behavior and ensure the + dependency is called again (if declared more than once) in the same request. + + Read more about it in the + [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times) + """ + ), + ] = True, +) -> Any: + """ + Declare a FastAPI Security dependency. + + The only difference with a regular dependency is that it can declare OAuth2 + scopes that will be integrated with OpenAPI and the automatic UI docs (by default + at `/docs`). + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and + in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Security, FastAPI + + from .db import User + from .security import get_current_active_user + + app = FastAPI() + + @app.get("/users/me/items/") + async def read_own_items( + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + ): + return [{"item_id": "Foo", "owner": current_user.username}] + ``` + """ + return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache) diff --git a/lib/python3.11/site-packages/fastapi/params.py b/lib/python3.11/site-packages/fastapi/params.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f2ae175b1fd3f0dc95c2be70ec7c546040f6ae --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/params.py @@ -0,0 +1,754 @@ +import warnings +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from enum import Enum +from typing import Annotated, Any, Literal + +from fastapi.exceptions import FastAPIDeprecationWarning +from fastapi.openapi.models import Example +from pydantic import AliasChoices, AliasPath +from pydantic.fields import FieldInfo +from typing_extensions import deprecated + +from ._compat import ( + Undefined, +) +from .datastructures import _Unset + + +class ParamTypes(Enum): + query = "query" + header = "header" + path = "path" + cookie = "cookie" + + +class Param(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class] + in_: ParamTypes + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + if example is not _Unset: + warnings.warn( + "`example` has been deprecated, please use `examples` instead", + category=FastAPIDeprecationWarning, + stacklevel=4, + ) + self.example = example + self.include_in_schema = include_in_schema + self.openapi_examples = openapi_examples + kwargs = dict( + default=default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + discriminator=discriminator, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + **extra, + ) + if examples is not None: + kwargs["examples"] = examples + if regex is not None: + warnings.warn( + "`regex` has been deprecated, please use `pattern` instead", + category=FastAPIDeprecationWarning, + stacklevel=4, + ) + current_json_schema_extra = json_schema_extra or extra + kwargs["deprecated"] = deprecated + + if serialization_alias in (_Unset, None) and isinstance(alias, str): + serialization_alias = alias + if validation_alias in (_Unset, None): + validation_alias = alias + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + } + ) + kwargs["pattern"] = pattern or regex + + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type] + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.default})" + + +class Path(Param): # type: ignore[misc] + in_ = ParamTypes.path + + def __init__( + self, + default: Any = ..., + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + assert default is ..., "Path parameters cannot have a default value" + self.in_ = self.in_ + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Query(Param): # type: ignore[misc] + in_ = ParamTypes.query + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Header(Param): # type: ignore[misc] + in_ = ParamTypes.header + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + convert_underscores: bool = True, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + self.convert_underscores = convert_underscores + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Cookie(Param): # type: ignore[misc] + in_ = ParamTypes.cookie + + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class Body(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class] + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + embed: bool | None = None, + media_type: str = "application/json", + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + self.embed = embed + self.media_type = media_type + if example is not _Unset: + warnings.warn( + "`example` has been deprecated, please use `examples` instead", + category=FastAPIDeprecationWarning, + stacklevel=4, + ) + self.example = example + self.include_in_schema = include_in_schema + self.openapi_examples = openapi_examples + kwargs = dict( + default=default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + discriminator=discriminator, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + **extra, + ) + if examples is not None: + kwargs["examples"] = examples + if regex is not None: + warnings.warn( + "`regex` has been deprecated, please use `pattern` instead", + category=FastAPIDeprecationWarning, + stacklevel=4, + ) + current_json_schema_extra = json_schema_extra or extra + kwargs["deprecated"] = deprecated + if serialization_alias in (_Unset, None) and isinstance(alias, str): + serialization_alias = alias + if validation_alias in (_Unset, None): + validation_alias = alias + kwargs.update( + { + "annotation": annotation, + "alias_priority": alias_priority, + "validation_alias": validation_alias, + "serialization_alias": serialization_alias, + "strict": strict, + "json_schema_extra": current_json_schema_extra, + } + ) + kwargs["pattern"] = pattern or regex + + use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} + + super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type] + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.default})" + + +class Form(Body): # type: ignore[misc] + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + media_type: str = "application/x-www-form-urlencoded", + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +class File(Form): # type: ignore[misc] + def __init__( + self, + default: Any = Undefined, + *, + default_factory: Callable[[], Any] | None = _Unset, + annotation: Any | None = None, + media_type: str = "multipart/form-data", + alias: str | None = None, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = None, + serialization_alias: str | None = None, + title: str | None = None, + description: str | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | None = None, + regex: Annotated[ + str | None, + deprecated( + "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." + ), + ] = None, + discriminator: str | None = None, + strict: bool | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + examples: list[Any] | None = None, + example: Annotated[ + Any | None, + deprecated( + "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " + "although still supported. Use examples instead." + ), + ] = _Unset, + openapi_examples: dict[str, Example] | None = None, + deprecated: deprecated | str | bool | None = None, + include_in_schema: bool = True, + json_schema_extra: dict[str, Any] | None = None, + **extra: Any, + ): + super().__init__( + default=default, + default_factory=default_factory, + annotation=annotation, + media_type=media_type, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + description=description, + gt=gt, + ge=ge, + lt=lt, + le=le, + min_length=min_length, + max_length=max_length, + pattern=pattern, + regex=regex, + discriminator=discriminator, + strict=strict, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + deprecated=deprecated, + example=example, + examples=examples, + openapi_examples=openapi_examples, + include_in_schema=include_in_schema, + json_schema_extra=json_schema_extra, + **extra, + ) + + +@dataclass(frozen=True) +class Depends: + dependency: Callable[..., Any] | None = None + use_cache: bool = True + scope: Literal["function", "request"] | None = None + + +@dataclass(frozen=True) +class Security(Depends): + scopes: Sequence[str] | None = None diff --git a/lib/python3.11/site-packages/fastapi/py.typed b/lib/python3.11/site-packages/fastapi/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/fastapi/requests.py b/lib/python3.11/site-packages/fastapi/requests.py new file mode 100644 index 0000000000000000000000000000000000000000..d16552c0a9535e1c0bd7f701987301681832eba5 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/requests.py @@ -0,0 +1,2 @@ +from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401 +from starlette.requests import Request as Request # noqa: F401 diff --git a/lib/python3.11/site-packages/fastapi/responses.py b/lib/python3.11/site-packages/fastapi/responses.py new file mode 100644 index 0000000000000000000000000000000000000000..29df4b7a614b411237700d25c4ac27b985811730 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/responses.py @@ -0,0 +1,98 @@ +import importlib +from typing import Any, Protocol, cast + +from fastapi.exceptions import FastAPIDeprecationWarning +from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa +from starlette.responses import FileResponse as FileResponse # noqa +from starlette.responses import HTMLResponse as HTMLResponse # noqa +from starlette.responses import JSONResponse as JSONResponse # noqa +from starlette.responses import PlainTextResponse as PlainTextResponse # noqa +from starlette.responses import RedirectResponse as RedirectResponse # noqa +from starlette.responses import Response as Response # noqa +from starlette.responses import StreamingResponse as StreamingResponse # noqa +from typing_extensions import deprecated + + +class _UjsonModule(Protocol): + def dumps(self, __obj: Any, *, ensure_ascii: bool = ...) -> str: ... + + +class _OrjsonModule(Protocol): + OPT_NON_STR_KEYS: int + OPT_SERIALIZE_NUMPY: int + + def dumps(self, __obj: Any, *, option: int = ...) -> bytes: ... + + +try: + ujson = cast(_UjsonModule, importlib.import_module("ujson")) +except ModuleNotFoundError: # pragma: nocover + ujson = None # type: ignore[assignment] + + +try: + orjson = cast(_OrjsonModule, importlib.import_module("orjson")) +except ModuleNotFoundError: # pragma: nocover + orjson = None # type: ignore[assignment] + + +@deprecated( + "UJSONResponse is deprecated, FastAPI now serializes data directly to JSON " + "bytes via Pydantic when a return type or response model is set, which is " + "faster and doesn't need a custom response class. Read more in the FastAPI " + "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model " + "and https://fastapi.tiangolo.com/tutorial/response-model/", + category=FastAPIDeprecationWarning, + stacklevel=2, +) +class UJSONResponse(JSONResponse): + """JSON response using the ujson library to serialize data to JSON. + + **Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data + directly to JSON bytes via Pydantic when a return type or response model is + set, which is faster and doesn't need a custom response class. + + Read more in the + [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model) + and the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + + **Note**: `ujson` is not included with FastAPI and must be installed + separately, e.g. `pip install ujson`. + """ + + def render(self, content: Any) -> bytes: + assert ujson is not None, "ujson must be installed to use UJSONResponse" + return ujson.dumps(content, ensure_ascii=False).encode("utf-8") + + +@deprecated( + "ORJSONResponse is deprecated, FastAPI now serializes data directly to JSON " + "bytes via Pydantic when a return type or response model is set, which is " + "faster and doesn't need a custom response class. Read more in the FastAPI " + "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model " + "and https://fastapi.tiangolo.com/tutorial/response-model/", + category=FastAPIDeprecationWarning, + stacklevel=2, +) +class ORJSONResponse(JSONResponse): + """JSON response using the orjson library to serialize data to JSON. + + **Deprecated**: `ORJSONResponse` is deprecated. FastAPI now serializes data + directly to JSON bytes via Pydantic when a return type or response model is + set, which is faster and doesn't need a custom response class. + + Read more in the + [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model) + and the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + + **Note**: `orjson` is not included with FastAPI and must be installed + separately, e.g. `pip install orjson`. + """ + + def render(self, content: Any) -> bytes: + assert orjson is not None, "orjson must be installed to use ORJSONResponse" + return orjson.dumps( + content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY + ) diff --git a/lib/python3.11/site-packages/fastapi/routing.py b/lib/python3.11/site-packages/fastapi/routing.py new file mode 100644 index 0000000000000000000000000000000000000000..21a1385a27b4223eb20d3726cf2c711b0e698d91 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/routing.py @@ -0,0 +1,4956 @@ +import contextlib +import email.message +import functools +import inspect +import json +import types +from collections.abc import ( + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Generator, + Iterator, + Mapping, + Sequence, +) +from contextlib import ( + AbstractAsyncContextManager, + AbstractContextManager, + AsyncExitStack, + asynccontextmanager, +) +from enum import Enum, IntEnum +from typing import ( + Annotated, + Any, + TypeVar, + cast, +) + +import anyio +from annotated_doc import Doc +from anyio.abc import ObjectReceiveStream +from fastapi import params +from fastapi._compat import ( + ModelField, + Undefined, + lenient_issubclass, +) +from fastapi.datastructures import Default, DefaultPlaceholder +from fastapi.dependencies.models import Dependant +from fastapi.dependencies.utils import ( + _should_embed_body_fields, + get_body_field, + get_dependant, + get_flat_dependant, + get_parameterless_sub_dependant, + get_stream_item_type, + get_typed_return_annotation, + solve_dependencies, +) +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import ( + EndpointContext, + FastAPIError, + RequestValidationError, + ResponseValidationError, + WebSocketRequestValidationError, +) +from fastapi.sse import ( + _PING_INTERVAL, + KEEPALIVE_COMMENT, + EventSourceResponse, + ServerSentEvent, + format_sse_event, +) +from fastapi.types import DecoratedCallable, IncEx +from fastapi.utils import ( + create_model_field, + generate_unique_id, + get_value_or_default, + is_body_allowed_for_status_code, +) +from starlette import routing +from starlette._exception_handler import wrap_app_handling_exceptions +from starlette._utils import is_async_callable +from starlette.concurrency import iterate_in_threadpool, run_in_threadpool +from starlette.datastructures import FormData +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import JSONResponse, Response, StreamingResponse +from starlette.routing import ( + BaseRoute, + Match, + compile_path, + get_name, +) +from starlette.routing import Mount as Mount # noqa +from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send +from starlette.websockets import WebSocket +from typing_extensions import deprecated + + +# Copy of starlette.routing.request_response modified to include the +# dependencies' AsyncExitStack +def request_response( + func: Callable[[Request], Awaitable[Response] | Response], +) -> ASGIApp: + """ + Takes a function or coroutine `func(request) -> response`, + and returns an ASGI application. + """ + f: Callable[[Request], Awaitable[Response]] = ( + func # type: ignore[assignment] + if is_async_callable(func) + else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] + ) # ty: ignore[invalid-assignment] + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + request = Request(scope, receive, send) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + # Starts customization + response_awaited = False + async with AsyncExitStack() as request_stack: + scope["fastapi_inner_astack"] = request_stack + async with AsyncExitStack() as function_stack: + scope["fastapi_function_astack"] = function_stack + response = await f(request) + await response(scope, receive, send) + # Continues customization + response_awaited = True + if not response_awaited: + raise FastAPIError( + "Response not awaited. There's a high chance that the " + "application code is raising an exception and a dependency with yield " + "has a block with a bare except, or a block with except Exception, " + "and is not raising the exception again. Read more about it in the " + "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" + ) + + # Same as in Starlette + await wrap_app_handling_exceptions(app, request)(scope, receive, send) + + return app + + +# Copy of starlette.routing.websocket_session modified to include the +# dependencies' AsyncExitStack +def websocket_session( + func: Callable[[WebSocket], Awaitable[None]], +) -> ASGIApp: + """ + Takes a coroutine `func(session)`, and returns an ASGI application. + """ + # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async" + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + session = WebSocket(scope, receive=receive, send=send) + + async def app(scope: Scope, receive: Receive, send: Send) -> None: + async with AsyncExitStack() as request_stack: + scope["fastapi_inner_astack"] = request_stack + async with AsyncExitStack() as function_stack: + scope["fastapi_function_astack"] = function_stack + await func(session) + + # Same as in Starlette + await wrap_app_handling_exceptions(app, session)(scope, receive, send) + + return app + + +_T = TypeVar("_T") + + +# Vendored from starlette.routing to avoid importing private symbols +class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]): + """ + Wraps a synchronous context manager to make it async. + + This is vendored from Starlette to avoid importing private symbols. + """ + + def __init__(self, cm: AbstractContextManager[_T]) -> None: + self._cm = cm + + async def __aenter__(self) -> _T: + return self._cm.__enter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: types.TracebackType | None, + ) -> bool | None: + return self._cm.__exit__(exc_type, exc_value, traceback) + + +# Vendored from starlette.routing to avoid importing private symbols +def _wrap_gen_lifespan_context( + lifespan_context: Callable[[Any], Generator[Any, Any, Any]], +) -> Callable[[Any], AbstractAsyncContextManager[Any]]: + """ + Wrap a generator-based lifespan context into an async context manager. + + This is vendored from Starlette to avoid importing private symbols. + """ + cmgr = contextlib.contextmanager(lifespan_context) + + @functools.wraps(cmgr) + def wrapper(app: Any) -> _AsyncLiftContextManager[Any]: + return _AsyncLiftContextManager(cmgr(app)) + + return wrapper + + +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Mapping[str, Any] | None]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] # ty: ignore[invalid-return-type] + + +class _DefaultLifespan: + """ + Default lifespan context manager that runs on_startup and on_shutdown handlers. + + This is a copy of the Starlette _DefaultLifespan class that was removed + in Starlette. FastAPI keeps it to maintain backward compatibility with + on_startup and on_shutdown event handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ + + def __init__(self, router: "APIRouter") -> None: + self._router = router + + async def __aenter__(self) -> None: + await self._router._startup() + + async def __aexit__(self, *exc_info: object) -> None: + await self._router._shutdown() + + def __call__(self: _T, app: object) -> _T: + return self + + +# Cache for endpoint context to avoid re-extracting on every request +_endpoint_context_cache: dict[int, EndpointContext] = {} + + +def _extract_endpoint_context(func: Any) -> EndpointContext: + """Extract endpoint context with caching to avoid repeated file I/O.""" + func_id = id(func) + + if func_id in _endpoint_context_cache: + return _endpoint_context_cache[func_id] + + try: + ctx: EndpointContext = {} + + if (source_file := inspect.getsourcefile(func)) is not None: + ctx["file"] = source_file + if (line_number := inspect.getsourcelines(func)[1]) is not None: + ctx["line"] = line_number + if (func_name := getattr(func, "__name__", None)) is not None: + ctx["function"] = func_name + except Exception: + ctx = EndpointContext() + + _endpoint_context_cache[func_id] = ctx + return ctx + + +async def serialize_response( + *, + field: ModelField | None = None, + response_content: Any, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + is_coroutine: bool = True, + endpoint_ctx: EndpointContext | None = None, + dump_json: bool = False, +) -> Any: + if field: + if is_coroutine: + value, errors = field.validate(response_content, {}, loc=("response",)) + else: + value, errors = await run_in_threadpool( + field.validate, response_content, {}, loc=("response",) + ) + if errors: + ctx = endpoint_ctx or EndpointContext() + raise ResponseValidationError( + errors=errors, + body=response_content, + endpoint_ctx=ctx, + ) + serializer = field.serialize_json if dump_json else field.serialize + return serializer( + value, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + else: + return jsonable_encoder(response_content) + + +async def run_endpoint_function( + *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool +) -> Any: + # Only called by get_request_handler. Has been split into its own function to + # facilitate profiling endpoints, since inner functions are harder to profile. + assert dependant.call is not None, "dependant.call must be a function" + + if is_coroutine: + return await dependant.call(**values) + else: + return await run_in_threadpool(dependant.call, **values) + + +def _build_response_args( + *, status_code: int | None, solved_result: Any +) -> dict[str, Any]: + response_args: dict[str, Any] = { + "background": solved_result.background_tasks, + } + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code if status_code else solved_result.response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if solved_result.response.status_code: + response_args["status_code"] = solved_result.response.status_code + return response_args + + +def get_request_handler( + dependant: Dependant, + body_field: ModelField | None = None, + status_code: int | None = None, + response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), + response_field: ModelField | None = None, + response_model_include: IncEx | None = None, + response_model_exclude: IncEx | None = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + dependency_overrides_provider: Any | None = None, + embed_body_fields: bool = False, + strict_content_type: bool | DefaultPlaceholder = Default(True), + stream_item_field: ModelField | None = None, + is_json_stream: bool = False, +) -> Callable[[Request], Coroutine[Any, Any, Response]]: + assert dependant.call is not None, "dependant.call must be a function" + is_coroutine = dependant.is_coroutine_callable + is_body_form = body_field and isinstance(body_field.field_info, params.Form) + if isinstance(response_class, DefaultPlaceholder): + actual_response_class: type[Response] = response_class.value + else: + actual_response_class = response_class + is_sse_stream = lenient_issubclass(actual_response_class, EventSourceResponse) + if isinstance(strict_content_type, DefaultPlaceholder): + actual_strict_content_type: bool = strict_content_type.value + else: + actual_strict_content_type = strict_content_type + + async def app(request: Request) -> Response: + response: Response | None = None + file_stack = request.scope.get("fastapi_middleware_astack") + assert isinstance(file_stack, AsyncExitStack), ( + "fastapi_middleware_astack not found in request scope" + ) + + # Extract endpoint context for error messages + endpoint_ctx = ( + _extract_endpoint_context(dependant.call) + if dependant.call + else EndpointContext() + ) + + if dependant.path: + # For mounted sub-apps, include the mount path prefix + mount_path = request.scope.get("root_path", "").rstrip("/") + endpoint_ctx["path"] = f"{request.method} {mount_path}{dependant.path}" + + # Read body and auto-close files + try: + body: Any = None + if body_field: + if is_body_form: + body = await request.form() + file_stack.push_async_callback(body.close) + else: + body_bytes = await request.body() + if body_bytes: + json_body: Any = Undefined + content_type_value = request.headers.get("content-type") + if not content_type_value: + if not actual_strict_content_type: + json_body = await request.json() + else: + message = email.message.Message() + message["content-type"] = content_type_value + if message.get_content_maintype() == "application": + subtype = message.get_content_subtype() + if subtype == "json" or subtype.endswith("+json"): + json_body = await request.json() + if json_body != Undefined: + body = json_body + else: + body = body_bytes + except json.JSONDecodeError as e: + validation_error = RequestValidationError( + [ + { + "type": "json_invalid", + "loc": ("body", e.pos), + "msg": "JSON decode error", + "input": {}, + "ctx": {"error": e.msg}, + } + ], + body=e.doc, + endpoint_ctx=endpoint_ctx, + ) + raise validation_error from e + except HTTPException: + # If a middleware raises an HTTPException, it should be raised again + raise + except Exception as e: + http_error = HTTPException( + status_code=400, detail="There was an error parsing the body" + ) + raise http_error from e + + # Solve dependencies and run path operation function, auto-closing dependencies + errors: list[Any] = [] + async_exit_stack = request.scope.get("fastapi_inner_astack") + assert isinstance(async_exit_stack, AsyncExitStack), ( + "fastapi_inner_astack not found in request scope" + ) + solved_result = await solve_dependencies( + request=request, + dependant=dependant, + body=cast(dict[str, Any] | FormData | bytes | None, body), + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, + ) + errors = solved_result.errors + assert dependant.call # For types + if not errors: + # Shared serializer for stream items (JSONL and SSE). + # Validates against stream_item_field when set, then + # serializes to JSON bytes. + def _serialize_data(data: Any) -> bytes: + if stream_item_field: + value, errors_ = stream_item_field.validate( + data, {}, loc=("response",) + ) + if errors_: + ctx = endpoint_ctx or EndpointContext() + raise ResponseValidationError( + errors=errors_, + body=data, + endpoint_ctx=ctx, + ) + return stream_item_field.serialize_json( + value, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + ) + else: + data = jsonable_encoder(data) + return json.dumps(data).encode("utf-8") + + if is_sse_stream: + # Generator endpoint: stream as Server-Sent Events + gen = dependant.call(**solved_result.values) + + def _serialize_sse_item(item: Any) -> bytes: + if isinstance(item, ServerSentEvent): + # User controls the event structure. + # Serialize the data payload if present. + # For ServerSentEvent items we skip stream_item_field + # validation (the user may mix types intentionally). + if item.raw_data is not None: + data_str: str | None = item.raw_data + elif item.data is not None: + if hasattr(item.data, "model_dump_json"): + data_str = item.data.model_dump_json() + else: + data_str = json.dumps(jsonable_encoder(item.data)) + else: + data_str = None + return format_sse_event( + data_str=data_str, + event=item.event, + id=item.id, + retry=item.retry, + comment=item.comment, + ) + else: + # Plain object: validate + serialize via + # stream_item_field (if set) and wrap in data field + return format_sse_event( + data_str=_serialize_data(item).decode("utf-8") + ) + + if dependant.is_async_gen_callable: + sse_aiter: AsyncIterator[Any] = gen.__aiter__() + else: + sse_aiter = iterate_in_threadpool(gen) + + @asynccontextmanager + async def _sse_producer_cm() -> AsyncIterator[ + ObjectReceiveStream[bytes] + ]: + # Use a memory stream to decouple generator iteration + # from the keepalive timer. A producer task pulls items + # from the generator independently, so + # `anyio.fail_after` never wraps the generator's + # `__anext__` directly - avoiding CancelledError that + # would finalize the generator and also working for sync + # generators running in a thread pool. + # + # This context manager is entered on the request-scoped + # AsyncExitStack so its __aexit__ (which cancels the + # task group) is called by the exit stack after the + # streaming response completes — not by async generator + # finalization via GeneratorExit. + # Ref: https://peps.python.org/pep-0789/ + send_stream, receive_stream = anyio.create_memory_object_stream[ + bytes + ](max_buffer_size=1) + + async def _producer() -> None: + async with send_stream: + async for raw_item in sse_aiter: + await send_stream.send(_serialize_sse_item(raw_item)) + + send_keepalive, receive_keepalive = ( + anyio.create_memory_object_stream[bytes](max_buffer_size=1) + ) + + async def _keepalive_inserter() -> None: + """Read from the producer and forward to the output, + inserting keepalive comments on timeout.""" + async with send_keepalive, receive_stream: + try: + while True: + try: + with anyio.fail_after(_PING_INTERVAL): + data = await receive_stream.receive() + await send_keepalive.send(data) + except TimeoutError: + await send_keepalive.send(KEEPALIVE_COMMENT) + except anyio.EndOfStream: + pass + + async with anyio.create_task_group() as tg: + tg.start_soon(_producer) + tg.start_soon(_keepalive_inserter) + yield receive_keepalive + tg.cancel_scope.cancel() + + # Enter the SSE context manager on the request-scoped + # exit stack. The stack outlives the streaming response, + # so __aexit__ runs via proper structured teardown, not + # via GeneratorExit thrown into an async generator. + sse_receive_stream = await async_exit_stack.enter_async_context( + _sse_producer_cm() + ) + # Ensure the receive stream is closed when the exit stack + # unwinds, preventing ResourceWarning from __del__. + async_exit_stack.push_async_callback(sse_receive_stream.aclose) + + async def _sse_with_checkpoints( + stream: ObjectReceiveStream[bytes], + ) -> AsyncIterator[bytes]: + async for data in stream: + yield data + # Guarantee a checkpoint so cancellation can be + # delivered even when the producer is faster than + # the consumer and receive() never suspends. + await anyio.sleep(0) + + sse_stream_content: AsyncIterator[bytes] | Iterator[bytes] = ( + _sse_with_checkpoints(sse_receive_stream) + ) + + response = StreamingResponse( + sse_stream_content, + media_type="text/event-stream", + background=solved_result.background_tasks, + ) + response.headers["Cache-Control"] = "no-cache" + # For Nginx proxies to not buffer server sent events + response.headers["X-Accel-Buffering"] = "no" + response.headers.raw.extend(solved_result.response.headers.raw) + elif is_json_stream: + # Generator endpoint: stream as JSONL + gen = dependant.call(**solved_result.values) + + def _serialize_item(item: Any) -> bytes: + return _serialize_data(item) + b"\n" + + if dependant.is_async_gen_callable: + + async def _async_stream_jsonl() -> AsyncIterator[bytes]: + async for item in gen: + yield _serialize_item(item) + # To allow for cancellation to trigger + # Ref: https://github.com/fastapi/fastapi/issues/14680 + await anyio.sleep(0) + + jsonl_stream_content: AsyncIterator[bytes] | Iterator[bytes] = ( + _async_stream_jsonl() + ) + else: + + def _sync_stream_jsonl() -> Iterator[bytes]: + for item in gen: # ty: ignore[not-iterable] + yield _serialize_item(item) + + jsonl_stream_content = _sync_stream_jsonl() + + response = StreamingResponse( + jsonl_stream_content, + media_type="application/jsonl", + background=solved_result.background_tasks, + ) + response.headers.raw.extend(solved_result.response.headers.raw) + elif dependant.is_async_gen_callable or dependant.is_gen_callable: + # Raw streaming with explicit response_class (e.g. StreamingResponse) + gen = dependant.call(**solved_result.values) + if dependant.is_async_gen_callable: + + async def _async_stream_raw( + async_gen: AsyncIterator[Any], + ) -> AsyncIterator[Any]: + async for chunk in async_gen: + yield chunk + # To allow for cancellation to trigger + # Ref: https://github.com/fastapi/fastapi/issues/14680 + await anyio.sleep(0) + + gen = _async_stream_raw(gen) + response_args = _build_response_args( + status_code=status_code, solved_result=solved_result + ) + response = actual_response_class(content=gen, **response_args) + response.headers.raw.extend(solved_result.response.headers.raw) + else: + raw_response = await run_endpoint_function( + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, + ) + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = solved_result.background_tasks + response = raw_response + else: + response_args = _build_response_args( + status_code=status_code, solved_result=solved_result + ) + # Use the fast path (dump_json) when no custom response + # class was set and a response field with a TypeAdapter + # exists. Serializes directly to JSON bytes via Pydantic's + # Rust core, skipping the intermediate Python dict + + # json.dumps() step. + use_dump_json = response_field is not None and isinstance( + response_class, DefaultPlaceholder + ) + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + endpoint_ctx=endpoint_ctx, + dump_json=use_dump_json, + ) + if use_dump_json: + response = Response( + content=content, + media_type="application/json", + **response_args, + ) + else: + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(solved_result.response.headers.raw) + if errors: + validation_error = RequestValidationError( + errors, body=body, endpoint_ctx=endpoint_ctx + ) + raise validation_error + + # Return response + assert response + return response + + return app + + +def get_websocket_app( + dependant: Dependant, + dependency_overrides_provider: Any | None = None, + embed_body_fields: bool = False, +) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: + async def app(websocket: WebSocket) -> None: + endpoint_ctx = ( + _extract_endpoint_context(dependant.call) + if dependant.call + else EndpointContext() + ) + if dependant.path: + # For mounted sub-apps, include the mount path prefix + mount_path = websocket.scope.get("root_path", "").rstrip("/") + endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}" + async_exit_stack = websocket.scope.get("fastapi_inner_astack") + assert isinstance(async_exit_stack, AsyncExitStack), ( + "fastapi_inner_astack not found in request scope" + ) + solved_result = await solve_dependencies( + request=websocket, + dependant=dependant, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, + ) + if solved_result.errors: + raise WebSocketRequestValidationError( + solved_result.errors, + endpoint_ctx=endpoint_ctx, + ) + assert dependant.call is not None, "dependant.call must be a function" + await dependant.call(**solved_result.values) + + return app + + +class APIWebSocketRoute(routing.WebSocketRoute): + def __init__( + self, + path: str, + endpoint: Callable[..., Any], + *, + name: str | None = None, + dependencies: Sequence[params.Depends] | None = None, + dependency_overrides_provider: Any | None = None, + ) -> None: + self.path = path + self.endpoint = endpoint + self.name = get_name(endpoint) if name is None else name + self.dependencies = list(dependencies or []) + self.path_regex, self.path_format, self.param_convertors = compile_path(path) + self.dependant = get_dependant( + path=self.path_format, call=self.endpoint, scope="function" + ) + for depends in self.dependencies[::-1]: + self.dependant.dependencies.insert( + 0, + get_parameterless_sub_dependant(depends=depends, path=self.path_format), + ) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.app = websocket_session( + get_websocket_app( + dependant=self.dependant, + dependency_overrides_provider=dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, + ) + ) + + def matches(self, scope: Scope) -> tuple[Match, Scope]: + match, child_scope = super().matches(scope) + if match != Match.NONE: + child_scope["route"] = self + return match, child_scope + + +class APIRoute(routing.Route): + def __init__( + self, + path: str, + endpoint: Callable[..., Any], + *, + response_model: Any = Default(None), + status_code: int | None = None, + tags: list[str | Enum] | None = None, + dependencies: Sequence[params.Depends] | None = None, + summary: str | None = None, + description: str | None = None, + response_description: str = "Successful Response", + responses: dict[int | str, dict[str, Any]] | None = None, + deprecated: bool | None = None, + name: str | None = None, + methods: set[str] | list[str] | None = None, + operation_id: str | None = None, + response_model_include: IncEx | None = None, + response_model_exclude: IncEx | None = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), + dependency_overrides_provider: Any | None = None, + callbacks: list[BaseRoute] | None = None, + openapi_extra: dict[str, Any] | None = None, + generate_unique_id_function: Callable[["APIRoute"], str] + | DefaultPlaceholder = Default(generate_unique_id), + strict_content_type: bool | DefaultPlaceholder = Default(True), + ) -> None: + self.path = path + self.endpoint = endpoint + self.stream_item_type: Any | None = None + if isinstance(response_model, DefaultPlaceholder): + return_annotation = get_typed_return_annotation(endpoint) + if lenient_issubclass(return_annotation, Response): + response_model = None + else: + stream_item = get_stream_item_type(return_annotation) + if stream_item is not None: + # Extract item type for JSONL or SSE streaming when + # response_class is DefaultPlaceholder (JSONL) or + # EventSourceResponse (SSE). + # ServerSentEvent is excluded: it's a transport + # wrapper, not a data model, so it shouldn't feed + # into validation or OpenAPI schema generation. + if ( + isinstance(response_class, DefaultPlaceholder) + or lenient_issubclass(response_class, EventSourceResponse) + ) and not lenient_issubclass(stream_item, ServerSentEvent): + self.stream_item_type = stream_item + response_model = None + else: + response_model = return_annotation + self.response_model = response_model + self.summary = summary + self.response_description = response_description + self.deprecated = deprecated + self.operation_id = operation_id + self.response_model_include = response_model_include + self.response_model_exclude = response_model_exclude + self.response_model_by_alias = response_model_by_alias + self.response_model_exclude_unset = response_model_exclude_unset + self.response_model_exclude_defaults = response_model_exclude_defaults + self.response_model_exclude_none = response_model_exclude_none + self.include_in_schema = include_in_schema + self.response_class = response_class + self.dependency_overrides_provider = dependency_overrides_provider + self.callbacks = callbacks + self.openapi_extra = openapi_extra + self.generate_unique_id_function = generate_unique_id_function + self.strict_content_type = strict_content_type + self.tags = tags or [] + self.responses = responses or {} + self.name = get_name(endpoint) if name is None else name + self.path_regex, self.path_format, self.param_convertors = compile_path(path) + if methods is None: + methods = ["GET"] + self.methods: set[str] = {method.upper() for method in methods} + if isinstance(generate_unique_id_function, DefaultPlaceholder): + current_generate_unique_id: Callable[[APIRoute], str] = ( + generate_unique_id_function.value + ) + else: + current_generate_unique_id = generate_unique_id_function + self.unique_id = self.operation_id or current_generate_unique_id(self) + # normalize enums e.g. http.HTTPStatus + if isinstance(status_code, IntEnum): + status_code = int(status_code) + self.status_code = status_code + if self.response_model: + assert is_body_allowed_for_status_code(status_code), ( + f"Status code {status_code} must not have a response body" + ) + response_name = "Response_" + self.unique_id + self.response_field = create_model_field( + name=response_name, + type_=self.response_model, + mode="serialization", + ) + else: + self.response_field = None # type: ignore[assignment] + if self.stream_item_type: + stream_item_name = "StreamItem_" + self.unique_id + self.stream_item_field: ModelField | None = create_model_field( + name=stream_item_name, + type_=self.stream_item_type, + mode="serialization", + ) + else: + self.stream_item_field = None + self.dependencies = list(dependencies or []) + self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") + # if a "form feed" character (page break) is found in the description text, + # truncate description text to the content preceding the first "form feed" + self.description = self.description.split("\f")[0].strip() + response_fields = {} + for additional_status_code, response in self.responses.items(): + assert isinstance(response, dict), "An additional response must be a dict" + model = response.get("model") + if model: + assert is_body_allowed_for_status_code(additional_status_code), ( + f"Status code {additional_status_code} must not have a response body" + ) + response_name = f"Response_{additional_status_code}_{self.unique_id}" + response_field = create_model_field( + name=response_name, type_=model, mode="serialization" + ) + response_fields[additional_status_code] = response_field + if response_fields: + self.response_fields: dict[int | str, ModelField] = response_fields + else: + self.response_fields = {} + + assert callable(endpoint), "An endpoint must be a callable" + self.dependant = get_dependant( + path=self.path_format, call=self.endpoint, scope="function" + ) + for depends in self.dependencies[::-1]: + self.dependant.dependencies.insert( + 0, + get_parameterless_sub_dependant(depends=depends, path=self.path_format), + ) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.body_field = get_body_field( + flat_dependant=self._flat_dependant, + name=self.unique_id, + embed_body_fields=self._embed_body_fields, + ) + # Detect generator endpoints that should stream as JSONL or SSE + is_generator = ( + self.dependant.is_async_gen_callable or self.dependant.is_gen_callable + ) + self.is_sse_stream = is_generator and lenient_issubclass( + response_class, EventSourceResponse + ) + self.is_json_stream = is_generator and isinstance( + response_class, DefaultPlaceholder + ) + self.app = request_response(self.get_route_handler()) + + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: + return get_request_handler( + dependant=self.dependant, + body_field=self.body_field, + status_code=self.status_code, + response_class=self.response_class, + response_field=self.response_field, + response_model_include=self.response_model_include, + response_model_exclude=self.response_model_exclude, + response_model_by_alias=self.response_model_by_alias, + response_model_exclude_unset=self.response_model_exclude_unset, + response_model_exclude_defaults=self.response_model_exclude_defaults, + response_model_exclude_none=self.response_model_exclude_none, + dependency_overrides_provider=self.dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, + strict_content_type=self.strict_content_type, + stream_item_field=self.stream_item_field, + is_json_stream=self.is_json_stream, + ) + + def matches(self, scope: Scope) -> tuple[Match, Scope]: + match, child_scope = super().matches(scope) + if match != Match.NONE: + child_scope["route"] = self + return match, child_scope + + +class APIRouter(routing.Router): + """ + `APIRouter` class, used to group *path operations*, for example to structure + an app in multiple files. It would then be included in the `FastAPI` app, or + in another `APIRouter` (ultimately included in the app). + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + + @router.get("/users/", tags=["users"]) + async def read_users(): + return [{"username": "Rick"}, {"username": "Morty"}] + + + app.include_router(router) + ``` + """ + + def __init__( + self, + *, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + default_response_class: Annotated[ + type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + """ + ), + ] = Default(JSONResponse), + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + OpenAPI callbacks that should apply to all *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + routes: Annotated[ + list[BaseRoute] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Starlette and supported for compatibility. + + --- + + A list of routes to serve incoming HTTP and WebSocket requests. + """ + ), + deprecated( + """ + You normally wouldn't use this parameter with FastAPI, it is inherited + from Starlette and supported for compatibility. + + In FastAPI, you normally would use the *path operation methods*, + like `router.get()`, `router.post()`, etc. + """ + ), + ] = None, + redirect_slashes: Annotated[ + bool, + Doc( + """ + Whether to detect and redirect slashes in URLs when the client doesn't + use the same format. + """ + ), + ] = True, + default: Annotated[ + ASGIApp | None, + Doc( + """ + Default function handler for this router. Used to handle + 404 Not Found errors. + """ + ), + ] = None, + dependency_overrides_provider: Annotated[ + Any | None, + Doc( + """ + Only used internally by FastAPI to handle dependency overrides. + + You shouldn't need to use it. It normally points to the `FastAPI` app + object. + """ + ), + ] = None, + route_class: Annotated[ + type[APIRoute], + Doc( + """ + Custom route (*path operation*) class to be used by this router. + + Read more about it in the + [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). + """ + ), + ] = APIRoute, + on_startup: Annotated[ + Sequence[Callable[[], Any]] | None, + Doc( + """ + A list of startup event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + on_shutdown: Annotated[ + Sequence[Callable[[], Any]] | None, + Doc( + """ + A list of shutdown event handler functions. + + You should instead use the `lifespan` handlers. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + # the generic to Lifespan[AppType] is the type of the top level application + # which the router cannot know statically, so we use typing.Any + lifespan: Annotated[ + Lifespan[Any] | None, + Doc( + """ + A `Lifespan` context manager handler. This replaces `startup` and + `shutdown` functions with a single context manager. + + Read more in the + [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark all *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + To include (or not) all the *path operations* in this router in the + generated OpenAPI. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + strict_content_type: Annotated[ + bool, + Doc( + """ + Enable strict checking for request Content-Type headers. + + When `True` (the default), requests with a body that do not include + a `Content-Type` header will **not** be parsed as JSON. + + This prevents potential cross-site request forgery (CSRF) attacks + that exploit the browser's ability to send requests without a + Content-Type header, bypassing CORS preflight checks. In particular + applicable for apps that need to be run locally (in localhost). + + When `False`, requests without a `Content-Type` header will have + their body parsed as JSON, which maintains compatibility with + certain clients that don't send `Content-Type` headers. + + Read more about it in the + [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/). + """ + ), + ] = Default(True), + ) -> None: + # Determine the lifespan context to use + if lifespan is None: + # Use the default lifespan that runs on_startup/on_shutdown handlers + lifespan_context: Lifespan[Any] = _DefaultLifespan(self) + elif inspect.isasyncgenfunction(lifespan): + lifespan_context = asynccontextmanager(lifespan) + elif inspect.isgeneratorfunction(lifespan): + lifespan_context = _wrap_gen_lifespan_context(lifespan) + else: + lifespan_context = lifespan + self.lifespan_context = lifespan_context + + super().__init__( + routes=routes, + redirect_slashes=redirect_slashes, + default=default, + lifespan=lifespan_context, + ) + if prefix: + assert prefix.startswith("/"), "A path prefix must start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) + + # Handle on_startup/on_shutdown locally since Starlette removed support + # Ref: https://github.com/Kludex/starlette/pull/3117 + # TODO: deprecate this once the lifespan (or alternative) interface is improved + self.on_startup: list[Callable[[], Any]] = ( + [] if on_startup is None else list(on_startup) + ) + self.on_shutdown: list[Callable[[], Any]] = ( + [] if on_shutdown is None else list(on_shutdown) + ) + + self.prefix = prefix + self.tags: list[str | Enum] = tags or [] + self.dependencies = list(dependencies or []) + self.deprecated = deprecated + self.include_in_schema = include_in_schema + self.responses = responses or {} + self.callbacks = callbacks or [] + self.dependency_overrides_provider = dependency_overrides_provider + self.route_class = route_class + self.default_response_class = default_response_class + self.generate_unique_id_function = generate_unique_id_function + self.strict_content_type = strict_content_type + + def route( + self, + path: str, + methods: Collection[str] | None = None, + name: str | None = None, + include_in_schema: bool = True, + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_route( + path, + func, + methods=methods, + name=name, + include_in_schema=include_in_schema, + ) + return func + + return decorator + + def add_api_route( + self, + path: str, + endpoint: Callable[..., Any], + *, + response_model: Any = Default(None), + status_code: int | None = None, + tags: list[str | Enum] | None = None, + dependencies: Sequence[params.Depends] | None = None, + summary: str | None = None, + description: str | None = None, + response_description: str = "Successful Response", + responses: dict[int | str, dict[str, Any]] | None = None, + deprecated: bool | None = None, + methods: set[str] | list[str] | None = None, + operation_id: str | None = None, + response_model_include: IncEx | None = None, + response_model_exclude: IncEx | None = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), + name: str | None = None, + route_class_override: type[APIRoute] | None = None, + callbacks: list[BaseRoute] | None = None, + openapi_extra: dict[str, Any] | None = None, + generate_unique_id_function: Callable[[APIRoute], str] + | DefaultPlaceholder = Default(generate_unique_id), + strict_content_type: bool | DefaultPlaceholder = Default(True), + ) -> None: + route_class = route_class_override or self.route_class + responses = responses or {} + combined_responses = {**self.responses, **responses} + current_response_class = get_value_or_default( + response_class, self.default_response_class + ) + current_tags = self.tags.copy() + if tags: + current_tags.extend(tags) + current_dependencies = self.dependencies.copy() + if dependencies: + current_dependencies.extend(dependencies) + current_callbacks = self.callbacks.copy() + if callbacks: + current_callbacks.extend(callbacks) + current_generate_unique_id = get_value_or_default( + generate_unique_id_function, self.generate_unique_id_function + ) + route = route_class( + self.prefix + path, + endpoint=endpoint, + response_model=response_model, + status_code=status_code, + tags=current_tags, + dependencies=current_dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=combined_responses, + deprecated=deprecated or self.deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema and self.include_in_schema, + response_class=current_response_class, + name=name, + dependency_overrides_provider=self.dependency_overrides_provider, + callbacks=current_callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=current_generate_unique_id, + strict_content_type=get_value_or_default( + strict_content_type, self.strict_content_type + ), + ) + self.routes.append(route) + + def api_route( + self, + path: str, + *, + response_model: Any = Default(None), + status_code: int | None = None, + tags: list[str | Enum] | None = None, + dependencies: Sequence[params.Depends] | None = None, + summary: str | None = None, + description: str | None = None, + response_description: str = "Successful Response", + responses: dict[int | str, dict[str, Any]] | None = None, + deprecated: bool | None = None, + methods: list[str] | None = None, + operation_id: str | None = None, + response_model_include: IncEx | None = None, + response_model_exclude: IncEx | None = None, + response_model_by_alias: bool = True, + response_model_exclude_unset: bool = False, + response_model_exclude_defaults: bool = False, + response_model_exclude_none: bool = False, + include_in_schema: bool = True, + response_class: type[Response] = Default(JSONResponse), + name: str | None = None, + callbacks: list[BaseRoute] | None = None, + openapi_extra: dict[str, Any] | None = None, + generate_unique_id_function: Callable[[APIRoute], str] = Default( + generate_unique_id + ), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_api_route( + path, + func, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=methods, + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + return func + + return decorator + + def add_api_websocket_route( + self, + path: str, + endpoint: Callable[..., Any], + name: str | None = None, + *, + dependencies: Sequence[params.Depends] | None = None, + ) -> None: + current_dependencies = self.dependencies.copy() + if dependencies: + current_dependencies.extend(dependencies) + + route = APIWebSocketRoute( + self.prefix + path, + endpoint=endpoint, + name=name, + dependencies=current_dependencies, + dependency_overrides_provider=self.dependency_overrides_provider, + ) + self.routes.append(route) + + def websocket( + self, + path: Annotated[ + str, + Doc( + """ + WebSocket path. + """ + ), + ], + name: Annotated[ + str | None, + Doc( + """ + A name for the WebSocket. Only used internally. + """ + ), + ] = None, + *, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be used for this + WebSocket. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + """ + ), + ] = None, + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ## Example + + ```python + from fastapi import APIRouter, FastAPI, WebSocket + + app = FastAPI() + router = APIRouter() + + @router.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + + app.include_router(router) + ``` + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_api_websocket_route( + path, func, name=name, dependencies=dependencies + ) + return func + + return decorator + + def websocket_route( + self, path: str, name: str | None = None + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_websocket_route(path, func, name=name) + return func + + return decorator + + def include_router( + self, + router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], + *, + prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to all the *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to all the + *path operations* in this router. + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + default_response_class: Annotated[ + type[Response], + Doc( + """ + The default response class to be used. + + Read more in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). + """ + ), + ] = Default(JSONResponse), + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses to be shown in OpenAPI. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). + + And in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + OpenAPI callbacks that should apply to all *path operations* in this + router. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark all *path operations* in this router as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include (or not) all the *path operations* in this router in the + generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = True, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> None: + """ + Include another `APIRouter` in the same current `APIRouter`. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + internal_router = APIRouter() + users_router = APIRouter() + + @users_router.get("/users/") + def read_users(): + return [{"name": "Rick"}, {"name": "Morty"}] + + internal_router.include_router(users_router) + app.include_router(internal_router) + ``` + """ + assert self is not router, ( + "Cannot include the same APIRouter instance into itself. " + "Did you mean to include a different router?" + ) + if prefix: + assert prefix.startswith("/"), "A path prefix must start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) + else: + for r in router.routes: + path = getattr(r, "path") # noqa: B009 + name = getattr(r, "name", "unknown") + if path is not None and not path: + raise FastAPIError( + f"Prefix and path cannot be both empty (path operation: {name})" + ) + if responses is None: + responses = {} + for route in router.routes: + if isinstance(route, APIRoute): + combined_responses = {**responses, **route.responses} + use_response_class = get_value_or_default( + route.response_class, + router.default_response_class, + default_response_class, + self.default_response_class, + ) + current_tags = [] + if tags: + current_tags.extend(tags) + if route.tags: + current_tags.extend(route.tags) + current_dependencies: list[params.Depends] = [] + if dependencies: + current_dependencies.extend(dependencies) + if route.dependencies: + current_dependencies.extend(route.dependencies) + current_callbacks = [] + if callbacks: + current_callbacks.extend(callbacks) + if route.callbacks: + current_callbacks.extend(route.callbacks) + current_generate_unique_id = get_value_or_default( + route.generate_unique_id_function, + router.generate_unique_id_function, + generate_unique_id_function, + self.generate_unique_id_function, + ) + self.add_api_route( + prefix + route.path, + route.endpoint, + response_model=route.response_model, + status_code=route.status_code, + tags=current_tags, + dependencies=current_dependencies, + summary=route.summary, + description=route.description, + response_description=route.response_description, + responses=combined_responses, + deprecated=route.deprecated or deprecated or self.deprecated, + methods=route.methods, + operation_id=route.operation_id, + response_model_include=route.response_model_include, + response_model_exclude=route.response_model_exclude, + response_model_by_alias=route.response_model_by_alias, + response_model_exclude_unset=route.response_model_exclude_unset, + response_model_exclude_defaults=route.response_model_exclude_defaults, + response_model_exclude_none=route.response_model_exclude_none, + include_in_schema=route.include_in_schema + and self.include_in_schema + and include_in_schema, + response_class=use_response_class, + name=route.name, + route_class_override=type(route), + callbacks=current_callbacks, + openapi_extra=route.openapi_extra, + generate_unique_id_function=current_generate_unique_id, + strict_content_type=get_value_or_default( + route.strict_content_type, + router.strict_content_type, + self.strict_content_type, + ), + ) + elif isinstance(route, routing.Route): + methods = list(route.methods or []) + self.add_route( + prefix + route.path, + route.endpoint, + methods=methods, + include_in_schema=route.include_in_schema, + name=route.name, + ) + elif isinstance(route, APIWebSocketRoute): + current_dependencies = [] + if dependencies: + current_dependencies.extend(dependencies) + if route.dependencies: + current_dependencies.extend(route.dependencies) + self.add_api_websocket_route( + prefix + route.path, + route.endpoint, + dependencies=current_dependencies, + name=route.name, + ) + elif isinstance(route, routing.WebSocketRoute): + self.add_websocket_route( + prefix + route.path, route.endpoint, name=route.name + ) + for handler in router.on_startup: + self.add_event_handler("startup", handler) + for handler in router.on_shutdown: + self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) + + def get( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["GET"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def put( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["PUT"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def post( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["POST"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def delete( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["DELETE"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def options( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["OPTIONS"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def head( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["HEAD"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def patch( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["PATCH"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + def trace( + self, + path: Annotated[ + str, + Doc( + """ + The URL path to be used for this *path operation*. + + For example, in `http://example.com/items`, the path is `/items`. + """ + ), + ], + *, + response_model: Annotated[ + Any, + Doc( + """ + The type to use for the response. + + It could be any valid Pydantic *field* type. So, it doesn't have to + be a Pydantic model, it could be other things, like a `list`, `dict`, + etc. + + It will be used for: + + * Documentation: the generated OpenAPI (and the UI at `/docs`) will + show it as the response (JSON Schema). + * Serialization: you could return an arbitrary object and the + `response_model` would be used to serialize that object into the + corresponding JSON. + * Filtering: the JSON sent to the client will only contain the data + (fields) defined in the `response_model`. If you returned an object + that contains an attribute `password` but the `response_model` does + not include that field, the JSON sent to the client would not have + that `password`. + * Validation: whatever you return will be serialized with the + `response_model`, converting any data as necessary to generate the + corresponding JSON. But if the data in the object returned is not + valid, that would mean a violation of the contract with the client, + so it's an error from the API developer. So, FastAPI will raise an + error and return a 500 error code (Internal Server Error). + + Read more about it in the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + """ + ), + ] = Default(None), + status_code: Annotated[ + int | None, + Doc( + """ + The default status code to be used for the response. + + You could override the status code by returning a response directly. + + Read more about it in the + [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). + """ + ), + ] = None, + tags: Annotated[ + list[str | Enum] | None, + Doc( + """ + A list of tags to be applied to the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). + """ + ), + ] = None, + dependencies: Annotated[ + Sequence[params.Depends] | None, + Doc( + """ + A list of dependencies (using `Depends()`) to be applied to the + *path operation*. + + Read more about it in the + [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). + """ + ), + ] = None, + summary: Annotated[ + str | None, + Doc( + """ + A summary for the *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + description: Annotated[ + str | None, + Doc( + """ + A description for the *path operation*. + + If not provided, it will be extracted automatically from the docstring + of the *path operation function*. + + It can contain Markdown. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). + """ + ), + ] = None, + response_description: Annotated[ + str, + Doc( + """ + The description for the default response. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = "Successful Response", + responses: Annotated[ + dict[int | str, dict[str, Any]] | None, + Doc( + """ + Additional responses that could be returned by this *path operation*. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + deprecated: Annotated[ + bool | None, + Doc( + """ + Mark this *path operation* as deprecated. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + """ + ), + ] = None, + operation_id: Annotated[ + str | None, + Doc( + """ + Custom operation ID to be used by this *path operation*. + + By default, it is generated automatically. + + If you provide a custom operation ID, you need to make sure it is + unique for the whole API. + + You can customize the + operation ID generation with the parameter + `generate_unique_id_function` in the `FastAPI` class. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = None, + response_model_include: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to include only certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_exclude: Annotated[ + IncEx | None, + Doc( + """ + Configuration passed to Pydantic to exclude certain fields in the + response data. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = None, + response_model_by_alias: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response model + should be serialized by alias when an alias is used. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). + """ + ), + ] = True, + response_model_exclude_unset: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that were not set and + have their default values. This is different from + `response_model_exclude_defaults` in that if the fields are set, + they will be included in the response, even if the value is the same + as the default. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_defaults: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data + should have all the fields, including the ones that have the same value + as the default. This is different from `response_model_exclude_unset` + in that if the fields are set but contain the same default values, + they will be excluded from the response. + + When `True`, default values are omitted from the response. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). + """ + ), + ] = False, + response_model_exclude_none: Annotated[ + bool, + Doc( + """ + Configuration passed to Pydantic to define if the response data should + exclude fields set to `None`. + + This is much simpler (less smart) than `response_model_exclude_unset` + and `response_model_exclude_defaults`. You probably want to use one of + those two instead of this one, as those allow returning `None` values + when it makes sense. + + Read more about it in the + [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). + """ + ), + ] = False, + include_in_schema: Annotated[ + bool, + Doc( + """ + Include this *path operation* in the generated OpenAPI schema. + + This affects the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). + """ + ), + ] = True, + response_class: Annotated[ + type[Response], + Doc( + """ + Response class to be used for this *path operation*. + + This will not be used if you return a response directly. + + Read more about it in the + [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). + """ + ), + ] = Default(JSONResponse), + name: Annotated[ + str | None, + Doc( + """ + Name for this *path operation*. Only used internally. + """ + ), + ] = None, + callbacks: Annotated[ + list[BaseRoute] | None, + Doc( + """ + List of *path operations* that will be used as OpenAPI callbacks. + + This is only for OpenAPI documentation, the callbacks won't be used + directly. + + It will be added to the generated OpenAPI (e.g. visible at `/docs`). + + Read more about it in the + [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). + """ + ), + ] = None, + openapi_extra: Annotated[ + dict[str, Any] | None, + Doc( + """ + Extra metadata to be included in the OpenAPI schema for this *path + operation*. + + Read more about it in the + [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). + """ + ), + ] = None, + generate_unique_id_function: Annotated[ + Callable[[APIRoute], str], + Doc( + """ + Customize the function used to generate unique IDs for the *path + operations* shown in the generated OpenAPI. + + This is particularly useful when automatically generating clients or + SDKs for your API. + + Read more about it in the + [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). + """ + ), + ] = Default(generate_unique_id), + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + + app.include_router(router) + ``` + """ + return self.api_route( + path=path, + response_model=response_model, + status_code=status_code, + tags=tags, + dependencies=dependencies, + summary=summary, + description=description, + response_description=response_description, + responses=responses, + deprecated=deprecated, + methods=["TRACE"], + operation_id=operation_id, + response_model_include=response_model_include, + response_model_exclude=response_model_exclude, + response_model_by_alias=response_model_by_alias, + response_model_exclude_unset=response_model_exclude_unset, + response_model_exclude_defaults=response_model_exclude_defaults, + response_model_exclude_none=response_model_exclude_none, + include_in_schema=include_in_schema, + response_class=response_class, + name=name, + callbacks=callbacks, + openapi_extra=openapi_extra, + generate_unique_id_function=generate_unique_id_function, + ) + + # TODO: remove this once the lifespan (or alternative) interface is improved + async def _startup(self) -> None: + """ + Run any `.on_startup` event handlers. + + This method is kept for backward compatibility after Starlette removed + support for on_startup/on_shutdown handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ + for handler in self.on_startup: + if is_async_callable(handler): + await handler() + else: + handler() + + # TODO: remove this once the lifespan (or alternative) interface is improved + async def _shutdown(self) -> None: + """ + Run any `.on_shutdown` event handlers. + + This method is kept for backward compatibility after Starlette removed + support for on_startup/on_shutdown handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ + for handler in self.on_shutdown: + if is_async_callable(handler): + await handler() + else: + handler() + + # TODO: remove this once the lifespan (or alternative) interface is improved + def add_event_handler( + self, + event_type: str, + func: Callable[[], Any], + ) -> None: + """ + Add an event handler function for startup or shutdown. + + This method is kept for backward compatibility after Starlette removed + support for on_startup/on_shutdown handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ + assert event_type in ("startup", "shutdown") + if event_type == "startup": + self.on_startup.append(func) + else: + self.on_shutdown.append(func) + + @deprecated( + """ + on_event is deprecated, use lifespan event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). + """ + ) + def on_event( + self, + event_type: Annotated[ + str, + Doc( + """ + The type of event. `startup` or `shutdown`. + """ + ), + ], + ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the router. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ + + def decorator(func: DecoratedCallable) -> DecoratedCallable: + self.add_event_handler(event_type, func) + return func + + return decorator diff --git a/lib/python3.11/site-packages/fastapi/sse.py b/lib/python3.11/site-packages/fastapi/sse.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2bd8617161016098a4e33bd6ad0fc425091a37 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/sse.py @@ -0,0 +1,235 @@ +from typing import Annotated, Any + +from annotated_doc import Doc +from pydantic import AfterValidator, BaseModel, Field, model_validator +from starlette.responses import StreamingResponse + +# Canonical SSE event schema matching the OpenAPI 3.2 spec +# (Section 4.14.4 "Special Considerations for Server-Sent Events") +_SSE_EVENT_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "data": {"type": "string"}, + "event": {"type": "string"}, + "id": {"type": "string"}, + "retry": {"type": "integer", "minimum": 0}, + }, +} + + +class EventSourceResponse(StreamingResponse): + """Streaming response with `text/event-stream` media type. + + Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield` + to enable Server Sent Events (SSE) responses. + + Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible + with protocols like MCP that stream SSE over `POST`. + + The actual encoding logic lives in the FastAPI routing layer. This class + serves mainly as a marker and sets the correct `Content-Type`. + """ + + media_type = "text/event-stream" + + +def _check_single_line(v: str | None, field_name: str) -> str | None: + if v is not None and ("\r" in v or "\n" in v): + raise ValueError(f"SSE '{field_name}' must be a single line") + return v + + +def _check_event_single_line(v: str | None) -> str | None: + return _check_single_line(v, "event") + + +def _check_id_valid(v: str | None) -> str | None: + if v is not None and "\0" in v: + raise ValueError("SSE 'id' must not contain null characters") + return _check_single_line(v, "id") + + +class ServerSentEvent(BaseModel): + """Represents a single Server-Sent Event. + + When `yield`ed from a *path operation function* that uses + `response_class=EventSourceResponse`, each `ServerSentEvent` is encoded + into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream) + (`text/event-stream`). + + If you yield a plain object (dict, Pydantic model, etc.) instead, it is + automatically JSON-encoded and sent as the `data:` field. + + All `data` values **including plain strings** are JSON-serialized. + + For example, `data="hello"` produces `data: "hello"` on the wire (with + quotes). + """ + + data: Annotated[ + Any, + Doc( + """ + The event payload. + + Can be any JSON-serializable value: a Pydantic model, dict, list, + string, number, etc. It is **always** serialized to JSON: strings + are quoted (`"hello"` becomes `data: "hello"` on the wire). + + Mutually exclusive with `raw_data`. + """ + ), + ] = None + raw_data: Annotated[ + str | None, + Doc( + """ + Raw string to send as the `data:` field **without** JSON encoding. + + Use this when you need to send pre-formatted text, HTML fragments, + CSV lines, or any non-JSON payload. The string is placed directly + into the `data:` field as-is. + + Mutually exclusive with `data`. + """ + ), + ] = None + event: Annotated[ + str | None, + AfterValidator(_check_event_single_line), + Doc( + """ + Optional event type name. + + Maps to `addEventListener(event, ...)` on the browser. When omitted, + the browser dispatches on the generic `message` event. Must be a + single line. + """ + ), + ] = None + id: Annotated[ + str | None, + AfterValidator(_check_id_valid), + Doc( + """ + Optional event ID. + + The browser sends this value back as the `Last-Event-ID` header on + automatic reconnection. **Must be a single line** and must not contain + null (`\\0`) characters. + """ + ), + ] = None + retry: Annotated[ + int | None, + Field(ge=0), + Doc( + """ + Optional reconnection time in **milliseconds**. + + Tells the browser how long to wait before reconnecting after the + connection is lost. Must be a non-negative integer. + """ + ), + ] = None + comment: Annotated[ + str | None, + Doc( + """ + Optional comment line(s). + + Comment lines start with `:` in the SSE wire format and are ignored by + `EventSource` clients. Useful for keep-alive pings to prevent + proxy/load-balancer timeouts. + """ + ), + ] = None + + @model_validator(mode="after") + def _check_data_exclusive(self) -> "ServerSentEvent": + if self.data is not None and self.raw_data is not None: + raise ValueError( + "Cannot set both 'data' and 'raw_data' on the same " + "ServerSentEvent. Use 'data' for JSON-serialized payloads " + "or 'raw_data' for pre-formatted strings." + ) + return self + + +def format_sse_event( + *, + data_str: Annotated[ + str | None, + Doc( + """ + Pre-serialized data string to use as the `data:` field. + """ + ), + ] = None, + event: Annotated[ + str | None, + Doc( + """ + Optional event type name (`event:` field). + """ + ), + ] = None, + id: Annotated[ + str | None, + Doc( + """ + Optional event ID (`id:` field). + """ + ), + ] = None, + retry: Annotated[ + int | None, + Doc( + """ + Optional reconnection time in milliseconds (`retry:` field). + """ + ), + ] = None, + comment: Annotated[ + str | None, + Doc( + """ + Optional comment line(s) (`:` prefix). + """ + ), + ] = None, +) -> bytes: + """Build SSE wire-format bytes from **pre-serialized** data. + + The result always ends with `\n\n` (the event terminator). + """ + lines: list[str] = [] + + if comment is not None: + for line in comment.splitlines(): + lines.append(f": {line}") + + if event is not None: + lines.append(f"event: {event}") + + if data_str is not None: + for line in data_str.splitlines(): + lines.append(f"data: {line}") + + if id is not None: + lines.append(f"id: {id}") + + if retry is not None: + lines.append(f"retry: {retry}") + + lines.append("") + lines.append("") + return "\n".join(lines).encode("utf-8") + + +# Keep-alive comment, per the SSE spec recommendation +KEEPALIVE_COMMENT = b": ping\n\n" + +# Seconds between keep-alive pings when a generator is idle. +# Private but importable so tests can monkeypatch it. +_PING_INTERVAL: float = 15.0 diff --git a/lib/python3.11/site-packages/fastapi/staticfiles.py b/lib/python3.11/site-packages/fastapi/staticfiles.py new file mode 100644 index 0000000000000000000000000000000000000000..299015d4fef268cde91273790251f35192e1c8a6 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/staticfiles.py @@ -0,0 +1 @@ +from starlette.staticfiles import StaticFiles as StaticFiles # noqa diff --git a/lib/python3.11/site-packages/fastapi/templating.py b/lib/python3.11/site-packages/fastapi/templating.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb868486edd9dda38f90c65f314597813128cf8 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/templating.py @@ -0,0 +1 @@ +from starlette.templating import Jinja2Templates as Jinja2Templates # noqa diff --git a/lib/python3.11/site-packages/fastapi/testclient.py b/lib/python3.11/site-packages/fastapi/testclient.py new file mode 100644 index 0000000000000000000000000000000000000000..4012406aa76f743c5c5d1ab8ff56d6d67cfb6653 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/testclient.py @@ -0,0 +1 @@ +from starlette.testclient import TestClient as TestClient # noqa diff --git a/lib/python3.11/site-packages/fastapi/types.py b/lib/python3.11/site-packages/fastapi/types.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb86e13b126ff7d20432d414f00b6bc372554a6 --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/types.py @@ -0,0 +1,12 @@ +import types +from collections.abc import Callable +from enum import Enum +from typing import Any, TypeVar, Union + +from pydantic import BaseModel +from pydantic.main import IncEx as IncEx + +DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) +UnionType = getattr(types, "UnionType", Union) +ModelNameMap = dict[type[BaseModel] | type[Enum], str] +DependencyCacheKey = tuple[Callable[..., Any] | None, tuple[str, ...], str] diff --git a/lib/python3.11/site-packages/fastapi/utils.py b/lib/python3.11/site-packages/fastapi/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..12eaa2bf089c827f20a72dd82cbdb75deaac970a --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/utils.py @@ -0,0 +1,136 @@ +import re +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Literal, +) + +import fastapi +from fastapi._compat import ( + ModelField, + PydanticSchemaGenerationError, + Undefined, + annotation_is_pydantic_v1, +) +from fastapi.datastructures import DefaultPlaceholder, DefaultType +from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError +from pydantic.fields import FieldInfo + +from ._compat import v2 + +if TYPE_CHECKING: # pragma: nocover + from .routing import APIRoute + + +def is_body_allowed_for_status_code(status_code: int | str | None) -> bool: + if status_code is None: + return True + # Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1 + if status_code in { + "default", + "1XX", + "2XX", + "3XX", + "4XX", + "5XX", + }: + return True + current_status_code = int(status_code) + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) + + +def get_path_param_names(path: str) -> set[str]: + return set(re.findall("{(.*?)}", path)) + + +_invalid_args_message = ( + "Invalid args for response field! Hint: " + "check that {type_} is a valid Pydantic field type. " + "If you are using a return type annotation that is not a valid Pydantic " + "field (e.g. Union[Response, dict, None]) you can disable generating the " + "response model from the type annotation with the path operation decorator " + "parameter response_model=None. Read more: " + "https://fastapi.tiangolo.com/tutorial/response-model/" +) + + +def create_model_field( + name: str, + type_: Any, + default: Any | None = Undefined, + field_info: FieldInfo | None = None, + alias: str | None = None, + mode: Literal["validation", "serialization"] = "validation", +) -> ModelField: + if annotation_is_pydantic_v1(type_): + raise PydanticV1NotSupportedError( + "pydantic.v1 models are no longer supported by FastAPI." + f" Please update the response model {type_!r}." + ) + field_info = field_info or FieldInfo(annotation=type_, default=default, alias=alias) + try: + return v2.ModelField(mode=mode, name=name, field_info=field_info) + except PydanticSchemaGenerationError: + raise fastapi.exceptions.FastAPIError( + _invalid_args_message.format(type_=type_) + ) from None + + +def generate_operation_id_for_path( + *, name: str, path: str, method: str +) -> str: # pragma: nocover + warnings.warn( + message="fastapi.utils.generate_operation_id_for_path() was deprecated, " + "it is not used internally, and will be removed soon", + category=FastAPIDeprecationWarning, + stacklevel=2, + ) + operation_id = f"{name}{path}" + operation_id = re.sub(r"\W", "_", operation_id) + operation_id = f"{operation_id}_{method.lower()}" + return operation_id + + +def generate_unique_id(route: "APIRoute") -> str: + operation_id = f"{route.name}{route.path_format}" + operation_id = re.sub(r"\W", "_", operation_id) + assert route.methods + operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" + return operation_id + + +def deep_dict_update(main_dict: dict[Any, Any], update_dict: dict[Any, Any]) -> None: + for key, value in update_dict.items(): + if ( + key in main_dict + and isinstance(main_dict[key], dict) + and isinstance(value, dict) + ): + deep_dict_update(main_dict[key], value) + elif ( + key in main_dict + and isinstance(main_dict[key], list) + and isinstance(update_dict[key], list) + ): + main_dict[key] = main_dict[key] + update_dict[key] + else: + main_dict[key] = value + + +def get_value_or_default( + first_item: DefaultPlaceholder | DefaultType, + *extra_items: DefaultPlaceholder | DefaultType, +) -> DefaultPlaceholder | DefaultType: + """ + Pass items or `DefaultPlaceholder`s by descending priority. + + The first one to _not_ be a `DefaultPlaceholder` will be returned. + + Otherwise, the first item (a `DefaultPlaceholder`) will be returned. + """ + items = (first_item,) + extra_items + for item in items: + if not isinstance(item, DefaultPlaceholder): + return item + return first_item diff --git a/lib/python3.11/site-packages/fastapi/websockets.py b/lib/python3.11/site-packages/fastapi/websockets.py new file mode 100644 index 0000000000000000000000000000000000000000..55a4ac4a1a918720bb3b94eaea6f8737b968216a --- /dev/null +++ b/lib/python3.11/site-packages/fastapi/websockets.py @@ -0,0 +1,3 @@ +from starlette.websockets import WebSocket as WebSocket # noqa +from starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa +from starlette.websockets import WebSocketState as WebSocketState # noqa diff --git a/lib/python3.11/site-packages/flash_attn/__init__.py b/lib/python3.11/site-packages/flash_attn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43612080291eb86f43f238256b2f9b7d6a8d244c --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/__init__.py @@ -0,0 +1,11 @@ +__version__ = "2.7.1.post1" + +from flash_attn.flash_attn_interface import ( + flash_attn_func, + flash_attn_kvpacked_func, + flash_attn_qkvpacked_func, + flash_attn_varlen_func, + flash_attn_varlen_kvpacked_func, + flash_attn_varlen_qkvpacked_func, + flash_attn_with_kvcache, +) diff --git a/lib/python3.11/site-packages/flash_attn/bert_padding.py b/lib/python3.11/site-packages/flash_attn/bert_padding.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2d35159a014a9d03aabead9e52e009168696ea --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/bert_padding.py @@ -0,0 +1,218 @@ +# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py + +import torch +import torch.nn.functional as F +from einops import rearrange, repeat + + +class IndexFirstAxis(torch.autograd.Function): + @staticmethod + def forward(ctx, input, indices): + ctx.save_for_backward(indices) + assert input.ndim >= 2 + ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:] + second_dim = other_shape.numel() + # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing. + # return input[indices] + return torch.gather( + rearrange(input, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim) + ).reshape(-1, *other_shape) + + @staticmethod + def backward(ctx, grad_output): + (indices,) = ctx.saved_tensors + assert grad_output.ndim >= 2 + other_shape = grad_output.shape[1:] + grad_output = rearrange(grad_output, "b ... -> b (...)") + grad_input = torch.zeros( + [ctx.first_axis_dim, grad_output.shape[1]], + device=grad_output.device, + dtype=grad_output.dtype, + ) + # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing. + # grad_input[indices] = grad_output + grad_input.scatter_(0, repeat(indices, "z -> z d", d=grad_output.shape[1]), grad_output) + return grad_input.reshape(ctx.first_axis_dim, *other_shape), None + + +index_first_axis = IndexFirstAxis.apply + + +class IndexPutFirstAxis(torch.autograd.Function): + @staticmethod + def forward(ctx, values, indices, first_axis_dim): + ctx.save_for_backward(indices) + assert indices.ndim == 1 + assert values.ndim >= 2 + output = torch.zeros( + first_axis_dim, *values.shape[1:], device=values.device, dtype=values.dtype + ) + # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing. + output[indices] = values + # output.scatter_(0, repeat(indices, 'z -> z d', d=values.shape[1]), values) + return output + + @staticmethod + def backward(ctx, grad_output): + (indices,) = ctx.saved_tensors + # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing. + grad_values = grad_output[indices] + # grad_values = torch.gather(grad_output, 0, repeat(indices, 'z -> z d', d=grad_output.shape[1])) + return grad_values, None, None + + +index_put_first_axis = IndexPutFirstAxis.apply + + +class IndexFirstAxisResidual(torch.autograd.Function): + @staticmethod + def forward(ctx, input, indices): + ctx.save_for_backward(indices) + assert input.ndim >= 2 + ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:] + second_dim = other_shape.numel() + # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing. + output = input[indices] + # We don't want to reshape input (b ... -> b (...)) since it could change the channel_last + # memory format to channel_first. In other words, input might not be contiguous. + # If we don't detach, Pytorch complains about output being a view and is being modified inplace + return output, input.detach() + + @staticmethod + def backward(ctx, grad_output, grad_residual): + (indices,) = ctx.saved_tensors + assert grad_output.ndim >= 2 + other_shape = grad_output.shape[1:] + assert grad_residual.shape[1:] == other_shape + grad_input = grad_residual + # grad_input[indices] += grad_output + indices = indices.reshape(indices.shape[0], *((1,) * (grad_output.ndim - 1))) + indices = indices.expand_as(grad_output) + grad_input.scatter_add_(0, indices, grad_output) + return grad_input.reshape(ctx.first_axis_dim, *other_shape), None + + +index_first_axis_residual = IndexFirstAxisResidual.apply + + +def unpad_input(hidden_states, attention_mask, unused_mask=None): + """ + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. + unused_mask: (batch, seqlen), bool / int, 1 means the element is allocated but unused. + Return: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask + unused_mask. + indices: (total_nnz), the indices of masked tokens from the flattened input sequence. + cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states. + max_seqlen_in_batch: int + seqused: (batch), returns the number of tokens selected in attention_mask + unused_mask. + """ + all_masks = (attention_mask + unused_mask) if unused_mask is not None else attention_mask + seqlens_in_batch = all_masks.sum(dim=-1, dtype=torch.int32) + used_seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(all_masks.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) + # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the + # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim + # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to + # index with integer indices. Moreover, torch's index is a bit slower than it needs to be, + # so we write custom forward and backward to make it a bit faster. + return ( + index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices), + indices, + cu_seqlens, + max_seqlen_in_batch, + used_seqlens_in_batch, + ) + + +def unpad_input_for_concatenated_sequences(hidden_states, attention_mask_in_length): + """ + Supports concatenating short samples in one sequence. The attention_mask_in_length is utilized to mask other short samples. It helps efficient training of variant lengths-based samples (e.g., the supervised fine-tuning task in large language model). + The motivation for this function is explained [here](https://github.com/Dao-AILab/flash-attention/issues/432#issuecomment-1668822286). + + For example, if batch = 3 and seqlen = 6, the attention_mask_in_length is: + ``` + [ + [2, 3, 0, 0, 0, 0], + [3, 2, 0, 0, 0, 0], + [6, 0, 0, 0, 0, 0] + ] + ``` + , which refers to the 3D-attention mask: + ``` + [ + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1] + ], + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 1] + ], + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1] + ] + ] + ```. + + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask_in_length: (batch, seqlen), int, a nonzero number (e.g., 1, 2, 3, etc.) means length of concatenated sequence in b-th batch, and 0 means none. + Return: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask. + indices: (total_nnz), the indices of non-masked tokens from the flattened input sequence. + cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states. + max_seqlen_in_batch: int + """ + length = attention_mask_in_length.sum(dim=-1) + seqlen = attention_mask_in_length.size(-1) + attention_mask_2d = torch.arange(seqlen, device=length.device, dtype=length.dtype).expand(len(length), seqlen) < length.unsqueeze(1) + real_indices_idx = torch.nonzero(attention_mask_in_length.flatten(), as_tuple=False).flatten() + seqlens_in_batch = attention_mask_in_length.flatten()[real_indices_idx] + indices = torch.nonzero(attention_mask_2d.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) + # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the + # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim + # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to + # index with integer indices. Moreover, torch's index is a bit slower than it needs to be, + # so we write custom forward and backward to make it a bit faster. + return ( + index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices), + indices, + cu_seqlens, + max_seqlen_in_batch, + ) + + +def pad_input(hidden_states, indices, batch, seqlen): + """ + Arguments: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask. + indices: (total_nnz), the indices that represent the non-masked tokens of the original padded input sequence. + batch: int, batch size for the padded sequence. + seqlen: int, maximum sequence length for the padded sequence. + Return: + hidden_states: (batch, seqlen, ...) + """ + dim = hidden_states.shape[-1] + # output = torch.zeros((batch * seqlen), dim, device=hidden_states.device, dtype=hidden_states.dtype) + # output[indices] = hidden_states + output = index_put_first_axis(hidden_states, indices, batch * seqlen) + return rearrange(output, "(b s) ... -> b s ...", b=batch) diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_interface.py b/lib/python3.11/site-packages/flash_attn/flash_attn_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..1018349de8ff2e7ebde4fcca684e47fb2bf0c401 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_interface.py @@ -0,0 +1,1574 @@ +# Copyright (c) 2023, Tri Dao. + +from typing import Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import os + +# isort: off +# We need to import the CUDA kernels after importing torch +USE_TRITON_ROCM = os.getenv("FLASH_ATTENTION_TRITON_AMD_ENABLE", "FALSE") == "TRUE" +if USE_TRITON_ROCM: + from .flash_attn_triton_amd import interface_fa as flash_attn_gpu +else: + import flash_attn_2_cuda as flash_attn_gpu + +# isort: on + +def maybe_contiguous(x): + return x.contiguous() if x is not None and x.stride(-1) != 1 else x + + +def _get_block_size_n(device, head_dim, is_dropout, is_causal): + # This should match the block sizes in the CUDA kernel + assert head_dim <= 256 + major, minor = torch.cuda.get_device_capability(device) + is_sm8x = major == 8 and minor > 0 # Only include sm86 and sm89, exclude sm80 (A100) + is_sm80 = major == 8 and minor == 0 + is_sm90 = major == 9 and minor == 0 + if head_dim <= 32: + return 128 + if head_dim <= 64: + return 128 if not is_dropout else 64 + elif head_dim <= 96: + return 64 + elif head_dim <= 128: + if is_sm8x: + return 64 if (not is_dropout and is_causal) else 32 + else: + return 64 if not is_dropout else 32 + elif head_dim <= 160: + if is_sm8x: + return 64 + else: + return 32 + elif head_dim <= 192: + return 64 + elif head_dim <= 224: + return 64 + elif head_dim <= 256: + return 64 + + +def round_multiple(x, m): + return (x + m - 1) // m * m + + +# torch.compile() support is only enabled for pytorch >= 2.4 +# The reason for this is that we are using the new custom_op and register_fake +# APIs, which support inplace modification of inputs in the function itself +if torch.__version__ >= "2.4.0": + _torch_custom_op_wrapper = torch.library.custom_op + _torch_register_fake_wrapper = torch.library.register_fake +else: + def noop_custom_op_wrapper(name, fn=None, /, *, mutates_args, device_types=None, schema=None): + def wrap(func): + return func + if fn is None: + return wrap + return fn + def noop_register_fake_wrapper(op, fn=None, /, *, lib=None, _stacklevel=1): + def wrap(func): + return func + if fn is None: + return wrap + return fn + _torch_custom_op_wrapper = noop_custom_op_wrapper + _torch_register_fake_wrapper = noop_register_fake_wrapper + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_forward", mutates_args=(), device_types="cuda") +def _flash_attn_forward( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + return_softmax: bool +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + out, softmax_lse, S_dmask, rng_state = flash_attn_gpu.fwd( + q, + k, + v, + None, + alibi_slopes, + dropout_p, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + return_softmax, + None, + ) + return out, softmax_lse, S_dmask, rng_state + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_forward") +def _flash_attn_forward_fake( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + return_softmax: bool +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + batch_size, seqlen_q, num_heads, head_size = q.shape + seqlen_k = k.shape[1] + out = torch.empty_like(q) + softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device, layout=q.layout) + p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout) + if return_softmax: + p = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128), round_multiple(seqlen_k, 128)), dtype=q.dtype, device=q.device, layout=q.layout) + rng_state = torch.empty((2,), dtype=torch.int64, device=q.device) + + return out, softmax_lse, p, rng_state + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_forward = torch.ops.flash_attn._flash_attn_forward +else: + _wrapped_flash_attn_forward = _flash_attn_forward + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_varlen_forward", mutates_args=(), device_types="cuda") +def _flash_attn_varlen_forward( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int = -1, + window_size_right: int = -1, + softcap: float = 0.0, + alibi_slopes: Optional[torch.Tensor] = None, + return_softmax: bool = False, + block_table: Optional[torch.Tensor] = None, + leftpad_k: Optional[torch.Tensor] = None, + seqused_k: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + out, softmax_lse, S_dmask, rng_state = flash_attn_gpu.varlen_fwd( + q, + k, + v, + None, + cu_seqlens_q, + cu_seqlens_k, + seqused_k, + leftpad_k, + block_table, + alibi_slopes, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + False, + causal, + window_size_left, + window_size_right, + softcap, + return_softmax, + None, + ) + # if out.isnan().any() or softmax_lse.isnan().any(): + # breakpoint() + return out, softmax_lse, S_dmask, rng_state + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_varlen_forward") +def _flash_attn_varlen_forward_fake( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int = -1, + window_size_right: int = -1, + softcap: float = 0.0, + alibi_slopes: Optional[torch.Tensor] = None, + return_softmax: bool = False, + block_table: Optional[torch.Tensor] = None, + leftpad_k: Optional[torch.Tensor] = None, + seqused_k: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + paged_kv = block_table is not None + batch_size = cu_seqlens_q.numel() - 1 + total_q, num_heads, _ = q.shape + + out = torch.empty_like(q) + softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout) + p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout) + seqlen_q_rounded = round_multiple(max_seqlen_q, 128) + seqlen_k_rounded = round_multiple(max_seqlen_k, 128) + if return_softmax: + p = torch.empty((batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded), dtype=q.dtype, device=q.device, layout=q.layout) + rng_state = torch.empty((2,), dtype=torch.int64, device=q.device) + return out, softmax_lse, p, rng_state + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_varlen_forward = torch.ops.flash_attn._flash_attn_varlen_forward +else: + _wrapped_flash_attn_varlen_forward = _flash_attn_varlen_forward + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_backward", mutates_args=("dq", "dk", "dv"), device_types="cuda") +def _flash_attn_backward( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, +) -> torch.Tensor: + # dq, dk, dv are allocated by us so they should already be contiguous + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + ( + dq, + dk, + dv, + softmax_d, + ) = flash_attn_gpu.bwd( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + alibi_slopes, + dropout_p, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + deterministic, + None, + rng_state, + ) + return softmax_d + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_backward") +def _flash_attn_backward_fake( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, +) -> torch.Tensor: + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + if dq is None: + dq = torch.empty_like(q) + if dk is None: + dk = torch.empty_like(k) + if dv is None: + dv = torch.empty_like(v) + batch_size, seqlen_q, num_heads, _ = q.shape + softmax_d = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128)), device=q.device, dtype=torch.float32) + + return softmax_d + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_backward = torch.ops.flash_attn._flash_attn_backward +else: + _wrapped_flash_attn_backward = _flash_attn_backward + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_varlen_backward", mutates_args=("dq", "dk", "dv"), device_types="cuda") +def _flash_attn_varlen_backward( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, +) -> torch.Tensor: + # dq, dk, dv are allocated by us so they should already be contiguous + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + ( + dq, + dk, + dv, + softmax_d, + ) = flash_attn_gpu.varlen_bwd( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + alibi_slopes, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + False, + causal, + window_size_left, + window_size_right, + softcap, + deterministic, + None, + rng_state, + ) + # if dk.isnan().any() or dk.isnan().any() or dv.isnan().any() or softmax_d.isnan().any(): + # breakpoint() + return softmax_d + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_varlen_backward") +def _flash_attn_varlen_backward_fake( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, +) -> torch.Tensor: + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + batch_size = cu_seqlens_q.numel() - 1 + total_q, num_heads, _ = q.shape + + if dq is None: + dq = torch.empty_like(q) + if dk is None: + dk = torch.empty_like(k) + if dv is None: + dv = torch.empty_like(v) + softmax_d = torch.empty((num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32) + + return softmax_d + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_varlen_backward = torch.ops.flash_attn._flash_attn_varlen_backward +else: + _wrapped_flash_attn_varlen_backward = _flash_attn_varlen_backward + + +class FlashAttnQKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + ): + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + q, k, v = qkv[:, :, 0].detach(), qkv[:, :, 1].detach(), qkv[:, :, 2].detach() + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + ) + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, rng_state) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, rng_state = ctx.saved_tensors + qkv_shape = q.shape[:-2] + (3, *q.shape[-2:]) + dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dqkv[:, :, 0], + dqkv[:, :, 1], + dqkv[:, :, 2], + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension + return dqkv, None, None, None, None, None, None, None, None + + +class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + cu_seqlens, + max_seqlen, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + ): + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + q, k, v = qkv[:, 0].detach(), qkv[:, 1].detach(), qkv[:, 2].detach() + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward( + q, + k, + v, + cu_seqlens, + cu_seqlens, + max_seqlen, + max_seqlen, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + block_table=None, + ) + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state) + ctx.dropout_p = dropout_p + ctx.max_seqlen = max_seqlen + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, cu_seqlens, rng_state = ctx.saved_tensors + qkv_shape = q.shape[:-2] + (3, *q.shape[-2:]) + dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_varlen_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dqkv[:, 0], + dqkv[:, 1], + dqkv[:, 2], + cu_seqlens, + cu_seqlens, + ctx.max_seqlen, + ctx.max_seqlen, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension + return dqkv, None, None, None, None, None, None, None, None, None, None + + +class FlashAttnKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + kv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + ): + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach() + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + ) + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, rng_state) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, rng_state = ctx.saved_tensors + dq = torch.empty_like(q) + kv_shape = k.shape[:-2] + (2, *k.shape[-2:]) + dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dkv[:, :, 0], + dkv[:, :, 1], + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dkv = dkv[..., : dout.shape[-1]] + return dq, dkv, None, None, None, None, None, None, None, None + + +class FlashAttnVarlenKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + kv, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + ): + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + k, v = kv[:, 0].detach(), kv[:, 1].detach() + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + block_table=None, + ) + ctx.save_for_backward( + q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state + ) + ctx.dropout_p = dropout_p + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors + dq = torch.empty_like(q) + kv_shape = k.shape[:-2] + (2, *k.shape[-2:]) + dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_varlen_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dkv[:, 0], + dkv[:, 1], + cu_seqlens_q, + cu_seqlens_k, + ctx.max_seqlen_q, + ctx.max_seqlen_k, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dkv = dkv[..., : dout.shape[-1]] + return dq, dkv, None, None, None, None, None, None, None, None, None, None, None, None + + +class FlashAttnFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + ): + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + ) + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, rng_state) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, rng_state = ctx.saved_tensors + dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dk = dk[..., : dout.shape[-1]] + dv = dv[..., : dout.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None + + +class FlashAttnVarlenFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + block_table, + ): + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + block_table=block_table, + ) + ctx.save_for_backward( + q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state + ) + ctx.dropout_p = dropout_p + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors + dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_varlen_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + ctx.max_seqlen_q, + ctx.max_seqlen_k, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dk = dk[..., : dout.shape[-1]] + dv = dv[..., : dout.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None + + +def flash_attn_qkvpacked_func( + qkv, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # <=0.0 means deactivate + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If Q, K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of Q, K, V. + For multi-query and grouped-query attention (MQA/GQA), please see + flash_attn_kvpacked_func and flash_attn_func. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive. + + Arguments: + qkv: (batch_size, seqlen, 3, nheads, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to + the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnQKVPackedFunc.apply( + qkv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + ) + + +def flash_attn_kvpacked_func( + q, + kv, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of K, V. + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + kv: (batch_size, seqlen, 2, nheads_k, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnKVPackedFunc.apply( + q, + kv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + ) + + +def flash_attn_func( + q, + k, + v, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + k: (batch_size, seqlen, nheads_k, headdim) + v: (batch_size, seqlen, nheads_k, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnFunc.apply( + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + ) + + +def flash_attn_varlen_qkvpacked_func( + qkv, + cu_seqlens, + max_seqlen, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If Q, K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_varlen_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of Q, K, V. + For multi-query and grouped-query attention (MQA/GQA), please see + flash_attn_varlen_kvpacked_func and flash_attn_varlen_func. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive. + + Arguments: + qkv: (total, 3, nheads, headdim), where total = total number of tokens in the batch. + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into qkv. + max_seqlen: int. Maximum sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenQKVPackedFunc.apply( + qkv, + cu_seqlens, + max_seqlen, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + ) + + +def flash_attn_varlen_kvpacked_func( + q, + kv, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of K, V. + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch. + kv: (total_k, 2, nheads_k, headdim), where total_k = total number of key tokens in the batch. + cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_q: int. Maximum query sequence length in the batch. + max_seqlen_k: int. Maximum key sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenKVPackedFunc.apply( + q, + kv, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + ) + + +def flash_attn_varlen_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, + block_table=None, +): + """dropout_p should be set to 0.0 during evaluation + Supports multi-query and grouped-query attention (MQA/GQA) by passing in K, V with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch. + k: (total_k, nheads_k, headdim), where total_k = total number of key tokens in the batch. + v: (total_k, nheads_k, headdim), where total_k = total number of key tokens in the batch. + cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_q: int. Maximum query sequence length in the batch. + max_seqlen_k: int. Maximum key sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenFunc.apply( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + block_table, + ) + + +def flash_attn_with_kvcache( + q, + k_cache, + v_cache, + k=None, + v=None, + rotary_cos=None, + rotary_sin=None, + cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None, + cache_batch_idx: Optional[torch.Tensor] = None, + cache_leftpad: Optional[torch.Tensor] = None, + block_table: Optional[torch.Tensor] = None, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + rotary_interleaved=True, + alibi_slopes=None, + num_splits=0, + return_softmax_lse=False, +): + """ + If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from + k and v. This is useful for incremental decoding: you can pass in the cached keys/values from + the previous step, and update them with the new keys/values from the current step, and do + attention with the updated cache, all in 1 kernel. + + If you pass in k / v, you must make sure that the cache is large enough to hold the new values. + For example, the KV cache could be pre-allocated with the max sequence length, and you can use + cache_seqlens to keep track of the current sequence lengths of each sequence in the batch. + + Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be + rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc. + If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos + and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc. + If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at + indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens). + + See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function. + + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Note: Does not support backward pass. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no block_table, + or (num_blocks, page_block_size, nheads_k, headdim) if there's a block_table (i.e. paged KV cache) + page_block_size must be a multiple of 256. + v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no block_table, + or (num_blocks, page_block_size, nheads_k, headdim) if there's a block_table (i.e. paged KV cache) + k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate + k with k_cache, starting at the indices specified by cache_seqlens. + v [optional]: (batch_size, seqlen_new, nheads_k, headdim). Similar to k. + rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding + to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16. + rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos. + cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the + KV cache. + cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache. + If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1]. + If the indices are not distinct, and k and v are provided, the values updated in the cache + might come from any of the duplicate indices. + cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0. + block_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in. + If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False, + rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1 + (i.e. GPT-NeoX style). + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + num_splits: int. If > 1, split the key/value into this many chunks along the sequence. + If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic + to automatically determine the number of splits. + Don't change this unless you know what you are doing. + return_softmax_lse: bool. Whether to return the logsumexp of the attention scores. + + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + """ + assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension" + assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension" + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + if cache_seqlens is not None and isinstance(cache_seqlens, int): + cache_seqlens = torch.full( + (k_cache.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device + ) + cache_seqlens = maybe_contiguous(cache_seqlens) + cache_batch_idx = maybe_contiguous(cache_batch_idx) + block_table = maybe_contiguous(block_table) + out, softmax_lse = flash_attn_gpu.fwd_kvcache( + q, + k_cache, + v_cache, + k, + v, + cache_seqlens, + rotary_cos, + rotary_sin, + cache_batch_idx, + cache_leftpad, + block_table, + alibi_slopes, + None, + softmax_scale, + causal, + window_size[0], + window_size[1], + softcap, + rotary_interleaved, + num_splits, + ) + return (out, softmax_lse) if return_softmax_lse else out diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..30420c057adf1916e16403d3f0d02d0e26c8b7a3 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton.py @@ -0,0 +1,1160 @@ +""" +*Experimental* implementation of FlashAttention in Triton. +Tested with triton==2.0.0.dev20221202. +Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions +other than 64: +https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207 +We'll update this implementation with the new Triton backend once this is fixed. + +We use the FlashAttention implementation from Phil Tillet a starting point. +https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py + +Changes: +- Implement both causal and non-causal attention. +- Implement both self-attention and cross-attention. +- Support arbitrary seqlens (not just multiples of 128), for both forward and backward. +- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward. +- Support attention bias. +- Speed up the forward pass a bit, and only store the LSE instead of m and l. +- Make the backward for d=128 much faster by reducing register spilling. +- Optionally parallelize the backward pass across seqlen_k, to deal with the case of +small batch size * nheads. + +Caution: +- This is an *experimental* implementation. The forward pass should be quite robust but +I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler). +- This implementation has only been tested on A100. +- If you plan to use headdim other than 64 and 128, you should test for race conditions +(due to the Triton compiler), as done in tests/test_flash_attn.py +"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions +for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident +that there are none left for other head dimensions. + +Differences between this Triton version and the CUDA version: +- Triton version doesn't support dropout. +- Triton forward is generally faster than CUDA forward, while Triton backward is +generally slower than CUDA backward. Overall Triton forward + backward is slightly slower +than CUDA forward + backward. +- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor). +- Triton version supports attention bias, while CUDA version doesn't. +""" + +import math + +import torch +import triton +import triton.language as tl + + +# Disabling autotune for now, set num_warps=4 if headdim=64 and num_warps=8 if headdim=128 +# @triton.autotune( +# configs=[ +# triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1), +# # This config has a race condition when EVEN_M == False, disabling it for now. +# # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1), +# ], +# key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'] +# ) +@triton.heuristics( + { + "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0, + "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0, + "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"], + } +) +@triton.jit +def _fwd_kernel( + Q, + K, + V, + Bias, + Out, + Lse, + TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug + softmax_scale, + stride_qb, + stride_qh, + stride_qm, + stride_kb, + stride_kh, + stride_kn, + stride_vb, + stride_vh, + stride_vn, + stride_bb, + stride_bh, + stride_bm, + stride_ob, + stride_oh, + stride_om, + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + headdim, + CACHE_KEY_SEQLEN_Q, + CACHE_KEY_SEQLEN_K, + BIAS_TYPE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + start_m = tl.program_id(0) + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + # off_b = tl.program_id(1) + # off_h = tl.program_id(2) + # off_hb = off_b * nheads + off_h + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_HEADDIM) + # Initialize pointers to Q, K, V + # Adding parenthesis around indexing might use int32 math instead of int64 math? + # https://github.com/openai/triton/issues/741 + # I'm seeing a tiny bit of difference (5-7us) + q_ptrs = ( + Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :]) + ) + k_ptrs = ( + K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :]) + ) + v_ptrs = ( + V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :]) + ) + if BIAS_TYPE == "vector": + b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n + elif BIAS_TYPE == "matrix": + b_ptrs = ( + Bias + + off_b * stride_bb + + off_h * stride_bh + + (offs_m[:, None] * stride_bm + offs_n[None, :]) + ) + # initialize pointer to m and l + t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m + lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32) + # load q: it will stay in SRAM throughout + # [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call + # tl.load(q_ptrs), we get the wrong output! + if EVEN_M & EVEN_N: + if EVEN_HEADDIM: + q = tl.load(q_ptrs) + else: + q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0) + else: + q = tl.load( + q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0 + ) + # loop over k, v and update accumulator + end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k) + for start_n in range(0, end_n, BLOCK_N): + start_n = tl.multiple_of(start_n, BLOCK_N) + # -- compute qk ---- + if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition + if EVEN_HEADDIM: + k = tl.load(k_ptrs + start_n * stride_kn) + else: + k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + k = tl.load( + k_ptrs + start_n * stride_kn, + mask=(start_n + offs_n)[:, None] < seqlen_k, + other=0.0, + ) + else: + k = tl.load( + k_ptrs + start_n * stride_kn, + mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), + other=0.0, + ) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, k, trans_b=True) + # Trying to combine the two masks seem to make the result wrong + if not EVEN_N: # Need to mask out otherwise the softmax is wrong + qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float("-inf")) + if IS_CAUSAL: + qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float("-inf")) + if BIAS_TYPE != "none": + if BIAS_TYPE == "vector": + if EVEN_N: + bias = tl.load(b_ptrs + start_n).to(tl.float32) + else: + bias = tl.load( + b_ptrs + start_n, mask=(start_n + offs_n) < seqlen_k, other=0.0 + ).to(tl.float32) + bias = bias[None, :] + elif BIAS_TYPE == "matrix": + if EVEN_M & EVEN_N: + bias = tl.load(b_ptrs + start_n).to(tl.float32) + else: + bias = tl.load( + b_ptrs + start_n, + mask=(offs_m[:, None] < seqlen_q) + & ((start_n + offs_n)[None, :] < seqlen_k), + other=0.0, + ).to(tl.float32) + # Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler + # can then fuse the mult and add into an fma instruction. But if we have bias we need to + # to multiply with softmax_scale here. + qk = qk * softmax_scale + bias + m_ij = tl.maximum(tl.max(qk, 1), lse_i) + p = tl.exp(qk - m_ij[:, None]) + else: + m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i) + p = tl.exp(qk * softmax_scale - m_ij[:, None]) + l_ij = tl.sum(p, 1) + + # scale acc_o + acc_o_scale = tl.exp(m_i - m_ij) + + # # -- update output accumulator -- + # BUG: have to store and immediately load + tl.store(t_ptrs, acc_o_scale) + acc_o_scale = tl.load(t_ptrs) + acc_o = acc_o * acc_o_scale[:, None] + # update acc_o + if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition + if EVEN_HEADDIM: + v = tl.load(v_ptrs + start_n * stride_vn) + else: + v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + v = tl.load( + v_ptrs + start_n * stride_vn, + mask=(start_n + offs_n)[:, None] < seqlen_k, + other=0.0, + ) + else: + v = tl.load( + v_ptrs + start_n * stride_vn, + mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), + other=0.0, + ) + p = p.to(v.dtype) + acc_o += tl.dot(p, v) + + # -- update statistics + m_i = m_ij + l_i_new = tl.exp(lse_i - m_ij) + l_ij + lse_i = m_ij + tl.log(l_i_new) + + o_scale = tl.exp(m_i - lse_i) + # BUG: have to store and immediately load + tl.store(t_ptrs, o_scale) + o_scale = tl.load(t_ptrs) + acc_o = acc_o * o_scale[:, None] + # rematerialize offsets to save registers + start_m = tl.program_id(0) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + # write back l and m + lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m + tl.store(lse_ptrs, lse_i) + # initialize pointers to output + offs_d = tl.arange(0, BLOCK_HEADDIM) + out_ptrs = ( + Out + + off_b * stride_ob + + off_h * stride_oh + + (offs_m[:, None] * stride_om + offs_d[None, :]) + ) + if EVEN_M: + if EVEN_HEADDIM: + tl.store(out_ptrs, acc_o) + else: + tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim) + else: + if EVEN_HEADDIM: + tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q) + else: + tl.store( + out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim) + ) + + +@triton.jit +def _bwd_preprocess_do_o_dot( + Out, + DO, + Delta, + stride_ob, + stride_oh, + stride_om, + stride_dob, + stride_doh, + stride_dom, + nheads, + seqlen_q, + seqlen_q_rounded, + headdim, + BLOCK_M: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, +): + start_m = tl.program_id(0) + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_d = tl.arange(0, BLOCK_HEADDIM) + # load + o = tl.load( + Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], + mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ).to(tl.float32) + do = tl.load( + DO + + off_b * stride_dob + + off_h * stride_doh + + offs_m[:, None] * stride_dom + + offs_d[None, :], + mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ).to(tl.float32) + delta = tl.sum(o * do, axis=1) + # write-back + tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta) + + +@triton.jit +def _bwd_store_dk_dv( + dk_ptrs, + dv_ptrs, + dk, + dv, + offs_n, + offs_d, + seqlen_k, + headdim, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, +): + # [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False, + # if we just call tl.store(dv_ptrs), there's a race condition + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + tl.store(dv_ptrs, dv) + tl.store(dk_ptrs, dk) + else: + tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim) + tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim) + else: + if EVEN_HEADDIM: + tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k) + tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k) + else: + tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) + tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) + + +@triton.jit +def _bwd_kernel_one_col_block( + start_n, + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qm, + stride_kn, + stride_vn, + stride_bm, + stride_dom, + stride_dqm, + stride_dkn, + stride_dvn, + seqlen_q, + seqlen_k, + headdim, + ATOMIC_ADD: tl.constexpr, + BIAS_TYPE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + # We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N) + begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M + # initialize row/col offsets + offs_qm = begin_m + tl.arange(0, BLOCK_M) + offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) + offs_m = tl.arange(0, BLOCK_M) + offs_d = tl.arange(0, BLOCK_HEADDIM) + # initialize pointers to value-like data + q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :]) + k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :]) + v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :]) + do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :]) + dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :]) + if BIAS_TYPE == "vector": + b_ptrs = Bias + offs_n + elif BIAS_TYPE == "matrix": + b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :]) + # initialize dv and dk + dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) + dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) + # There seems to be some problem with Triton pipelining that makes results wrong for + # headdim=64, seqlen=(113, 255), bias_type='matrix'. In this case the for loop + # may have zero step, and pipelining with the bias matrix could screw it up. + # So we just exit early. + if begin_m >= seqlen_q: + dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) + dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) + _bwd_store_dk_dv( + dk_ptrs, + dv_ptrs, + dk, + dv, + offs_n, + offs_d, + seqlen_k, + headdim, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + ) + return + # k and v stay in SRAM throughout + # [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False, + # if we just call tl.load(k_ptrs), we get the wrong output! + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + k = tl.load(k_ptrs) + v = tl.load(v_ptrs) + else: + k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) + v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) + else: + k = tl.load( + k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0 + ) + v = tl.load( + v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0 + ) + # loop over rows + num_block_m = tl.cdiv(seqlen_q, BLOCK_M) + for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M): + start_m = tl.multiple_of(start_m, BLOCK_M) + offs_m_curr = start_m + offs_m + # load q, k, v, do on-chip + # Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117) + if EVEN_M & EVEN_HEADDIM: + q = tl.load(q_ptrs) + else: + if EVEN_HEADDIM: + q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0) + else: + q = tl.load( + q_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ) + # recompute p = softmax(qk, dim=-1).T + qk = tl.dot(q, k, trans_b=True) + # Trying to combine the two masks seem to make the result wrong + if not EVEN_N: # Need to mask out otherwise the softmax is wrong + qk = tl.where(offs_n[None, :] < seqlen_k, qk, float("-inf")) + if IS_CAUSAL: + qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf")) + if BIAS_TYPE != "none": + tl.debug_barrier() # Race condition otherwise + if BIAS_TYPE == "vector": + if EVEN_N: + bias = tl.load(b_ptrs).to(tl.float32) + else: + bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32) + bias = bias[None, :] + elif BIAS_TYPE == "matrix": + if EVEN_M & EVEN_N: + bias = tl.load(b_ptrs).to(tl.float32) + else: + bias = tl.load( + b_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), + other=0.0, + ).to(tl.float32) + qk = qk * softmax_scale + bias + # There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong. + # Also wrong for headdim=64. + if not (EVEN_M & EVEN_HEADDIM): + tl.debug_barrier() + lse_i = tl.load(LSE + offs_m_curr) + if BIAS_TYPE == "none": + p = tl.exp(qk * softmax_scale - lse_i[:, None]) + else: + p = tl.exp(qk - lse_i[:, None]) + # compute dv + # [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call + # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs + # in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512, + # the output is correct. + if EVEN_M & EVEN_HEADDIM: + do = tl.load(do_ptrs) + else: + # [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask. + do = tl.load( + do_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ) + # if EVEN_M: + # if EVEN_HEADDIM: + # do = tl.load(do_ptrs) + # else: + # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + # else: + # if EVEN_HEADDIM: + # do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0) + # else: + # do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) + # & (offs_d[None, :] < headdim), other=0.0) + dv += tl.dot(p.to(do.dtype), do, trans_a=True) + # compute dp = dot(v, do) + # There seems to be a race condition when headdim=48/96, and dq, dk are wrong. + # Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True + # Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False + if not (EVEN_M & EVEN_HEADDIM): + tl.debug_barrier() + dp = tl.dot(do, v, trans_b=True) + # There's a race condition for headdim=48 + if not EVEN_HEADDIM: + tl.debug_barrier() + # compute ds = p * (dp - delta[:, None]) + # Putting the subtraction after the dp matmul (instead of before) is slightly faster + Di = tl.load(D + offs_m_curr) + # Converting ds to q.dtype here reduces register pressure and makes it much faster + # for BLOCK_HEADDIM=128 + ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype) + # compute dk = dot(ds.T, q) + dk += tl.dot(ds, q, trans_a=True) + # compute dq + if not ( + EVEN_M & EVEN_HEADDIM + ): # Otherewise there's a race condition when BIAS_TYPE='matrix' + tl.debug_barrier() + if not ATOMIC_ADD: + if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M + dq = tl.load(dq_ptrs, eviction_policy="evict_last") + dq += tl.dot(ds, k) + tl.store(dq_ptrs, dq, eviction_policy="evict_last") + else: + if EVEN_HEADDIM: + dq = tl.load( + dq_ptrs, + mask=offs_m_curr[:, None] < seqlen_q, + other=0.0, + eviction_policy="evict_last", + ) + dq += tl.dot(ds, k) + tl.store( + dq_ptrs, + dq, + mask=offs_m_curr[:, None] < seqlen_q, + eviction_policy="evict_last", + ) + else: + dq = tl.load( + dq_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + eviction_policy="evict_last", + ) + dq += tl.dot(ds, k) + tl.store( + dq_ptrs, + dq, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + eviction_policy="evict_last", + ) + else: # If we're parallelizing across the seqlen_k dimension + dq = tl.dot(ds, k) + if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M + tl.atomic_add(dq_ptrs, dq) + else: + if EVEN_HEADDIM: + tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q) + else: + tl.atomic_add( + dq_ptrs, + dq, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + ) + # increment pointers + dq_ptrs += BLOCK_M * stride_dqm + q_ptrs += BLOCK_M * stride_qm + do_ptrs += BLOCK_M * stride_dom + if BIAS_TYPE == "matrix": + b_ptrs += BLOCK_M * stride_bm + # write-back + dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) + dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) + _bwd_store_dk_dv( + dk_ptrs, + dv_ptrs, + dk, + dv, + offs_n, + offs_d, + seqlen_k, + headdim, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + ) + + +def init_to_zero(name): + return lambda nargs: nargs[name].zero_() + + +@triton.autotune( + configs=[ + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": False}, + num_warps=8, + num_stages=1, + pre_hook=init_to_zero("DQ"), + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": True}, + num_warps=8, + num_stages=1, + pre_hook=init_to_zero("DQ"), + ), + # Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now + # # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4* + # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), + # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), + # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')), + # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')), + ], + key=["CACHE_KEY_SEQLEN_Q", "CACHE_KEY_SEQLEN_K", "BIAS_TYPE", "IS_CAUSAL", "BLOCK_HEADDIM"], +) +@triton.heuristics( + { + "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0, + "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0, + "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"], + } +) +@triton.jit +def _bwd_kernel( + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qb, + stride_qh, + stride_qm, + stride_kb, + stride_kh, + stride_kn, + stride_vb, + stride_vh, + stride_vn, + stride_bb, + stride_bh, + stride_bm, + stride_dob, + stride_doh, + stride_dom, + stride_dqb, + stride_dqh, + stride_dqm, + stride_dkb, + stride_dkh, + stride_dkn, + stride_dvb, + stride_dvh, + stride_dvn, + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + headdim, + CACHE_KEY_SEQLEN_Q, + CACHE_KEY_SEQLEN_K, + BIAS_TYPE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, + SEQUENCE_PARALLEL: tl.constexpr, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + # offset pointers for batch/head + Q += off_b * stride_qb + off_h * stride_qh + K += off_b * stride_kb + off_h * stride_kh + V += off_b * stride_vb + off_h * stride_vh + DO += off_b * stride_dob + off_h * stride_doh + DQ += off_b * stride_dqb + off_h * stride_dqh + DK += off_b * stride_dkb + off_h * stride_dkh + DV += off_b * stride_dvb + off_h * stride_dvh + if BIAS_TYPE != "none": + Bias += off_b * stride_bb + off_h * stride_bh + # pointer to row-wise quantities in value-like data + D += off_hb * seqlen_q_rounded + LSE += off_hb * seqlen_q_rounded + if not SEQUENCE_PARALLEL: + num_block_n = tl.cdiv(seqlen_k, BLOCK_N) + for start_n in range(0, num_block_n): + _bwd_kernel_one_col_block( + start_n, + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qm, + stride_kn, + stride_vn, + stride_bm, + stride_dom, + stride_dqm, + stride_dkn, + stride_dvn, + seqlen_q, + seqlen_k, + headdim, + ATOMIC_ADD=False, + BIAS_TYPE=BIAS_TYPE, + IS_CAUSAL=IS_CAUSAL, + BLOCK_HEADDIM=BLOCK_HEADDIM, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + ) + else: + start_n = tl.program_id(0) + _bwd_kernel_one_col_block( + start_n, + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qm, + stride_kn, + stride_vn, + stride_bm, + stride_dom, + stride_dqm, + stride_dkn, + stride_dvn, + seqlen_q, + seqlen_k, + headdim, + ATOMIC_ADD=True, + BIAS_TYPE=BIAS_TYPE, + IS_CAUSAL=IS_CAUSAL, + BLOCK_HEADDIM=BLOCK_HEADDIM, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + ) + + +def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None): + # shape constraints + batch, seqlen_q, nheads, d = q.shape + _, seqlen_k, _, _ = k.shape + assert k.shape == (batch, seqlen_k, nheads, d) + assert v.shape == (batch, seqlen_k, nheads, d) + assert d <= 128, "FlashAttention only support head dimensions up to 128" + assert q.dtype == k.dtype == v.dtype, "All tensors must have the same type" + assert q.dtype in [torch.float16, torch.bfloat16], "Only support fp16 and bf16" + assert q.is_cuda and k.is_cuda and v.is_cuda + softmax_scale = softmax_scale or 1.0 / math.sqrt(d) + + has_bias = bias is not None + bias_type = "none" + if has_bias: + assert bias.dtype in [q.dtype, torch.float] + assert bias.is_cuda + assert bias.dim() == 4 + if bias.stride(-1) != 1: + bias = bias.contiguous() + if bias.shape[2:] == (1, seqlen_k): + bias_type = "vector" + elif bias.shape[2:] == (seqlen_q, seqlen_k): + bias_type = "matrix" + else: + raise RuntimeError( + "Last 2 dimensions of bias must be (1, seqlen_k)" " or (seqlen_q, seqlen_k)" + ) + bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) + bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) + + seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 + lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) + tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) + o = torch.empty_like(q) + + BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) + BLOCK = 128 + num_warps = 4 if d <= 64 else 8 + grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads) + _fwd_kernel[grid]( + q, + k, + v, + bias, + o, + lse, + tmp, + softmax_scale, + q.stride(0), + q.stride(2), + q.stride(1), + k.stride(0), + k.stride(2), + k.stride(1), + v.stride(0), + v.stride(2), + v.stride(1), + *bias_strides, + o.stride(0), + o.stride(2), + o.stride(1), + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + d, + seqlen_q // 32, + seqlen_k // 32, # key for triton cache (limit number of compilations) + # Can't use kwargs here because triton autotune expects key to be args, not kwargs + # IS_CAUSAL=causal, BLOCK_HEADDIM=d, + bias_type, + causal, + BLOCK_HEADDIM, + BLOCK_M=BLOCK, + BLOCK_N=BLOCK, + num_warps=num_warps, + num_stages=1, + ) + return o, lse, softmax_scale # softmax_scale could have been updated + + +def _flash_attn_backward( + do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None +): + # Make sure that the last dimension is contiguous + if do.stride(-1) != 1: + do = do.contiguous() + batch, seqlen_q, nheads, d = q.shape + _, seqlen_k, _, _ = k.shape + # assert d in {16, 32, 64, 128} + assert d <= 128 + seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 + assert lse.shape == (batch, nheads, seqlen_q_rounded) + assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1 + assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1 + softmax_scale = softmax_scale or 1.0 / math.sqrt(d) + # dq_accum = torch.zeros_like(q, dtype=torch.float32) + dq_accum = torch.empty_like(q, dtype=torch.float32) + delta = torch.empty_like(lse) + # delta = torch.zeros_like(lse) + + BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) + grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads) + _bwd_preprocess_do_o_dot[grid]( + o, + do, + delta, + o.stride(0), + o.stride(2), + o.stride(1), + do.stride(0), + do.stride(2), + do.stride(1), + nheads, + seqlen_q, + seqlen_q_rounded, + d, + BLOCK_M=128, + BLOCK_HEADDIM=BLOCK_HEADDIM, + ) + + has_bias = bias is not None + bias_type = "none" + if has_bias: + assert bias.dtype in [q.dtype, torch.float] + assert bias.is_cuda + assert bias.dim() == 4 + assert bias.stride(-1) == 1 + if bias.shape[2:] == (1, seqlen_k): + bias_type = "vector" + elif bias.shape[2:] == (seqlen_q, seqlen_k): + bias_type = "matrix" + else: + raise RuntimeError( + "Last 2 dimensions of bias must be (1, seqlen_k)" " or (seqlen_q, seqlen_k)" + ) + bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) + bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) + + # BLOCK_M = 128 + # BLOCK_N = 64 + # num_warps = 4 + grid = lambda META: ( + triton.cdiv(seqlen_k, META["BLOCK_N"]) if META["SEQUENCE_PARALLEL"] else 1, + batch * nheads, + ) + _bwd_kernel[grid]( + q, + k, + v, + bias, + do, + dq_accum, + dk, + dv, + lse, + delta, + softmax_scale, + q.stride(0), + q.stride(2), + q.stride(1), + k.stride(0), + k.stride(2), + k.stride(1), + v.stride(0), + v.stride(2), + v.stride(1), + *bias_strides, + do.stride(0), + do.stride(2), + do.stride(1), + dq_accum.stride(0), + dq_accum.stride(2), + dq_accum.stride(1), + dk.stride(0), + dk.stride(2), + dk.stride(1), + dv.stride(0), + dv.stride(2), + dv.stride(1), + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + d, + seqlen_q // 32, + seqlen_k // 32, # key for triton cache (limit number of compilations) + # Can't use kwargs here because triton autotune expects key to be args, not kwargs + # IS_CAUSAL=causal, BLOCK_HEADDIM=d, + bias_type, + causal, + BLOCK_HEADDIM, + # SEQUENCE_PARALLEL=False, + # BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, + # num_warps=num_warps, + # num_stages=1, + ) + dq.copy_(dq_accum) + + +class FlashAttnQKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None): + """ + qkv: (batch, seqlen, 3, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen). + ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen) + """ + # Make sure that the last dimension is contiguous + if qkv.stride(-1) != 1: + qkv = qkv.contiguous() + o, lse, ctx.softmax_scale = _flash_attn_forward( + qkv[:, :, 0], + qkv[:, :, 1], + qkv[:, :, 2], + bias=bias, + causal=causal, + softmax_scale=softmax_scale, + ) + ctx.save_for_backward(qkv, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + qkv, o, lse, bias = ctx.saved_tensors + assert not ctx.needs_input_grad[1], "FlashAttention does not support bias gradient yet" + # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd + # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version. + with torch.inference_mode(): + dqkv = torch.empty_like(qkv) + _flash_attn_backward( + do, + qkv[:, :, 0], + qkv[:, :, 1], + qkv[:, :, 2], + o, + lse, + dqkv[:, :, 0], + dqkv[:, :, 1], + dqkv[:, :, 2], + bias=bias, + causal=ctx.causal, + softmax_scale=ctx.softmax_scale, + ) + return dqkv, None, None, None + + +flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply + + +class FlashAttnKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None): + """ + q: (batch, seqlen_q, nheads, headdim) + kv: (batch, seqlen_k, 2, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). + ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) + """ + # Make sure that the last dimension is contiguous + q, kv = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]] + o, lse, ctx.softmax_scale = _flash_attn_forward( + q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale + ) + ctx.save_for_backward(q, kv, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + q, kv, o, lse, bias = ctx.saved_tensors + if len(ctx.needs_input_grad) >= 3: + assert not ctx.needs_input_grad[2], "FlashAttention does not support bias gradient yet" + # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd + # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version. + with torch.inference_mode(): + dq = torch.empty_like(q) + dkv = torch.empty_like(kv) + _flash_attn_backward( + do, + q, + kv[:, :, 0], + kv[:, :, 1], + o, + lse, + dq, + dkv[:, :, 0], + dkv[:, :, 1], + bias=bias, + causal=ctx.causal, + softmax_scale=ctx.softmax_scale, + ) + return dq, dkv, None, None, None + + +flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply + + +class FlashAttnFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None): + """ + q: (batch_size, seqlen_q, nheads, headdim) + k, v: (batch_size, seqlen_k, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). + ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) + """ + # Make sure that the last dimension is contiguous + q, k, v = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]] + o, lse, ctx.softmax_scale = _flash_attn_forward( + q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale + ) + ctx.save_for_backward(q, k, v, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + q, k, v, o, lse, bias = ctx.saved_tensors + assert not ctx.needs_input_grad[3], "FlashAttention does not support bias gradient yet" + # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd + # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version. + with torch.inference_mode(): + dq = torch.empty_like(q) + dk = torch.empty_like(k) + dv = torch.empty_like(v) + _flash_attn_backward( + do, + q, + k, + v, + o, + lse, + dq, + dk, + dv, + bias=bias, + causal=ctx.causal, + softmax_scale=ctx.softmax_scale, + ) + return dq, dk, dv, None, None, None + + +flash_attn_func = FlashAttnFunc.apply diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__init__.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4e3e9d12390f4c30c6a93d97106756f1d72c3f5 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bench.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bench.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..082caa7b00bc925f4f1f752801ed7fd191d7ee55 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bench.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e00ba3c6b218b066afbfc097edb06fbe4adb5d04 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bwd_ref.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bwd_ref.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d504573ec007290a5186dee13ca0516c92a9db16 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/bwd_ref.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_decode.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_decode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63da9fc75c8736e8ef920f37b1db90e2b24ea55c Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_decode.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_prefill.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_prefill.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14f821d61f8a9766b18bca6b00906198a983095f Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_prefill.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_ref.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_ref.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4820dccb75cba43f04d3e7bd04b1b5f2da3fefb Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/fwd_ref.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/interface_fa.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/interface_fa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1cb57ec6563c11766278e0245f5f4021b5f3880 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/interface_fa.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/interface_torch.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/interface_torch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f13b162534bd7553da12b788dae2df3d1373318 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/interface_torch.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/test.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f2148a412f43a19b81d47fb02a089ea4c3da46e Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/test.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/utils.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9749242cfd69a37b1f531257b671c42b14cf8806 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/__pycache__/utils.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bench.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bench.py new file mode 100644 index 0000000000000000000000000000000000000000..91939f831f06396f5b4f7aa2ac3dfecba6b72b23 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bench.py @@ -0,0 +1,290 @@ +import argparse +import torch +import triton +from flash_attn.flash_attn_triton_amd.utils import ( + MetaData, + input_helper, + varlen_input_helper, +) +from flash_attn.flash_attn_triton_amd.interface_torch import attention_prefill, attention_decode + +ARGS_TO_TORCH_DTYPE = { + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32, +} + +FUNCTIONS = { + "prefill": attention_prefill, + "decode": attention_decode +} + +def get_benchmark_configs(args, varlen=False): + """ + Returns benchmark configurations based on whether variable-length sequences are used. + """ + if args.custom_config: + hk = args.hq if not args.hk else args.hk + sk = args.sq if not args.sk else args.sk + return [(args.b, args.hq, hk, args.sq, sk)] + elif varlen: + return [ + (2, 16, 4, 1024, 1024), + (8, 16, 2, 2048, 2048), + (4, 16, 8, 4096, 4096), + (2, 16, 4, 8192, 8192), + (2, 16, 8, 16384, 16384), + (2, 48, 12, 1024, 1024), + (2, 48, 24, 2048, 2048), + (2, 48, 8, 4096, 4096), + (2, 48, 4, 8192, 8192), + (2, 48, 2, 16384, 16384), + (2, 64, 32, 1024, 1024), + (4, 64, 16, 2048, 2048), + (4, 64, 8, 4096, 4096), + (4, 64, 32, 8192, 8192), + (4, 128, 16, 16384, 16384), + ] + else: + return [ + (16, 16, 16, 1024, 1024), + (8, 16, 16, 2048, 2048), + (4, 16, 16, 4096, 4096), + (1, 8, 8, 8192, 8192), + (1, 2, 2, 16384, 16384), + (2, 48, 48, 1024, 1024), + (2, 48, 48, 2048, 1024), + (1, 8, 8, 4096, 8192), + (1, 8, 8, 8192, 4096), + (2, 4, 4, 16384, 8192), + (2, 8, 8, 1989, 15344), + (4, 16, 16, 4097, 163), + (2, 16, 16, 8122, 2159), + (1, 16, 16, 16281, 7), + (2, 48, 48, 1021, 1020), + (2, 48, 48, 2001, 2048), + (2, 8, 8, 3996, 9639), + (2, 8, 8, 8181, 1021), + ] + +def gen_fn_inputs(fn_name, BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, device, layout, causal): + flops_per_matmul = 0 + + if fn_name.startswith("prefill"): + if layout == "thd": + q, k, v, input_metadata = varlen_input_helper( + BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, device=device) + for i in range(input_metadata.num_contexts): + seqlen_q = input_metadata.cu_seqlens_q[i + 1] - input_metadata.cu_seqlens_q[i] + seqlen_k = input_metadata.cu_seqlens_k[i + 1] - input_metadata.cu_seqlens_k[i] + flops_per_matmul += seqlen_q.item() * seqlen_k.item() * HQ * D_HEAD * 2 + else: + q, k, v, input_metadata = input_helper( + BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, layout, device=device + ) + flops_per_matmul = 2.0 * BATCH * HQ * N_CTX_Q * N_CTX_K * D_HEAD + + if causal: + input_metadata.need_causal() + + o = torch.empty_like(q) + input_data = (q, k, v, o, input_metadata) + elif fn_name.startswith("decode"): + q = torch.randn( + [BATCH, N_CTX_Q, HK, HQ // HK, D_HEAD], + device=device, + dtype=dtype, + requires_grad=False, + ) + k = torch.randn( + [BATCH, N_CTX_K, HK, 1, D_HEAD], + device=device, + dtype=dtype, + requires_grad=False, + ).expand(-1, -1, -1, HQ // HK, -1) + v = torch.randn( + [BATCH, N_CTX_K, HK, 1, D_HEAD], + device=device, + dtype=dtype, + requires_grad=False, + ).expand(-1, -1, -1, HQ // HK, -1) + input_metadata = MetaData(sm_scale=1.3) + input_metadata.layout = "bsghd" + + # Adjust flops calculation if needed + flops_per_matmul = 2.0 * BATCH * HQ * N_CTX_Q * N_CTX_K * D_HEAD + + input_data = (q, k, v, input_metadata) + else: + raise ValueError("Unsupported benchmark function") + return input_data, flops_per_matmul + +def run_benchmark(args, fn_name, fn, mode): + """ + Runs the benchmark for the provided function based on the provided arguments. + """ + print(f"Benchmarking {fn_name} in {mode} mode...") + + dtype = ARGS_TO_TORCH_DTYPE[args.dtype] + head_size = args.d if args.d else 128 + causal = args.causal + varlen = args.layout == "thd" + return_tflops = args.return_tflops + line_names = "TFLOPS" if return_tflops else "Time (ms)" + + # Determine configurations + x_vals_list = get_benchmark_configs(args, varlen=varlen) + + # Setup benchmark configurations + configs = [ + triton.testing.Benchmark( + x_names=["BATCH", "HQ", "HK", "N_CTX_Q", "N_CTX_K"], + x_vals=x_vals_list, + line_arg="provider", + line_vals=["triton"], + line_names=[line_names], + styles=[("red", "-")], + ylabel="ms", + plot_name=f"benchmark-{fn_name}-d{head_size}-layout{args.layout}-mode{mode}", + args={ + "D_HEAD": head_size, + "dtype": dtype, + "causal": causal, + "mode": mode, + }, + ) + ] + + @triton.testing.perf_report(configs) + def bench_function( + BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, causal, mode, provider, device="cuda" + ): + warmup = 25 + rep = 100 + flops_per_matmul = 0 + + # generate function inputs + fn_inputs, flops_per_matmul = gen_fn_inputs( + fn_name, BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, device, args.layout, causal + ) + + # define the function to benchmark + if mode == "fwd": + benchmark_fn = lambda: fn(*fn_inputs) + total_flops = 2 * flops_per_matmul + elif mode == "bwd": + outputs = fn(*fn_inputs) + output = outputs[0] + grad_output = torch.randn_like(output) + benchmark_fn = lambda: output.backward(grad_output, retain_graph=True) + total_flops = 2 * flops_per_matmul * 2.5 + else: + raise ValueError("Unsupported mode. Choose 'fwd' or 'bwd'.") + + if causal: + total_flops *= 0.5 + + # Run the benchmark + ms = triton.testing.do_bench(benchmark_fn, warmup=warmup, rep=rep) + + if return_tflops: + return total_flops / ms * 1e-9 + else: + return ms + + bench_function.run(save_path=".", print_data=True) + +def supported_layouts(): + """ + Returns a string describing the supported layouts. + """ + return ( + "bhsd: Q, K, V are individual tensors of [batch, num_heads, seqlen_q/k, head_size]\n" + "bshd: Q, K, V are individual tensors of [batch, seqlen_q/k, num_heads, head_size]\n" + "thd: Q, K, V are individual tensors of [total_q/k, num_heads, head_size]\n" + 'This layout is sometimes called "varlen" or "grouped" layout.' + ) + +def parse_args(): + """ + Parses command-line arguments. + """ + parser = argparse.ArgumentParser( + prog="Benchmark FlashAttention", + allow_abbrev=False, + ) + parser.add_argument("-b", type=int, default=0) + parser.add_argument("-hq", type=int, default=0) + parser.add_argument("-hk", type=int, default=0) + parser.add_argument("-sq", type=int, default=0) + parser.add_argument("-sk", type=int, default=0) + parser.add_argument( + "-equal_seqlens", + action="store_true", + default=False, + help="If specified, each context within the thd layout has same seqlen as sq and sk", + ) + parser.add_argument("-d", type=int, default=0) + parser.add_argument("-causal", action="store_true", default=False) + parser.add_argument("-dtype", default="fp16") + parser.add_argument("-return_tflops", action="store_true", default=False) + parser.add_argument( + "-layout", + type=str, + default="bhsd", + help=supported_layouts(), + ) + parser.add_argument( + "-benchmark_fn", + type=str, + nargs="*", + choices=FUNCTIONS.keys(), + help="Function(s) to benchmark: prefill, decode, or both", + ) + parser.add_argument( + "-mode", + type=str, + nargs='*', + default=["fwd", "bwd"], + choices=["fwd", "bwd"], + help="Mode(s) to run: 'fwd' for forward pass, 'bwd' for backward pass", + ) + return parser.parse_args() + +def main(): + """ + Main function to run benchmarks. + """ + args = parse_args() + + # Validate arguments + assert ( + args.layout == "thd" or not args.equal_seqlens + ), "Equal sequence lengths arg must be used with the thd layout." + args.custom_config = False + if args.b or args.hq or args.hk or args.sq or args.sk or args.d: + args.custom_config = True + assert args.b and args.hq and args.sq and args.d, ( + "If custom config is specified, please provide all of batch, " + "number of Q heads, Q sequence length, and head size." + ) + assert args.dtype in ARGS_TO_TORCH_DTYPE, "Only fp16, bf16 and fp32 types currently supported." + + # determine the functions to benchmark + if args.benchmark_fn is None or len(args.benchmark_fn) == 0: + bench_fn_list = FUNCTIONS.keys() + else: + bench_fn_list = args.benchmark_fn + + # benchmark functions + for fn_name in bench_fn_list: + if fn_name not in FUNCTIONS: + raise ValueError(f"Invalid benchmark function specified: {fn_name}") + for mode in args.mode: + if fn_name == "decode" and mode == "bwd": + print(f"Decode kernel doesnot have a backward pass") + continue + run_benchmark(args, fn_name, FUNCTIONS[fn_name], mode) + +if __name__ == "__main__": + main() diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bwd_prefill.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bwd_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..84212235a64924b4baf2817173f585c7b4991af4 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bwd_prefill.py @@ -0,0 +1,691 @@ +import torch +import triton +import triton.language as tl +from .utils import get_shape_from_layout, get_strides_from_layout, DEBUG, PERF + +@triton.jit +def _bwd_preprocess_use_o( + Out, + DO, + Delta, + stride_oz, stride_oh, stride_om, stride_ok, + stride_doz, stride_doh, stride_dom, stride_dok, + stride_deltaz, stride_deltah, stride_deltam, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + N_CTX_Q: tl.constexpr, + Z: tl.constexpr, + H: tl.constexpr, + IS_VARLEN: tl.constexpr +): + pid_m = tl.program_id(0) + pid_bh = tl.program_id(1) + + # Compute batch and head indices + off_z = pid_bh // H + off_h = pid_bh % H + + if IS_VARLEN: + # Compute sequence lengths for the current batch + q_start = tl.load(cu_seqlens_q + off_z) + q_end = tl.load(cu_seqlens_q + off_z + 1) + k_start = tl.load(cu_seqlens_k + off_z) + k_end = tl.load(cu_seqlens_k + off_z + 1) + + # Compute actual sequence lengths + N_CTX_Q = q_end - q_start + N_CTX_K = k_end - k_start + else: + q_start = 0 + k_start = 0 + N_CTX_Q = max_seqlen_q + N_CTX_K = max_seqlen_k + + off_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + off_d = tl.arange(0, BLOCK_DMODEL) + + # create masks + mask_m = off_m < N_CTX_Q + mask_d = off_d < ACTUAL_BLOCK_DMODEL + + # compute offsets + o_offset = Out + off_z * stride_oz + off_h * stride_oh + q_start * stride_om + do_offset = DO + off_z * stride_oz + off_h * stride_oh + q_start * stride_om + + # compute pointers + out_ptrs = o_offset + off_m[:, None] * stride_om + off_d[None, :] * stride_ok + do_ptrs = do_offset + off_m[:, None] * stride_dom + off_d[None, :] * stride_dok + + # load + o = tl.load(out_ptrs, mask=mask_m[:, None] & mask_d[None, :], other=0.0).to(tl.float32) + do = tl.load(do_ptrs, mask=mask_m[:, None] & mask_d[None, :], other=0.0).to(tl.float32) + + # compute delta + delta = tl.sum(o * do, axis=1) + + # write-back delta + delta_offset = Delta + off_z * stride_deltaz + off_h * stride_deltah + q_start * stride_deltam + delta_ptrs = delta_offset + off_m * stride_deltam + tl.store(delta_ptrs, delta, mask=mask_m) + + +@triton.jit +def _bwd_kernel_one_col_block( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + D, + q_offset, + k_offset, + v_offset, + do_offset, + dq_offset, + dk_offset, + dv_offset, + d_offset, + l_offset, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + Z, + H, + N_CTX_Q, + N_CTX_K, + off_h, + off_z, + off_hz, + start_n, + num_block_m, + num_block_n, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, + SEQUENCE_PARALLEL: tl.constexpr, + CAUSAL: tl.constexpr, + USE_EXP2: tl.constexpr, +): + if CAUSAL: + # TODO: Causal can skip more blocks with something like lo = start_m * BLOCK_M + lo = 0 + else: + lo = 0 + + # initialize col and head offsets + offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + + # masks + mask_n = offs_n < N_CTX_K + mask_d = offs_d < ACTUAL_BLOCK_DMODEL + kv_mask = mask_n[:, None] & mask_d[None, :] + + + # initialize grad accumulators + dv = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) + dk = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) + + # load k and v once per column block + k_ptrs = k_offset + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk + v_ptrs = v_offset + offs_n[:, None] * stride_vn + offs_d[None, :] * stride_vk + k = tl.load(k_ptrs, mask=kv_mask, other=0.0) + v = tl.load(v_ptrs, mask=kv_mask, other=0.0) + + # loop over rows + for start_m in range(lo, num_block_m * BLOCK_M, BLOCK_M): + offs_m = start_m + tl.arange(0, BLOCK_M) + q_ptrs = q_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + dq_ptrs = dq_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + do_ptrs = do_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + + # update mask as row block changes + mask_m = offs_m < N_CTX_Q + q_mask = mask_m[:, None] & mask_d[None, :] + + # load q, k, v, do on-chip + q = tl.load(q_ptrs, mask=q_mask, other=0.0) + do = tl.load(do_ptrs, mask=q_mask, other=0.0) + + # recompute p = softmax(qk, dim=-1).T + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, tl.trans(k)) + + if CAUSAL: + col_offset = N_CTX_Q - N_CTX_K + causal_mask = offs_m[:, None] >= (col_offset + offs_n[None, :]) + qk = tl.where(causal_mask, qk, float("-inf")) + + l_ptrs = l_offset + offs_m * stride_deltam + l_i = tl.load(l_ptrs, mask=mask_m) + + # compute p + if USE_EXP2: + RCP_LN2: tl.constexpr = 1.4426950408889634 + qk *= sm_scale * RCP_LN2 + l_i *= RCP_LN2 + p = tl.math.exp2(qk - l_i[:, None]) + else: + qk *= sm_scale + p = tl.math.exp(qk - l_i[:, None]) + + # mask block in the cases where the data is smaller the block size + p_mask = mask_m[:, None] & mask_n[None, :] + p = tl.where(p_mask, p, 0.0) + + # compute dv + dv += tl.dot(tl.trans(p.to(Q.dtype.element_ty)), do) + + # compute dp + dp = tl.dot(do, tl.trans(v)) + + # compute ds , ds = p * (dp - delta[:, None]) + d_ptrs = d_offset + offs_m * stride_deltam + Di = tl.load(d_ptrs, mask=mask_m) + ds = (p * (dp - Di[:, None])) * sm_scale + ds = tl.where(p_mask, ds, 0.0).to(Q.dtype.element_ty) + + # compute dk = dot(ds.T, q) + dk += tl.dot(tl.trans(ds), q) + + # compute dq + if SEQUENCE_PARALLEL: + dq = tl.dot(ds, k) + else: + dq = tl.load(dq_ptrs, mask=q_mask, other=0.0) + dq += tl.dot(ds, k) + tl.store(dq_ptrs, dq.to(Q.dtype.element_ty), mask=q_mask) + + # write-back dv and dk + dk_ptrs = dk_offset + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk + dv_ptrs = dv_offset + offs_n[:, None] * stride_vn + offs_d[None, :] * stride_vk + + # write-back + tl.store(dk_ptrs, dk.to(K.dtype.element_ty), mask=kv_mask) + tl.store(dv_ptrs, dv.to(V.dtype.element_ty), mask=kv_mask) + +@triton.jit +def _bwd_kernel( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + D, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + Z, + H, + num_block_m, + num_block_n, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, + SEQUENCE_PARALLEL: tl.constexpr, + CAUSAL: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_VARLEN: tl.constexpr, +): + # program ids + off_hz = tl.program_id(0) + if SEQUENCE_PARALLEL: + start_n = tl.program_id(1) + off_z = off_hz // H + off_h = off_hz % H + + if IS_VARLEN: + # Compute sequence lengths for the current batch + q_start = tl.load(cu_seqlens_q + off_z) + q_end = tl.load(cu_seqlens_q + off_z + 1) + k_start = tl.load(cu_seqlens_k + off_z) + k_end = tl.load(cu_seqlens_k + off_z + 1) + + # Compute actual sequence lengths + N_CTX_Q = q_end - q_start + N_CTX_K = k_end - k_start + else: + q_start = 0 + k_start = 0 + N_CTX_Q = max_seqlen_q + N_CTX_K = max_seqlen_k + + + # input tensor offsets + q_offset = Q + off_z * stride_qz + off_h * stride_qh + q_start * stride_qm + k_offset = K + off_z * stride_kz + off_h * stride_kh + k_start * stride_kn + v_offset = V + off_z * stride_vz + off_h * stride_vh + k_start * stride_vn + do_offset = DO + off_z * stride_qz + off_h * stride_qh + q_start * stride_qm + l_offset = L + off_z * stride_deltaz + off_h * stride_deltah + q_start * stride_deltam + d_offset = D + off_z * stride_deltaz + off_h * stride_deltah + q_start * stride_deltam + + # output tensor offsets + dk_offset = DK + off_z * stride_kz + off_h * stride_kh + k_start * stride_kn + dv_offset = DV + off_z * stride_vz + off_h * stride_vh + k_start * stride_vn + if SEQUENCE_PARALLEL: + dq_offset = DQ + start_n * stride_dq_all + off_z * stride_qz + off_h * stride_qh + q_start * stride_qm + else: + dq_offset = DQ + off_z * stride_qz + off_h * stride_qh + q_start * stride_qm + + # inner loop + if SEQUENCE_PARALLEL: + _bwd_kernel_one_col_block( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + D, + q_offset, + k_offset, + v_offset, + do_offset, + dq_offset, + dk_offset, + dv_offset, + d_offset, + l_offset, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + Z, + H, + N_CTX_Q, + N_CTX_K, + off_h, + off_z, + off_hz, + start_n, + num_block_m, + num_block_n, + BLOCK_M=BLOCK_M, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + BLOCK_N=BLOCK_N, + SEQUENCE_PARALLEL=SEQUENCE_PARALLEL, + CAUSAL=CAUSAL, + USE_EXP2=USE_EXP2, + ) + else: + for start_n in range(0, num_block_n): + _bwd_kernel_one_col_block( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + D, + q_offset, + k_offset, + v_offset, + do_offset, + dq_offset, + dk_offset, + dv_offset, + d_offset, + l_offset, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + Z, + H, + N_CTX_Q, + N_CTX_K, + off_h, + off_z, + off_hz, + start_n, + num_block_m, + num_block_n, + BLOCK_M=BLOCK_M, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + BLOCK_N=BLOCK_N, + SEQUENCE_PARALLEL=SEQUENCE_PARALLEL, + CAUSAL=CAUSAL, + USE_EXP2=USE_EXP2, + ) + + +# NOTE: smaller blocks have lower accuracy. more accumlation error probably 128 * 128 seems good but leads to oom. 64 * 64 has accumlation errors but no oom. +def attention_prefill_backward_triton_impl( + do, + q, + k, + v, + o, + softmax_lse, + dq, + dk, + dv, + sm_scale: float, + alibi_slopes, + causal, + layout: str, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q: int, + max_seqlen_k: int, + use_exp2: bool, + sequence_parallel = True, +): + if DEBUG: + print() + print("attention_prefill_backward_triton_new_impl") + print("do:", do, do.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("o:", o, o.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("dq:", dq, dq.shape if dq is not None else None) + print("dk:", dk, dk.shape if dk is not None else None) + print("dv:", dv, dv.shape if dv is not None else None) + print("sm_scale:", sm_scale) + print("alibi_slopes:", alibi_slopes) + print("causal:", causal) + print("layout:", layout) + print("cu_seqlens_q:", cu_seqlens_q) + print("cu_seqlens_k:", cu_seqlens_k) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("use_exp2:", use_exp2) + print("sequence_parallel:", sequence_parallel) + + # make contigious + q = q.contiguous() + k = k.contiguous() + v = v.contiguous() + softmax_lse = softmax_lse.contiguous() + + # get strides and shape + batch, nheads_q, nheads_k, head_size, max_seqlen_q, max_seqlen_k = get_shape_from_layout(q, k, layout, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) + q_strides, k_strides, v_strides, o_strides = get_strides_from_layout(q, k, v, o, layout) + stride_qz, stride_qh, stride_qm, stride_qk = q_strides + stride_kz, stride_kh, stride_kn, stride_kk = k_strides + stride_vz, stride_vh, stride_vn, stride_vk = v_strides + stride_oz, stride_oh, stride_om, stride_ok = o_strides + batch_headsize = batch * nheads_q + is_varlen = layout == "thd" + + # FIXME: some configs lead to oom for some reason when using 64 x 64 blocks + if max_seqlen_q <= 32 or max_seqlen_k <= 32: + BLOCK_M = 32 + BLOCK_N = 32 + else: + BLOCK_M = 64 + BLOCK_N = 64 + num_warps = 4 # NOTE: originial is 8. changing it to 1 caused issues be careful + num_stages = 1 + waves_per_eu = 1 + + # divide up the problem + num_blocks_m = triton.cdiv(max_seqlen_q, BLOCK_M) + num_blocks_n = triton.cdiv(max_seqlen_k, BLOCK_N) + + # get closest power of 2 over or equal to 32. + padded_d_model = 1 << (head_size - 1).bit_length() + padded_d_model = max(padded_d_model, 16) + BLOCK_DMODEL = padded_d_model + ACTUAL_BLOCK_DMODEL = head_size + + do = do.contiguous() + # NOTE: we might need to copy the output tensor if they are not continuous or have other issues + copy_back = {"dq": False, "dk": False, "dv": False} + + # deal with dq + if dq is None: + if sequence_parallel: + dq = torch.zeros((num_blocks_n,) + q.shape, device=q.device, dtype=q.dtype) + else: + dq = torch.zeros(q.shape, device=q.device, dtype=q.dtype) + else: + dq_og = dq + if (not dq.is_contiguous()): + dq = dq.contiguous() + copy_back["dq"] = True + + if sequence_parallel: + dq = torch.zeros((num_blocks_n,) + q.shape, device=q.device, dtype=q.dtype) + copy_back["dq"] = True + else: + # NOTE: the kernel does inplace accumlation so dq has to be zeros. This avoids the case where we are passed empty dq and it is not all zeros + dq.zero_() + stride_dq_all = dq.stride()[0] + + # deal with dk, dv + if (dk is None) or (dv is None): + dk = torch.empty_like(k) + dv = torch.empty_like(v) + else: + if (not dk.is_contiguous()): + dk_og = dk + dk = dk.contiguous() + copy_back["dk"] = True + + if (not dv.is_contiguous()): + dv_og = dv + dv = dv.contiguous() + copy_back["dv"] = True + + if DEBUG: + print("copy_back:", copy_back) + + # assert contigious + assert do.is_contiguous() + assert q.is_contiguous() + assert k.is_contiguous() + assert v.is_contiguous() + assert o.is_contiguous() + assert softmax_lse.is_contiguous() + + # init delta + delta = torch.empty_like(softmax_lse) + if is_varlen: + stride_deltam, stride_deltah = delta.stride() + stride_deltaz = 0 + else: + stride_deltaz, stride_deltah, stride_deltam = delta.stride() + + _bwd_preprocess_use_o[(num_blocks_m, batch_headsize)]( + o, + do, + delta, + stride_oz, stride_oh, stride_om, stride_ok, + stride_oz, stride_oh, stride_om, stride_ok, + stride_deltaz, stride_deltah, stride_deltam, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + BLOCK_M=BLOCK_M, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + N_CTX_Q=max_seqlen_q, + Z=batch, + H=nheads_q, + IS_VARLEN=is_varlen + ) + + if DEBUG: + print("_bwd_kernel inputs") + print("do:", do, do.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("sm_scale", sm_scale) + print("o:", o, o.shape) + print("dq:", dq, dq.shape) + print("dk:", dk, dk.shape) + print("dv:", dv, dv.shape) + print("L:", softmax_lse, softmax_lse.shape) + print("delta:", delta, delta.shape) + print("stride_qz, stride_qh, stride_qm, stride_qk:", stride_qz, stride_qh, stride_qm, stride_qk) + print("stride_kz, stride_kh, stride_kn, stride_kk:", stride_kz, stride_kh, stride_kn, stride_kk) + print("stride_vz, stride_vh, stride_vn, stride_vk:", stride_vz, stride_vh, stride_vn, stride_vk) + print("batch_q:", batch) + print("heads_q:",nheads_q) + print("max_seqlen_q:",max_seqlen_q) + print("max_seqlen_k:",max_seqlen_k) + print("BLOCK_M:",BLOCK_M) + print("BLOCK_N:",BLOCK_M) + print("BLOCK_DMODEL:",BLOCK_DMODEL) + print("ACTUAL_BLOCK_DMODEL:",ACTUAL_BLOCK_DMODEL) + print("SEQUENCE_PARALLEL:",sequence_parallel) + print("CAUSAL:",causal) + print("num_warps:",num_warps) + print("num_stages:", num_stages) + print("USE_EXP2:", use_exp2) + print("num_blocks_m:", num_blocks_m) + print("num_blocks_n:", num_blocks_n) + + _bwd_kernel[(batch_headsize, num_blocks_n if sequence_parallel else 1)]( + q, + k, + v, + sm_scale, + o, + do, + dq, + dk, + dv, + softmax_lse, + delta, + stride_dq_all, + stride_qz, stride_qh, stride_qm, stride_qk, + stride_kz, stride_kh, stride_kn, stride_kk, + stride_vz, stride_vh, stride_vn, stride_vk, + stride_deltaz, stride_deltah, stride_deltam, + batch, + nheads_q, + num_blocks_m, + num_blocks_n, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + SEQUENCE_PARALLEL=sequence_parallel, + CAUSAL=causal, + USE_EXP2=use_exp2, + num_warps=num_warps, + num_stages=num_stages, + waves_per_eu = waves_per_eu, + IS_VARLEN=is_varlen + ) + + if DEBUG: + print("_bwd_kernel outputs") + print("dq:", dq, dq.shape) + print("dk:", dk, dk.shape) + print("dv:", dv, dv.shape) + print("delta:", delta, delta.shape) + + if sequence_parallel: + dq = dq.sum(dim=0) + + if DEBUG: + print("attention_prefill_backward_triton_new_impl outputs") + print("dq:", dq, dq.shape) + print("dk:", dk, dk.shape) + print("dv:", dv, dv.shape) + print("delta:", delta, delta.shape) + print("copy_back:", copy_back) + + if copy_back["dq"]: + dq_og.copy_(dq) + dq = dq_og + if copy_back["dk"]: + dk_og.copy_(dk) + dk = dk_og + if copy_back["dv"]: + dv_og.copy_(dv) + dv = dv_og + + return dq, dk, dv, delta, None, None diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bwd_ref.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bwd_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea7c32bf7f788b1b8b97d4e6e9d6f6b7dd37b53 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/bwd_ref.py @@ -0,0 +1,328 @@ +import torch +import math +from .utils import DEBUG + +def attention_backward_core_ref_impl( + do, q, k, v, o, softmax_lse, sm_scale, causal, use_exp2 +): + if DEBUG: + print() + print("attention_backward_core_ref_impl") + print("do:", do, do.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("o:", o, o.shape) # is a bad number + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("sm_scale:", sm_scale) + print("causal:", causal) + print("use_exp2:", use_exp2) + + # cast to float32 + do = do.to(torch.float32) + q = q.to(torch.float32) + k = k.to(torch.float32) + v = v.to(torch.float32) + o = o.to(torch.float32) + softmax_lse = softmax_lse.to(torch.float32) + + + # recompute attention_scores. Make sure it matches the forward impl. i.e. It use float32 + attention_scores = torch.matmul(q.to(torch.float32), k.transpose(-2, -1).to(torch.float32)) + if DEBUG: + print("attention_scores:", attention_scores, attention_scores.shape) + + # scale scores + attention_scaled_scores = sm_scale * attention_scores + if DEBUG: + print("attention_scaled_scores:", attention_scaled_scores, attention_scaled_scores.shape) + + # Apply causal mask if necessary + if causal: + L_q, L_k = q.shape[1], k.shape[1] + row_idx = torch.arange(L_q, device=q.device).unsqueeze(1) + col_idx = torch.arange(L_k, device=q.device).unsqueeze(0) + col_offset = L_q-L_k + causal_mask = row_idx >= (col_offset + col_idx) + if DEBUG: + print("causal_mask:", causal_mask) + # set -inf to places the causal mask is false + attention_scaled_scores = attention_scaled_scores.masked_fill( + torch.logical_not(causal_mask.unsqueeze(0)), float('-inf') + ) + if DEBUG: + print("attention_scaled_scores after causal:", attention_scaled_scores, attention_scaled_scores.shape) + + # compute probabilities using softmax_lse + if use_exp2: + RCP_LN = 1 / math.log(2) + attention_scaled_scores_base2 = attention_scaled_scores * RCP_LN + softmax_lse_base2 = softmax_lse * RCP_LN + softmax_lse_3d = softmax_lse_base2.unsqueeze(-1) + p = torch.exp2(attention_scaled_scores_base2 - softmax_lse_3d) + else: + softmax_lse_3d = softmax_lse.unsqueeze(-1) + p = torch.exp(attention_scaled_scores - softmax_lse_3d) + + if DEBUG: + print("softmax_lse_3d:", softmax_lse_3d, softmax_lse_3d.shape) + print("p:", p, p.shape) + # compute gradient wrt v + dv = torch.matmul(p.transpose(-2, -1), do.to(torch.float32)) + if DEBUG: + print("dv:", dv, dv.shape) + + # compute dp + dp = torch.matmul(do, v.transpose(-2, -1)) + if DEBUG: + print("dp:", dp, dp.shape) + + # calculate ds using dp + if True: + delta = torch.sum(o * do, axis=-1).to(torch.float32) # what OAI kernel uses + delta_3d = delta.unsqueeze(-1) + else: + delta = torch.sum(p * dp, axis=-1) # what the math says you should use + delta_3d = delta.unsqueeze(-1) + if DEBUG: + print("delta_3d:", delta_3d, delta_3d.shape) + ds = (p * (dp - delta_3d)) * sm_scale + if DEBUG: + print("ds:", ds, ds.shape) + + + # compute gradient wrt k + dk = torch.matmul(ds.transpose(-2, -1), q.to(torch.float32)) + if DEBUG: + print("dk:", dk, dk.shape) + + # compute gradient wrt q + dq = torch.matmul(ds, k.to(torch.float32)) + if DEBUG: + print("dq:", dq, dq.shape) + + # cast back to original dtype + dq = dq.to(torch.float16) + dk = dk.to(torch.float16) + dv = dv.to(torch.float16) + + # remove d dim with size 1 + delta = delta_3d.squeeze(-1) + + if DEBUG: + print("attention_backward_core_ref_impl output") + print("dq:", dq, dq.shape) + print("dk:", dk, dk.shape) + print("dv:", dv, dv.shape) + print("delta:", delta, delta.shape) + + return dq, dk, dv, delta + +def attention_varlen_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + use_exp2, +): + # Ensure the layout is 'thd' + if layout != 'thd': + raise ValueError(f"Unsupported layout {layout}. Expected 'thd'.") + + batch_size = cu_seqlens_q.shape[0] - 1 + num_heads = q.shape[1] + head_dim = q.shape[2] + + # Pre-allocate outputs + total_L_q = q.shape[0] + total_L_k = k.shape[0] + + dq = torch.zeros_like(q) + dk = torch.zeros_like(k) + dv = torch.zeros_like(v) + # delta has the same shape as softmax_lse: [total_L_q, num_heads] + delta = torch.zeros((total_L_q, num_heads), dtype=torch.float32, device=o.device) + + for i in range(batch_size): + # Get the start and end indices for the current sequence + start_q = cu_seqlens_q[i].item() + end_q = cu_seqlens_q[i + 1].item() + start_k = cu_seqlens_k[i].item() + end_k = cu_seqlens_k[i + 1].item() + + # Extract q_i, k_i, v_i, do_i, o_i, softmax_lse_i + q_i = q[start_q:end_q, :, :] # [L_q_i, num_heads, head_dim] + k_i = k[start_k:end_k, :, :] # [L_k_i, num_heads, head_dim] + v_i = v[start_k:end_k, :, :] # [L_k_i, num_heads, head_dim] + do_i = do[start_q:end_q, :, :] # [L_q_i, num_heads, head_dim] + o_i = o[start_q:end_q, :, :] # [L_q_i, num_heads, head_dim] + # softmax_lse has shape [total_L_q, num_heads] + softmax_lse_i = softmax_lse[start_q:end_q, :] # [L_q_i, num_heads] + softmax_lse_i = softmax_lse_i.transpose(0, 1) # [num_heads, L_q_i] + + # Permute to [num_heads, L_q_i, head_dim] + q_i = q_i.permute(1, 0, 2) + k_i = k_i.permute(1, 0, 2) + v_i = v_i.permute(1, 0, 2) + do_i = do_i.permute(1, 0, 2) + o_i = o_i.permute(1, 0, 2) + # softmax_lse_i is already in [num_heads, L_q_i] + + # Call the core backward function for this sequence + dq_i, dk_i, dv_i, delta_i = attention_backward_core_ref_impl( + do_i, + q_i, + k_i, + v_i, + o_i, + softmax_lse_i, + sm_scale, + causal, + use_exp2 + ) + + # Convert back to 'thd' layout + dq_i = dq_i.permute(1, 0, 2) # [L_q_i, num_heads, head_dim] + dk_i = dk_i.permute(1, 0, 2) # [L_k_i, num_heads, head_dim] + dv_i = dv_i.permute(1, 0, 2) # [L_k_i, num_heads, head_dim] + + # Place outputs in pre-allocated tensors + dq[start_q:end_q, :, :] = dq_i + dk[start_k:end_k, :, :] += dk_i # Accumulate gradients for shared keys + dv[start_k:end_k, :, :] += dv_i # Accumulate gradients for shared values + # delta_i has shape [num_heads, L_q_i] + delta_i = delta_i.transpose(1, 0) # [L_q_i, num_heads] + delta[start_q:end_q, :] = delta_i + + return dq, dk, dv, delta + +def attention_vanilla_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + use_exp2, +): + if layout == "bshd": + if DEBUG: + print() + print("Changing layout to bhsd!") + do = do.transpose(1, 2).contiguous() + q = q.transpose(1, 2).contiguous() + k = k.transpose(1, 2).contiguous() + v = v.transpose(1, 2).contiguous() + o = o.transpose(1, 2).contiguous() + elif layout == "bhsd": + pass + else: + raise ValueError(f"Unknown layout {layout}") + + # Prepare tensors in [batch_size * num_heads, seq_len, head_dim] format + batch_size, num_heads, seq_len_q, head_dim = q.shape + seq_len_k = k.shape[2] + + # Merge batch and heads dimensions + do = do.reshape(batch_size * num_heads, seq_len_q, head_dim) + q = q.reshape(batch_size * num_heads, seq_len_q, head_dim) + k = k.reshape(batch_size * num_heads, seq_len_k, head_dim) + v = v.reshape(batch_size * num_heads, seq_len_k, head_dim) + softmax_lse = softmax_lse.reshape(batch_size * num_heads, seq_len_q) + o = o.reshape(batch_size * num_heads, seq_len_q, head_dim) + + dq, dk, dv, delta = attention_backward_core_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + use_exp2 + ) + + # Reshape outputs back to [batch_size, num_heads, seq_len, head_dim] + dq = dq.reshape(batch_size, num_heads, seq_len_q, head_dim) + dk = dk.reshape(batch_size, num_heads, seq_len_k, head_dim) + dv = dv.reshape(batch_size, num_heads, seq_len_k, head_dim) + delta = delta.reshape(batch_size, num_heads, seq_len_q) + + # Go back to original layout + if layout == "bshd": + if DEBUG: + print() + print("Changing back to bshd!") + dq = dq.transpose(1, 2) + dk = dk.transpose(1, 2) + dv = dv.transpose(1, 2) + elif layout == "bhsd": + pass + else: + raise ValueError(f"Unknown layout {layout}") + + return dq, dk, dv, delta + + +def attention_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + use_exp2 +): + if layout == "thd": + dq, dk, dv, delta = attention_varlen_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + use_exp2, + ) + else: + dq, dk, dv, delta = attention_vanilla_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + use_exp2, + ) + + + return dq, dk, dv, delta diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_decode.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..b37308be49193dbae2ad1b8482494a395641a395 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_decode.py @@ -0,0 +1,703 @@ +import torch +import triton +import triton.language as tl +from .utils import _strides, get_padded_headsize + +@triton.jit +def _fwd_kernel_splitK( + Q, + K, + V, + sm_scale, + Out_splitK, # [B, H, split_k, Mq, K] + Metadata, # [B, H, 2, split_k, M_ceil] contains [mi, li] + K_new, + V_new, + Cache_seqlens, + Cache_batch_idx, + Alibi_slopes, + stride_qz, + stride_qm, + stride_qg, + stride_qh, + stride_qd, + stride_kz, + stride_kn, + stride_kg, + stride_kh, + stride_kd, + stride_vz, + stride_vn, + stride_vg, + stride_vh, + stride_vd, + stride_osk_zhg, + stride_osk_s, + stride_osk_m, + stride_osk_d, + stride_mzhg, + stride_m2, + stride_ms, + stride_mm, + stride_kn_z, + stride_kn_n, + stride_kn_g, + stride_kn_h, + stride_kn_d, + stride_vn_z, + stride_vn_n, + stride_vn_g, + stride_vn_h, + stride_vn_d, + stride_az, + stride_ah, + Z, + N_CTX_Q, + N_CTX_K, + N_CTX_NEW, + BLOCK_N_PER_SPLIT, + H_q: tl.constexpr, + H_kv: tl.constexpr, + G_q: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, + BOUNDS_CHECKS_N: tl.constexpr, + USE_CACHE_SEQLENs: tl.constexpr, + USE_CACHE_BATCH_IDX: tl.constexpr, + NEW_KV: tl.constexpr, + IS_GQA: tl.constexpr, + IS_CAUSAL: tl.constexpr, + USE_ALIBI: tl.constexpr, +): + # Padding + PADDED_HEAD: tl.constexpr = (ACTUAL_BLOCK_DMODEL != BLOCK_DMODEL) + if PADDED_HEAD: + d_mask = tl.arange(0, BLOCK_DMODEL) < ACTUAL_BLOCK_DMODEL + + start_m = tl.program_id(0) + off_zhg = tl.program_id(1) + off_z = off_zhg // (H_q * G_q) + off_h_q = (off_zhg // G_q) % H_q + off_g_q = off_zhg % G_q + splitk_idx = tl.program_id(2) + + # pick batch index + if USE_CACHE_BATCH_IDX: + cache_batch_idx = tl.load(Cache_batch_idx + off_z) + else: + cache_batch_idx = off_z + + # Load ALiBi slope if enabled + if USE_ALIBI: + a_offset = off_z * stride_az + off_h_q * stride_ah + alibi_slope = tl.load(Alibi_slopes + a_offset) + else: + alibi_slope = None + + lo = splitk_idx * BLOCK_N_PER_SPLIT + if USE_CACHE_SEQLENs: + cache_seqlen_last_idx = tl.load(Cache_seqlens + off_z) + if NEW_KV: + kv_len = cache_seqlen_last_idx + N_CTX_NEW + else: + kv_len = cache_seqlen_last_idx + else: + kv_len = N_CTX_K + hi = tl.minimum((splitk_idx + 1) * BLOCK_N_PER_SPLIT, kv_len) + + HEAD_RATIO: tl.constexpr = H_q // H_kv + if IS_GQA: + k_head_idx = off_h_q // HEAD_RATIO + v_head_idx = k_head_idx + else: + k_head_idx = off_h_q + v_head_idx = off_h_q + + # calculate base offset + k_base = K + k_head_idx * stride_kh + cache_batch_idx * stride_kz + off_g_q * stride_kg + v_base = V + v_head_idx * stride_vh + cache_batch_idx * stride_vz + off_g_q * stride_vg + + # Copy new Keys and Values into Cache + if NEW_KV: + knew_base = K_new + k_head_idx * stride_kn_h + off_z * stride_kn_z + off_g_q * stride_kn_g + + # Determine the starting position for new data in the cache + if USE_CACHE_SEQLENs: + start_idx = tl.load(Cache_seqlens + off_z) + else: + start_idx = N_CTX_K - N_CTX_NEW + + # Copy new Keys + for i in range(0, N_CTX_NEW, BLOCK_N): + # Load from K_new + k_new_block = tl.load( + knew_base + + tl.arange(0, BLOCK_DMODEL)[:, None] * stride_kn_d + + (tl.arange(0, BLOCK_N) + i)[None, :] * stride_kn_n, + mask=(tl.arange(0, BLOCK_N)[None, :] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[:, None] < ACTUAL_BLOCK_DMODEL), + other=0 + ) + + # Store to K + tl.store( + k_base + + tl.arange(0, BLOCK_DMODEL)[:, None] * stride_kd + + (tl.arange(0, BLOCK_N) + i + start_idx)[None, :] * stride_kn, + k_new_block, + mask=(tl.arange(0, BLOCK_N)[None, :] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[:, None] < ACTUAL_BLOCK_DMODEL), + ) + + # Copy new Values + vnew_base = V_new + v_head_idx * stride_vn_h + off_z * stride_vn_z + off_g_q * stride_vn_g + for i in range(0, N_CTX_NEW, BLOCK_N): + # Load from V_new + v_new_block = tl.load( + vnew_base + + (tl.arange(0, BLOCK_N) + i)[:, None] * stride_vn_n + + tl.arange(0, BLOCK_DMODEL)[None, :] * stride_vn_d, + mask=(tl.arange(0, BLOCK_N)[:, None] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[None, :] < ACTUAL_BLOCK_DMODEL), + other=0 + ) + + # Store to V + tl.store( + v_base + + (tl.arange(0, BLOCK_N) + i + start_idx)[:, None] * stride_vn + + tl.arange(0, BLOCK_DMODEL)[None, :] * stride_vd, + v_new_block, + mask=(tl.arange(0, BLOCK_N)[:, None] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[None, :] < ACTUAL_BLOCK_DMODEL), + ) + + Q_block_ptr = tl.make_block_ptr( + base=Q + off_h_q * stride_qh + off_z * stride_qz + off_g_q * stride_qg, + shape=(N_CTX_Q, ACTUAL_BLOCK_DMODEL), + strides=(stride_qm, stride_qd), + offsets=(start_m * BLOCK_M, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + + K_block_ptr = tl.make_block_ptr( + base=k_base, + shape=(ACTUAL_BLOCK_DMODEL, hi), + strides=(stride_kd, stride_kn), + offsets=(0, lo), + block_shape=(BLOCK_DMODEL, BLOCK_N), + order=(0, 1), + ) + V_block_ptr = tl.make_block_ptr( + base=v_base, + shape=(hi, ACTUAL_BLOCK_DMODEL), + strides=(stride_vn, stride_vd), + offsets=(lo, 0), + block_shape=(BLOCK_N, BLOCK_DMODEL), + order=(1, 0), + ) + + K_scale_shift_block_ptr = None + V_scale_shift_block_ptr = None + + # initialize pointer to m and l + m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32) + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) # noqa: F821 + + # scale sm_scale by log_2(e) and use + # 2^x instead of exp in the loop because CSE and LICM + # don't work as expected with `exp` in the loop + qk_scale = sm_scale * 1.44269504 + # load q: it will stay in SRAM throughout + q = tl.load( # noqa: F821 + tl.advance(Q_block_ptr, (0, 0)), boundary_check=(0, )) + q = (q * qk_scale).to(q.dtype) + if PADDED_HEAD: + q = tl.where(d_mask[None, :], q, 0.0) + + # loop over k, v and update accumulator + for start_n in range(lo, hi, BLOCK_N): + k, v = load_k_v_group( + K_block_ptr, + V_block_ptr, + K_scale_shift_block_ptr, + V_scale_shift_block_ptr, + BOUNDS_CHECKS_N, + 1, + BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL, + Q.dtype.element_ty, + 0, + ) + if PADDED_HEAD: + k = tl.where(d_mask[:, None], k, 0.0) + v = tl.where(d_mask[None, :], v, 0.0) + + # -- compute qk --- + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, k) # noqa: F821 + + if USE_ALIBI: + row_idx = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + col_idx = start_n + tl.arange(0, BLOCK_N) + + # Compute relative positions + relative_pos = row_idx[:, None] + kv_len - (N_CTX_Q + col_idx[None, :]) + relative_pos = tl.abs(relative_pos) + + # Compute ALiBi bias + alibi_bias = -1 * alibi_slope * relative_pos + qk += (alibi_bias * 1.44269504) + + # Apply causal mask if IS_CAUSAL is True + if IS_CAUSAL: + row_idx = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + col_idx = start_n + tl.arange(0, BLOCK_N) + + # create a N_CTX_Q x kv_len causal mask + col_offset = N_CTX_Q - kv_len + causal_mask = row_idx[:, None] >= (col_offset + col_idx[None, :]) + + # Apply the mask + qk = tl.where(causal_mask, qk, float("-inf")) + + # TODO: This is slow, and only needed at the last iteration. + # Maybe we can unroll the last iteration instead? + if BOUNDS_CHECKS_N: + qk = tl.where(tl.arange(0, BLOCK_N) < hi - start_n, qk, float("-inf")) + + # -- compute scaling constant --- + m_i_new = tl.maximum(m_i, tl.max(qk, 1)) + if IS_CAUSAL: + alpha = tl.math.exp2(tl.where(m_i > float("-inf"), m_i - m_i_new, float("-inf"))) + else: + alpha = tl.math.exp2(m_i - m_i_new) + # cause of nan because subtracting infs + if IS_CAUSAL: + qk = tl.where(qk > float("-inf"), qk - m_i_new[:, None], float("-inf")) + else: + qk = qk - m_i_new[:, None] + + p = tl.math.exp2(qk) + + # -- update m_i and l_i -- + l_i = l_i * alpha + tl.sum(p, 1) + m_i = m_i_new + p = p.to(Q.dtype.element_ty) + + # -- scale and update acc -- + acc *= alpha[:, None] + acc += tl.dot(p.to(v.dtype), v) + + # update pointers + K_block_ptr = tl.advance(K_block_ptr, (0, BLOCK_N)) + V_block_ptr = tl.advance(V_block_ptr, (BLOCK_N, 0)) + + # write back O + O_block_ptr = tl.make_block_ptr( + base=Out_splitK + off_zhg * stride_osk_zhg + splitk_idx * stride_osk_s, + shape=(N_CTX_Q, BLOCK_DMODEL), + strides=(stride_osk_m, 1), + offsets=(start_m * BLOCK_M, 0), + block_shape=(BLOCK_M, BLOCK_DMODEL), + order=(1, 0), + ) + tl.store( + tl.advance(O_block_ptr, (0, 0)), + acc, + boundary_check=(0, ), + ) + # Write metadata for split-K reduction + Metadata_ptr = (Metadata + off_zhg * stride_mzhg + splitk_idx * stride_ms + start_m * BLOCK_M + + tl.arange(0, BLOCK_M)) + tl.store(Metadata_ptr, m_i) + tl.store(Metadata_ptr + stride_m2, l_i) + + +@triton.jit +def load_k_v_group( + K_block_ptr, + V_block_ptr, + K_scale_shift_block_ptr, + V_scale_shift_block_ptr, + BOUNDS_CHECKS_N: tl.constexpr, + PACKED_PER_VAL: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + dtype: tl.constexpr, + group_id: tl.constexpr, +): + #Load K/V for a given block + + # Advance to the current quantization group + K_block_ptr = tl.advance(K_block_ptr, (ACTUAL_BLOCK_DMODEL * group_id, 0)) + V_block_ptr = tl.advance(V_block_ptr, (0, ACTUAL_BLOCK_DMODEL * group_id)) + + # -- load k, v -- + k = tl.load(K_block_ptr, boundary_check=(1, ) if BOUNDS_CHECKS_N else ()) + v = tl.load(V_block_ptr, boundary_check=(0, ) if BOUNDS_CHECKS_N else ()) + + return k, v + + +@triton.jit +def cast_uint32_to_half2(scale_shift): + # Extract two float16 packed into one int32 + scale = scale_shift & 0xFFFF + shift = scale_shift >> 16 + scale = scale.to(tl.uint16).to(tl.float16, bitcast=True) + shift = shift.to(tl.uint16).to(tl.float16, bitcast=True) + return scale, shift + + +@triton.jit +def dequantize( + x_, + scale, + shift, + PACKED_PER_VAL: tl.constexpr = 8, +): + # PACKED_PER_VAL is the number of values packed into + # each element x_. For example, for int4 quantization + #and x_ of type int32, PACKED_PER_VAL is 8. + + BLOCK_N: tl.constexpr = x_.shape[0] + BLOCK_DMODEL_PACKED: tl.constexpr = x_.shape[1] + offsets = tl.arange(0, PACKED_PER_VAL) * 4 + quant_offset = (x_[:, None, :] >> offsets[None, :, None]) # (BLOCK_N, PACKED_PER_VAL, D // PACKED_PER_VAL) + + quant_offset = tl.view(quant_offset, (BLOCK_N, BLOCK_DMODEL_PACKED * PACKED_PER_VAL)) + # Trick - instead of converting int4 to float16 we view it as float16 + # and then multiply by 32768 * 512 == 2**24 + quant_offset = (quant_offset & 0xF).to(tl.uint16).to(tl.float16, bitcast=True) + quant_offset = (quant_offset * 32768.0).to(tl.float16) + scale_512 = scale * 512 + + dequant = quant_offset * scale_512 + shift + return dequant + + +@triton.jit +def _splitK_reduce( + Out_splitK, # [B, H, split_k, Mq, K] + Metadata, # [B, H, 2, split_k, M_ceil] contains [mi, li] + Out, # [B, H, M, K] + LSE, # [B, H, M] + stride_osk_zhg, + stride_osk_s, + stride_osk_m, + stride_osk_k, + stride_mzhg, + stride_m2, + stride_ms, + stride_mm, + stride_oz, + stride_oh, + stride_og, + stride_om, + stride_ok, + stride_lse_zhg, + stride_lse_m, + M_ceil: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + H: tl.constexpr, + G: tl.constexpr, + split_k: tl.constexpr, + splitK_pow2: tl.constexpr, + use_mask: tl.constexpr, + IS_CAUSAL: tl.constexpr, +): + off_zhg = tl.program_id(0) + off_z = off_zhg // (H * G) + off_h = (off_zhg // G) % H + off_g = off_zhg % G + off_m = tl.program_id(1) + off_k = tl.program_id(2) + + # read chunk + spk_idx = tl.arange(0, splitK_pow2) + kidx = tl.arange(0, BLOCK_SIZE) + + Metadata_ptr = (Metadata + stride_mzhg * off_zhg + spk_idx * stride_ms + off_m * stride_mm) + + o_ptr = (Out_splitK + off_zhg * stride_osk_zhg + stride_osk_m * off_m + off_k * BLOCK_SIZE + + stride_osk_s * spk_idx[:, None] + kidx[None, :] * stride_osk_k) + + # read max values of each splitK + if use_mask: + spk_mask = spk_idx < split_k + l_m = tl.load(Metadata_ptr, mask=spk_mask, other=float("-inf")) + l_sum = tl.load(Metadata_ptr + stride_m2, mask=spk_mask, other=0.0) + acc = tl.load(o_ptr, mask=spk_mask[:, None], other=0.0) + else: + l_m = tl.load(Metadata_ptr) + l_sum = tl.load(Metadata_ptr + stride_m2) + acc = tl.load(o_ptr) + + g_m = tl.max(l_m, axis=0) + + if IS_CAUSAL: + l_m_offset = l_m - g_m + alpha = tl.where(l_m_offset > float("-inf"), tl.math.exp2(l_m_offset), 0.0) + else: + alpha = tl.math.exp2(l_m - g_m) + + # read sum + l_sum *= alpha + g_sum = tl.sum(l_sum, axis=0) + acc = acc * alpha[:, None] + + if IS_CAUSAL: + # Avoid division by zero + g_sum_safe = tl.where(g_sum > 0, g_sum, 1.0) + acc_out = tl.sum(acc, axis=0) / g_sum_safe + else: + acc_out = tl.sum(acc, axis=0) / g_sum + + # Store output + Out_ptr = (Out + stride_oz * off_z + stride_oh * off_h + stride_og * off_g + stride_om * off_m + + off_k * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)) + tl.store(Out_ptr, acc_out) + + # Store lse + l_ptrs = LSE + off_zhg * stride_lse_zhg + off_m + if IS_CAUSAL: + lse = tl.where(g_sum > 0, (g_m + tl.math.log2(g_sum)) / 1.44269504, g_m) + tl.store(l_ptrs, lse) + else: + tl.store(l_ptrs, (g_m + tl.math.log2(g_sum)) / 1.44269504) + + +def quantize_kv_int4(k: torch.Tensor, num_groups: int = 1) -> torch.Tensor: + # Scale and shift are such that quantization linearly maps + # int4 values range [0..15] to input values range min(k)..max(k) + # individually for every row + k = k.reshape(*k.shape[:-1], num_groups, k.shape[-1] // num_groups) + max_vals = torch.max(k, dim=-1, keepdim=True).values + min_vals = torch.min(k, dim=-1, keepdim=True).values + scale_k: torch.Tensor = (max_vals - min_vals) / 15 + + shift_k = torch.min(k, dim=-1, keepdim=True).values + scale_k = scale_k.to(torch.float16) + shift_k = shift_k.to(torch.float16) + + in_bytes = ((k - shift_k.expand(k.shape)) / scale_k.expand(k.shape)) + 0.5 + in_bytes = in_bytes.to(torch.uint8) + in_int4 = in_bytes & 0xF + in_int4_packed = in_int4[..., ::2] + (in_int4[..., 1::2] << 4) + scale_shift = torch.concat([scale_k.view(torch.uint8), shift_k.view(torch.uint8)], dim=-1) + k_quant = torch.concat( + [ + scale_shift.flatten(start_dim=-2), + in_int4_packed.flatten(start_dim=-2), + ], + dim=-1, + ).view(torch.int16) + return k_quant + + +def dequantize_kv_fp16(quant_k: torch.Tensor, num_groups: int = 1) -> torch.Tensor: + k_i16 = quant_k.view(torch.int16) + k_ui8 = k_i16.view(torch.uint8) + + ss_size = num_groups * 4 + scale_shift_ui8 = k_ui8[..., 0:ss_size] + scale_shift_ui8 = scale_shift_ui8.reshape(*scale_shift_ui8.shape[:-1], num_groups, 4) + scale = scale_shift_ui8[..., 0:2].view(torch.float16) + shift = scale_shift_ui8[..., 2:4].view(torch.float16) + + kv_ui8 = k_ui8[..., ss_size:] + k_ui8 = kv_ui8.reshape(*kv_ui8.shape[:-1], num_groups, -1) + k1_i4 = k_ui8 & 0xF + k2_i4 = (k_ui8 & 0xF0) >> 4 + k_shape = k1_i4.shape + k1_f16 = k1_i4.to(torch.float16) * scale.expand(k_shape) + shift.expand(k_shape) + k2_f16 = k2_i4.to(torch.float16) * scale.expand(k_shape) + shift.expand(k_shape) + + out = torch.empty((*k1_f16.shape[:-1], k1_f16.shape[-1] * 2), dtype=torch.float16, device=quant_k.device) + out[..., ::2] = k1_f16 + out[..., 1::2] = k2_f16 + out = out.reshape(*k_shape[:-2], -1) + + return out + + +def get_split_k(B: int, G: int, H: int, Mk: int) -> int: + """Heuristic for the number of splits""" + bh = max(B * H, 1) # NOTE: Handle B*h=0 case + split_k = max(Mk, 1024) // bh + max_chunk_size = 64 + while split_k > 0 and Mk / split_k < max_chunk_size: + split_k = split_k // 2 + while B * H * G * split_k >= 1024: + split_k = split_k // 2 + split_k = min(split_k, 512) + split_k = max(split_k, 1) + return split_k + +def attention_decode_forward_triton_impl(q, k, v, sm_scale, causal, alibi_slopes, layout, cache_seqlens, cache_batch_idx, new_kv, k_new, v_new): + # kernel config + BLOCK_M = 16 + BLOCK_N = 64 + SPLIT_K = None + NUM_QUANT_GROUPS = 1 + + # kernels expects "bsghd" + original_layout = layout + if layout == "bshd": + q=q.unsqueeze(2) + k=k.unsqueeze(2) + v=v.unsqueeze(2) + if new_kv: + k_new = k_new.unsqueeze(2) + v_new = v_new.unsqueeze(2) + layout = "bsghd" + elif layout == "bhsd": + q=q.permute(0, 2, 1, 3).unsqueeze(2) + k=k.permute(0, 2, 1, 3).unsqueeze(2) + v=v.permute(0, 2, 1, 3).unsqueeze(2) + if new_kv: + k_new = k_new.permute(0, 2, 1, 3).unsqueeze(2) + v_new = v_new.permute(0, 2, 1, 3).unsqueeze(2) + layout = "bsghd" + elif layout == "bsghd": + pass + elif layout is None: + raise ValueError("Layout not given") + assert layout == "bsghd" + + # get dims + batch_size, seqlen_q, n_group_q, heads_per_group_q, dim_q = q.shape + _, seqlen_k, n_group_k, heads_per_group_k, dim_k = k.shape + _, seqlen_v, n_group_v, heads_per_group_v, dim_v = v.shape + + assert dim_q == dim_k == dim_v, f"Dimensions must match: {dim_q}, {dim_k}, {dim_v}" + + # get padded size + dim_padded = get_padded_headsize(dim_k) + + # Handle MQA/GQA case + if heads_per_group_q > heads_per_group_k: + is_gqa = True + elif heads_per_group_q < heads_per_group_k: + raise ValueError("heads_per_group_q < heads_per_group_k") + else: + is_gqa = False + + assert dim_k == dim_q, f"Keys have head dim {dim_k} but queries have head dim {dim_q}" + + if SPLIT_K is not None: + split_k = SPLIT_K + else: + # Use heuristics + split_k = get_split_k(batch_size, n_group_q, heads_per_group_q, seqlen_k) # NOTE: should the split think about seqlens? + + seqlen_q_ceil = (seqlen_q + BLOCK_M - 1) // BLOCK_M * BLOCK_M + out_splitk = torch.empty([batch_size * n_group_q * heads_per_group_q, split_k, seqlen_q_ceil, dim_padded], dtype=torch.float32, device=q.device) + metadata = torch.empty([batch_size * n_group_q * heads_per_group_q, 2, split_k, seqlen_q_ceil], dtype=torch.float32, device=q.device) + lse = torch.empty((batch_size * n_group_q * heads_per_group_q, seqlen_q), device=q.device, dtype=torch.float32) + grid = (triton.cdiv(seqlen_q, BLOCK_M), batch_size * n_group_q * heads_per_group_q, split_k) + + num_warps = 1 + split_size = (seqlen_k + split_k - 1) // split_k + use_cache_seqlens = cache_seqlens is not None + + # TODO: enable quantization + _fwd_kernel_splitK[grid]( + Q=q, + K=k, + V=v, + sm_scale=sm_scale, + Out_splitK=out_splitk, + Metadata=metadata, + K_new = k_new, + V_new = v_new, + Cache_seqlens=cache_seqlens, + Cache_batch_idx=cache_batch_idx, + Alibi_slopes=alibi_slopes, + **_strides(q, "qz", "qm", "qg", "qh", "qd"), + **_strides(k, "kz", "kn", "kg", "kh", "kd"), + **_strides(v, "vz", "vn", "vg", "vh", "vd"), + **_strides(out_splitk, "osk_zhg", "osk_s", "osk_m", "osk_d"), + **_strides(metadata, "mzhg", "m2", "ms", "mm"), + **_strides(k_new, "kn_z", "kn_n", "kn_g", "kn_h", "kn_d"), + **_strides(v_new, "vn_z", "vn_n", "vn_g", "vn_h", "vn_d"), + **_strides(alibi_slopes, "az", "ah"), + Z=batch_size, + H_q=heads_per_group_q, + H_kv=heads_per_group_k, + G_q=n_group_q, + N_CTX_Q=seqlen_q, + N_CTX_K=seqlen_k, + N_CTX_NEW=k_new.shape[1] if new_kv else None, + BLOCK_N_PER_SPLIT=split_size, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + BLOCK_DMODEL=dim_padded, + ACTUAL_BLOCK_DMODEL=dim_k, + BOUNDS_CHECKS_N=(split_size % BLOCK_N) > 0 or use_cache_seqlens, + USE_CACHE_SEQLENs=use_cache_seqlens, + USE_CACHE_BATCH_IDX=cache_batch_idx is not None, + NEW_KV=new_kv, + IS_GQA=is_gqa, + IS_CAUSAL=causal, + USE_ALIBI=False if alibi_slopes is None else True, + num_warps=num_warps, + num_stages=1, + ) + + out = torch.empty((batch_size, seqlen_q, n_group_q, heads_per_group_q, dim_padded), device=q.device, dtype=q.dtype) + + # Merge together + splitK_pow2 = triton.next_power_of_2(split_k) + use_mask = splitK_pow2 > split_k + if batch_size * n_group_q * heads_per_group_q * seqlen_q >= 512: + k_block_num = 1 + else: + k_block_num = 2 + assert dim_padded % k_block_num == 0 + k_block_size = dim_padded // k_block_num + grid = (batch_size * n_group_q * heads_per_group_q, seqlen_q, k_block_num) + + _splitK_reduce[grid]( + out_splitk, + metadata, + out, + lse, + **_strides(out_splitk, "osk_zhg", "osk_s", "osk_m", "osk_k"), + **_strides(metadata, "mzhg", "m2", "ms", "mm"), + **_strides(out, "oz", "om", "og", "oh", "ok"), + **_strides(lse, "lse_zhg", "lse_m"), + M_ceil=seqlen_q_ceil, + BLOCK_SIZE=k_block_size, + G=n_group_q, + H=heads_per_group_q, + # TODO: Tune num_warps + split_k=split_k, + splitK_pow2=splitK_pow2, + use_mask=use_mask, + IS_CAUSAL=causal, + num_warps=4) + + lse = lse.reshape([batch_size, n_group_q, heads_per_group_q, seqlen_q]) + if q.ndim == 4: + # BMGHK -> BMHK + assert n_group_q == 1 + out = out[:, :, 0] + lse = lse[:, 0] + if seqlen_k == 0: + out.zero_() + out = out.reshape(batch_size, heads_per_group_q * n_group_q, -1, dim_padded).contiguous() + + # output is batch_size, heads_per_group_q * group_q, seqlen_q, dim_q + if original_layout == "bshd": + # out=out.transpose(1, 2).contiguous() # this screws up heads and data. + # the data is laid out properly. Just need to reshape dims + out = out.reshape(batch_size, seqlen_q, -1, dim_padded) + + return out.narrow(-1, 0, dim_k), lse diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_prefill.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..2a59dc4e5d250db67076d114ae97b2b5b5c0ca48 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_prefill.py @@ -0,0 +1,652 @@ +import torch +import triton +import triton.language as tl +from .utils import get_shape_from_layout, get_strides_from_layout, is_cdna, is_rdna, DEBUG, AUTOTUNE + +@triton.jit +def cdiv_fn(x, y): + return (x + y - 1) // y + +@triton.jit +def dropout_offsets(philox_seed, philox_offset, dropout_p, m, n, stride): + ms = tl.arange(0, m) + ns = tl.arange(0, n) + return philox_offset + ms[:, None] * stride + ns[None, :] + + +@triton.jit +def dropout_rng(philox_seed, philox_offset, dropout_p, m, n, stride): + rng_offsets = dropout_offsets(philox_seed, philox_offset, dropout_p, m, n, stride).to(tl.uint32) + # TODO: use tl.randint for better performance + return tl.rand(philox_seed, rng_offsets) + + +@triton.jit +def dropout_mask(philox_seed, philox_offset, dropout_p, m, n, stride): + rng_output = dropout_rng(philox_seed, philox_offset, dropout_p, m, n, stride) + rng_keep = rng_output > dropout_p + return rng_keep + + +# Convenience function to load with optional boundary checks. +# "First" is the major dim, "second" is the minor dim. +@triton.jit +def load_fn(ptrs, offset_first, offset_second, boundary_first, boundary_second): + if offset_first is not None and offset_second is not None: + mask = (offset_first[:, None] < boundary_first) & \ + (offset_second[None, :] < boundary_second) + tensor = tl.load(ptrs, mask=mask, other=0.0) + elif offset_first is not None: + mask = offset_first[:, None] < boundary_first + tensor = tl.load(ptrs, mask=mask, other=0.0) + elif offset_second is not None: + mask = offset_second[None, :] < boundary_second + tensor = tl.load(ptrs, mask=mask, other=0.0) + else: + tensor = tl.load(ptrs) + return tensor + + +@triton.jit +def compute_alibi_block(alibi_slope, seqlen_q, seqlen_k, offs_m, offs_n, transpose=False): + # when seqlen_k and seqlen_q are different we want the diagonal to stick to the bottom right of the attention matrix + # for casual mask we want something like this where (1 is kept and 0 is masked) + # seqlen_q = 2 and seqlen_k = 5 + # 1 1 1 1 0 + # 1 1 1 1 1 + # seqlen_q = 5 and seqlen_k = 2 + # 0 0 + # 0 0 + # 0 0 + # 1 0 + # 1 1 + # for alibi the diagonal is 0 indicating no penalty for attending to that spot and increasing penalty for attending further from the diagonal + # e.g. alibi_slope = 1, seqlen_q = 2, seqlen_k = 5, offs_m = [0, 1, 2, 3], offs_n = [0, 1, 2, 3, 4], transpose = False + # 1. offs_m[:,None] = [[0], + # [1], + # 2. offs_m[:,None] + seqlen_k = [[5], + # [6], + # 3. offs_m[:,None] + seqlen_k - seqlen_q = [[3], + # [4], + # 4. offs_m[:,None] + seqlen_k - seqlen_q - offs_n[None,:] = [[3], - [[0, 1, 2, 3, 4]] = [[ 3, 2, 1, 0,-1], + # [4], [ 4, 3, 2, 1, 0]] + # 5. -1 * alibi_slope * tl.abs(relative_pos_block) = [[ -3, -2, -1, 0,-1], + # [ -4, -3, -2, -1, 0]], + relative_pos_block = offs_m[:, None] + seqlen_k - seqlen_q - offs_n[None, :] + alibi_block = -1 * alibi_slope * tl.abs(relative_pos_block) + if transpose: + return alibi_block.T + else: + return alibi_block + + +@triton.jit +def _attn_fwd_inner(acc, l_i, m_i, q, k_ptrs, v_ptrs, bias_ptrs, stride_kn, stride_vk, stride_bn, start_m, + actual_seqlen_k, actual_seqlen_q, dropout_p, philox_seed, batch_philox_offset, exp_scores_ptrs, + block_min, block_max, offs_n_causal, masked_blocks, n_extra_tokens, alibi_slope, score_ptrs, scores_scaled_shifted_ptrs, + IS_CAUSAL: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, + OFFS_M: tl.constexpr, OFFS_N: tl.constexpr, PRE_LOAD_V: tl.constexpr, MASK_STEPS: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, PADDED_HEAD: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, SM_SCALE: tl.constexpr, USE_EXP2: tl.constexpr, + RETURN_SCORES: tl.constexpr): + if USE_EXP2: + RCP_LN2: tl.constexpr = 1.4426950408889634 + + # loop over k, v, and update accumulator + for start_n in range(block_min, block_max, BLOCK_N): + # For padded blocks, we will overrun the tensor size if + # we load all BLOCK_N. For others, the blocks are all within range. + if MASK_STEPS: + k_offs_n = start_n + tl.arange(0, BLOCK_N) + else: + k_offs_n = None + k_offs_k = None if not PADDED_HEAD else tl.arange(0, BLOCK_DMODEL) + k = load_fn(k_ptrs, k_offs_k, k_offs_n, ACTUAL_BLOCK_DMODEL, actual_seqlen_k) + if PRE_LOAD_V: + # We can use the same offsets as k, just with dims transposed. + v = load_fn(v_ptrs, k_offs_n, k_offs_k, actual_seqlen_k, ACTUAL_BLOCK_DMODEL) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + # We start from end of seqlen_k so only the first iteration would need + # to be checked for padding if it is not a multiple of block_n + # TODO: This can be optimized to only be true for the padded block. + if MASK_STEPS: + # If this is the last block / iteration, we want to + # mask if the sequence length is not a multiple of block size + # a solution is to always do BLOCK_M // BLOCK_N + 1 steps if not is_modulo_mn. + # last step might get wasted but that is okay. check if this masking works For + # that case. + if (start_n + BLOCK_N == block_max) and (n_extra_tokens != 0): + boundary_m = tl.full([BLOCK_M], actual_seqlen_k, dtype=tl.int32) + size_n = start_n + OFFS_N[None, :] + mask = size_n < boundary_m[:, None] + qk = tl.where(mask, qk, float("-inf")) + + # -- compute qk ---- + qk += tl.dot(q, k) + qk_scaled = qk * SM_SCALE + if RETURN_SCORES: + score_mask = (OFFS_M[:, None] < actual_seqlen_q) & ((start_n + tl.arange(0, BLOCK_N))[None, :] < actual_seqlen_k) + tl.store(score_ptrs, qk_scaled, mask=score_mask) + + if IS_CAUSAL: + causal_boundary = start_n + offs_n_causal + causal_mask = OFFS_M[:, None] >= causal_boundary[None, :] + qk_scaled = tl.where(causal_mask, qk_scaled, float("-inf")) + if bias_ptrs is not None: + bias_offs_n = start_n + tl.arange(0, BLOCK_N) if MASK_STEPS else None + bias = load_fn(bias_ptrs, OFFS_M, bias_offs_n, actual_seqlen_q, actual_seqlen_k) + qk_scaled += bias + + if alibi_slope is not None: + # Compute the global position of each token within the sequence + global_m_positions = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + global_n_positions = start_n + tl.arange(0, BLOCK_N) + alibi_block = compute_alibi_block(alibi_slope, actual_seqlen_q, actual_seqlen_k, global_m_positions, + global_n_positions) + qk_scaled += alibi_block + # get max scores so far + m_ij = tl.maximum(m_i, tl.max(qk_scaled, 1)) + + # scale and subtract max + q_shifted = qk_scaled - m_ij[:, None] + if RETURN_SCORES: + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + scores_scaled_shifted_mask = (OFFS_M[:, None] < actual_seqlen_q) & ((start_n + tl.arange(0, BLOCK_N))[None, :] < actual_seqlen_k) + tl.store(scores_scaled_shifted_ptrs, q_shifted, mask=scores_scaled_shifted_mask) + + # Compute scaled QK and softmax probabilities + if USE_EXP2: + p = tl.math.exp2(q_shifted * RCP_LN2) + else: + p = tl.math.exp(q_shifted) + + # CAVEAT: Must update l_ij before applying dropout + l_ij = tl.sum(p, 1) + if ENABLE_DROPOUT: + philox_offset = batch_philox_offset + start_m * BLOCK_M * actual_seqlen_k + start_n - BLOCK_N + keep = dropout_mask(philox_seed, philox_offset, dropout_p, BLOCK_M, BLOCK_N, actual_seqlen_k) + if RETURN_SCORES: + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + exp_score_mask = (OFFS_M[:, None] < actual_seqlen_q) & ((start_n + tl.arange(0, BLOCK_N))[None, :] < actual_seqlen_k) + tl.store(exp_scores_ptrs, tl.where(keep, p, -p), mask=exp_score_mask) + p = tl.where(keep, p, 0.0) + elif RETURN_SCORES: + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + exp_score_mask = (OFFS_M[:, None] < actual_seqlen_q) & ((start_n + tl.arange(0, BLOCK_N))[None, :] < actual_seqlen_k) + tl.store(exp_scores_ptrs, p, mask=exp_score_mask) + + # -- update output accumulator -- + # alpha is an adjustment factor for acc and li as we loop and find new maxes + # store the diff in maxes to adjust acc and li as we discover new maxes + m_diff = m_i - m_ij + if USE_EXP2: + alpha = tl.math.exp2(m_diff * RCP_LN2) + else: + alpha = tl.math.exp(m_diff) + acc = acc * alpha[:, None] + if not PRE_LOAD_V: + v = load_fn(v_ptrs, k_offs_n, k_offs_k, actual_seqlen_k, ACTUAL_BLOCK_DMODEL) + # -- update m_i and l_i + l_i = l_i * alpha + l_ij + # update m_i and l_i + m_i = m_ij + acc += tl.dot(p.to(v.type.element_ty), v) + k_ptrs += BLOCK_N * stride_kn + v_ptrs += BLOCK_N * stride_vk + if bias_ptrs is not None: + bias_ptrs += BLOCK_N * stride_bn + if RETURN_SCORES: + score_ptrs += BLOCK_N + scores_scaled_shifted_ptrs += BLOCK_N + exp_scores_ptrs += BLOCK_N + return acc, l_i, m_i + + +def get_cdna_autotune_configs(): + return [ + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 3, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 32, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 64, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + # Fall-back config. + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + ], ['IS_CAUSAL', 'dropout_p', 'MAX_SEQLENS_Q', 'MAX_SEQLENS_K', 'ACTUAL_BLOCK_DMODEL', 'VARLEN', 'HQ', 'HK'] + + +def get_rdna_autotune_configs(): + return [ + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32, 'waves_per_eu': 4, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 16, 'waves_per_eu': 4, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 16, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 4, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + # Fall-back config. + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + ], ['IS_CAUSAL', 'dropout_p', 'MAX_SEQLENS_Q', 'MAX_SEQLENS_K', 'ACTUAL_BLOCK_DMODEL', 'VARLEN', 'HQ', 'HK'] + + +def get_autotune_configs(): + if AUTOTUNE: + if is_rdna(): + return get_rdna_autotune_configs() + elif is_cdna(): + return get_cdna_autotune_configs() + else: + raise ValueError("Unknown Device Type") + else: + return [ + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 64, "waves_per_eu": 1, "PRE_LOAD_V": False}, + num_stages=1, + num_warps=4, + ), + ], [ + "IS_CAUSAL", + "dropout_p", + "MAX_SEQLENS_Q", + "MAX_SEQLENS_K", + "ACTUAL_BLOCK_DMODEL", + "VARLEN", + "HQ", + "HK", + ] + + +autotune_configs, autotune_keys = get_autotune_configs() + +@triton.autotune( + configs=autotune_configs, + key=autotune_keys, + use_cuda_graph=True, +) +@triton.jit +def attn_fwd(Q, K, V, bias, SM_SCALE: tl.constexpr, LSE, Out, stride_qz, stride_qh, stride_qm, stride_qk, + stride_kz, stride_kh, stride_kn, stride_kk, stride_vz, stride_vh, stride_vk, stride_vn, + stride_oz, stride_oh, stride_om, stride_on, stride_bz, stride_bh, stride_bm, stride_bn, stride_az, stride_ah, + stride_sz, stride_sh, stride_sm, stride_sn, stride_lse_z, stride_lse_h, stride_lse_m, cu_seqlens_q, cu_seqlens_k, + dropout_p, philox_seed, philox_offset_base, scores, scores_scaled_shifted, exp_scores, alibi_slopes, HQ: tl.constexpr, + HK: tl.constexpr, ACTUAL_BLOCK_DMODEL: tl.constexpr, MAX_SEQLENS_Q: tl.constexpr, + MAX_SEQLENS_K: tl.constexpr, VARLEN: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, PRE_LOAD_V: tl.constexpr, USE_BIAS: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, RETURN_SCORES: tl.constexpr, USE_ALIBI: tl.constexpr, USE_EXP2: tl.constexpr): + start_m = tl.program_id(0) + off_h_q = tl.program_id(1) + off_z = tl.program_id(2) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + if VARLEN: + cu_seqlens_q_start = tl.load(cu_seqlens_q + off_z) + cu_seqlens_q_end = tl.load(cu_seqlens_q + off_z + 1) + # print("cu_seqlens_q_start:", cu_seqlens_q_start) + + seqlen_q = cu_seqlens_q_end - cu_seqlens_q_start + # We have a one-size-fits-all grid in id(0). Some seqlens might be too + # small for all start_m so for those we return early. + if start_m * BLOCK_M > seqlen_q: + return + cu_seqlens_k_start = tl.load(cu_seqlens_k + off_z) + cu_seqlens_k_end = tl.load(cu_seqlens_k + off_z + 1) + seqlen_k = cu_seqlens_k_end - cu_seqlens_k_start + else: + cu_seqlens_q_start = 0 + cu_seqlens_k_start = 0 + seqlen_q = MAX_SEQLENS_Q + seqlen_k = MAX_SEQLENS_K + + # Now we compute whether we need to exit early due to causal masking. + # This is because for seqlen_q > seqlen_k, M rows of the attn scores + # are completely masked, resulting in 0s written to the output, and + # inf written to LSE. We don't need to do any GEMMs in this case. + # This block of code determines what N is, and if this WG is operating + # on those M rows. + n_blocks = cdiv_fn(seqlen_k, BLOCK_N) + if (IS_CAUSAL): + # If seqlen_q == seqlen_k, the attn scores are a square matrix. + # If seqlen_q != seqlen_k, attn scores are rectangular which means + # the causal mask boundary is bottom right aligned, and ends at either + # the top edge (seqlen_q < seqlen_k) or left edge. + # This captures the decrease in n_blocks if we have a rectangular attn matrix + n_blocks_seqlen = cdiv_fn((start_m + 1) * BLOCK_M + seqlen_k - seqlen_q, BLOCK_N) + # This is what adjusts the block_max for the current WG, only + # if IS_CAUSAL. Otherwise we want to always iterate through all n_blocks + n_blocks = min(n_blocks, n_blocks_seqlen) + # If we have no blocks after adjusting for seqlen deltas, this WG is part of + # the blocks that are all 0. We exit early. + if n_blocks <= 0: + o_offset = Out + off_z * stride_oz + off_h_q * stride_oh + cu_seqlens_q_start * stride_om + o_ptrs = o_offset + offs_m[:, None] * stride_om + offs_d[None, :] * stride_on + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=Out.type.element_ty) + o_ptrs_mask = offs_m[:, None] < seqlen_q + # We still need to write 0s to the result + tl.store(o_ptrs, acc, mask=o_ptrs_mask) + # The tensor allocated for L is based on MAX_SEQLENS_Q as that is + # statically known. + l_offset = LSE + off_z * stride_lse_z + off_h_q * stride_lse_h + cu_seqlens_q_start * stride_lse_m + l_ptrs = l_offset + offs_m * stride_lse_m + + l = tl.full([BLOCK_M], value=0.0, dtype=tl.float32) + + # mask_m_offsets = start_m + tl.arange(0, BLOCK_M) + # lse_mask = mask_m_offsets < causal_start_idx + # softmax_lse = tl.where(lse_mask, 0.0, softmax_lse) + l_ptrs_mask = offs_m < MAX_SEQLENS_Q + tl.store(l_ptrs, l, mask=l_ptrs_mask) + # TODO: Should dropout and return encoded softmax be handled here too? + return + + # If MQA / GQA, set the K and V head offsets appropriately. + GROUP_SIZE: tl.constexpr = HQ // HK + if GROUP_SIZE != 1: + off_h_k = off_h_q // GROUP_SIZE + else: + off_h_k = off_h_q + + n_extra_tokens = 0 + # print("n_extra_tokens:", n_extra_tokens) + # print("seqlen_k:", seqlen_k) + # print("BLOCK_N:", BLOCK_N) + # return + if seqlen_k < BLOCK_N: + n_extra_tokens = BLOCK_N - seqlen_k + elif seqlen_k % BLOCK_N: + n_extra_tokens = seqlen_k % BLOCK_N + PADDED_HEAD: tl.constexpr = (ACTUAL_BLOCK_DMODEL != BLOCK_DMODEL) + + # Compute pointers for all the tensors used in this kernel. + q_offset = Q + off_z * stride_qz + off_h_q * stride_qh + cu_seqlens_q_start * stride_qm + q_ptrs = q_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + k_offset = K + off_z * stride_kz + off_h_k * stride_kh + cu_seqlens_k_start * stride_kn + k_ptrs = k_offset + offs_d[:, None] * stride_kk + offs_n[None, :] * stride_kn + v_offset = V + off_z * stride_vz + off_h_k * stride_vh + cu_seqlens_k_start * stride_vk + v_ptrs = v_offset + offs_n[:, None] * stride_vk + offs_d[None, :] * stride_vn + if USE_BIAS: + # Note: this might get large enough to overflow on some configs + bias_offset = off_h_q * stride_bh + bias_ptrs = bias + bias_offset + offs_m[:, None] * stride_bm + offs_n[None, :] * stride_bn + else: + bias_ptrs = None + + if USE_ALIBI: + a_offset = off_z * stride_az + off_h_q * stride_ah + alibi_slope = tl.load(alibi_slopes + a_offset) + else: + alibi_slope = None + + if RETURN_SCORES: + scores_offset = scores + off_z * stride_sz + off_h_q * stride_sh + cu_seqlens_q_start * stride_sm + score_ptrs = scores_offset + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn + + scores_scaled_shifted_offset = scores_scaled_shifted + off_z * stride_sz + off_h_q * stride_sh + cu_seqlens_q_start * stride_sm + scores_scaled_shifted_ptrs = scores_scaled_shifted_offset + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn + + exp_scores_offset = exp_scores + off_z * stride_sz + off_h_q * stride_sh + cu_seqlens_q_start * stride_sm + exp_scores_ptrs = exp_scores_offset + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn + else: + score_ptrs = None + scores_scaled_shifted_ptrs = None + exp_scores_ptrs = None + + if ENABLE_DROPOUT: + off_hz = off_z * HQ + off_h_q + batch_philox_offset = philox_offset_base + off_hz * seqlen_q * seqlen_k + else: + batch_philox_offset = 0 + # initialize pointer to m and l + m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32) + l_i = tl.full([BLOCK_M], 1.0, dtype=tl.float32) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # Q is loaded once at the beginning and shared by all N blocks. + q_ptrs_mask = offs_m[:, None] < seqlen_q + if PADDED_HEAD: + q_ptrs_mask = q_ptrs_mask & (offs_d[None, :] < ACTUAL_BLOCK_DMODEL) + q = tl.load(q_ptrs, mask=q_ptrs_mask, other=0.0) + + # Here we compute how many full and masked blocks we have. + padded_block_k = n_extra_tokens != 0 + is_modulo_mn = not padded_block_k and (seqlen_q % BLOCK_M == 0) + if IS_CAUSAL: + # There are always at least BLOCK_M // BLOCK_N masked blocks. + # Additionally there might be one more due to dissimilar seqlens. + masked_blocks = BLOCK_M // BLOCK_N + (not is_modulo_mn) + else: + # Padding on Q does not need to be masked in the FA loop. + masked_blocks = padded_block_k + # if IS_CAUSAL, not is_modulo_mn does not always result in an additional block. + # In this case we might exceed n_blocks so pick the min. + masked_blocks = min(masked_blocks, n_blocks) + n_full_blocks = n_blocks - masked_blocks + block_min = 0 + block_max = n_blocks * BLOCK_N + # Compute for full blocks. Here we set causal to false regardless of its actual + # value because there is no masking. Similarly we do not need padding. + if n_full_blocks > 0: + block_max = (n_blocks - masked_blocks) * BLOCK_N + acc, l_i, m_i = _attn_fwd_inner(acc, l_i, m_i, q, k_ptrs, v_ptrs, bias_ptrs, stride_kn, stride_vk, stride_bn, + start_m, seqlen_k, seqlen_q, dropout_p, philox_seed, batch_philox_offset, + exp_scores_ptrs, + # _, _, offs_n_causal, masked_blocks, n_extra_tokens, _ + block_min, block_max, 0, 0, 0, alibi_slope, score_ptrs, scores_scaled_shifted_ptrs, + # IS_CAUSAL, .... + False, BLOCK_M, BLOCK_DMODEL, BLOCK_N, offs_m, offs_n, + # _, MASK_STEPS, ... + PRE_LOAD_V, False, ENABLE_DROPOUT, PADDED_HEAD, + ACTUAL_BLOCK_DMODEL, SM_SCALE, USE_EXP2=USE_EXP2, RETURN_SCORES=RETURN_SCORES) + block_min = block_max + block_max = n_blocks * BLOCK_N + + tl.debug_barrier() + # Remaining blocks, if any, are full / not masked. + if (masked_blocks > 0): + if IS_CAUSAL: + offs_n_causal = offs_n + (seqlen_q - seqlen_k) + else: + offs_n_causal = 0 + k_ptrs += n_full_blocks * BLOCK_N * stride_kn + v_ptrs += n_full_blocks * BLOCK_N * stride_vk + if USE_BIAS: + bias_ptrs += n_full_blocks * BLOCK_N * stride_bn + if RETURN_SCORES: + score_ptrs += n_full_blocks * BLOCK_N + scores_scaled_shifted_ptrs += n_full_blocks * BLOCK_N + exp_scores_ptrs += n_full_blocks * BLOCK_N + acc, l_i, m_i = _attn_fwd_inner(acc, l_i, m_i, q, k_ptrs, v_ptrs, bias_ptrs, stride_kn, stride_vk, stride_bn, + start_m, seqlen_k, seqlen_q, dropout_p, philox_seed, batch_philox_offset, + exp_scores_ptrs, block_min, block_max, offs_n_causal, masked_blocks, + n_extra_tokens, alibi_slope, score_ptrs, scores_scaled_shifted_ptrs, + IS_CAUSAL, BLOCK_M, BLOCK_DMODEL, BLOCK_N, offs_m, offs_n, + # _, MASK_STEPS, ... + PRE_LOAD_V, True, ENABLE_DROPOUT, PADDED_HEAD, + ACTUAL_BLOCK_DMODEL, SM_SCALE, USE_EXP2=USE_EXP2, RETURN_SCORES=RETURN_SCORES) + # epilogue + # This helps the compiler do Newton Raphson on l_i vs on acc which is much larger. + l_recip = 1 / l_i[:, None] + acc = acc * l_recip + if ENABLE_DROPOUT: + acc = acc / (1 - dropout_p) + # If seqlen_q > seqlen_k but the delta is not a multiple of BLOCK_M, + # then we have one block with a row of all NaNs which come from computing + # softmax over a row of all -infs (-inf - inf = NaN). We check for that here + # and store 0s where there are NaNs as these rows should've been zeroed out. + end_m_idx = (start_m + 1) * BLOCK_M + start_m_idx = start_m * BLOCK_M + causal_start_idx = seqlen_q - seqlen_k + acc = acc.to(Out.type.element_ty) + if IS_CAUSAL: + if causal_start_idx > start_m_idx and causal_start_idx < end_m_idx: + out_mask_boundary = tl.full((BLOCK_DMODEL, ), causal_start_idx, dtype=tl.int32) + mask_m_offsets = start_m_idx + tl.arange(0, BLOCK_M) + out_ptrs_mask = mask_m_offsets[:, None] >= out_mask_boundary[None, :] + z = 0.0 + acc = tl.where(out_ptrs_mask, acc, z.to(acc.type.element_ty)) + + # write back LSE(Log Sum Exponents), the log of the normalization constant + l_offset = LSE + off_z * stride_lse_z + off_h_q * stride_lse_h + cu_seqlens_q_start * stride_lse_m + l_ptrs = l_offset + offs_m * stride_lse_m + if USE_EXP2: + RCP_LN2: tl.constexpr = 1.4426950408889634 + LN2: tl.constexpr = 0.6931471824645996 + # compute log-sum-exp in base 2 units + mi_base2 = m_i * RCP_LN2 + softmax_lse = mi_base2 + tl.math.log2(l_i) + # convert back to natural units + softmax_lse *= LN2 + else: + softmax_lse = m_i + tl.math.log(l_i) + + if IS_CAUSAL: + # zero out nans caused by -infs when doing causal + lse_mask = (start_m_idx + tl.arange(0, BLOCK_M)) < causal_start_idx + softmax_lse = tl.where(lse_mask, 0.0, softmax_lse) + + # If seqlen_q not multiple of BLOCK_M, we need to mask out the last few rows. + # This is only true for the last M block. For others, overflow_size will be -ve + overflow_size = end_m_idx - seqlen_q + if overflow_size > 0: + boundary = tl.full((BLOCK_M, ), BLOCK_M - overflow_size, dtype=tl.int32) + l_ptrs_mask = tl.arange(0, BLOCK_M) < boundary + tl.store(l_ptrs, softmax_lse, mask=l_ptrs_mask) # the log of the normalization constant + else: + tl.store(l_ptrs, softmax_lse) # the log of the normalization constant + + # write back O + o_offset = Out + off_z * stride_oz + off_h_q * stride_oh + cu_seqlens_q_start * stride_om + o_ptrs = o_offset + offs_m[:, None] * stride_om + offs_d[None, :] * stride_on + o_ptrs_mask = tl.full([BLOCK_M, BLOCK_DMODEL], 1, dtype=tl.int1) + if overflow_size > 0: + o_ptrs_mask = o_ptrs_mask & (offs_m[:, None] < seqlen_q) + if PADDED_HEAD: + o_ptrs_mask = o_ptrs_mask & (offs_d[None, :] < ACTUAL_BLOCK_DMODEL) + tl.store(o_ptrs, acc.to(Out.dtype.element_ty), mask=o_ptrs_mask) + + +def attention_prefill_forward_triton_impl( + q, + k, + v, + o, + sm_scale, + alibi_slopes, + causal, + bias, + dropout_p, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlens_q, + max_seqlens_k, + return_scores, + use_exp2): + + if DEBUG: + print() + print("attention_prefill_forward_triton_impl") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("o:", o, o.shape) + print("sm_scale:", sm_scale) + print("alibi_slopes:", alibi_slopes) + print("causal:", causal) + print("bias:", bias) + print("dropout_p:", dropout_p) + print("layout:", layout) + print("cu_seqlens_q:", cu_seqlens_q) + print("cu_seqlens_k:", cu_seqlens_k) + print("max_seqlens_q:", max_seqlens_q) + print("max_seqlens_k:", max_seqlens_k) + print("return_scores:", return_scores) + print("use_exp2:", use_exp2) + + # check if varlen + is_varlen = layout == "thd" + + # NOTE: a large bias tensor leads to overflow during pointer arithmetic + if (bias is not None): + assert (bias.numel() < 2**31) + + batch, nheads_q, nheads_k, head_size, seqlen_q, seqlen_k = get_shape_from_layout(q, k, layout, cu_seqlens_q, cu_seqlens_k, max_seqlens_q, max_seqlens_k) + q_strides, k_strides, v_strides, o_strides = get_strides_from_layout(q, k, v, o, layout) + + # Get closest power of 2 over or equal to 32. + padded_d_model = 1 << (head_size - 1).bit_length() + # Smallest head_dim supported is 16. If smaller, the tile in the + # kernel is padded - there is no padding in memory for any dims. + padded_d_model = max(padded_d_model, 16) + + grid = lambda META: (triton.cdiv(max_seqlens_q, META['BLOCK_M']), nheads_q, batch) + + if return_scores: + scores = torch.zeros((batch, nheads_q, max_seqlens_q, max_seqlens_k), device=q.device, + dtype=torch.float32) + scores_scaled_shifted = torch.zeros((batch, nheads_q, max_seqlens_q, max_seqlens_k), device=q.device, + dtype=torch.float32) + scores_strides = (scores.stride(0), scores.stride(1), scores.stride(2), scores.stride(3)) + else: + scores = None + scores_scaled_shifted = None + scores_strides = (0, 0 , 0 , 0) + + # exp_scores is used to validate dropout behavior vs the PyTorch SDPA math backend reference. We zero this out + # to give a consistent starting point and then populate it with the output of softmax with the sign bit set according + # to the dropout mask. The resulting return allows this mask to be fed into the reference implementation for testing + # only. This return holds no useful output aside from debugging. + if return_scores: + exp_scores = torch.zeros((batch, nheads_q, max_seqlens_q, max_seqlens_k), device=q.device, + dtype=torch.float32) + else: + exp_scores = None + + # stores LSE the log of the normalization constant / sum of expoential score(unnormalzied probablities) + if is_varlen: + softmax_lse = torch.empty((q.shape[0], nheads_q), device=q.device, dtype=torch.float32) + stride_lse_m, stride_lse_h = softmax_lse.stride() + stride_lse_z = 0 + else: + softmax_lse = torch.empty((batch, nheads_q, max_seqlens_q), device=q.device, dtype=torch.float32) + stride_lse_z, stride_lse_h, stride_lse_m = softmax_lse.stride() + + # Seed the RNG so we get reproducible results for testing. + philox_seed = 0x1BF52 + philox_offset = 0x1D4B42 + + if bias is not None: + bias_strides = (bias.stride(0), bias.stride(1),bias.stride(2), + bias.stride(3)) + else: + bias_strides = (0, 0, 0, 0) + + if alibi_slopes is not None: + alibi_strides = (alibi_slopes.stride(0), alibi_slopes.stride(1)) + else: + alibi_strides = (0, 0) + + + attn_fwd[grid](q, k, v, bias, sm_scale, softmax_lse, o, *q_strides, *k_strides, *v_strides, *o_strides, + *bias_strides, *alibi_strides, *scores_strides, stride_lse_z, stride_lse_h, stride_lse_m, cu_seqlens_q, cu_seqlens_k, + dropout_p=dropout_p, philox_seed=philox_seed, philox_offset_base=philox_offset, scores=scores, + scores_scaled_shifted=scores_scaled_shifted, exp_scores=exp_scores, alibi_slopes=alibi_slopes, + HQ=nheads_q, HK=nheads_k, ACTUAL_BLOCK_DMODEL=head_size, MAX_SEQLENS_Q=max_seqlens_q, + MAX_SEQLENS_K=max_seqlens_k, IS_CAUSAL=causal, VARLEN=is_varlen, + BLOCK_DMODEL=padded_d_model, USE_BIAS=False if bias is None else True, + USE_ALIBI=False if alibi_slopes is None else True, ENABLE_DROPOUT=dropout_p + > 0.0, USE_EXP2=use_exp2, RETURN_SCORES=return_scores) + + return o, softmax_lse, exp_scores, grid, head_size, philox_seed, philox_offset, scores, scores_scaled_shifted diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_ref.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc51d17e73c30e2b1d81ac5512365830bb91988 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/fwd_ref.py @@ -0,0 +1,319 @@ +import torch +import math +from .utils import DEBUG + +def attention_forward_core_ref_impl(q, k, v, sm_scale, causal, use_exp2): + if DEBUG: + print() + print("attention_forward_core_ref_impl") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("sm_scale:", sm_scale) + print("causal:", causal) + print("use_exp2:", use_exp2) + + # Compute attention scores + attention_scores = torch.matmul(q.to(torch.float32), k.transpose(-2, -1).to(torch.float32)) + if DEBUG: + print("attention_scores:", attention_scores, attention_scores.shape) + + # Scale scores + attention_scaled_scores = sm_scale * attention_scores + if DEBUG: + print("attention_scaled_scores:", attention_scaled_scores, attention_scaled_scores.shape) + + # Apply causal mask if necessary + if causal: + L_q, L_k = q.shape[1], k.shape[1] + row_idx = torch.arange(L_q, device=q.device).unsqueeze(1) + col_idx = torch.arange(L_k, device=q.device).unsqueeze(0) + col_offset = L_q-L_k + causal_mask = row_idx >= (col_offset + col_idx) + if DEBUG: + print("causal_mask:", causal_mask) + # set -inf to places the causal mask is false + attention_scaled_scores = attention_scaled_scores.masked_fill( + torch.logical_not(causal_mask.unsqueeze(0)), float('-inf') + ) + if DEBUG: + print("attention_scaled_scores after causal:", attention_scaled_scores, attention_scaled_scores.shape) + + + # Compute max for numerical stability + max_scores = torch.max(attention_scaled_scores, dim=-1, keepdim=True)[0] + if DEBUG: + print("max_scores:", max_scores, max_scores.shape) + if causal: + # Replace -inf in max_scores with zeros to avoid NaN in subtraction + max_scores = torch.where( + torch.isinf(max_scores), torch.zeros_like(max_scores), max_scores + ) + if DEBUG: + print("max_scores if causal:", max_scores, max_scores.shape) + + # Shift scores + attention_shifted_scaled_scores = attention_scaled_scores - max_scores + if DEBUG: + print("attention_shifted_scaled_scores:", attention_shifted_scaled_scores, attention_shifted_scaled_scores.shape) + + # Exponentiate + if use_exp2: + RCP_LN = 1 / math.log(2) + exp_scores = torch.exp2(RCP_LN * attention_shifted_scaled_scores) + else: + exp_scores = torch.exp(attention_shifted_scaled_scores) + + if DEBUG: + print("exp_scores:", exp_scores, exp_scores.shape) + + # Sum of exponentials + sum_exp_scores = torch.sum(exp_scores, dim=-1, keepdim=True) + if DEBUG: + print("sum_exp_scores:", sum_exp_scores, sum_exp_scores.shape) + if causal: + # if sum of exp scores is 0.0 it means scores where -inf, we cannot compute softmax and softmax_lse. Setting to 1 deals with -inf case cleanly + sum_exp_scores = torch.where( + sum_exp_scores == 0, + torch.ones_like(sum_exp_scores), + sum_exp_scores + ) + if DEBUG: + print("sum_exp_scores:", sum_exp_scores, sum_exp_scores.shape) + + # Compute softmax probabilities + softmax = exp_scores / sum_exp_scores + + if DEBUG: + print("softmax:", softmax, softmax.shape) + + # Compute log-sum-exp + if use_exp2: + LN2 = math.log(2) + RCP_LN = 1 / math.log(2) + max_scores_base2 = max_scores * RCP_LN + softmax_lse_base2 = max_scores_base2 + torch.log2(sum_exp_scores) + softmax_lse = softmax_lse_base2 * LN2 + softmax_lse.squeeze_(-1) + else: + softmax_lse = max_scores + torch.log(sum_exp_scores) + softmax_lse = softmax_lse.squeeze(-1) + + if DEBUG: + print("softmax_lse:", softmax_lse, softmax_lse.shape) + + # Compute output + o = torch.matmul(softmax, v.to(torch.float32)).to(torch.float16) + if DEBUG: + print("o:", o, o.shape) + + return o, softmax_lse, exp_scores, softmax, attention_shifted_scaled_scores, attention_scaled_scores, attention_scores + +def attention_vanilla_forward_pytorch_ref_impl(q, k, v, sm_scale, causal, layout, use_exp2): + """Compute reference output and softmax_lse using PyTorch's built-in function""" + + # Ensure the layout is 'bhsd' + if layout == "bshd": + q = q.transpose(1, 2).contiguous() + k = k.transpose(1, 2).contiguous() + v = v.transpose(1, 2).contiguous() + elif layout != "bhsd": + raise ValueError(f"Unknown layout {layout}") + + # Prepare tensors in [batch_size * num_heads, seq_len, head_dim] format + batch_size, num_heads, seq_len_q, head_dim = q.shape + seq_len_k = k.shape[2] + + # Merge batch and heads dimensions + q = q.reshape(batch_size * num_heads, seq_len_q, head_dim) + k = k.reshape(batch_size * num_heads, seq_len_k, head_dim) + v = v.reshape(batch_size * num_heads, seq_len_k, head_dim) + + # Call the core attention function + o, softmax_lse, exp_scores, softmax, attention_shifted_scaled_scores, attention_scaled_scores, attention_scores = attention_forward_core_ref_impl( + q, k, v, sm_scale, causal, use_exp2 + ) + + # Reshape outputs back to [batch_size, num_heads, seq_len, head_dim] + o = o.reshape(batch_size, num_heads, seq_len_q, head_dim) + softmax_lse = softmax_lse.reshape(batch_size, num_heads, seq_len_q) + exp_scores = exp_scores.reshape(batch_size, num_heads, seq_len_q, seq_len_k) + softmax = softmax.reshape(batch_size, num_heads, seq_len_q, seq_len_k) + attention_shifted_scaled_scores = attention_shifted_scaled_scores.reshape(batch_size, num_heads, seq_len_q, seq_len_k) + attention_scaled_scores = attention_scaled_scores.reshape(batch_size, num_heads, seq_len_q, seq_len_k) + attention_scores = attention_scores.reshape(batch_size, num_heads, seq_len_q, seq_len_k) + + # Restore original layout if necessary + if layout == "bshd": + o = o.transpose(1, 2) + + return o, softmax_lse, exp_scores, softmax, attention_shifted_scaled_scores, attention_scaled_scores, attention_scores + +def attention_varlen_forward_pytorch_ref_impl( + q, + k, + v, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + use_exp2 +): + # Ensure the layout is 'thd' + if layout != 'thd': + raise ValueError(f"Unsupported layout {layout}. Expected 'thd'.") + + batch_size = cu_seqlens_q.shape[0] - 1 + num_heads = q.shape[1] + head_dim = q.shape[2] + + # Pre-allocate outputs + total_L_q = q.shape[0] + total_L_k = k.shape[0] + + o = torch.empty((total_L_q, num_heads, head_dim), dtype=q.dtype, device=q.device) + softmax_lse = torch.empty((total_L_q, num_heads), dtype=torch.float32, device=q.device) + + for i in range(batch_size): + # Get the start and end indices for the current sequence + start_q = cu_seqlens_q[i].item() + end_q = cu_seqlens_q[i + 1].item() + start_k = cu_seqlens_k[i].item() + end_k = cu_seqlens_k[i + 1].item() + + # Extract q_i, k_i, v_i + q_i = q[start_q:end_q, :, :] # [L_q_i, num_heads, head_dim] + k_i = k[start_k:end_k, :, :] # [L_k_i, num_heads, head_dim] + v_i = v[start_k:end_k, :, :] # [L_k_i, num_heads, head_dim] + + # Permute to [num_heads, L_q_i, head_dim] + q_i = q_i.permute(1, 0, 2) + k_i = k_i.permute(1, 0, 2) + v_i = v_i.permute(1, 0, 2) + + # Call the core attention function for this sequence + ( + o_i, + softmax_lse_i, + exp_scores_i, + softmax_i, + attention_shifted_scaled_scores_i, + attention_scaled_scores_i, + attention_scores_i, + ) = attention_forward_core_ref_impl(q_i, k_i, v_i, sm_scale, causal, use_exp2) + + # Convert back to 'thd' layout and float16 + o_i = o_i.permute(1, 0, 2).to(torch.float16) # [L_q_i, num_heads, head_dim] + + # Place outputs in pre-allocated tensors + o[start_q:end_q, :, :] = o_i + softmax_lse[start_q:end_q, :] = softmax_lse_i.transpose(0, 1) # Transpose to [L_q_i, num_heads] + + # For variable-sized outputs, map them into the preallocated tensors + # exp_scores_i: [num_heads, L_q_i, L_k_i] -> [L_q_i, num_heads, L_k_i] + exp_scores_i = exp_scores_i.permute(1, 0, 2) + softmax_i = softmax_i.permute(1, 0, 2) + attention_shifted_scaled_scores_i = attention_shifted_scaled_scores_i.permute(1, 0, 2) + attention_scaled_scores_i = attention_scaled_scores_i.permute(1, 0, 2) + attention_scores_i = attention_scores_i.permute(1, 0, 2) + + return ( + o, + softmax_lse, + None, + None, + None, + None, + None, + ) + + +def attention_forward_pytorch_ref_impl( + q, + k, + v, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + use_exp2 + ): + if DEBUG: + print() + print("attention_forward_pytorch_ref_impl") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("sm_scale:", sm_scale) + print("causal:", causal) + print("cu_seqlens_q:", cu_seqlens_q) + print("cu_seqlens_k:", cu_seqlens_k) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("use_exp2:", use_exp2) + + # compute reference + if layout == "thd": + ( + o_ref, + softmax_lse_ref, + exp_scores_ref, + softmax_ref, + attention_shifted_scaled_scores_ref, + attention_scaled_scores_ref, + attention_scores_ref, + ) = attention_varlen_forward_pytorch_ref_impl( + q.clone(), + k.clone(), + v.clone(), + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + use_exp2, + ) + else: + ( + o_ref, + softmax_lse_ref, + exp_scores_ref, + softmax_ref, + attention_shifted_scaled_scores_ref, + attention_scaled_scores_ref, + attention_scores_ref, + ) = attention_vanilla_forward_pytorch_ref_impl( + q.clone(), k.clone(), v.clone(), sm_scale, causal, layout, use_exp2 + ) + + if DEBUG: + print() + print("attention_forward_pytorch_ref_impl outputs") + print("o_ref:", o_ref, o_ref.shape) + print("softmax_lse_ref:", softmax_lse_ref, softmax_lse_ref.shape) + print("exp_scores_ref:", exp_scores_ref, exp_scores_ref.shape if exp_scores_ref is not None else None) + + return ( + o_ref, + softmax_lse_ref, + exp_scores_ref, + softmax_ref, + attention_shifted_scaled_scores_ref, + attention_scaled_scores_ref, + attention_scores_ref, + ) + + +def compute_alibi_tensor_ref(alibi_slopes, seqlen_q, seqlen_k): + q_idx = torch.arange(seqlen_q, dtype=torch.int32, device="cuda").unsqueeze(-1) # (N_CTX_Q, 1) + k_idx = torch.arange(seqlen_k, dtype=torch.int32, device="cuda").unsqueeze(0) # (1, N_CTX_K) + relative_pos = torch.abs(q_idx + seqlen_k - seqlen_q - k_idx) # (N_CTX_Q, N_CTX_K) + return -1 * alibi_slopes.unsqueeze(-1).unsqueeze(-1) * relative_pos # (Z, H, N_CTX_Q, N_CTX_K) \ No newline at end of file diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/interface_fa.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/interface_fa.py new file mode 100644 index 0000000000000000000000000000000000000000..59a306d5d6ae3a343205cb5db9fbf98d80492709 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/interface_fa.py @@ -0,0 +1,535 @@ +import torch +import os +from .fwd_prefill import attention_prefill_forward_triton_impl +from .bwd_prefill import attention_prefill_backward_triton_impl +from .fwd_decode import attention_decode_forward_triton_impl +from .fwd_ref import attention_forward_pytorch_ref_impl +from .bwd_ref import attention_backward_pytorch_ref_impl +from .utils import MetaData, get_shape_from_layout, DEBUG + +USE_REF = os.environ.get('FLASH_ATTENTION_TRITON_AMD_REF', '0').lower() in ('1', 'true', 'yes') + +def fwd(q, + k, + v, + o, + alibi_slopes, + dropout_p, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + return_softmax, + gen_): + + if DEBUG: + print() + print("flash_attn_triton_amd.py::fwd") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("o:", o) + print("alibi_slopes:", alibi_slopes) + print("dropout_p:", dropout_p) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("softcap:", softcap) + print("softcap:", softcap) + print("return_softmax:", return_softmax) + + + if dropout_p != 0.0: + raise ValueError("dropout is not supported on AMD's Triton Backend yet") + + if o is None: + o = torch.empty_like(q) + + # Setup metadata + metadata = MetaData(sm_scale=softmax_scale) + metadata.max_seqlens_q = q.shape[1] + metadata.max_seqlens_k = k.shape[1] + metadata.layout = "bshd" + if return_softmax: + metadata.return_scores = True + + batch, nheads_q, nheads_k, head_size, _, _ = get_shape_from_layout(q, k, metadata.layout) + + if causal: + metadata.need_causal() + + if alibi_slopes is not None: + metadata.need_alibi(alibi_slopes, batch, nheads_q) + + if dropout_p > 0.0: + metadata.need_dropout(dropout_p, return_softmax) + + # Check arguments + metadata.check_args(q, k, v, o) + if USE_REF: + if DEBUG: + print("Using reference implementation") + (output, + softmax_lse, + exp_scores, + _, + _, + _, + _) = attention_forward_pytorch_ref_impl( + q, + k, + v, + metadata.sm_scale, + metadata.causal, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.use_exp2) + o.copy_(output) + else: + if DEBUG: + print("Using Triton implementation") + (_, + softmax_lse, + exp_scores, + _, + _, + _, + _, + _, + _) = attention_prefill_forward_triton_impl( + q, + k, + v, + o, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.bias, + metadata.dropout_p, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.return_scores, + metadata.use_exp2) + + if DEBUG: + print("fwd outputs") + print("o:", o, o.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("exp_scores:", exp_scores, exp_scores.shape if exp_scores is not None else None ) + + return o, softmax_lse, exp_scores, None + +def bwd( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + alibi_slopes, + dropout_p, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + deterministic, + gen_, + rng_state, +): + if DEBUG: + print() + print("flash_attn_triton_amd.py::bwd") + print("dout:", dout, dout.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("out:", out, out.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("dq:", dq, dq.shape) + print("dk:", dk, dk.shape) + print("dv:", dv, dv.shape) + print("alibi_slopes:", alibi_slopes) + print("dropout_p:", dropout_p) + print("out:", out) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("deterministic:", deterministic) + print("gen_:", gen_) + print("rng_state:", rng_state) + + if dropout_p != 0.0: + raise ValueError("dropout is not supported on AMD yet") + + if USE_REF: + if DEBUG: + print("Using reference implementation") + dq_ref, dk_ref, dv_ref, delta_ref = attention_backward_pytorch_ref_impl( + dout, + q, + k, + v, + out, + softmax_lse, + softmax_scale, + causal, + "bshd", + None, + None, + None, + None, + False, + ) + dq.copy_(dq_ref) + dk.copy_(dk_ref) + dv.copy_(dv_ref) + delta = delta_ref + else: + if DEBUG: + print("Using Triton implementation") + dq_triton, dk_triton, dv_triton, delta_triton, _, _ = attention_prefill_backward_triton_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "bshd", + None, + None, + None, + None, + False, + ) + delta = delta_triton + + if DEBUG: + print("bwd outputs") + print("dv:", dv, dv.shape) + print("dk:", dk, dk.shape) + print("dq:", dq, dq.shape) + return dq, dk, dv, delta + +def varlen_fwd( + q, + k, + v, + o, + cu_seqlens_q, + cu_seqlens_k, + seqused_k, + leftpad_k, + block_table_, + alibi_slopes,\ + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + zero_tensors, + causal, + window_size_left, + window_size_right, + softcap, + return_softmax, + gen_): + + if DEBUG: + print() + print("flash_attn_triton_amd.py::varlen_fwd") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("cu_seqlens_q:", cu_seqlens_q, cu_seqlens_q.shape) + print("cu_seqlens_k:", cu_seqlens_k, cu_seqlens_k.shape) + print("alibi_slopes:", alibi_slopes) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("dropout_p:", dropout_p) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("gen_:", gen_) + + if dropout_p != 0.0: + raise ValueError("dropout is not supported on AMD's Triton Backend yet") + + if o is None: + o = torch.empty_like(q) + + # Setup metadata + metadata = MetaData(sm_scale=softmax_scale) + if return_softmax: + metadata.return_scores = True + metadata.set_varlen_params(cu_seqlens_q, cu_seqlens_k) # set layout to "thd" and other metdata + + # get shapes + batch, nheads_q, nheads_k, head_size , seqlen_q, seqlen_k = get_shape_from_layout(q, k, metadata.layout, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) + + if causal: + metadata.need_causal() + + if alibi_slopes is not None: + metadata.need_alibi(alibi_slopes, batch, nheads_q) + + if dropout_p > 0.0: + metadata.need_dropout(dropout_p, return_softmax) + + # Check arguments + metadata.check_args(q, k, v, o) + if o is None: + o = torch.empty_like(q, dtype=v.dtype) + + if USE_REF: + if DEBUG: + print("Using reference implementation") + (output, + softmax_lse, + exp_scores, + _, + _, + _, + _) = attention_forward_pytorch_ref_impl( + q, + k, + v, + metadata.sm_scale, + metadata.causal, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.use_exp2) + o.copy_(output) + else: + if DEBUG: + print("Using Triton implementation") + (_, + softmax_lse, + exp_scores, + _, + _, + _, + _, + _, + _) = attention_prefill_forward_triton_impl( + q, + k, + v, + o, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.bias, + metadata.dropout_p, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.return_scores, + metadata.use_exp2) + if DEBUG: + print("varlen_fwd outputs") + print("o:", o, o.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("exp_scores:", exp_scores, exp_scores.shape if exp_scores is not None else None ) + + + return o, softmax_lse, exp_scores, None + +def varlen_bwd( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + alibi_slopes, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + zero_tensors, + causal, + window_size_left, + window_size_right, + softcap, + deterministic, + gen_, + rng_state, +): + if DEBUG: + print() + print("varlen_bwd") + print("dout:", dout, dout.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("dq:", dq, dq.shape) + print("dk:", dk, dk.shape) + print("dv:", dv, dv.shape) + print("cu_seqlens_q:", cu_seqlens_q, cu_seqlens_q.shape) + print("cu_seqlens_k:", cu_seqlens_k, cu_seqlens_k.shape) + print("alibi_slopes:", alibi_slopes) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("dropout_p:", dropout_p) + print("out:", out) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("deterministic:", deterministic) + print("gen_:", gen_) + print("rng_state:", rng_state) + + if dropout_p != 0.0: + raise ValueError("dropout is not supported on AMD yet") + + if USE_REF: + if DEBUG: + print("Using reference implementation") + dq_ref, dk_ref, dv_ref, delta_ref = attention_backward_pytorch_ref_impl( + dout, + q, + k, + v, + out, + softmax_lse, + softmax_scale, + causal, + "thd", + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + False, + ) + dq.copy_(dq_ref) + dk.copy_(dk_ref) + dv.copy_(dv_ref) + delta = delta_ref + else: + if DEBUG: + print("Using Triton implementation") + dq_triton, dk_triton, dv_triton, delta_triton, _, _ = attention_prefill_backward_triton_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "thd", + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + False, + ) + delta = delta_triton + + if DEBUG: + print("varlen_bwd outputs") + print("delta:", delta, delta.shape) + print("dv:", dv, dv.shape) + print("dk:", dk, dk.shape) + print("dq:", dq, dq.shape) + + return dq, dk, dv, delta + +def fwd_kvcache( + q, + k_cache, + v_cache, + k, + v, + cache_seqlens, + rotary_cos, + rotary_sin, + cache_batch_idx, + cache_leftpad, + block_table, + alibi_slopes, + out, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + rotary_interleaved, + num_splits): + + if out is None: + out = torch.empty_like(q) + + # fill metadata + metadata = MetaData(sm_scale=softmax_scale) + metadata.layout = "bshd" + metadata.max_seqlens_q = q.shape[1] + metadata.max_seqlens_k = k_cache.shape[1] + metadata.cache_seqlens = cache_seqlens + metadata.cache_batch_idx = cache_batch_idx + + if k is not None and v is not None: + metadata.new_kv = True + metadata.seqlen_new = k.shape[1] + metadata.k_new = k + metadata.v_new = v + + if causal: + metadata.need_causal() + + if alibi_slopes is not None: + batch, _ , nheads_q, _= q.shape + metadata.need_alibi(alibi_slopes, batch, nheads_q) + + # launch kernel + # TODO: pass output as an arg. Maybe we are copying output which is causing slow down + output, softmax_lse = attention_decode_forward_triton_impl( + q, + k_cache, + v_cache, + metadata.sm_scale, + metadata.causal, + metadata.alibi_slopes, + metadata.layout, + metadata.cache_seqlens, + metadata.cache_batch_idx, + metadata.new_kv, + metadata.k_new, + metadata.v_new, + ) + return output, softmax_lse diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/interface_torch.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/interface_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..d4906606eda950d1d4c3ac6d60ce612e45eba79e --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/interface_torch.py @@ -0,0 +1,97 @@ +import torch +from .fwd_prefill import attention_prefill_forward_triton_impl +from .bwd_prefill import attention_prefill_backward_triton_impl +from .fwd_decode import attention_decode_forward_triton_impl + + +class _attention_prefill(torch.autograd.Function): + @staticmethod + def forward(ctx, q, k, v, o, metadata): + (output, + softmax_lse, + exp_scores, + grid, + head_size, + philox_seed, + philox_offset, + _, + _) = attention_prefill_forward_triton_impl( + q, + k, + v, + o, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.bias, + metadata.dropout_p, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.return_scores, + metadata.use_exp2) + + ctx.save_for_backward(q, k, v, o, softmax_lse) + ctx.grid = grid + ctx.sm_scale = metadata.sm_scale + ctx.head_size = head_size + ctx.causal = metadata.causal + ctx.alibi_slopes = metadata.alibi_slopes + ctx.dropout_p = metadata.dropout_p + ctx.philox_seed = philox_seed + ctx.philox_offset = philox_offset + ctx.exp_scores = exp_scores + ctx.return_scores = metadata.return_scores + ctx.layout = metadata.layout + ctx.use_exp2 = metadata.use_exp2 + return output, softmax_lse, exp_scores + + @staticmethod + def backward(ctx, do, *args): + q, k, v, o, softmax_lse = ctx.saved_tensors + return attention_prefill_backward_triton_impl( + do, + q, + k, + v, + o, + softmax_lse, + None, + None, + None, + ctx.sm_scale, + ctx.alibi_slopes, + ctx.causal, + ctx.layout, + None, + None, + None, + None, + ctx.use_exp2 + ) + +attention_prefill = _attention_prefill.apply + + +class _attention_decode(torch.autograd.Function): + @staticmethod + def forward(ctx, q, k, v, metadata): + output, softmax_lse = attention_decode_forward_triton_impl( + q, + k, + v, + metadata.sm_scale, + metadata.causal, + metadata.alibi_slopes, + metadata.layout, + metadata.cache_seqlens, + metadata.cache_batch_idx, + metadata.new_kv, + metadata.k_new, + metadata.v_new, + ) + return output, softmax_lse + +attention_decode = _attention_decode.apply diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/test.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/test.py new file mode 100644 index 0000000000000000000000000000000000000000..9a6ab8dab28c15be2d430b792920511aec97ec98 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/test.py @@ -0,0 +1,724 @@ +import torch +import pytest + +from .utils import MetaData, get_input_shapes, input_helper, varlen_input_helper, DEBUG +from .interface_torch import attention_prefill, attention_decode +from .fwd_ref import attention_forward_pytorch_ref_impl, compute_alibi_tensor_ref +from .fwd_prefill import attention_prefill_forward_triton_impl +from .bwd_prefill import attention_prefill_backward_triton_impl +from .bwd_ref import attention_backward_pytorch_ref_impl +from .fwd_decode import dequantize_kv_fp16, quantize_kv_int4 + +# defailt fp16 tolerance is ATOL, RTOL = 1e-5, 1e-3. See table https://pytorch.org/docs/stable/testing.html +ATOL, RTOL = 1e-2, 1e-2 # old standard. maybe to lose. +# ATOL, RTOL = 1e-3, 1e-3 # catchs fa mismatch issues +# ATOL, RTOL = 1e-4, 1e-3 # to strict. there will be small diffs +# ATOL, RTOL = 1e-5, 1e-3 # # default fp16. there will be small diffs +EQUAL_NAN = True + +@pytest.mark.parametrize('Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD', [ + (4, 48, 24, 1024, 1024, 64), + (1, 24, 6, 8192, 8192, 64), + (1, 4, 2, 16384, 16384, 128), + (2, 16, 4, 1020, 987, 128), + (2, 16, 4, 15498, 2, 128), + (2, 16, 2, 7, 16219, 64), + (4, 48, 12, 1, 1, 64), + (4, 48, 48, 1, 1, 128), + (4, 48, 24, 3, 3, 128), + (4, 48, 48, 1001, 990, 64), + (1, 8, 8, 8081, 7099, 64), + (1, 4, 4, 16330, 15989, 128), + (4, 4, 1, 1024, 1024, 33), + (4, 4, 2, 65, 1018, 65), + (4, 4, 4, 128, 128, 65), + (4, 4, 4, 113, 123, 1), +]) +@pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('use_alibi', [True, False]) +@pytest.mark.parametrize('layout', ['bshd', 'bhsd']) +def test_op_fwd_prefill(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, use_alibi, layout, dtype=torch.float16): + torch.manual_seed(20) + q, k, v, input_metadata = input_helper(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, layout) + if causal: + input_metadata.need_causal() + + if use_alibi: + # for n heads the set of slopes is the geometric sequence that starts 2^(-8/n) + alibi_slopes = torch.tensor([2**(-8 / HQ * i) for i in range(1, HQ + 1)], dtype=torch.float32, + device="cuda").repeat(Z, 1) + input_metadata.need_alibi(alibi_slopes, Z, HQ) + else: + alibi_slopes = None + + o = torch.empty_like(q) + + # triton implementation + tri_out, _, _ = attention_prefill(q, k, v, o, input_metadata) + + # Transpose here if layout is bshd so we have same reference code for all layouts + if layout == 'bshd': + q = q.transpose(1, 2).clone() + k = k.transpose(1, 2).clone() + v = v.transpose(1, 2).clone() + # Replicate K and V if using MQA/GQA + if HQ != HK: + k = k.view(k.shape[0], k.shape[1], -1, k.shape[2], + k.shape[3]).expand(-1, -1, HQ // HK, -1, -1).reshape(k.shape[0], -1, k.shape[2], k.shape[3]) + v = v.view(v.shape[0], v.shape[1], -1, v.shape[2], + v.shape[3]).expand(-1, -1, HQ // HK, -1, -1).reshape(v.shape[0], -1, v.shape[2], v.shape[3]) + + scores = torch.einsum('bhqd,bhkd->bhqk', q, k).float() * input_metadata.sm_scale + if causal: + mask = torch.tril(torch.ones(N_CTX_Q, N_CTX_K, device="cuda"), diagonal=N_CTX_K - N_CTX_Q) + scores[:, :, mask == 0] = float("-inf") + if use_alibi: + scores += compute_alibi_tensor_ref(alibi_slopes, N_CTX_Q, N_CTX_K) + + p = torch.softmax(scores, dim=-1) + if causal: + # If N_CTX_Q > N_CTX_K, there is at least one row of all -infs going into + # the softmax. This produces a row of NaNs as -inf - -inf == NaN. So we fix + # this by converting the NaNs to 0s, which is what they should be out of the softmax. + nan_mask = torch.isnan(p) + p[nan_mask == 1] = 0 + ref_out = torch.einsum('bhqk,bhkd->bhqd', p.half(), v) + # compare + if layout == 'bshd': + ref_out = ref_out.transpose(1, 2).clone() + torch.testing.assert_close(ref_out, tri_out, atol=2e-2, rtol=2e-2) + + +@pytest.mark.parametrize('Z, H, N_CTX_Q, N_CTX_K, D_HEAD', [ + (4, 48, 1024, 1024, 64), + (4, 12, 8192, 8192, 64), + (2, 4, 16384, 16384, 128), + (2, 16, 15498, 2, 128), + (2, 4, 7, 16219, 64), + (4, 48, 1, 1, 64), + (4, 48, 1, 1, 128), + (4, 48, 3, 3, 128), + (4, 48, 1001, 990, 64), + (1, 8, 8081, 7099, 64), + (1, 8, 16330, 15989, 128), + (4, 4, 1024, 1024, 33), + (4, 4, 65, 1019, 65), + (4, 4, 128, 128, 65), + # TODO: This config fails. Disabled until triaged and fixed. + # (2, 16, 1020, 987, 128), + # (4, 4, 113, 123, 1), +]) +@pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('use_bias', [True]) +def test_op_fwd_prefill_bias(Z, H, N_CTX_Q, N_CTX_K, D_HEAD, causal, use_bias, dtype=torch.float16): + torch.manual_seed(20) + sm_scale = D_HEAD**-0.5 + input_metadata = MetaData(sm_scale=sm_scale) + q, k, v, input_metadata = input_helper(Z, H, H, N_CTX_Q, N_CTX_K, D_HEAD, dtype, layout='bhsd') + if causal: + input_metadata.need_causal() + if use_bias: + bias = torch.randn((1, H, N_CTX_Q, N_CTX_K), dtype=torch.float32, device="cuda") + input_metadata.need_bias(bias, Z, H, N_CTX_Q, N_CTX_K) + else: + bias = None + o = torch.empty_like(q) + + # triton implementation + tri_out, _, _ = attention_prefill(q, k, v, o, input_metadata) + # reference implementation:171 + + scores = torch.einsum('bhqd,bhkd->bhqk', q, k).float() * sm_scale + if causal: + mask = torch.tril(torch.ones(N_CTX_Q, N_CTX_K, device="cuda"), diagonal=N_CTX_K - N_CTX_Q) + scores[:, :, mask == 0] = float("-inf") + if use_bias: + scores += input_metadata.bias + p = torch.softmax(scores, dim=-1) + if causal: + # If N_CTX_Q > N_CTX_K, there is at least one row of all -infs going into + # the softmax. This produces a row of NaNs as -inf - -inf == NaN. So we fix + # this by converting the NaNs to 0s, which is what they should be out of the softmax. + nan_mask = torch.isnan(p) + p[nan_mask == 1] = 0 + ref_out = torch.einsum('bhqk,bhkd->bhqd', p.half(), v) + # compare + torch.testing.assert_close(ref_out, tri_out, atol=2e-2, rtol=2e-2) + + +@pytest.mark.parametrize('Z, H, N_CTX, D_HEAD', [ + (4, 48, 8192, 64), + (4, 48, 256, 64), + (4, 48, 512, 64), + (4, 48, 1024, 64), + (8, 48, 4096, 64), + (4, 48, 8192, 64), + (4, 48, 128, 128), + (4, 48, 4096, 128), + (4, 48, 16384, 128), + (4, 16, 1024, 128), + (4, 16, 8192, 128), + (32, 48, 8192, 128) + ] + ) +@pytest.mark.parametrize('causal', [True, False]) +def test_op_varlen_fwd(Z, H, N_CTX, D_HEAD, causal, dtype=torch.float16): + + q, k, v, input_metadata = varlen_input_helper(Z, H, H, N_CTX, N_CTX, D_HEAD, dtype) + + tri_out = torch.empty_like(q) + ref_out = torch.empty_like(q) + + for i in range(0, input_metadata.num_contexts): + start_q, start_k = input_metadata.cu_seqlens_q[i], input_metadata.cu_seqlens_k[i] + end_q, end_k = input_metadata.cu_seqlens_q[i + 1], input_metadata.cu_seqlens_k[i + 1] + scores = torch.einsum('qhd,khd->qhk', q[start_q:end_q], k[start_k:end_k]).float() + p = torch.softmax(scores * input_metadata.sm_scale, dim=-1).half() + ref_out[start_q:end_q] = torch.einsum('qhk,khd->qhd', p, v[start_k:end_k]) + attention_prefill(q, k, v, tri_out, input_metadata) + torch.testing.assert_close(ref_out, tri_out, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize('Z, HQ, HK, N_CTX, D_HEAD', [(2, 48, 24, 128, 64), (4, 48, 12, 256, 64), (4, 48, 4, 512, 64), + (4, 48, 2, 1024, 64), (8, 48, 6, 4096, 64), (4, 48, 8, 16384, 64), + (4, 64, 16, 128, 128), (4, 64, 4, 4096, 128), + (4, 64, 8, 16384, 128), (4, 16, 4, 1024, 128), + (4, 16, 2, 8192, 128), (32, 128, 32, 8192, 128)]) +@pytest.mark.parametrize('causal', [False]) +def test_op_varlen_mqa_fwd(Z, HQ, HK, N_CTX, D_HEAD, causal, dtype=torch.float16): + q, k, v, input_metadata = varlen_input_helper(Z, HQ, HK, N_CTX, N_CTX, D_HEAD, dtype) + ref_out = torch.empty_like(q) + tri_out = torch.empty_like(q) + # Make KV look like HQ/HK "groups" of HK. Later, we will reshape so the + # size aligns with Q. + k_ref = k.view(k.shape[0], k.shape[1], 1, k.shape[2]).expand(-1, -1, HQ // HK, -1) + v_ref = v.view(v.shape[0], v.shape[1], 1, v.shape[2]).expand(-1, -1, HQ // HK, -1) + for i in range(0, input_metadata.num_contexts): + start_q, start_k = input_metadata.cu_seqlens_q[i], input_metadata.cu_seqlens_k[i] + end_q, end_k = input_metadata.cu_seqlens_q[i + 1], input_metadata.cu_seqlens_k[i + 1] + k_curr = k_ref[start_k:end_k] + k_curr = k_curr.reshape(k_curr.shape[0], -1, k_curr.shape[3]) + v_curr = v_ref[start_k:end_k] + v_curr = v_curr.reshape(v_curr.shape[0], -1, v_curr.shape[3]) + scores = torch.einsum('qhd,khd->qhk', q[start_q:end_q], k_curr).float() + p = torch.softmax(scores * input_metadata.sm_scale, dim=-1).half() + ref_out[start_q:end_q] = torch.einsum('qhk,khd->qhd', p, v_curr) + attention_prefill(q, k, v, tri_out, input_metadata) + torch.testing.assert_close(ref_out, tri_out, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize('Z, H, N_CTX_Q, N_CTX_K, D_HEAD', [ + # smallest config test + (1, 1, 16, 16, 64), # pass on new # fail on old + (1, 1, 32, 32, 64), # pass on new # fail on old + (1, 1, 64, 64, 16), # pass # smallest head_size = 16 + (1, 1, 64, 64, 64), # pass # smallest seq len seems to be 64 + (1, 1, 128, 128, 64), # pass + (1, 1, 256, 256, 64), # pass + (1, 1, 512, 512, 64), # pass + # failing FA + (1, 1, 256, 512, 16), + # old tests that work + (4, 48, 1024, 1024, 64), # pass + (4, 48, 2048, 2048, 64), # pass + (2, 48, 4096, 4096, 64), # pass + (1, 16, 1024, 1024, 64), # pass + (1, 16, 1024, 1024, 128), # pass + # old tests that were commented out + # (1, 16, 8192, 8192, 63), + # (1, 16, 1022, 1022, 64), +]) +# @pytest.mark.parametrize('torch_sdpa_test', [False, True]) +@pytest.mark.parametrize('torch_sdpa_test', [False]) +# @pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('causal', [False]) +# @pytest.mark.parametrize('use_alibi', [False, True]) +@pytest.mark.parametrize('use_alibi', [False]) +def test_op_bwd(Z, H, N_CTX_Q, N_CTX_K, D_HEAD, causal, torch_sdpa_test, use_alibi, dtype=torch.float16): + torch.manual_seed(20) + + DEBUG_INPUT = False + + # seqlens + seqlen_q = N_CTX_Q + seqlen_k = N_CTX_K + + # setup up metadata + if DEBUG_INPUT: + sm_scale = 1 + else: + sm_scale = D_HEAD**-0.5 + input_metadata = MetaData(sm_scale=sm_scale) + input_metadata.max_seqlens_q = seqlen_q + input_metadata.max_seqlens_k = seqlen_k + input_metadata.layout = "bhsd" + + dropout_p = 0 + if DEBUG_INPUT: + q = torch.arange(seqlen_q, dtype=dtype, device="cuda").view(1, 1, seqlen_q, 1).expand(Z, H, seqlen_q, D_HEAD).requires_grad_() + k = torch.arange(seqlen_k, dtype=dtype, device="cuda").view(1, 1, seqlen_k, 1).expand(Z, H, seqlen_k, D_HEAD).requires_grad_() + v = torch.arange(seqlen_k, dtype=dtype, device="cuda").view(1, 1, seqlen_k, 1).expand(Z, H, seqlen_k, D_HEAD).requires_grad_() + o = torch.zeros_like(q) + else: + # Generate random inputs + q = torch.randn(Z, H, N_CTX_Q, D_HEAD, device='cuda', dtype=dtype, requires_grad=True) + k = torch.randn(Z, H, N_CTX_K, D_HEAD, device='cuda', dtype=dtype, requires_grad=True) + v = torch.randn(Z, H, N_CTX_K, D_HEAD, device='cuda', dtype=dtype, requires_grad=True) + o = torch.empty_like(q) + + if causal: + input_metadata.need_causal() + + if use_alibi and not torch_sdpa_test: + # for n heads the set of slopes is the geometric sequence that starts 2^(-8/n) + alibi_slopes = torch.tensor([2**(-8 / H * i) for i in range(1, H + 1)], dtype=torch.float32, + device="cuda").repeat(Z, 1) + input_metadata.need_alibi(alibi_slopes, Z, H) + + if DEBUG_INPUT: + dout = torch.ones_like(q) + else: + dout = torch.randn_like(q) + + # reference implementation + if torch_sdpa_test: + ref_out, ref_softmax = torch.ops.aten._scaled_dot_product_attention_math(q, k, v, dropout_p=dropout_p, + is_causal=causal, scale=sm_scale, + dropout_mask=None) + ref_out.backward(dout.to(device=ref_out.device, dtype=ref_out.dtype)) + ref_dv, v.grad = v.grad.clone(), None + ref_dk, k.grad = k.grad.clone(), None + ref_dq, q.grad = q.grad.clone(), None + else: + M = torch.tril(torch.ones((seqlen_q, seqlen_k), device="cuda")) + p = torch.matmul(q, k.transpose(2, 3)) * sm_scale + if use_alibi: + p += compute_alibi_tensor_ref(alibi_slopes, N_CTX_Q, N_CTX_K) + if causal: + p[:, :, M == 0] = float("-inf") + + p = torch.softmax(p.float(), dim=-1).type(dtype=p.dtype) + ref_out = torch.matmul(p, v) + ref_out.backward(dout) + ref_dv, v.grad = v.grad.clone(), None + ref_dk, k.grad = k.grad.clone(), None + ref_dq, q.grad = q.grad.clone(), None + + # # triton implementation + tri_out, _, _ = attention_prefill(q, k, v, o, input_metadata) + tri_out.backward(dout) + tri_dv, v.grad = v.grad.clone(), None + tri_dk, k.grad = k.grad.clone(), None + tri_dq, q.grad = q.grad.clone(), None + # compare + if DEBUG: + print("tri_out:", tri_out) + print("ref_out:",ref_out ) + torch.testing.assert_close(ref_out, tri_out, atol=1e-2, rtol=0) + + # The current block size for MI200 series is 64x64. This results in + # larger differences in float results due to rounding. + if dtype == torch.bfloat16: + ATOL = 1e-1 * max(1.0, (seqlen_q + D_HEAD) / 64.0) + if dtype == torch.float32: + ATOL = 1e-3 * max(1.0, (seqlen_q + D_HEAD) / 64.0) + else: + ATOL = 1e-1 * max(1.0, (seqlen_q + D_HEAD) / 64.0) + + RTOL = 0 + + if DEBUG: + print("ref_dv:", ref_dv) + print("tri_dv:", tri_dv) + print("ref_dk:", ref_dk) + print("tri_dk:", tri_dk) + print("ref_dq:", ref_dq) + print("tri_dq:", tri_dq) + + torch.testing.assert_close(ref_dv, tri_dv, atol=ATOL, rtol=RTOL) + torch.testing.assert_close(ref_dk, tri_dk, atol=ATOL, rtol=RTOL) + torch.testing.assert_close(ref_dq, tri_dq, atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize('Z, H, N_CTX_Q, N_CTX_K, D_HEAD', [ + (1, 1, 1, 1, 1), + (1, 1, 2, 4, 16), + (1, 1, 4, 2, 16), + (1, 1, 4, 4, 16), + (1, 2, 4, 4, 16), + (2, 1, 4, 4, 16), + (2, 2, 4, 4, 16), + (1, 1, 128, 64, 16), + (2, 2, 2, 128, 1), + (2, 3, 2, 128, 16), + (3, 2, 256, 512, 16), + (3, 3, 128, 128, 64), + (2, 4, 1024, 1024, 64), + (4, 6, 108, 256, 224), + (4, 8, 2048, 2048, 128), + (4, 16, 4096, 4096, 64), + (2, 4, 8192, 8192, 32), + # # fa configs + (4, 6, 113, 203, 256), + (4, 6, 128, 217, 256), + (4, 6, 113, 211, 128), + (4, 6, 108, 256, 128), + (4, 6, 256, 512, 64), + (4, 6, 512, 256, 64), + (4, 6, 1024, 1024, 32), + (4, 6, 1023, 1024, 32), + (4, 6, 1024, 1023, 32), + (4, 6, 2048, 2048, 32), +]) +@pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('return_scores', [False]) +@pytest.mark.parametrize('layout', ["bhsd", "bshd", "thd"]) +@pytest.mark.parametrize('use_exp2', [True, False]) # works when use_exp2 is false +@pytest.mark.parametrize('DEBUG_INPUT', [False]) # NOTE: debug input can overflow when the tensors are large. Just use to figure out issues +def test_op_prefill_fwd_impl(Z, H, N_CTX_Q, N_CTX_K, D_HEAD, causal, return_scores, layout, use_exp2, DEBUG_INPUT): + dtype = torch.float16 + torch.manual_seed(0) + alibi_slopes = None + dropout_p = 0.0 + device = "cuda" + + if layout == "thd": + q, k, v, metadata = varlen_input_helper(Z, H, H, N_CTX_Q, N_CTX_K, D_HEAD, dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + else: + q, k, v, metadata = input_helper(Z, H, H, N_CTX_Q, N_CTX_K, D_HEAD, dtype, layout, device=device, DEBUG_INPUT=DEBUG_INPUT) + if DEBUG_INPUT: + output_triton = torch.zeros_like(q).contiguous() + else: + output_triton = torch.empty_like(q) + + # update metadata + metadata.use_exp2 = use_exp2 + if causal: + metadata.need_causal() + + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + if return_scores: + metadata.return_scores = True + + # call Triton's forward implementation directly + ( output_triton, + softmax_lse_triton, + exp_scores_triton, + _, + _, + _, + _, + _, + _) = attention_prefill_forward_triton_impl( + q, + k, + v, + output_triton, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.bias, + metadata.dropout_p, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.return_scores, + metadata.use_exp2) + + ( + output_ref, + softmax_lse_ref, + exp_scores_ref, + softmax_ref, + attention_shifted_scaled_scores_ref, + attention_scaled_scores_ref, + attention_scores_ref, + ) = attention_forward_pytorch_ref_impl( + q.clone(), + k.clone(), + v.clone(), + metadata.sm_scale, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + use_exp2 + ) + + if DEBUG: + print("softmax_lse_triton:", softmax_lse_triton, softmax_lse_triton.shape) + print("softmax_lse_ref:", softmax_lse_ref, softmax_lse_ref.shape) + torch.testing.assert_close(softmax_lse_triton, softmax_lse_ref, atol=ATOL, rtol=RTOL) + + if layout != "thd": + # use trick with lse to get the softmax. you need the scores but is it + softmax_triton = torch.exp(attention_scaled_scores_ref - softmax_lse_triton.unsqueeze(-1)) + if DEBUG: + print("attention_scaled_scores_ref:", attention_scaled_scores_ref, attention_scaled_scores_ref.shape) + print("softmax_lse_triton:", softmax_lse_triton, softmax_lse_triton.shape) + print("softmax_triton:", softmax_triton, softmax_triton.shape) + print("softmax_ref:", softmax_ref, softmax_ref.shape) + torch.testing.assert_close(softmax_triton, softmax_ref, atol=ATOL, rtol=RTOL) + + if DEBUG: + print("output_triton:", output_triton, output_triton.shape) + print("output_ref:", output_ref, output_ref.shape) + torch.testing.assert_close(output_triton, output_ref, atol=ATOL, rtol=RTOL) + + + # compare with pytorch expect thd and causal impl is different + if False and layout in ["bhsd", "bshd"] and not causal: + out_pytorch, softmax_pytorch = torch.ops.aten._scaled_dot_product_attention_math( + q.transpose(1, 2) if layout == "bshd" else q , + k.transpose(1, 2) if layout == "bshd" else k, + v.transpose(1, 2) if layout == "bshd" else v, + dropout_p=dropout_p, + is_causal=causal, scale=metadata.sm_scale, + dropout_mask=None) + out_pytorch = out_pytorch.transpose(1, 2) if layout == "bshd" else out_pytorch + + if DEBUG: + print("o:", output_triton, output_triton.shape) + print("out_pytorch:", out_pytorch, out_pytorch.shape) + torch.testing.assert_close(output_triton, out_pytorch, atol=ATOL, rtol=RTOL) + + # compare with pytorch output + if DEBUG: + print("softmax_triton:", softmax_triton, softmax_triton.shape) + print("softmax_pytorch:", softmax_pytorch, softmax_pytorch.shape) + torch.testing.assert_close(softmax_triton, softmax_pytorch.to(torch.float32), atol=ATOL, rtol=RTOL) + + +@pytest.mark.parametrize('Z, H, N_CTX_Q, N_CTX_K, D_HEAD', [ + (1, 1, 1, 1, 1), + (1, 1, 4, 4, 4), + (2, 1, 4, 4, 16), + (1, 2, 4, 4, 16), + (2, 2, 4, 4, 16), + (1, 1, 4, 4, 16), + (2, 1, 4, 4 , 16), + (4, 6, 8, 8 , 16), + (1, 1, 4, 4, 32), + (1, 1, 16, 16, 16), + (1, 1, 32, 32, 16), + (1, 1, 64, 64, 16), + (1, 1, 64, 64, 64), + (1, 1, 64, 128, 32), + (1, 1, 128, 128, 64), + (1, 1, 128, 256, 45), + (1, 1, 113, 203, 192), + (1, 1, 256, 256, 64), + (1, 1, 256, 512, 16), + (1, 1, 512, 512, 64), + (1, 1, 1024, 1024, 64), + # fa configs + (2, 2, 128, 128, 65), + (2, 2, 128, 128, 224), + (4, 6, 108, 256, 224), + (1, 1, 256, 512, 16), + # old tests that work + (4, 48, 1024, 1024, 73), + (4, 48, 1024, 1024, 64), + (4, 48, 2048, 2048, 64), + (1, 24, 4096, 4096, 64), + (1, 16, 1024, 1024, 64), + (1, 16, 1024, 1024, 128), +]) +@pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('use_exp2', [False]) # FIXME: using exp2 causes issue when used with causal +@pytest.mark.parametrize('layout', ["bhsd", "bshd", "thd"]) +@pytest.mark.parametrize('sequence_parallel', [True, False]) +@pytest.mark.parametrize('DEBUG_INPUT', [False]) # debug output causes nans in both new and old backend +def test_op_prefill_bwd_impl(Z, H, N_CTX_Q, N_CTX_K, D_HEAD, causal, use_exp2, layout, sequence_parallel, DEBUG_INPUT): + dtype = torch.float16 + torch.manual_seed(20) # seed from test_op_bwd + + alibi_slopes = None + if layout == "thd": + q, k, v, metadata = varlen_input_helper(Z, H, H, N_CTX_Q, N_CTX_K, D_HEAD, dtype, DEBUG_INPUT=DEBUG_INPUT) + else: + q, k, v, metadata = input_helper(Z, H, H, N_CTX_Q, N_CTX_K, D_HEAD, dtype, layout, DEBUG_INPUT=DEBUG_INPUT) + if DEBUG_INPUT: + do = torch.ones_like(q).contiguous() + else: + do = torch.randn_like(q) + + # =============================================== Reference ============================================================== + q_ref = q.clone() + k_ref = k.clone() + v_ref = v.clone() + ( + o_ref, + softmax_lse_ref, + _, + _, + _, + _, + _, + ) = attention_forward_pytorch_ref_impl( + q_ref, + k_ref, + v_ref, + metadata.sm_scale, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + use_exp2 + ) + + dq = torch.zeros_like(q, dtype=q.dtype) # NOTE: the kernel does inplace accumlation on dq so dq has to be zeros + if DEBUG_INPUT: + dk = torch.zeros_like(k, dtype=k.dtype) + dv = torch.zeros_like(v, dtype=v.dtype) + else: + dk = torch.empty_like(k, dtype=k.dtype) + dv = torch.empty_like(v, dtype=v.dtype) + + do_ref = do.clone() + dq_ref, dk_ref, dv_ref, delta_ref = attention_backward_pytorch_ref_impl( + do_ref, + q_ref, + k_ref, + v_ref, + o_ref, + softmax_lse_ref, + metadata.sm_scale, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + use_exp2 + ) + + # =============================================== Triton ============================================================== + o = o_ref.clone().contiguous() + softmax_lse = softmax_lse_ref.clone().contiguous() + dq_triton, dk_triton, dv_triton, delta_triton, _, _ = attention_prefill_backward_triton_impl( + do, + q, + k, + v, + o, + softmax_lse, + dq, + dk, + dv, + metadata.sm_scale, + alibi_slopes, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + use_exp2, + sequence_parallel=sequence_parallel + ) + + # =============================================== Check ============================================================== + if DEBUG: + print() + if DEBUG: + print("delta_triton:", delta_triton, delta_triton.shape) + print("delta_ref:", delta_ref, delta_ref.shape) + torch.testing.assert_close(delta_triton, delta_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + if DEBUG: + print("dv_triton:", dv_triton, dv_triton.shape) + print("dv_ref:", dv_ref, dv_ref.shape) + torch.testing.assert_close(dv_triton, dv_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + if DEBUG: + print("dk_triton:", dk_triton, dk_triton.shape) + print("dk_ref:", dk_ref, dk_ref.shape) + torch.testing.assert_close(dk_triton, dk_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + if DEBUG: + print("dq_triton:", dq_triton, dq_triton.shape) + print("dq_ref:", dq_ref, dq_ref.shape) + torch.testing.assert_close(dq_triton, dq_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + +@pytest.mark.parametrize('batch_size, seqlen_q, seqlen_k, group_q, group_k, dim', get_input_shapes()) +def test_op_fwd_decode(batch_size, seqlen_q, seqlen_k, group_q, group_k, dim, dtype=torch.bfloat16): + if DEBUG: + print() + print(f"batch_size = {batch_size}, seqlen_q = {seqlen_q}, seqlen_k = {seqlen_k}, group_q = {group_q}, group_k = {group_k}, dim = {dim}") + torch.manual_seed(20) + query_group_head_size = (group_q + group_k - 1) // group_k + q = (torch.empty((batch_size, seqlen_q, group_k, query_group_head_size, dim), dtype=dtype, + device="cuda").normal_(mean=0., std=0.5).requires_grad_()) + k = (torch.empty((batch_size, seqlen_k, group_k, 1, dim), dtype=dtype, + device="cuda").normal_(mean=0., + std=0.5).requires_grad_()).expand(-1, -1, -1, query_group_head_size, -1) + v = (torch.empty((batch_size, seqlen_k, group_k, 1, dim), dtype=dtype, + device="cuda").normal_(mean=0., + std=0.5).requires_grad_()).expand(-1, -1, -1, query_group_head_size, -1) + scale = 1 / dim**0.5 + input_metadata = MetaData(sm_scale=scale) + input_metadata.layout = "bsghd" + tri_out, _ = attention_decode(q, k, v, input_metadata) + + q = q.reshape([batch_size, seqlen_q, -1, dim]).permute(0, 2, 1, 3) + k = k.reshape([batch_size, seqlen_k, -1, dim]).permute(0, 2, 1, 3) + v = v.reshape([batch_size, seqlen_k, -1, dim]).permute(0, 2, 1, 3) + attn = (q @ k.transpose(-1, -2) * scale).softmax(-1) + ref_out = attn @ v + + # compare + torch.testing.assert_close(ref_out, tri_out, atol=1e-3, rtol=0) + +def test_quantization(): + a = torch.randn((2, 4, 32), dtype=torch.float16, device='cuda') + qa = quantize_kv_int4(a, num_groups=4) + dqa = dequantize_kv_fp16(qa, num_groups=4) + torch.testing.assert_close(a, dqa, atol=1.5e-1, rtol=1e-1) + +@pytest.mark.parametrize('B, Mq, Mkv, Hq, Hkv, K', get_input_shapes()) +def test_op_fwd_decode_int4_kv(B, Mq, Mkv, Hq, Hkv, K, dtype=torch.float16): + pytest.skip("Decode kernel doesnot support quantization yet") + torch.manual_seed(2) + q = (torch.empty((B, Mq, Hkv, (Hq + Hkv - 1) // Hkv, K), dtype=dtype, + device="cuda").normal_(mean=1.0, std=0.5).requires_grad_()) + k = (torch.empty((B, Mkv, Hkv, 1, K), dtype=dtype, + device="cuda").normal_(mean=1.0, + std=0.5).requires_grad_()).expand(-1, -1, -1, (Hq + Hkv - 1) // Hkv, -1) + v = (torch.empty((B, Mkv, Hkv, 1, K), dtype=dtype, + device="cuda").normal_(mean=1.0, + std=0.5).requires_grad_()).expand(-1, -1, -1, (Hq + Hkv - 1) // Hkv, -1) + + num_groups = 1 + quant_k = (quantize_kv_int4(k, num_groups=num_groups).contiguous().view(torch.int32)) + quant_v = (quantize_kv_int4(v, num_groups=num_groups).contiguous().view(torch.int32)) + scale = 1 / K**0.5 + input_metadata = MetaData(sm_scale=scale) + input_metadata.layout = "bsghd" + tri_out, _ = attention_decode(q, quant_k, quant_v, input_metadata) + + q = q.reshape([B, Mq, -1, K]).permute(0, 2, 1, 3) + k = k.reshape([B, Mkv, -1, K]).permute(0, 2, 1, 3) + v = v.reshape([B, Mkv, -1, K]).permute(0, 2, 1, 3) + attn = (q @ k.transpose(-1, -2) * scale).softmax(-1) + ref_out = attn @ v + # compare + torch.testing.assert_close(ref_out, tri_out, atol=2.1e-2, rtol=0) + + # since quantization introduces rounding error, use the + # dequantized kv as inputs to the ref implementation to reduce + # the tolerance to 1e-3 + dqk = dequantize_kv_fp16(quant_k, num_groups=num_groups) + dqv = dequantize_kv_fp16(quant_v, num_groups=num_groups) + dqk = dqk.reshape([B, Mkv, -1, K]).permute(0, 2, 1, 3) + dqv = dqv.reshape([B, Mkv, -1, K]).permute(0, 2, 1, 3) + dq_attn = (q @ dqk.transpose(-1, -2) * scale).softmax(-1) + dq_ref_out = dq_attn @ dqv + torch.testing.assert_close(dq_ref_out, tri_out, atol=1e-3, rtol=0) diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/utils.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..530455063e2a19a7192fdfa996c500d23ee1c6e8 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_amd/utils.py @@ -0,0 +1,274 @@ + +import torch +import os +import triton + +AUTOTUNE = os.environ.get('FLASH_ATTENTION_TRITON_AMD_AUTOTUNE', '0').lower() in ('1', 'true', 'yes') +DEBUG = os.environ.get('FLASH_ATTENTION_TRITON_AMD_DEBUG', '0').lower() in ('1', 'true', 'yes') +PERF = os.environ.get('FLASH_ATTENTION_TRITON_AMD_PERF', '0').lower() in ('1', 'true', 'yes') + +class MetaData(): + cu_seqlens_q = None + cu_seqlens_k = None + max_seqlens_q = 0 + max_seqlens_k = 0 + bias = None + alibi_slopes = None + causal = False + num_contexts = 0 + varlen = False + layout = None + cache_seqlens = None + cache_batch_idx = None + new_kv = False + seqlen_new = None + k_new = None + v_new = None + dropout_p, return_scores= 0.0, False + # NOTE: scale sm_scale by log_2(e) and use 2^x in the loop as we do not have native e^x support in HW. + use_exp2 = False + + + def __repr__(self) -> str: + return (f"MetaData(\n" + f" sm_scale={self.sm_scale},\n" + f" cu_seqlens_q={self.cu_seqlens_q},\n" + f" cu_seqlens_k={self.cu_seqlens_k},\n" + f" max_seqlens_q={self.max_seqlens_q},\n" + f" max_seqlens_k={self.max_seqlens_k},\n" + f" bias={self.bias},\n" + f" alibi_slopes={self.alibi_slopes},\n" + f" causal={self.causal},\n" + f" num_contexts={self.num_contexts},\n" + f" varlen={self.varlen},\n" + f" layout={self.layout},\n" + f" cache_seqlens={self.cache_seqlens},\n" + f" cache_batch_idx={self.cache_batch_idx},\n" + f" new_kv={self.new_kv},\n" + f" seqlen_new={self.seqlen_new},\n" + f" k_new={self.k_new},\n" + f" v_new={self.v_new},\n" + f" dropout_p={self.dropout_p},\n" + f" return_scores={self.return_scores}\n" + f")") + + def __init__(self, sm_scale=1.0): + self.sm_scale = sm_scale + + def set_varlen_params(self, cu_seqlens_q, cu_seqlens_k): + self.varlen = True + self.layout = 'thd' + self.cu_seqlens_q = cu_seqlens_q + self.cu_seqlens_k = cu_seqlens_k + # Without "varlen", there should still be one sequence. + assert len(cu_seqlens_q) >= 2 + assert len(cu_seqlens_q) == len(cu_seqlens_k) + self.num_contexts = len(cu_seqlens_q) - 1 + for i in range(0, self.num_contexts): + self.max_seqlens_q = max(cu_seqlens_q[i + 1].item() - cu_seqlens_q[i].item(), self.max_seqlens_q) + self.max_seqlens_k = max(cu_seqlens_k[i + 1].item() - cu_seqlens_k[i].item(), self.max_seqlens_k) + + def need_bias(self, bias, batch, nheads, seqlen_q, seqlen_k): + assert bias.is_cuda + assert bias.dim() == 4 + assert bias.shape[0] == 1 + assert bias.shape[2:] == (seqlen_q, seqlen_k) + self.bias = bias + + def need_alibi(self, alibi_slopes, batch, nheads): + assert alibi_slopes.is_cuda + assert alibi_slopes.dim() == 2 + assert alibi_slopes.shape[0] == batch + assert alibi_slopes.shape[1] == nheads + self.alibi_slopes = alibi_slopes + + def need_causal(self): + self.causal = True + + def need_dropout(self, dropout_p, return_scores): + self.dropout_p = dropout_p + self.return_scores = return_scores + + def check_args(self, q, k, v, o): + assert q.dim() == k.dim() and q.dim() == v.dim() + + batch, nheads_q, nheads_k, head_size, _, _ = get_shape_from_layout(q, k, self.layout, self.cu_seqlens_q, self.cu_seqlens_k, self.max_seqlens_q, self.max_seqlens_k) + if self.varlen: + assert q.dim() == 3 + assert self.cu_seqlens_q is not None + assert self.cu_seqlens_k is not None + assert len(self.cu_seqlens_q) == len(self.cu_seqlens_k) + # TODO: Remove once bias is supported with varlen + assert self.bias is None + # TODO:Remove once dropout is supported with varlen + assert self.dropout_p == 0.0 + # assert not self.return_scores + else: + assert q.dim() == 4 + assert self.max_seqlens_q > 0 and self.max_seqlens_k > 0 + assert self.cu_seqlens_q is None and self.cu_seqlens_k is None + assert k.shape == v.shape + assert q.shape[-1] == k.shape[-1] and q.shape[-1] == v.shape[-1] + # TODO: Change assert if we support qkl f8 and v f16 + assert q.dtype == k.dtype and q.dtype == v.dtype + assert head_size <= 256 + assert o.shape == q.shape + assert (nheads_q % nheads_k) == 0 + assert self.layout is not None + assert self.layout == 'thd' or not self.varlen + +def input_helper(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, layout, device="cuda", DEBUG_INPUT=False): + torch.manual_seed(20) + + # Initialize q, k, v + if layout == 'bhsd': + q_tensor_shape = (Z, HQ, N_CTX_Q, D_HEAD) + k_tensor_shape = (Z, HK, N_CTX_K, D_HEAD) + elif layout == 'bshd': + q_tensor_shape = (Z, N_CTX_Q, HQ, D_HEAD) + k_tensor_shape = (Z, N_CTX_K, HK, D_HEAD) + else: + assert False, f'Got unsupported tensor layout: {layout}' + + if DEBUG_INPUT: + if layout == "bhsd": + q = torch.arange(N_CTX_Q, dtype=dtype, device=device).view(1, 1, N_CTX_Q, 1).expand(*q_tensor_shape).contiguous().requires_grad_() + k = torch.arange(N_CTX_K, dtype=dtype, device=device).view(1, 1, N_CTX_K, 1).expand(*k_tensor_shape).contiguous().requires_grad_() + v = torch.arange(N_CTX_K, dtype=dtype, device=device).view(1, 1, N_CTX_K, 1).expand(*k_tensor_shape).contiguous().requires_grad_() + elif layout == "bshd": + q = torch.arange(N_CTX_Q, dtype=dtype, device=device).view(1, N_CTX_Q, 1, 1).expand(*q_tensor_shape).contiguous().requires_grad_() + k = torch.arange(N_CTX_K, dtype=dtype, device=device).view(1, N_CTX_K, 1, 1).expand(*k_tensor_shape).contiguous().requires_grad_() + v = torch.arange(N_CTX_K, dtype=dtype, device=device).view(1, N_CTX_K, 1, 1).expand(*k_tensor_shape).contiguous().requires_grad_() + else: + q = torch.randn(q_tensor_shape, dtype=dtype, device=device, requires_grad=True) + k = torch.randn(k_tensor_shape, dtype=dtype, device=device, requires_grad=True) + v = torch.randn(k_tensor_shape, dtype=dtype, device=device, requires_grad=True) + + if DEBUG_INPUT: + sm_scale = 1 + else: + sm_scale = D_HEAD**-0.5 + input_metadata = MetaData(sm_scale=sm_scale) + input_metadata.max_seqlens_q = N_CTX_Q + input_metadata.max_seqlens_k = N_CTX_K + input_metadata.layout = layout + return q, k, v, input_metadata + + +def varlen_input_helper(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, dtype, device="cuda", equal_seqlens=False, DEBUG_INPUT=False): + torch.manual_seed(20) + + # Random or equal sequence lengths based on 'equal_seqlens' flag + if not equal_seqlens: + max_seqlens_q = N_CTX_Q // Z + max_seqlens_k = N_CTX_K // Z + seqlens_q = torch.randint(1, max_seqlens_q + 1, (Z,), dtype=torch.int32) + seqlens_k = torch.randint(1, max_seqlens_k + 1, (Z,), dtype=torch.int32) + else: + seqlens_q = torch.full((Z,), N_CTX_Q // Z, dtype=torch.int32) + seqlens_k = torch.full((Z,), N_CTX_K // Z, dtype=torch.int32) + + # Calculate cumulative sequence lengths + cu_seqlens_q = torch.cat([torch.tensor([0], dtype=torch.int32), seqlens_q.cumsum(dim=0)]) + cu_seqlens_k = torch.cat([torch.tensor([0], dtype=torch.int32), seqlens_k.cumsum(dim=0)]) + cu_seqlens_q = cu_seqlens_q.to(device=device).to(torch.int32) + cu_seqlens_k = cu_seqlens_k.to(device=device).to(torch.int32) + + # Total lengths + total_q = cu_seqlens_q[-1].item() + total_k = cu_seqlens_k[-1].item() + + if DEBUG_INPUT: + # Initialize q, k, v with deterministic values + q = torch.arange(total_q, dtype=dtype, device=device).view(total_q, 1, 1) + q = q.expand(total_q, HQ, D_HEAD).contiguous().requires_grad_() + k = torch.arange(total_k, dtype=dtype, device=device).view(total_k, 1, 1) + k = k.expand(total_k, HK, D_HEAD).contiguous().requires_grad_() + v = torch.arange(total_k, dtype=dtype, device=device).view(total_k, 1, 1) + v = v.expand(total_k, HK, D_HEAD).contiguous().requires_grad_() + sm_scale = 1 + else: + # Initialize q, k, v with random values + q = torch.randn((total_q, HQ, D_HEAD), dtype=dtype, device=device).requires_grad_() + k = torch.randn((total_k, HK, D_HEAD), dtype=dtype, device=device).requires_grad_() + v = torch.randn((total_k, HK, D_HEAD), dtype=dtype, device=device).requires_grad_() + sm_scale = D_HEAD ** -0.5 + + input_metadata = MetaData(sm_scale=sm_scale) + input_metadata.set_varlen_params(cu_seqlens_q, cu_seqlens_k) + return q, k, v, input_metadata + + +def get_shape_from_layout(q, k, layout, cu_seqlens_q = None, cu_seqlens_k = None, max_seqlen_q=None, max_seqlen_k=None): + if layout == 'bhsd': + batch_q, nheads_q, max_seqlen_q, head_size_q = q.shape + batch_k, nheads_k, max_seqlen_k, head_size_k = k.shape + elif layout == 'bshd': + batch_q, max_seqlen_q, nheads_q, head_size_q = q.shape + batch_k, max_seqlen_k, nheads_k, head_size_k = k.shape + elif layout == 'thd': + batch_q, max_seqlen_q, nheads_q, head_size_q = len(cu_seqlens_q) - 1, max_seqlen_q, q.shape[1], q.shape[2] + batch_k, max_seqlen_k, nheads_k, head_size_k = len(cu_seqlens_k) - 1, max_seqlen_k, k.shape[1], k.shape[2] + else: + assert False, "Got unsupported layout." + + # assert + assert batch_q == batch_k + assert head_size_q == head_size_k + + return batch_q, nheads_q, nheads_k, head_size_q, max_seqlen_q, max_seqlen_k + +def get_strides_from_layout(q, k, v, o, layout): + if layout == 'thd': + q_strides = (0, q.stride(1), q.stride(0), q.stride(2)) + k_strides = (0, k.stride(1), k.stride(0), k.stride(2)) + v_strides = (0, v.stride(1), v.stride(0), v.stride(2)) + o_strides = (0, o.stride(1), o.stride(0), o.stride(2)) + elif layout == 'bhsd': + q_strides = (q.stride(0), q.stride(1), q.stride(2), q.stride(3)) + k_strides = (k.stride(0), k.stride(1), k.stride(2), k.stride(3)) + v_strides = (v.stride(0), v.stride(1), v.stride(2), v.stride(3)) + o_strides = (o.stride(0), o.stride(1), o.stride(2), o.stride(3)) + elif layout == 'bshd': + q_strides = (q.stride(0), q.stride(2), q.stride(1), q.stride(3)) + k_strides = (k.stride(0), k.stride(2), k.stride(1), k.stride(3)) + v_strides = (v.stride(0), v.stride(2), v.stride(1), v.stride(3)) + o_strides = (o.stride(0), o.stride(2), o.stride(1), o.stride(3)) + else: + assert False, 'Got unsupported layout.' + return q_strides, k_strides, v_strides, o_strides + +def get_padded_headsize(size): + # Get closest power of 2 over or equal to 32. + padded_d_model = 1 << (size - 1).bit_length() + # Smallest head_dim supported is 16. If smaller, the tile in the + # kernel is padded - there is no padding in memory for any dims. + padded_d_model = max(padded_d_model, 16) + return padded_d_model + + +def _strides(x: torch.Tensor, *stride_names: str): + if x is None: + return {f"stride_{s}": 0 for i, s in enumerate(stride_names)} + + assert x.ndim == len(stride_names) + return {f"stride_{s}": x.stride(i) for i, s in enumerate(stride_names)} + +def get_input_shapes(): + cases = [(max(1, 2**(16 - i)), 1, 2**i, 16, 1, 128) + for i in range(8, 18)] + [(max(1, 2**(16 - i)), 1, 2**i, 16, 2, 128) for i in range(8, 18)] + return cases + +def is_hip(): + return triton.runtime.driver.active.get_current_target().backend == "hip" + + +def is_cdna(): + return is_hip() and triton.runtime.driver.active.get_current_target().arch in ('gfx940', 'gfx941', 'gfx942', + 'gfx90a', 'gfx908') + + +def is_rdna(): + return is_hip() and triton.runtime.driver.active.get_current_target().arch in ("gfx1030", "gfx1100", "gfx1101", + "gfx1102", "gfx1200", "gfx1201") + diff --git a/lib/python3.11/site-packages/flash_attn/flash_attn_triton_og.py b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_og.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ddb99487b4f162745e2f6dd3d1744946dc3fb2 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_attn_triton_og.py @@ -0,0 +1,365 @@ +# [2022-10-23] Downloaded from https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py +# for benchmarking. +# We fixed a few dtype cast to make it work for bf16 + +""" +Fused Attention +=============== +This is a Triton implementation of the Flash Attention algorithm +(see: Dao et al., https://arxiv.org/pdf/2205.14135v2.pdf; Rabe and Staats https://arxiv.org/pdf/2112.05682v2.pdf) +""" + +import pytest +import torch +import triton +import triton.language as tl + + +@triton.jit +def _fwd_kernel( + Q, + K, + V, + sm_scale, + TMP, + L, + M, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug + Out, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vk, + stride_vn, + stride_oz, + stride_oh, + stride_om, + stride_on, + Z, + H, + N_CTX, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, +): + start_m = tl.program_id(0) + off_hz = tl.program_id(1) + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + off_q = off_hz * stride_qh + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + off_k = off_hz * stride_qh + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk + off_v = off_hz * stride_qh + offs_n[:, None] * stride_qm + offs_d[None, :] * stride_qk + # Initialize pointers to Q, K, V + q_ptrs = Q + off_q + k_ptrs = K + off_k + v_ptrs = V + off_v + # initialize pointer to m and l + t_ptrs = TMP + off_hz * N_CTX + offs_m + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # load q: it will stay in SRAM throughout + q = tl.load(q_ptrs) + # loop over k, v and update accumulator + for start_n in range(0, (start_m + 1) * BLOCK_M, BLOCK_N): + start_n = tl.multiple_of(start_n, BLOCK_N) + # -- compute qk ---- + k = tl.load(k_ptrs + start_n * stride_kn) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, k, trans_b=True) + qk *= sm_scale + qk += tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), 0, float("-inf")) + # -- compute m_ij, p, l_ij + m_ij = tl.max(qk, 1) + p = tl.exp(qk - m_ij[:, None]) + l_ij = tl.sum(p, 1) + # -- update m_i and l_i + m_i_new = tl.maximum(m_i, m_ij) + alpha = tl.exp(m_i - m_i_new) + beta = tl.exp(m_ij - m_i_new) + l_i_new = alpha * l_i + beta * l_ij + # -- update output accumulator -- + # scale p + p_scale = beta / l_i_new + p = p * p_scale[:, None] + # scale acc + acc_scale = l_i / l_i_new * alpha + tl.store(t_ptrs, acc_scale) + acc_scale = tl.load(t_ptrs) # BUG: have to store and immediately load + acc = acc * acc_scale[:, None] + # update acc + v = tl.load(v_ptrs + start_n * stride_vk) + p = p.to(v.dtype) + acc += tl.dot(p, v) + # update m_i and l_i + l_i = l_i_new + m_i = m_i_new + # rematerialize offsets to save registers + start_m = tl.program_id(0) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + # write back l and m + l_ptrs = L + off_hz * N_CTX + offs_m + m_ptrs = M + off_hz * N_CTX + offs_m + tl.store(l_ptrs, l_i) + tl.store(m_ptrs, m_i) + # initialize pointers to output + offs_n = tl.arange(0, BLOCK_DMODEL) + off_o = off_hz * stride_oh + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on + out_ptrs = Out + off_o + tl.store(out_ptrs, acc) + + +@triton.jit +def _bwd_preprocess( + Out, + DO, + L, + NewDO, + Delta, + BLOCK_M: tl.constexpr, + D_HEAD: tl.constexpr, +): + off_m = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + off_n = tl.arange(0, D_HEAD) + # load + o = tl.load(Out + off_m[:, None] * D_HEAD + off_n[None, :]).to(tl.float32) + do = tl.load(DO + off_m[:, None] * D_HEAD + off_n[None, :]).to(tl.float32) + denom = tl.load(L + off_m).to(tl.float32) + # compute + do = do / denom[:, None] + delta = tl.sum(o * do, axis=1) + # write-back + tl.store(NewDO + off_m[:, None] * D_HEAD + off_n[None, :], do) + tl.store(Delta + off_m, delta) + + +@triton.jit +def _bwd_kernel( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + M, + D, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vk, + stride_vn, + Z, + H, + N_CTX, + num_block, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, +): + off_hz = tl.program_id(0) + off_z = off_hz // H + off_h = off_hz % H + # offset pointers for batch/head + Q += off_z * stride_qz + off_h * stride_qh + K += off_z * stride_qz + off_h * stride_qh + V += off_z * stride_qz + off_h * stride_qh + DO += off_z * stride_qz + off_h * stride_qh + DQ += off_z * stride_qz + off_h * stride_qh + DK += off_z * stride_qz + off_h * stride_qh + DV += off_z * stride_qz + off_h * stride_qh + for start_n in range(0, num_block): + lo = start_n * BLOCK_M + # initialize row/col offsets + offs_qm = lo + tl.arange(0, BLOCK_M) + offs_n = start_n * BLOCK_M + tl.arange(0, BLOCK_M) + offs_m = tl.arange(0, BLOCK_N) + offs_k = tl.arange(0, BLOCK_DMODEL) + # initialize pointers to value-like data + q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_k[None, :] * stride_qk) + k_ptrs = K + (offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk) + v_ptrs = V + (offs_n[:, None] * stride_qm + offs_k[None, :] * stride_qk) + do_ptrs = DO + (offs_qm[:, None] * stride_qm + offs_k[None, :] * stride_qk) + dq_ptrs = DQ + (offs_qm[:, None] * stride_qm + offs_k[None, :] * stride_qk) + # pointer to row-wise quantities in value-like data + D_ptrs = D + off_hz * N_CTX + m_ptrs = M + off_hz * N_CTX + # initialize dv amd dk + dv = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + dk = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # k and v stay in SRAM throughout + k = tl.load(k_ptrs) + v = tl.load(v_ptrs) + # loop over rows + for start_m in range(lo, num_block * BLOCK_M, BLOCK_M): + offs_m_curr = start_m + offs_m + # load q, k, v, do on-chip + q = tl.load(q_ptrs) + # recompute p = softmax(qk, dim=-1).T + # NOTE: `do` is pre-divided by `l`; no normalization here + qk = tl.dot(q, k, trans_b=True) + qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf")) + m = tl.load(m_ptrs + offs_m_curr) + p = tl.exp(qk * sm_scale - m[:, None]) + # compute dv + do = tl.load(do_ptrs) + dv += tl.dot(p.to(do.dtype), do, trans_a=True) + # compute dp = dot(v, do) + Di = tl.load(D_ptrs + offs_m_curr) + dp = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) - Di[:, None] + dp += tl.dot(do, v, trans_b=True) + # compute ds = p * (dp - delta[:, None]) + ds = p * dp * sm_scale + # compute dk = dot(ds.T, q) + dk += tl.dot(ds.to(q.dtype), q, trans_a=True) + # # compute dq + dq = tl.load(dq_ptrs, eviction_policy="evict_last") + dq += tl.dot(ds.to(k.dtype), k) + tl.store(dq_ptrs, dq, eviction_policy="evict_last") + # # increment pointers + dq_ptrs += BLOCK_M * stride_qm + q_ptrs += BLOCK_M * stride_qm + do_ptrs += BLOCK_M * stride_qm + # write-back + dv_ptrs = DV + (offs_n[:, None] * stride_qm + offs_k[None, :] * stride_qk) + dk_ptrs = DK + (offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk) + tl.store(dv_ptrs, dv) + tl.store(dk_ptrs, dk) + + +class _attention(torch.autograd.Function): + @staticmethod + def forward(ctx, q, k, v, sm_scale): + BLOCK = 128 + # shape constraints + Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1] + assert Lq == Lk and Lk == Lv + assert Lk in {16, 32, 64, 128} + o = torch.empty_like(q) + grid = (triton.cdiv(q.shape[2], BLOCK), q.shape[0] * q.shape[1]) + tmp = torch.empty( + (q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32 + ) + L = torch.empty((q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32) + m = torch.empty((q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32) + num_warps = 4 if Lk <= 64 else 8 + + _fwd_kernel[grid]( + q, + k, + v, + sm_scale, + tmp, + L, + m, + o, + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + o.stride(0), + o.stride(1), + o.stride(2), + o.stride(3), + q.shape[0], + q.shape[1], + q.shape[2], + BLOCK_M=BLOCK, + BLOCK_N=BLOCK, + BLOCK_DMODEL=Lk, + num_warps=num_warps, + num_stages=1, + ) + ctx.save_for_backward(q, k, v, o, L, m) + ctx.BLOCK = BLOCK + ctx.grid = grid + ctx.sm_scale = sm_scale + ctx.BLOCK_DMODEL = Lk + return o + + @staticmethod + def backward(ctx, do): + q, k, v, o, l, m = ctx.saved_tensors + do = do.contiguous() + dq = torch.zeros_like(q, dtype=torch.float32) + dk = torch.empty_like(k) + dv = torch.empty_like(v) + do_scaled = torch.empty_like(do) + delta = torch.empty_like(l) + _bwd_preprocess[(ctx.grid[0] * ctx.grid[1],)]( + o, + do, + l, + do_scaled, + delta, + BLOCK_M=ctx.BLOCK, + D_HEAD=ctx.BLOCK_DMODEL, + ) + + # NOTE: kernel currently buggy for other values of `num_warps` + num_warps = 8 + _bwd_kernel[(ctx.grid[1],)]( + q, + k, + v, + ctx.sm_scale, + o, + do_scaled, + dq, + dk, + dv, + l, + m, + delta, + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + q.shape[0], + q.shape[1], + q.shape[2], + ctx.grid[0], + BLOCK_M=ctx.BLOCK, + BLOCK_N=ctx.BLOCK, + BLOCK_DMODEL=ctx.BLOCK_DMODEL, + num_warps=num_warps, + num_stages=1, + ) + return dq.to(q.dtype), dk, dv, None + + +attention = _attention.apply diff --git a/lib/python3.11/site-packages/flash_attn/flash_blocksparse_attention.py b/lib/python3.11/site-packages/flash_attn/flash_blocksparse_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..4c930291063db1350ce05aecf55c6050bad28fd4 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_blocksparse_attention.py @@ -0,0 +1,197 @@ +import math + +import hydra +import torch +import torch.nn as nn +from einops import rearrange + +from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input +from flash_attn.flash_blocksparse_attn_interface import ( + convert_blockmask, + flash_blocksparse_attn_func, +) + + +class FlashBlocksparseAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_temp: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.1) + """ + + def __init__( + self, + sparsity_config, + softmax_temp=None, + attention_dropout=0.0, + max_seq_length=2048, + device=None, + dtype=None, + ): + super().__init__() + self.sparsity_config = hydra.utils.instantiate(sparsity_config) + self.softmax_temp = softmax_temp + self.dropout_p = attention_dropout + + # initialize sparse layout and register as buffer + max_seq_length = ((max_seq_length + 256 - 1) // 256) * 256 + layout = self.sparsity_config.make_layout(max_seq_length) + self.register_buffer("layout", layout) + blockmask_converted = convert_blockmask(self.layout, causal=False) + self.register_buffer("blockmask_converted", blockmask_converted) + # logger.info(f'Attention class {self.__class__}: saving={self.layout.float().mean()}') + + def forward( + self, + qkv, + attn_mask=None, + key_padding_mask=None, + causal=False, + cu_seqlens=None, + max_s=None, + need_weights=False, + convert_mask=True, + ): + """Implements the multihead softmax attention. + Arguments + --------- + qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None + attn_mask: An implementation of BaseMask that encodes where each + query can attend to + key_padding_mask: An implementation of BaseMask that encodes how + many query each sequence in the batch consists of + """ + assert not need_weights + assert attn_mask is None + assert qkv.dtype == torch.float16 + assert qkv.is_cuda + + if cu_seqlens is None: + batch_size = qkv.shape[0] + seqlen = qkv.shape[1] + # Convert mask to take a subset + seqlen_rounded = ((seqlen + 256 - 1) // 256) * 256 + assert seqlen_rounded // 16 <= self.layout.shape[0], ( + seqlen_rounded // 256 <= self.layout.shape[1] + ) + blockmask = self.layout[: seqlen_rounded // 16, : seqlen_rounded // 256] + if key_padding_mask is None: + qkv = rearrange(qkv, "b s ... -> (b s) ...") + max_s = seqlen + cu_seqlens = torch.arange( + 0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32, device=qkv.device + ) + output = flash_blocksparse_attn_func( + qkv, + cu_seqlens, + blockmask, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + ) + output = rearrange(output, "(b s) ... -> b s ...", b=batch_size) + else: + key_padding_mask_bool = key_padding_mask.bool_matrix + nheads = qkv.shape[-2] + x = rearrange(qkv, "b s three h d -> b s (three h d)") + x_unpad, indices, cu_seqlens, max_s, _ = unpad_input(x, key_padding_mask_bool) + x_unpad = rearrange(x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads) + output_unpad = flash_blocksparse_attn_func( + x_unpad, + cu_seqlens, + blockmask, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + ) + output = rearrange( + pad_input( + rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, batch_size, seqlen + ), + "b s (h d) -> b s h d", + h=nheads, + ) + else: + assert max_s is not None + seqlen = max_s + # Convert mask to take a subset + seqlen_rounded = ((seqlen + 256 - 1) // 256) * 256 + assert seqlen_rounded // 16 <= self.layout.shape[0], ( + seqlen_rounded // 256 <= self.layout.shape[1] + ) + blockmask = self.layout[: seqlen_rounded // 16, : seqlen_rounded // 256] + if convert_mask: + output = flash_blocksparse_attn_func( + qkv, + cu_seqlens, + blockmask, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + ) + else: + output = flash_blocksparse_attn_func( + qkv, + cu_seqlens, + self.blockmask_converted, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + convert_mask=False, + ) + + return output, None + + +class FlashBlocksparseMHA(nn.Module): + def __init__( + self, + embed_dim, + num_heads, + sparsity_config, + bias=True, + batch_first=True, + attention_dropout=0.0, + causal=False, + max_seq_length=2048, + device=None, + dtype=None, + **kwargs, + ) -> None: + assert batch_first + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.embed_dim = embed_dim + self.causal = causal + + self.num_heads = num_heads + assert self.embed_dim % num_heads == 0, "self.kdim must be divisible by num_heads" + self.head_dim = self.embed_dim // num_heads + assert self.head_dim in [16, 32, 64], "Only support head_dim == 16, 32, or 64" + + self.Wqkv = nn.Linear(embed_dim, 3 * embed_dim, bias=bias, **factory_kwargs) + self.inner_attn = FlashBlocksparseAttention( + sparsity_config, + attention_dropout=attention_dropout, + max_seq_length=max_seq_length, + **factory_kwargs, + ) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, **factory_kwargs) + + def forward( + self, x, x_ignored_, x_ignored_1_, attn_mask=None, key_padding_mask=None, need_weights=False + ): + qkv = self.Wqkv(x) + qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, h=self.num_heads) + context, attn_weights = self.inner_attn( + qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=self.causal + ) + return self.out_proj(rearrange(context, "b s h d -> b s (h d)")), attn_weights diff --git a/lib/python3.11/site-packages/flash_attn/flash_blocksparse_attn_interface.py b/lib/python3.11/site-packages/flash_attn/flash_blocksparse_attn_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..9ce3fe8c1344dd33165c43e4cc1ef0f70feb5d04 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/flash_blocksparse_attn_interface.py @@ -0,0 +1,200 @@ +# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/fmha.py +import flash_attn_cuda +import torch +import torch.nn as nn + + +def convert_blockmask(blockmask, causal): + """Convert from the 0-1 format to the format used by the CUDA code. + 0 means the block is skipped. + nonzero means the block is not skipped. + Argument: + blockmask: (row, col): a 0-1 tensor + Return: + blockmask_converted: (col, row), dtype torch.int32: for each column, it contains the row + indices of the nonzero blocks, padded with -1 to reach length @row. + The indices are multiplied by 4, with the smallest bit used to encode whether + it is the first nonzero in its row, and the 2nd smallest bit to encode whether it is + the last nonzero in its row.. + """ + assert not causal + # TD [2022-05-13]: The indexing and sorting is very tricky + nrow, ncol = blockmask.shape + # Sort does not support bool on CUDA + blockmask = blockmask.to(dtype=torch.uint8) + nonzero_val, nonzero_sorted_rowidx = blockmask.sort(dim=0, stable=True, descending=True) + nonzero_unsorted_rowidx = nonzero_sorted_rowidx.argsort(dim=0) + last_nonzero_col_per_row = blockmask.sort(dim=-1, stable=True).indices[:, -1] + last_nonzero_col_per_row_after_sort = nonzero_unsorted_rowidx[ + torch.arange(nrow, device=blockmask.device), last_nonzero_col_per_row + ] + first_nonzero_col_per_row = blockmask.sort(dim=-1, stable=True, descending=True).indices[:, 0] + first_nonzero_col_per_row_after_sort = nonzero_unsorted_rowidx[ + torch.arange(nrow, device=blockmask.device), first_nonzero_col_per_row + ] + nonzero_idx = nonzero_sorted_rowidx * 4 + nonzero_idx[last_nonzero_col_per_row_after_sort, last_nonzero_col_per_row] += 2 + nonzero_idx[first_nonzero_col_per_row_after_sort, first_nonzero_col_per_row] += 1 + nonzero_idx[nonzero_val == 0] = -1 + return nonzero_idx.T.contiguous().to(dtype=torch.int32) + + +def _flash_blocksparse_attn_forward( + qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal, return_softmax +): + context, softmax_lse, *rest = flash_attn_cuda.fwd_block( + qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal, return_softmax, None + ) + # if context.isnan().any() or softmax_lse.isnan().any(): + # breakpoint() + S_dmask = rest[0] if return_softmax else None + return context, softmax_lse, S_dmask + + +def _flash_blocksparse_attn_backward( + dout, + qkv, + out, + S_dmask, + softmax_lse, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale, + causal, +): + dqkv, dp, softmax_d = flash_attn_cuda.bwd_block( + dout, + qkv, + out, + S_dmask, + softmax_lse, + cu_seqlens, + blockmask, + dropout_p, + softmax_scale, + max_s, + causal, + None, + ) + # if dqkv.isnan().any() or softmax_d.isnan().any(): + # breakpoint() + return dqkv + + +class FlashBlocksparseAttnFun(torch.autograd.Function): + @staticmethod + def forward(ctx, qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal): + # Save rng_state because the backward pass will regenerate the dropout mask + rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + context, softmax_lse, S_dmask = _flash_blocksparse_attn_forward( + qkv, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale, + causal=causal, + return_softmax=False, + ) + ctx.save_for_backward(qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state) + ctx.dropout_p = dropout_p + ctx.max_s = max_s + ctx.softmax_scale = softmax_scale + ctx.causal = causal + return context + + @staticmethod + def backward(ctx, dout): + qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state = ctx.saved_tensors + if rng_state is not None: + cur_rng_state = torch.cuda.get_rng_state() + torch.cuda.set_rng_state(rng_state) + # S_dmask is None, temporarily use another tensor just to get it running + dqkv = _flash_blocksparse_attn_backward( + dout, + qkv, + context, + context, + softmax_lse, + cu_seqlens, + blockmask, + ctx.dropout_p, + ctx.max_s, + ctx.softmax_scale, + ctx.causal, + ) + if rng_state is not None: + torch.cuda.set_rng_state(cur_rng_state) + return dqkv, None, None, None, None, None, None, None + + +# We duplicate code to return both the output and the softmax for testing +# Returning both makes backward a bit slower, so we want to keep using the other version for speed. +class FlashBlocksparseAttnFunWithS(torch.autograd.Function): + @staticmethod + def forward(ctx, qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal): + # Save rng_state because the backward pass is gonna regenerate the dropout mask + rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + context, softmax_lse, S_dmask = _flash_blocksparse_attn_forward( + qkv, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale, + causal=causal, + return_softmax=True, + ) + ctx.save_for_backward(qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state) + ctx.dropout_p = dropout_p + ctx.max_s = max_s + ctx.softmax_scale = softmax_scale + ctx.causal = causal + return context, S_dmask, softmax_lse + + @staticmethod + def backward(ctx, dout, _dS_dmask_ignored, _dsoftmax_sum_ignored): + qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state = ctx.saved_tensors + if rng_state is not None: + cur_rng_state = torch.cuda.get_rng_state() + torch.cuda.set_rng_state(rng_state) + dqkv = _flash_blocksparse_attn_backward( + dout, + qkv, + context, + S_dmask, + softmax_lse, + cu_seqlens, + blockmask, + ctx.dropout_p, + ctx.max_s, + ctx.softmax_scale, + ctx.causal, + ) + if rng_state is not None: + torch.cuda.set_rng_state(cur_rng_state) + return dqkv, None, None, None, None, None, None + + +def flash_blocksparse_attn_func( + qkv, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale=None, + causal=False, + return_attn_probs=False, + convert_mask=True, +): + """dropout_p should be set to 0.0 during evaluation""" + func = FlashBlocksparseAttnFun if not return_attn_probs else FlashBlocksparseAttnFunWithS + if convert_mask: + blockmask = convert_blockmask(blockmask, causal=causal) + return func.apply(qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal) diff --git a/lib/python3.11/site-packages/flash_attn/fused_softmax.py b/lib/python3.11/site-packages/flash_attn/fused_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..382f94f092cd3999b2378dfc2fa165a7c08017e2 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/fused_softmax.py @@ -0,0 +1,201 @@ +# [2022-10-23] Copied from https://github.com/NVIDIA/apex/blob/master/apex/transformer/functional/fused_softmax.py +# for benchmarking. +# We added support for seqlen=2k and seqlen=4k + +# coding=utf-8 +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from apex._autocast_utils import _cast_if_autocast_enabled +from apex.transformer.enums import AttnMaskType +from fused_softmax_lib import ( + scaled_masked_softmax_backward, + scaled_masked_softmax_forward, + scaled_masked_softmax_get_batch_per_block, + scaled_upper_triang_masked_softmax_backward, + scaled_upper_triang_masked_softmax_forward, +) + + +class ScaledUpperTriangMaskedSoftmax(torch.autograd.Function): + """ + Fused operation which performs following three operations in sequence + 1. Scale the tensor. + 2. Apply upper triangular mask (typically used in gpt models). + 3. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, scale): + scale_t = torch.tensor([scale]) + softmax_results = scaled_upper_triang_masked_softmax_forward(inputs, scale_t[0]) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + softmax_results, scale_t = ctx.saved_tensors + input_grads = scaled_upper_triang_masked_softmax_backward( + output_grads, softmax_results, scale_t[0] + ) + return input_grads, None + + +def scaled_upper_triang_masked_softmax(inputs, _, scale): + b, np, sq, sk = inputs.size() + assert sq == sk, "causal mask is only for self attention" + # Reshaping input to 3D tensor (attn_batches, sq, sk) + inputs = inputs.view(-1, sq, sk) + args = _cast_if_autocast_enabled(inputs, scale) + with torch.cuda.amp.autocast(enabled=False): + probs = ScaledUpperTriangMaskedSoftmax.apply(*args) + return probs.view(b, np, sq, sk) + + +# NOTE (mkozuki): `ScaledMaskedSoftmax` somehow doesn't work well with `torch.cuda.amp.custom_fwd`. +# Without `cast_inputs` kwarg, somehow inputs are not cast to dtype used in the autocast context. +# So I needed to manually write two `torch.autograd.Function` inheritances. +# Fused operation which performs following three operations in sequence +# 1. Scale the tensor. +# 2. Apply the mask. +# 3. Perform softmax. +class ScaledMaskedSoftmax(torch.autograd.Function): + @staticmethod + def forward(ctx, inputs, mask, scale): + scale_t = torch.tensor([scale]) + softmax_results = scaled_masked_softmax_forward(inputs, mask, scale_t[0]) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + softmax_results, scale_t = ctx.saved_tensors + input_grads = scaled_masked_softmax_backward(output_grads, softmax_results, scale_t[0]) + return input_grads, None, None + + +def scaled_masked_softmax(inputs, mask, scale): + # input is 4D tensor (b, np, sq, sk) + args = _cast_if_autocast_enabled(inputs, mask, scale) + with torch.cuda.amp.autocast(enabled=False): + return ScaledMaskedSoftmax.apply(*args) + + +class FusedScaleMaskSoftmax(torch.nn.Module): + """ + fused operation: scaling + mask + softmax + + Arguments: + input_in_fp16: flag to indicate if input in fp16 data format. + input_in_bf16: flag to indicate if input in bf16 data format. + attn_mask_type: attention mask type (pad or causal) + scaled_masked_softmax_fusion: flag to indicate user want to use softmax fusion + mask_func: mask function to be applied. + softmax_in_fp32: if true, softmax in performed at fp32 precision. + scale: scaling factor used in input tensor scaling. + """ + + def __init__( + self, + input_in_fp16, + input_in_bf16, + attn_mask_type, + scaled_masked_softmax_fusion, + mask_func, + softmax_in_fp32, + scale, + ): + super().__init__() + self.input_in_fp16 = input_in_fp16 + self.input_in_bf16 = input_in_bf16 + if self.input_in_fp16 and self.input_in_bf16: + raise RuntimeError("both fp16 and bf16 flags cannot be active at the same time.") + self.input_in_float16 = self.input_in_fp16 or self.input_in_bf16 + self.attn_mask_type = attn_mask_type + self.scaled_masked_softmax_fusion = scaled_masked_softmax_fusion + self.mask_func = mask_func + self.softmax_in_fp32 = softmax_in_fp32 + self.scale = scale + + if not (self.scale is None or softmax_in_fp32): + raise RuntimeError("softmax should be in fp32 when scaled") + + if self.scaled_masked_softmax_fusion: + if self.attn_mask_type == AttnMaskType.causal: + self.fused_softmax_func = scaled_upper_triang_masked_softmax + elif self.attn_mask_type == AttnMaskType.padding: + self.fused_softmax_func = scaled_masked_softmax + else: + raise ValueError("Invalid attn_mask_type.") + + def forward(self, input, mask): + # [b, np, sq, sk] + assert input.dim() == 4 + + if self.is_kernel_available(mask, *input.size()): + return self.forward_fused_softmax(input, mask) + else: + return self.forward_torch_softmax(input, mask) + + def is_kernel_available(self, mask, b, np, sq, sk): + attn_batches = b * np + + if ( + self.scaled_masked_softmax_fusion # user want to fuse + and self.input_in_float16 # input must be fp16 + and ( + self.attn_mask_type == AttnMaskType.causal + or (self.attn_mask_type == AttnMaskType.padding and mask is not None) + ) + and 16 < sk <= 8192 # sk must be 16 ~ 8192 + and sq % 4 == 0 # sq must be divisor of 4 + and sk % 4 == 0 # sk must be divisor of 4 + and attn_batches % 4 == 0 # np * b must be divisor of 4 + ): + if 0 <= sk <= 8192: + batch_per_block = self.get_batch_per_block(sq, sk, b, np) + + if self.attn_mask_type == AttnMaskType.causal: + if attn_batches % batch_per_block == 0: + return True + else: + if sq % batch_per_block == 0: + return True + return False + + def forward_fused_softmax(self, input, mask): + # input.shape = [b, np, sq, sk] + scale = self.scale if self.scale is not None else 1.0 + return self.fused_softmax_func(input, mask, scale) + + def forward_torch_softmax(self, input, mask): + if self.input_in_float16 and self.softmax_in_fp32: + input = input.float() + + if self.scale is not None: + input = input * self.scale + mask_output = self.mask_func(input, mask) if mask is not None else input + probs = torch.nn.Softmax(dim=-1)(mask_output) + + if self.input_in_float16 and self.softmax_in_fp32: + if self.input_in_fp16: + probs = probs.half() + else: + probs = probs.bfloat16() + + return probs + + @staticmethod + def get_batch_per_block(sq, sk, b, np): + return scaled_masked_softmax_get_batch_per_block(sq, sk, b, np) diff --git a/lib/python3.11/site-packages/flash_attn/layers/__init__.py b/lib/python3.11/site-packages/flash_attn/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/flash_attn/layers/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/layers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26587409a8c27b0a57269bfef416e3ad72426766 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/layers/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/layers/__pycache__/patch_embed.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/layers/__pycache__/patch_embed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e1a787a522965d350cf9c81e95fb8b6886cfab2 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/layers/__pycache__/patch_embed.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/layers/__pycache__/rotary.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/layers/__pycache__/rotary.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b013855909f60dce7604ec12ef2f877c4ebe25d Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/layers/__pycache__/rotary.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/layers/patch_embed.py b/lib/python3.11/site-packages/flash_attn/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..05562f8e8bcdb58e947c6f402a49eacd2d031871 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/layers/patch_embed.py @@ -0,0 +1,67 @@ +# We use the same API as https://github.com/rwightman/pytorch-image-models/blob/v0.6.11/timm/models/layers/patch_embed.py +# But we use nn.Linear instead of Conv2d and it's about 8x faster. + +from functools import partial + +import torch.nn as nn +from einops import rearrange +from torch import _assert +from torch.nn.modules.utils import _pair + +try: + from flash_attn.ops.fused_dense import FusedDense +except ImportError: + FusedDense = None + + +class PatchEmbed(nn.Module): + """2D Image to Patch Embedding""" + + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + norm_layer=None, + flatten=True, + bias=True, + fused_bias_fc=False, + ): + super().__init__() + img_size = _pair(img_size) + patch_size = _pair(patch_size) + self.img_size = img_size + self.patch_size = patch_size + self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) + self.num_patches = self.grid_size[0] * self.grid_size[1] + self.flatten = flatten + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + + linear_cls = nn.Linear if not fused_bias_fc or not bias else FusedDense + self.proj = linear_cls(in_chans * patch_size[0] * patch_size[1], embed_dim, bias=bias) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x): + _, _, H, W = x.shape + _assert( + H == self.img_size[0], + f"Input image height ({H}) doesn't match model ({self.img_size[0]}).", + ) + _assert( + W == self.img_size[1], + f"Input image width ({W}) doesn't match model ({self.img_size[1]}).", + ) + x = self.proj( + rearrange( + x, + "b c (h p1) (w p2) -> b h w (c p1 p2)", + p1=self.patch_size[0], + p2=self.patch_size[1], + ) + ) + if self.flatten: + x = rearrange(x, "b h w c -> b (h w) c") + x = self.norm(x) + return x diff --git a/lib/python3.11/site-packages/flash_attn/layers/rotary.py b/lib/python3.11/site-packages/flash_attn/layers/rotary.py new file mode 100644 index 0000000000000000000000000000000000000000..6d021f8391079dcdb97b60e4084b963a81785ae2 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/layers/rotary.py @@ -0,0 +1,528 @@ +# Copyright (c) 2023, Tri Dao. + +import math +from typing import Optional, Tuple, Union + +import torch +from einops import rearrange, repeat +from flash_attn.ops.triton.rotary import apply_rotary + + +def rotate_half(x, interleaved=False): + if not interleaved: + x1, x2 = x.chunk(2, dim=-1) + return torch.cat((-x2, x1), dim=-1) + else: + x1, x2 = x[..., ::2], x[..., 1::2] + return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2) + + +def apply_rotary_emb_torch(x, cos, sin, interleaved=False): + """ + x: (batch_size, seqlen, nheads, headdim) + cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2) + """ + ro_dim = cos.shape[-1] * 2 + assert ro_dim <= x.shape[-1] + cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)") + sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)") + return torch.cat( + [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]], + dim=-1, + ) + + +class ApplyRotaryEmb(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x, + cos, + sin, + interleaved=False, + inplace=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, + cu_seqlens: Optional[torch.Tensor] = None, + max_seqlen: Optional[int] = None, + ): + out = apply_rotary( + x, + cos, + sin, + seqlen_offsets=seqlen_offsets, + cu_seqlens=cu_seqlens, + max_seqlen=max_seqlen, + interleaved=interleaved, + inplace=inplace, + ) + if isinstance(seqlen_offsets, int): + ctx.save_for_backward(cos, sin, cu_seqlens) # Can't save int with save_for_backward + ctx.seqlen_offsets = seqlen_offsets + else: + ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets) + ctx.seqlen_offsets = None + ctx.interleaved = interleaved + ctx.inplace = inplace + ctx.max_seqlen = max_seqlen + return out if not inplace else x + + @staticmethod + def backward(ctx, do): + seqlen_offsets = ctx.seqlen_offsets + if seqlen_offsets is None: + cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors + else: + cos, sin, cu_seqlens = ctx.saved_tensors + # TD [2023-09-02]: For some reason Triton (2.0.0.post1) errors with + # "[CUDA]: invalid device context", and cloning makes it work. Idk why. Triton 2.1.0 works. + if not ctx.interleaved and not ctx.inplace: + do = do.clone() + dx = apply_rotary( + do, + cos, + sin, + seqlen_offsets=seqlen_offsets, + cu_seqlens=cu_seqlens, + max_seqlen=ctx.max_seqlen, + interleaved=ctx.interleaved, + inplace=ctx.inplace, + conjugate=True, + ) + return dx, None, None, None, None, None, None, None + + +def apply_rotary_emb( + x, + cos, + sin, + interleaved=False, + inplace=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, + cu_seqlens: Optional[torch.Tensor] = None, + max_seqlen: Optional[int] = None, +): + """ + Arguments: + x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None + else (total_seqlen, nheads, headdim) + cos, sin: (seqlen_rotary, rotary_dim / 2) + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead + of 1st half and 2nd half (GPT-NeoX style). + inplace: if True, apply rotary embedding in-place. + seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount. + Most commonly used in inference when we have KV cache. + cu_seqlens: (batch + 1,) or None + max_seqlen: int + Return: + out: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None + else (total_seqlen, nheads, headdim) + rotary_dim must be <= headdim + Apply rotary embedding to the first rotary_dim of x. + """ + return ApplyRotaryEmb.apply( + x, cos, sin, interleaved, inplace, seqlen_offsets, cu_seqlens, max_seqlen + ) + + +# For backward compatibility +apply_rotary_emb_func = apply_rotary_emb + + +class ApplyRotaryEmbQKV_(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + cos, + sin, + cos_k=None, + sin_k=None, + interleaved=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, + num_heads_q: Union[int] = None, + ): + if cos_k is None and sin_k is None and qkv.is_contiguous(): + # Call 1 kernel instead of 2 kernels + # We need qkv to be contiguous so that when we reshape to combine (3, nheads) + # dimensions, we get the same tensor + if qkv.dim() == 5: + batch, seqlen, three, nheads, headdim = qkv.shape + assert three == 3 + # qk = rearrange(qkv[:, :, :2], "b s t h d -> b s (t h) d") + qk = qkv[:, :, :2].reshape(batch, seqlen, -1, headdim) + else: + assert qkv.dim() == 4 + assert num_heads_q is not None + num_heads_k = (qkv.shape[2] - num_heads_q) // 2 + assert qkv.shape[2] == num_heads_q + 2 * num_heads_k + qk = qkv[:, :, :num_heads_q + num_heads_k] + apply_rotary( + qk, cos, sin, seqlen_offsets=seqlen_offsets, interleaved=interleaved, inplace=True + ) + else: + cos_k = cos if cos_k is None else cos_k + sin_k = sin if sin_k is None else sin_k + if qkv.dim() == 5: + q, k = qkv[:, :, 0], qkv[:, :, 1] + else: + assert qkv.dim() == 4 + assert num_heads_q is not None + num_heads_k = (qkv.shape[2] - num_heads_q) // 2 + assert qkv.shape[2] == num_heads_q + 2 * num_heads_k + q, k = qkv[:, :, :num_heads_q], qkv[:, :, num_heads_q : num_heads_q + num_heads_k] + apply_rotary(q, cos, sin, seqlen_offsets, interleaved=interleaved, inplace=True) + apply_rotary(k, cos_k, sin_k, seqlen_offsets, interleaved=interleaved, inplace=True) + ctx.save_for_backward(cos, sin, cos_k, sin_k) + if isinstance(seqlen_offsets, int): + ctx.save_for_backward(cos, sin, cos_k, sin_k) + ctx.seqlen_offsets = seqlen_offsets + else: + ctx.save_for_backward(cos, sin, cos_k, sin_k, seqlen_offsets) + ctx.seqlen_offsets = None + ctx.interleaved = interleaved + ctx.num_heads_q = num_heads_q + return qkv + + @staticmethod + def backward(ctx, dqkv): + seqlen_offsets = ctx.seqlen_offsets + if seqlen_offsets is None: + cos, sin, cos_k, sin_k, seqlen_offsets = ctx.saved_tensors + else: + cos, sin, cos_k, sin_k = ctx.saved_tensors + if cos_k is None and sin_k is None and dqkv.is_contiguous(): + # Call 1 kernel instead of 2 kernels + # We need dqkv to be contiguous so that when we reshape to combine (3, nheads) + # dimensions, we get the same tensor + if dqkv.dim() == 5: + dqk = rearrange(dqkv[:, :, :2], "b s t h d -> b s (t h) d") + else: + assert dqkv.dim() == 4 + assert ctx.num_heads_q is not None + num_heads_k = (dqkv.shape[2] - ctx.num_heads_q) // 2 + assert dqkv.shape[2] == ctx.num_heads_q + 2 * num_heads_k + dqk = dqkv[:, :, : ctx.num_heads_q + num_heads_k] + apply_rotary( + dqk, + cos, + sin, + seqlen_offsets=seqlen_offsets, + interleaved=ctx.interleaved, + inplace=True, + conjugate=True, + ) + else: + cos_k = cos if cos_k is None else cos_k + sin_k = sin if sin_k is None else sin_k + if dqkv.dim() == 5: + dq, dk = dqkv[:, :, 0], dqkv[:, :, 1] + else: + assert dqkv.dim() == 4 + assert ctx.num_heads_q is not None + num_heads_k = (dqkv.shape[2] - ctx.num_heads_q) // 2 + assert dqkv.shape[2] == ctx.num_heads_q + 2 * num_heads_k + dq = dqkv[:, :, : ctx.num_heads_q] + dk = dqkv[:, :, ctx.num_heads_q : ctx.num_heads_q + num_heads_k] + apply_rotary( + dq, + cos, + sin, + seqlen_offsets, + interleaved=ctx.interleaved, + inplace=True, + conjugate=True, + ) + apply_rotary( + dk, + cos_k, + sin_k, + seqlen_offsets, + interleaved=ctx.interleaved, + inplace=True, + conjugate=True, + ) + return dqkv, None, None, None, None, None, None, None + + +def apply_rotary_emb_qkv_( + qkv, + cos, + sin, + cos_k=None, + sin_k=None, + interleaved=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, + num_heads_q: Optional[int] = None, +): + """ + Arguments: + qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim). + If qkv has shape (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA), + then num_heads_q must be provided. + cos, sin: (seqlen, rotary_dim / 2) + cos_k, sin_k: (seqlen, rotary_dim / 2), optional + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of + 1st half and 2nd half (GPT-NeoX style). + seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount. + Most commonly used in inference when we have KV cache. + Return: + qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) + rotary_dim must be <= headdim + Apply rotary embedding *inplace* to the first rotary_dim of Q and K. + """ + return ApplyRotaryEmbQKV_.apply( + qkv, cos, sin, cos_k, sin_k, interleaved, seqlen_offsets, num_heads_q + ) + + +class ApplyRotaryEmbKV_(torch.autograd.Function): + @staticmethod + def forward(ctx, kv, cos, sin, interleaved=False, seqlen_offsets: Union[int, torch.Tensor] = 0): + batch, seqlen, two, nheads, headdim = kv.shape + assert two == 2 + k = kv[:, :, 0] + apply_rotary( + k, cos, sin, seqlen_offsets=seqlen_offsets, interleaved=interleaved, inplace=True + ) + if isinstance(seqlen_offsets, int): + ctx.save_for_backward(cos, sin) # Can't save int with save_for_backward + ctx.seqlen_offsets = seqlen_offsets + else: + ctx.save_for_backward(cos, sin, seqlen_offsets) + ctx.seqlen_offsets = None + ctx.interleaved = interleaved + return kv + + @staticmethod + def backward(ctx, dkv): + seqlen_offsets = ctx.seqlen_offsets + if seqlen_offsets is None: + cos, sin, seqlen_offsets = ctx.saved_tensors + else: + cos, sin = ctx.saved_tensors + apply_rotary( + dkv[:, :, 0], + cos, + sin, + seqlen_offsets=seqlen_offsets, + interleaved=ctx.interleaved, + inplace=True, + conjugate=True, + ) + return dkv, None, None, None, None + + +apply_rotary_emb_kv_ = ApplyRotaryEmbKV_.apply + + +def apply_rotary_emb_kv_( + kv, + cos, + sin, + interleaved=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, +): + """ + Arguments: + kv: (batch_size, seqlen, 2, nheads, headdim) + cos, sin: (seqlen, rotary_dim / 2) + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of + 1st half and 2nd half (GPT-NeoX style). + seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount. + Most commonly used in inference when we have KV cache. + Return: + kv: (batch_size, seqlen, 2, nheads, headdim) + rotary_dim must be <= headdim + Apply rotary embedding *inplace* to the first rotary_dim of K. + """ + return ApplyRotaryEmbKV_.apply(kv, cos, sin, interleaved, seqlen_offsets) + + +class RotaryEmbedding(torch.nn.Module): + """ + The rotary position embeddings from RoFormer_ (Su et. al). + A crucial insight from the method is that the query and keys are + transformed by rotation matrices which depend on the relative positions. + + Other implementations are available in the Rotary Transformer repo_ and in + GPT-NeoX_, GPT-NeoX was an inspiration + + .. _RoFormer: https://arxiv.org/abs/2104.09864 + .. _repo: https://github.com/ZhuiyiTechnology/roformer + .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox + + If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554). + A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96 + Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py + """ + + def __init__( + self, + dim: int, + base=10000.0, + interleaved=False, + scale_base=None, + pos_idx_in_fp32=True, + device=None, + ): + """ + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead + of 1st half and 2nd half (GPT-NeoX style). + pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32, + otherwise they might be in lower precision. + This option was added because previously (before 2023-07-02), when we construct + the position indices, we use the dtype of self.inv_freq. In most cases this would + be fp32, but if the model is trained in pure bf16 (not mixed precision), then + self.inv_freq would be bf16, and the position indices are also in bf16. + Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the + embeddings for some positions will coincide. + To maintain compatibility with models previously trained in pure bf16, + we add this option. + """ + super().__init__() + self.dim = dim + self.base = float(base) + self.pos_idx_in_fp32 = pos_idx_in_fp32 + # Generate and save the inverse frequency buffer (non trainable) + inv_freq = self._compute_inv_freq(device) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self.interleaved = interleaved + self.scale_base = scale_base + scale = ( + (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim) + if scale_base is not None + else None + ) + self.register_buffer("scale", scale, persistent=False) + + self._seq_len_cached = 0 + self._cos_cached = None + self._sin_cached = None + self._cos_k_cached = None + self._sin_k_cached = None + + def _compute_inv_freq(self, device=None): + return 1.0 / ( + self.base + ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim) + ) + + def _update_cos_sin_cache(self, seqlen, device=None, dtype=None): + # Reset the tables if the sequence length has changed, + # if we're on a new device (possibly due to tracing for instance), + # or if we're switching from inference mode to training + if ( + seqlen > self._seq_len_cached + or self._cos_cached is None + or self._cos_cached.device != device + or self._cos_cached.dtype != dtype + or (self.training and self._cos_cached.is_inference()) + ): + self._seq_len_cached = seqlen + # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16 + # And the output of arange can be quite large, so bf16 would lose a lot of precision. + # However, for compatibility reason, we add an option to use the dtype of self.inv_freq. + if self.pos_idx_in_fp32: + t = torch.arange(seqlen, device=device, dtype=torch.float32) + # We want fp32 here as well since inv_freq will be multiplied with t, and the output + # will be large. Having it in bf16 will lose a lot of precision and cause the + # cos & sin output to change significantly. + # We want to recompute self.inv_freq if it was not loaded in fp32 + if self.inv_freq.dtype != torch.float32: + inv_freq = self._compute_inv_freq(device=device) + else: + inv_freq = self.inv_freq + else: + t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype) + inv_freq = self.inv_freq + # Don't do einsum, it converts fp32 to fp16 under AMP + # freqs = torch.einsum("i,j->ij", t, self.inv_freq) + freqs = torch.outer(t, inv_freq) + if self.scale is None: + self._cos_cached = torch.cos(freqs).to(dtype) + self._sin_cached = torch.sin(freqs).to(dtype) + else: + power = ( + torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) + - seqlen // 2 + ) / self.scale_base + scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1") + # We want the multiplication by scale to happen in fp32 + self._cos_cached = (torch.cos(freqs) * scale).to(dtype) + self._sin_cached = (torch.sin(freqs) * scale).to(dtype) + self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype) + self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype) + + def forward( + self, + qkv: torch.Tensor, + kv: Optional[torch.Tensor] = None, + seqlen_offset: Union[int, torch.Tensor] = 0, + max_seqlen: Optional[int] = None, + num_heads_q: Optional[int] = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + qkv: (batch, seqlen, 3, nheads, headdim) or (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) + if kv is none, else it's just q of shape (batch, seqlen, nheads, headdim). + If qkv has shape (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA), + then num_heads_q must be provided. + kv: (batch, seqlen, 2, nheads, headdim) + seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount. + Most commonly used in inference when we have KV cache. + If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one + should pass in max_seqlen, which will update the cos / sin cache up to that length. + Apply rotary embedding *inplace* to qkv and / or kv. + """ + seqlen = qkv.shape[1] + if max_seqlen is not None: + self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype) + elif isinstance(seqlen_offset, int): + self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype) + if kv is None: + if self.scale is None: + return apply_rotary_emb_qkv_( + qkv, + self._cos_cached, + self._sin_cached, + interleaved=self.interleaved, + seqlen_offsets=seqlen_offset, + num_heads_q=num_heads_q, + ) + else: + return apply_rotary_emb_qkv_( + qkv, + self._cos_cached, + self._sin_cached, + self._cos_k_cached, + self._sin_k_cached, + interleaved=self.interleaved, + seqlen_offsets=seqlen_offset, + num_heads_q=num_heads_q, + ) + else: + q = qkv + q = apply_rotary_emb_func( + q, + self._cos_cached, + self._sin_cached, + interleaved=self.interleaved, + inplace=True, + seqlen_offsets=seqlen_offset, + ) + if self.scale is None: + kv = apply_rotary_emb_kv_( + kv, + self._cos_cached, + self._sin_cached, + interleaved=self.interleaved, + seqlen_offsets=seqlen_offset, + ) + else: + kv = apply_rotary_emb_kv_( + kv, + self._cos_k_cached, + self._sin_k_cached, + interleaved=self.interleaved, + seqlen_offsets=seqlen_offset, + ) + return q, kv diff --git a/lib/python3.11/site-packages/flash_attn/losses/__init__.py b/lib/python3.11/site-packages/flash_attn/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/flash_attn/losses/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/losses/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80ad7f63da50a02214734f2ec54de46f8cf8b531 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/losses/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..545d8f77e7b49bc4ba3d845bf3c748c042860769 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/losses/cross_entropy.py b/lib/python3.11/site-packages/flash_attn/losses/cross_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dcf66758c353b1094218ac78f6f99db2b32224 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/losses/cross_entropy.py @@ -0,0 +1,85 @@ +# Copyright (c) 2024, Tri Dao. + +import torch +import torch.nn as nn + +from flash_attn.ops.triton.cross_entropy import cross_entropy_loss + + +class CrossEntropyLoss(nn.Module): + def __init__( + self, + ignore_index=-100, + reduction="mean", + label_smoothing=0.0, + logit_scale=1.0, + lse_square_scale=0.0, + inplace_backward=False, + process_group=None, + return_z_loss=False, + ): + """ + Arguments: + ignore_index: int. If labels == ignore_index, the loss is set to 0.0. + label_smoothing: float + lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss. + This is also referred to as "z-loss". + inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits. + This saves memory. + process_group: if not None, we're doing Tensor Parallel: each process is responsible for + one part of the vocab. The loss will be aggregated across processes. + return_z_loss: bool. If True, we return the component of the loss contributed by + the lse_square_scale value. This value is only for logging and does not support + backprop. + """ + super().__init__() + if reduction not in ["mean", "none", "sum"]: + raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'") + self.ignore_index = ignore_index + self.reduction = reduction + self.label_smoothing = label_smoothing + self.logit_scale = logit_scale + self.lse_square_scale = lse_square_scale + self.inplace_backward = inplace_backward + self.process_group = process_group + self.return_z_loss = return_z_loss + + def forward(self, input, target, precomputed_lse=None): + """ + Arguments: + input: (batch, vocab_size) + target: (batch,) + Returns: + losses: (batch,) if reduction is 'none', else (1,), dtype float + z_loss: (batch,) if reduction is 'none', else (1,), dtype float (if self.return_z_loss) + """ + assert input.is_cuda and target.is_cuda, "Only support CUDA tensors" + loss, z_loss = cross_entropy_loss( + input, + target, + precomputed_lse=precomputed_lse, + label_smoothing=self.label_smoothing, + logit_scale=self.logit_scale, + lse_square_scale=self.lse_square_scale, + ignore_index=self.ignore_index, + inplace_backward=self.inplace_backward, + process_group=self.process_group, + ) + if self.reduction == "mean": + loss = loss.sum() / (target != self.ignore_index).sum() + elif self.reduction == "sum": + loss = loss.sum() + else: + loss = loss + + if not self.return_z_loss: + return loss + + if self.reduction == "mean": + z_loss = z_loss.sum() / (target != self.ignore_index).sum() + elif self.reduction == "sum": + z_loss = z_loss.sum() + else: + z_loss = z_loss + + return loss, z_loss diff --git a/lib/python3.11/site-packages/flash_attn/models/__init__.py b/lib/python3.11/site-packages/flash_attn/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdf4ce6326c62183a5d495eec387b894952fdac3 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/baichuan.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/baichuan.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3825232ac0ff1d2277f31efe9a9b8a2de4a50e15 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/baichuan.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/bert.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/bert.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25ce1f6d7a181e81929e383616366f29b077c112 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/bert.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/bigcode.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/bigcode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20cf8c2645130a716d48ed6487306a9108542544 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/bigcode.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/btlm.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/btlm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bec16c0883fb42c1c2dd9050330e317b62c16da7 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/btlm.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/falcon.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/falcon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1ca2d110a882d3f3d667742460a1828eead6d32 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/falcon.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/gpt.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/gpt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c703876e3a0c5cf71b73ba52059c0aaf66b75e4c Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/gpt.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/gpt_neox.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/gpt_neox.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8824d69510efc8511df1606a86919d4dea0061a9 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/gpt_neox.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/gptj.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/gptj.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67fba93ab683a0b098ccf54cd7f0bb98212267ad Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/gptj.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/llama.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/llama.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..262c0c19028a4c377321c3cbedeefbde7ff079ba Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/llama.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/opt.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/opt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc90596ce7e790fe09837e547a66f32b949175cf Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/opt.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/__pycache__/vit.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/models/__pycache__/vit.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e6dff09f446029aaad7de074bce623a5ba0e110 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/models/__pycache__/vit.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/models/baichuan.py b/lib/python3.11/site-packages/flash_attn/models/baichuan.py new file mode 100644 index 0000000000000000000000000000000000000000..97d030782187afdfa22b9ad0a9a264b9f6c0a95e --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/baichuan.py @@ -0,0 +1,151 @@ +# Copyright (c) 2023, GGGGGGXY, Tri Dao. + +import math +import json +import re +from pathlib import Path + +from collections import OrderedDict + +import torch +import torch.nn.functional as F + +from einops import rearrange +from transformers import GPT2Config, AutoConfig, PretrainedConfig + + +def remap_state_dict_hf_baichuan(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^model.", "transformer.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + + # Word embedding + def key_mapping_emb(key): + return re.sub( + r"^transformer.embed_tokens.", + "transformer.embeddings.word_embeddings.", + key, + ) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict[ + "transformer.embeddings.word_embeddings.weight" + ] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # Need to recompute vocab_size since Baichuan shards the word embeddings and output embeddings + # differently. + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.", + r"transformer.layers.\1.norm1.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for l in range(config.n_layer): + w1 = state_dict.pop(f"transformer.layers.{l}.mlp.gate_proj.weight") + w3 = state_dict.pop(f"transformer.layers.{l}.mlp.up_proj.weight") + # Our ordering is different + state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat( + [w3, w1], dim=0 + ) + + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).mlp.down_proj.", + r"transformer.layers.\1.mlp.fc2.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).self_attn.W_pack.", + r"transformer.layers.\1.mixer.Wqkv.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attn.o_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + for l in range(config.n_layer): + # pop rotary_emb.inv_freq from state dict + state_dict.pop(f"transformer.layers.{l}.self_attn.rotary_emb.inv_freq", None) + return state_dict + + +def baichuan_config_to_gpt2_config(baichuan_config: PretrainedConfig) -> GPT2Config: + # HACK: the config doesn't have say whether it's rotary or alibi. + # So we have to infer from the hidden size (7B -> rotary, 13B -> alibi). + # HACK: the config doesn't have say whether it uses norm head. + # So we have to infer from the vocab size + # (v1, vocab size 64k, no norm head; v2, vocab size 128k, norm head). + use_rotary = baichuan_config.hidden_size < 5000 + return GPT2Config( + vocab_size=baichuan_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=baichuan_config.hidden_size, + n_layer=baichuan_config.num_hidden_layers, + n_head=baichuan_config.num_attention_heads, + n_inner=baichuan_config.intermediate_size, + activation_function="swiglu", # Hardcode since HF calls it 'silu' + # baichuan doesn't have dropout, idk if it's because they only release the inference code + resid_pdrop=0.0, + embd_pdrop=0.0, + attn_pdrop=0.0, + layer_norm_epsilon=baichuan_config.rms_norm_eps, + initializer_range=baichuan_config.initializer_range, + bos_token_id=baichuan_config.bos_token_id, + eos_token_id=baichuan_config.eos_token_id, + # These are new arguments not in the original GPT2Config + pad_token_id=baichuan_config.pad_token_id, # Idk if this does anything + rms_norm=True, + rotary_emb_fraction=1.0 if use_rotary else 0.0, + rotary_emb_interleaved=False, + use_alibi=not use_rotary, + use_flash_attn=not use_rotary, # Alibi code path requires flash_attn + tie_word_embeddings=False, + norm_head=baichuan_config.vocab_size > 70000, + qkv_proj_bias=False, + out_proj_bias=False, + mlp_fc1_bias=False, + mlp_fc2_bias=False, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/bert.py b/lib/python3.11/site-packages/flash_attn/models/bert.py new file mode 100644 index 0000000000000000000000000000000000000000..0904631968411eb227d729a328a36fa4ec97cf02 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/bert.py @@ -0,0 +1,764 @@ +# Copyright (c) 2022, Tri Dao. +# This BERT implementation is based on our MLPerf 2.0 and MLPerf 2.1 BERT implementation. +# https://github.com/mlcommons/training_results_v2.0/blob/main/HazyResearch/benchmarks/bert/implementations/pytorch/modeling.py +# https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-HazyResearch/benchmarks/bert/implementations/ND96amsr_A100_v4/modeling.py + +# Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py + +import logging +import re +from collections import OrderedDict +from collections.abc import Sequence +from functools import partial +from typing import Any, Mapping + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers import BertConfig, PretrainedConfig +from transformers.models.bert.modeling_bert import ( + BaseModelOutputWithPoolingAndCrossAttentions, + BertForPreTrainingOutput, +) + +from flash_attn.bert_padding import ( + index_first_axis, + index_first_axis_residual, + pad_input, + unpad_input, +) +from flash_attn.modules.block import Block +from flash_attn.modules.embedding import BertEmbeddings +from flash_attn.modules.mha import MHA +from flash_attn.modules.mlp import FusedMLP, Mlp +from flash_attn.utils.pretrained import state_dict_from_pretrained + +try: + from flash_attn.ops.fused_dense import FusedDense +except ImportError: + FusedDense = None + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn +except ImportError: + layer_norm_fn = None + + +try: + from flash_attn.losses.cross_entropy import CrossEntropyLoss +except ImportError: + CrossEntropyLoss = None + + +logger = logging.getLogger(__name__) + + +def create_mixer_cls(config, cross_attn=False, return_residual=False): + use_flash_attn = getattr(config, "use_flash_attn", False) + fused_bias_fc = getattr(config, "fused_bias_fc", False) + rotary_kwargs = {} + if config.position_embedding_type == "rotary": + rotary_kwargs["rotary_emb_dim"] = getattr(config, "rotary_emb_dim", config.hidden_size) + rotary_kwargs["rotary_emb_base"] = getattr(config, "rotary_emb_base", 10000.0) + rotary_kwargs["rotary_emb_scale_base"] = getattr(config, "rotary_emb_scale_base", None) + rotary_kwargs["rotary_emb_interleaved"] = getattr(config, "rotary_emb_interleaved", False) + mixer_cls = partial( + MHA, + num_heads=config.num_attention_heads, + cross_attn=cross_attn, + dropout=config.attention_probs_dropout_prob, + causal=False, + fused_bias_fc=fused_bias_fc, + use_flash_attn=use_flash_attn, + return_residual=return_residual, + **rotary_kwargs, + ) + return mixer_cls + + +def create_mlp_cls(config, layer_idx=None, return_residual=False): + inner_dim = config.intermediate_size + fused_mlp = getattr(config, "fused_mlp", False) + if fused_mlp: + assert config.hidden_act in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"], ( + "fused_mlp only " "supports approximate gelu" + ) + if not fused_mlp: + approximate = ( + "tanh" + if config.hidden_act in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] + else "none" + ) + mlp_cls = partial( + Mlp, + hidden_features=inner_dim, + activation=partial(F.gelu, approximate=approximate), + return_residual=return_residual, + ) + else: + if FusedMLP is None: + raise ImportError("fused_dense is not installed") + mlp_checkpoint_lvl = getattr(config, "mlp_checkpoint_lvl", 0) + # mlp_checkpoint_lvl could be a list, which contains the checkpoint_lvl for each layer + if isinstance(mlp_checkpoint_lvl, Sequence): + assert layer_idx is not None + mlp_checkpoint_lvl = mlp_checkpoint_lvl[layer_idx] + mlp_cls = partial( + FusedMLP, + hidden_features=inner_dim, + checkpoint_lvl=mlp_checkpoint_lvl, + return_residual=return_residual, + ) + return mlp_cls + + +def create_block(config, layer_idx=None): + last_layer_subset = getattr(config, "last_layer_subset", False) + cross_attn = last_layer_subset and layer_idx == config.num_hidden_layers - 1 + # TD [2022-12-19]: For cross attention (last layer), we actually want to return the + # residual x_kv, not residual x. But it's annoying to change the API (and it only affects + # one layer) so we just choose not to return residual in this case. + return_residual = not cross_attn + mixer_cls = create_mixer_cls(config, cross_attn, return_residual=return_residual) + mlp_cls = create_mlp_cls(config, layer_idx, return_residual=return_residual) + norm_cls = partial(nn.LayerNorm, eps=config.layer_norm_eps) + block = Block( + config.hidden_size, + mixer_cls, + mlp_cls, + norm_cls=norm_cls, + prenorm=False, + resid_dropout1=config.hidden_dropout_prob, + resid_dropout2=config.hidden_dropout_prob, + fused_dropout_add_ln=getattr(config, "fused_dropout_add_ln", False), + return_residual=return_residual, + ) + return block + + +# https://github.com/huggingface/transformers/blob/7032e0203262ebb2ebf55da8d2e01f873973e835/src/transformers/models/bert/modeling_bert.py#L748 +def _init_weights(module, initializer_range=0.02): + if isinstance(module, nn.Linear): + nn.init.normal_(module.weight, std=initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, std=initializer_range) + if module.padding_idx is not None: + nn.init.zeros_(module.weight[module.padding_idx]) + + +class BertEncoder(nn.Module): + def __init__(self, config: BertConfig): + super().__init__() + self.use_flash_attn = getattr(config, "use_flash_attn", False) + self.layers = nn.ModuleList( + [create_block(config, layer_idx=i) for i in range(config.num_hidden_layers)] + ) + + def forward(self, hidden_states, key_padding_mask=None, subset_mask=None): + """If subset_mask is not None, we only want output for the subset of the sequence. + This means that we only compute the last layer output for these tokens. + subset_mask: (batch, seqlen), dtype=torch.bool + """ + if key_padding_mask is None or not self.use_flash_attn: + mixer_kwargs = ( + {"key_padding_mask": key_padding_mask} if key_padding_mask is not None else None + ) + for layer in self.layers: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + if subset_mask is not None: + hidden_states = hidden_states[subset_mask] + else: + batch, seqlen = hidden_states.shape[:2] + hidden_states, indices, cu_seqlens, max_seqlen_in_batch, _ = unpad_input( + hidden_states, key_padding_mask + ) + mixer_kwargs = {"cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen_in_batch} + if subset_mask is None: + for layer in self.layers: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + hidden_states = pad_input(hidden_states, indices, batch, seqlen) + else: + for layer in self.layers[:-1]: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + if key_padding_mask is not None: + subset_idx = torch.nonzero( + subset_mask[key_padding_mask], as_tuple=False + ).flatten() + subset_seqlens = (subset_mask & key_padding_mask).sum(dim=-1, dtype=torch.int32) + subset_cu_seqlens = F.pad( + torch.cumsum(subset_seqlens, dim=0, dtype=torch.int32), (1, 0) + ) + else: + subset_idx = torch.nonzero(subset_mask, as_tuple=False).flatten() + subset_seqlens = subset_mask.sum(dim=-1, dtype=torch.int32) + subset_cu_seqlens = F.pad( + torch.cumsum(subset_seqlens, dim=0, dtype=torch.int32), (1, 0) + ) + hidden_states_subset, hidden_states = index_first_axis_residual( + hidden_states, subset_idx + ) + # It's ok to set max_seqlen_q to be much larger + mixer_kwargs = { + "x_kv": hidden_states, + "cu_seqlens": subset_cu_seqlens, + "max_seqlen": max_seqlen_in_batch, + "cu_seqlens_k": cu_seqlens, + "max_seqlen_k": max_seqlen_in_batch, + } + hidden_states = self.layers[-1](hidden_states_subset, mixer_kwargs=mixer_kwargs) + return hidden_states + + +class BertPooler(nn.Module): + def __init__(self, config): + super().__init__() + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + self.dense = linear_cls(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states, pool=True): + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] if pool else hidden_states + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class BertPredictionHeadTransform(nn.Module): + def __init__(self, config): + super().__init__() + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + self.fused_dropout_add_ln = getattr(config, "fused_dropout_add_ln", False) + if self.fused_dropout_add_ln and layer_norm_fn is None: + raise ImportError("Triton is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + self.dense = linear_cls(config.hidden_size, config.hidden_size) + approximate = ( + "tanh" + if config.hidden_act in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] + else "none" + ) + self.transform_act_fn = nn.GELU(approximate=approximate) + self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.transform_act_fn(hidden_states) + if not self.fused_dropout_add_ln: + hidden_states = self.layer_norm(hidden_states) + else: + hidden_states = layer_norm_fn( + hidden_states, self.layer_norm.weight, self.layer_norm.bias, eps=self.layer_norm.eps + ) + return hidden_states + + +class BertLMPredictionHead(nn.Module): + def __init__(self, config): + super().__init__() + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = linear_cls(config.hidden_size, config.vocab_size, bias=True) + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states + + +class BertPreTrainingHeads(nn.Module): + def __init__(self, config): + super().__init__() + self.predictions = BertLMPredictionHead(config) + self.seq_relationship = nn.Linear(config.hidden_size, 2) + + def forward(self, sequence_output, pooled_output): + prediction_scores = self.predictions(sequence_output) + seq_relationship_score = self.seq_relationship(pooled_output) + return prediction_scores, seq_relationship_score + + +class BertPreTrainedModel(nn.Module): + """An abstract class to handle weights initialization and + a simple interface for dowloading and loading pretrained models. + """ + + def __init__(self, config, *inputs, **kwargs): + super().__init__() + if not isinstance(config, BertConfig): + raise ValueError( + "Parameter config in `{}(config)` should be an instance of class `BertConfig`. " + "To create a model from a Google pretrained model use " + "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( + self.__class__.__name__, self.__class__.__name__ + ) + ) + self.config = config + + @classmethod + def from_pretrained(cls, model_name, config, *inputs, **kwargs): + """ + Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict. + Download and cache the pre-trained model file if needed. + + Params: + pretrained_model_name_or_path: either: + - a path or url to a pretrained model archive containing: + . `bert_config.json` a configuration file for the model + . `pytorch_model.bin` a PyTorch dump of a BertForPretraining instance + - a path or url to a pretrained model archive containing: + . `bert_config.json` a configuration file for the model + . `model.chkpt` a TensorFlow checkpoint + *inputs, **kwargs: additional input for the specific Bert class + (ex: num_labels for BertForSequenceClassification) + """ + # Instantiate model. + model = cls(config, *inputs, **kwargs) + load_return = model.load_state_dict( + remap_state_dict(state_dict_from_pretrained(model_name), config), strict=False + ) + logger.info(load_return) + return model + + +class BertModel(BertPreTrainedModel): + def __init__(self, config: BertConfig, add_pooling_layer=True): + super().__init__(config) + self.pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + if config.vocab_size % self.pad_vocab_size_multiple != 0: + config.vocab_size += self.pad_vocab_size_multiple - ( + config.vocab_size % self.pad_vocab_size_multiple + ) + self.fused_dropout_add_ln = getattr(config, "fused_dropout_add_ln", False) + if self.fused_dropout_add_ln and layer_norm_fn is None: + raise ImportError("Triton is not installed") + assert config.hidden_act in ["gelu", "gelu_new", "gelu_fast", "gelu_pytorch_tanh"] + + self.embeddings = BertEmbeddings( + config.hidden_size, + config.vocab_size, + config.max_position_embeddings, + config.type_vocab_size, + padding_idx=config.pad_token_id, + ) + self.emb_drop = nn.Dropout(config.hidden_dropout_prob) + self.emb_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.encoder = BertEncoder(config) + self.pooler = BertPooler(config) if add_pooling_layer else None + + self.apply(partial(_init_weights, initializer_range=config.initializer_range)) + + def forward( + self, + input_ids, + position_ids=None, + token_type_ids=None, + attention_mask=None, + masked_tokens_mask=None, + ): + """If masked_tokens_mask is not None (i.e. last_layer_subset == True in BertForPreTraining), + we only want the output for the masked tokens. This means that we only compute the last + layer output for these tokens. + masked_tokens_mask: (batch, seqlen), dtype=torch.bool + """ + hidden_states = self.embeddings( + input_ids, position_ids=position_ids, token_type_ids=token_type_ids + ) + # TD [2022-12:18]: Don't need to force residual in fp32 + # BERT puts embedding LayerNorm before embedding dropout. + if not self.fused_dropout_add_ln: + hidden_states = self.emb_ln(hidden_states) + else: + hidden_states = layer_norm_fn( + hidden_states, self.emb_ln.weight, self.emb_ln.bias, eps=self.emb_ln.eps + ) + hidden_states = self.emb_drop(hidden_states) + + if masked_tokens_mask is not None: + batch_size, seqlen = input_ids.shape[:2] + # We also need the first column for the CLS token + first_col_mask = torch.zeros( + batch_size, seqlen, dtype=torch.bool, device=input_ids.device + ) + first_col_mask[:, 0] = True + subset_mask = masked_tokens_mask | first_col_mask + else: + subset_mask = None + + sequence_output = self.encoder( + hidden_states, key_padding_mask=attention_mask, subset_mask=subset_mask + ) + + if masked_tokens_mask is None: + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + else: + # TD [2022-03-01]: the indexing here is very tricky. + if attention_mask is not None: + subset_idx = subset_mask[attention_mask] + pool_input = sequence_output[first_col_mask[attention_mask][subset_idx]] + sequence_output = sequence_output[masked_tokens_mask[attention_mask][subset_idx]] + else: + pool_input = sequence_output[first_col_mask[subset_mask]] + sequence_output = sequence_output[masked_tokens_mask[subset_mask]] + pooled_output = self.pooler(pool_input, pool=False) if self.pooler is not None else None + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + ) + + +class BertForPreTraining(BertPreTrainedModel): + def __init__(self, config: BertConfig): + super().__init__(config) + # If dense_seq_output, we only need to pass the hidden states for the masked out tokens + # (around 15%) to the classifier heads. + self.dense_seq_output = getattr(config, "dense_seq_output", False) + # If last_layer_subset, we only need the compute the last layer for a subset of tokens + # (e.g., the tokens we need to compute the masked LM loss and the next-sentence prediction). + self.last_layer_subset = getattr(config, "last_layer_subset", False) + if self.last_layer_subset: + assert self.dense_seq_output, "last_layer_subset requires dense_seq_output" + use_xentropy = getattr(config, "use_xentropy", False) + if use_xentropy and CrossEntropyLoss is None: + raise ImportError("xentropy_cuda is not installed") + loss_cls = ( + nn.CrossEntropyLoss + if not use_xentropy + else partial(CrossEntropyLoss, inplace_backward=True) + ) + + self.bert = BertModel(config) + self.cls = BertPreTrainingHeads(config) + self.mlm_loss = loss_cls(ignore_index=0) + self.nsp_loss = loss_cls(ignore_index=-1) + + # Initialize weights and apply final processing + self.apply(partial(_init_weights, initializer_range=config.initializer_range)) + self.tie_weights() + + def tie_weights(self): + self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.weight + + def forward( + self, + input_ids, + position_ids=None, + token_type_ids=None, + attention_mask=None, + labels=None, + next_sentence_label=None, + ): + """ + If labels are provided, they must be 0 for masked out tokens (as specified in the attention + mask). + Outputs: + if `labels` and `next_sentence_label` are not `None`: + Outputs the total_loss which is the sum of the masked language modeling loss and the next + sentence classification loss. + if `labels` or `next_sentence_label` is `None`: + Outputs a tuple comprising + - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and + - the next sentence classification logits of shape [batch_size, 2]. + + """ + masked_tokens_mask = labels > 0 if (self.last_layer_subset and labels is not None) else None + outputs = self.bert( + input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + attention_mask=attention_mask.bool() if attention_mask is not None else None, + masked_tokens_mask=masked_tokens_mask, + ) + sequence_output, pooled_output = outputs.last_hidden_state, outputs.pooler_output + if self.dense_seq_output and labels is not None: + masked_token_idx = torch.nonzero(labels.flatten() > 0, as_tuple=False).flatten() + if not self.last_layer_subset: + sequence_output = index_first_axis( + rearrange(sequence_output, "b s d -> (b s) d"), masked_token_idx + ) + prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output) + + total_loss = None + if labels is not None and next_sentence_label is not None: + if ( + self.dense_seq_output and labels is not None + ): # prediction_scores are already flattened + masked_lm_loss = self.mlm_loss( + prediction_scores, labels.flatten()[masked_token_idx] + ) + else: + masked_lm_loss = self.mlm_loss( + rearrange(prediction_scores, "... v -> (...) v"), + rearrange(labels, "... -> (...)"), + ) + next_sentence_loss = self.nsp_loss( + rearrange(seq_relationship_score, "... t -> (...) t"), + rearrange(next_sentence_label, "... -> (...)"), + ) + total_loss = masked_lm_loss.float() + next_sentence_loss.float() + + return BertForPreTrainingOutput( + loss=total_loss, + prediction_logits=prediction_scores, + seq_relationship_logits=seq_relationship_score, + ) + + +def remap_state_dict(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a Huggingface BERT model to be flash_attn compatible. + """ + + # LayerNorm + def key_mapping_ln_gamma_beta(key): + key = re.sub(r"LayerNorm.gamma$", "LayerNorm.weight", key) + key = re.sub(r"LayerNorm.beta$", "LayerNorm.bias", key) + return key + + state_dict = OrderedDict((key_mapping_ln_gamma_beta(k), v) for k, v in state_dict.items()) + + # Layers + def key_mapping_layers(key): + return re.sub(r"^bert.encoder.layer.", "bert.encoder.layers.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^bert.embeddings.LayerNorm.", "bert.emb_ln.", key) + key = re.sub( + r"^bert.encoder.layers.(\d+).attention.output.LayerNorm.(weight|bias)", + r"bert.encoder.layers.\1.norm1.\2", + key, + ) + key = re.sub( + r"^bert.encoder.layers.(\d+).output.LayerNorm.(weight|bias)", + r"bert.encoder.layers.\1.norm2.\2", + key, + ) + key = re.sub( + r"^cls.predictions.transform.LayerNorm.(weight|bias)", + r"cls.predictions.transform.layer_norm.\1", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^bert.encoder.layers.(\d+).intermediate.dense.(weight|bias)", + r"bert.encoder.layers.\1.mlp.fc1.\2", + key, + ) + key = re.sub( + r"^bert.encoder.layers.(\d+).output.dense.(weight|bias)", + r"bert.encoder.layers.\1.mlp.fc2.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + last_layer_subset = getattr(config, "last_layer_subset", False) + for d in range(config.num_hidden_layers): + Wq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.weight") + Wk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.weight") + Wv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.weight") + bq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.bias") + bk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.bias") + bv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.bias") + if not (last_layer_subset and d == config.num_hidden_layers - 1): + state_dict[f"bert.encoder.layers.{d}.mixer.Wqkv.weight"] = torch.cat( + [Wq, Wk, Wv], dim=0 + ) + state_dict[f"bert.encoder.layers.{d}.mixer.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0) + else: + state_dict[f"bert.encoder.layers.{d}.mixer.Wq.weight"] = Wq + state_dict[f"bert.encoder.layers.{d}.mixer.Wkv.weight"] = torch.cat([Wk, Wv], dim=0) + state_dict[f"bert.encoder.layers.{d}.mixer.Wq.bias"] = bq + state_dict[f"bert.encoder.layers.{d}.mixer.Wkv.bias"] = torch.cat([bk, bv], dim=0) + + def key_mapping_attn(key): + return re.sub( + r"^bert.encoder.layers.(\d+).attention.output.dense.(weight|bias)", + r"bert.encoder.layers.\1.mixer.out_proj.\2", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + def key_mapping_decoder_bias(key): + return re.sub(r"^cls.predictions.bias", "cls.predictions.decoder.bias", key) + + state_dict = OrderedDict((key_mapping_decoder_bias(k), v) for k, v in state_dict.items()) + + # Word embedding + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + if pad_vocab_size_multiple > 1: + word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"] + state_dict["bert.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, config.vocab_size - word_embeddings.shape[0]) + ) + decoder_weight = state_dict["cls.predictions.decoder.weight"] + state_dict["cls.predictions.decoder.weight"] = F.pad( + decoder_weight, (0, 0, 0, config.vocab_size - decoder_weight.shape[0]) + ) + # If the vocab was padded, we want to set the decoder bias for those padded indices to be + # strongly negative (i.e. the decoder shouldn't predict those indices). + # TD [2022-05-09]: I don't think it affects the MLPerf training. + decoder_bias = state_dict["cls.predictions.decoder.bias"] + state_dict["cls.predictions.decoder.bias"] = F.pad( + decoder_bias, (0, config.vocab_size - decoder_bias.shape[0]), value=-100.0 + ) + + return state_dict + + +def inv_remap_state_dict(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a flash_attn model to be Huggingface BERT compatible. + + This function is meant to be the inverse of remap_state_dict. + """ + # Word embedding + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + if pad_vocab_size_multiple > 1: + word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"] + decoder_weight = state_dict["cls.predictions.decoder.weight"] + decoder_bias = state_dict["cls.predictions.decoder.bias"] + # unpad embeddings + state_dict["bert.embeddings.word_embeddings.weight"] = word_embeddings[ + : config.orig_vocab_size, : + ] + state_dict["cls.predictions.decoder.weight"] = decoder_weight[: config.orig_vocab_size, :] + state_dict["cls.predictions.decoder.bias"] = decoder_bias[: config.orig_vocab_size] + + for d in range(config.num_hidden_layers): + last_layer_subset = getattr(config, "last_layer_subset", False) + if not last_layer_subset or d != (config.num_hidden_layers - 1): + Wqkv_weights = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wqkv.weight") + Wqkv_biases = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wqkv.bias") + state_dict[f"bert.encoder.layers.{d}.attention.self.query.weight"] = Wqkv_weights[ + : Wqkv_weights.shape[0] // 3, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.key.weight"] = Wqkv_weights[ + Wqkv_weights.shape[0] // 3 : 2 * Wqkv_weights.shape[0] // 3, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.weight"] = Wqkv_weights[ + 2 * Wqkv_weights.shape[0] // 3 :, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.query.bias"] = Wqkv_biases[ + : Wqkv_biases.shape[0] // 3 + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.key.bias"] = Wqkv_biases[ + Wqkv_biases.shape[0] // 3 : 2 * Wqkv_biases.shape[0] // 3 + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.bias"] = Wqkv_biases[ + 2 * Wqkv_biases.shape[0] // 3 : + ] + else: + Wq_weight = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wq.weight") + Wkv_weights = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wkv.weight") + Wq_bias = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wq.bias") + Wkv_biases = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wkv.bias") + state_dict[f"bert.encoder.layers.{d}.attention.self.query.weight"] = Wq_weight + state_dict[f"bert.encoder.layers.{d}.attention.self.key.weight"] = Wkv_weights[ + : Wkv_weights.shape[0] // 2, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.weight"] = Wkv_weights[ + Wkv_weights.shape[0] // 2 :, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.query.bias"] = Wq_bias + state_dict[f"bert.encoder.layers.{d}.attention.self.key.bias"] = Wkv_biases[ + : Wkv_biases.shape[0] // 2 + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.bias"] = Wkv_biases[ + Wkv_biases.shape[0] // 2 : + ] + + def inv_key_mapping_ln(key): + key = re.sub(r"bert.emb_ln.", "bert.embeddings.LayerNorm.", key) + key = re.sub( + r"bert.encoder.layers.(\d+).norm1.(weight|bias)", + r"bert.encoder.layers.\1.attention.output.LayerNorm.\2", + key, + ) + key = re.sub( + r"bert.encoder.layers.(\d+).norm2.(weight|bias)", + r"bert.encoder.layers.\1.output.LayerNorm.\2", + key, + ) + key = re.sub( + r"cls.predictions.transform.layer_norm.(weight|bias)", + r"cls.predictions.transform.LayerNorm.\1", + key, + ) + return key + + def inv_key_mapping_ln_gamma_beta(key): + key = re.sub(r"LayerNorm.weight$", "LayerNorm.gamma", key) + key = re.sub(r"LayerNorm.bias$", "LayerNorm.beta", key) + return key + + def inv_key_mapping_layers(key): + return re.sub(r"bert.encoder.layers.", "bert.encoder.layer.", key) + + def inv_key_mapping_mlp(key): + key = re.sub( + r"bert.encoder.layer.(\d+).mlp.fc1.(weight|bias)", + r"bert.encoder.layer.\1.intermediate.dense.\2", + key, + ) + key = re.sub( + r"bert.encoder.layer.(\d+).mlp.fc2.(weight|bias)", + r"bert.encoder.layer.\1.output.dense.\2", + key, + ) + return key + + def inv_key_mapping_attn(key): + return re.sub( + r"bert.encoder.layer.(\d+).mixer.out_proj.(weight|bias)", + r"bert.encoder.layer.\1.attention.output.dense.\2", + key, + ) + + def inv_key_mapping_decoder_bias(key): + return re.sub(r"cls.predictions.decoder.bias", "cls.predictions.bias", key) + + state_dict = OrderedDict((inv_key_mapping_ln(key), value) for key, value in state_dict.items()) + state_dict = OrderedDict( + (inv_key_mapping_ln_gamma_beta(key), value) for key, value in state_dict.items() + ) + state_dict = OrderedDict( + (inv_key_mapping_layers(key), value) for key, value in state_dict.items() + ) + state_dict = OrderedDict((inv_key_mapping_mlp(key), value) for key, value in state_dict.items()) + state_dict = OrderedDict( + (inv_key_mapping_attn(key), value) for key, value in state_dict.items() + ) + state_dict = OrderedDict( + (inv_key_mapping_decoder_bias(key), value) for key, value in state_dict.items() + ) + + return state_dict diff --git a/lib/python3.11/site-packages/flash_attn/models/bigcode.py b/lib/python3.11/site-packages/flash_attn/models/bigcode.py new file mode 100644 index 0000000000000000000000000000000000000000..234944d4d6907fb3e1b0c2c3c315a2bee29d7775 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/bigcode.py @@ -0,0 +1,233 @@ +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPTBigCodeConfig, PretrainedConfig + + +def remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a Huggingface BigCode model to be flash_attn compatible. + """ + + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^transformer.wpe.", "transformer.embeddings.position_embeddings.", key) + + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.wte.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub( + r"^transformer.h.(\d+).ln_(1|2).(weight|bias)", + r"transformer.layers.\1.norm\2.\3", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.h.(\d+).mlp.c_fc.weight", + r"transformer.layers.\1.mlp.fc1.weight", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).mlp.c_proj.weight", + r"transformer.layers.\1.mlp.fc2.weight", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).mlp.c_fc.bias", + r"transformer.layers.\1.mlp.fc1.bias", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).mlp.c_proj.bias", + r"transformer.layers.\1.mlp.fc2.bias", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # TODO: add support for multi-head attention + assert config.multi_query, "Only multi-query attention is supported" + + # Attention + for d in range(config.num_hidden_layers): + embed_dim = config.n_embd + head_dim = embed_dim // config.n_head + + c_attn_weight = state_dict.pop(f"transformer.h.{d}.attn.c_attn.weight") + # with multi-query attention, the weights have shape (embed_dim, embed_dim + head_dim + head_dim) + # see https://github.com/huggingface/transformers/blob/95b374952dc27d8511541d6f5a4e22c9ec11fb24/src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py#L112 + # see also https://github.com/ggerganov/ggml/blob/dd1d575956e54c5bdc07632f25506b3b1884dbd2/examples/starcoder/convert-hf-to-ggml.py#L183 + # ((n_head + 2) * head_dim, embed_dim) -> (3 * n_heads * head_dim, hidden_dim) + q, k, v = torch.split(c_attn_weight, [embed_dim, head_dim, head_dim], dim=0) + # duplicate k, v along the first axis (head_dim, hidden_dim) -> (n_heads * head_dim, hidden_dim) + k = torch.tile(k, (config.n_head, 1)) + v = torch.tile(v, (config.n_head, 1)) + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = torch.cat((q, k, v), dim=0) + + # same deal with the bias + c_attn_bias = state_dict.pop(f"transformer.h.{d}.attn.c_attn.bias") + # ((n_head + 2) * head_dim, embed_dim) -> (3 * n_heads * head_dim, hidden_dim) + q, k, v = torch.split(c_attn_bias, [embed_dim, head_dim, head_dim], dim=0) + # duplicate k, v along the first axis (head_dim, hidden_dim) -> (n_heads * head_dim, hidden_dim) + k = torch.tile(k, (config.n_head,)) + v = torch.tile(v, (config.n_head,)) + state_dict[f"transformer.layers.{d}.mixer.Wqkv.bias"] = torch.cat((q, k, v), dim=0) + + def key_mapping_attn(key): + key = re.sub( + r"^transformer.h.(\d+).attn.c_proj.weight", + r"transformer.layers.\1.mixer.out_proj.weight", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).attn.c_proj.bias", + r"transformer.layers.\1.mixer.out_proj.bias", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def inv_remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a flash_attn model to be Huggingface BigCode compatible. + + This function is meant to be the inverse of remap_state_dict_hf_bigcode. + """ + + # Word embedding and position embeddings + def inv_key_mapping_pos_emb(key): + return re.sub(r"^transformer.embeddings.position_embeddings.", "transformer.wpe.", key) + + state_dict = OrderedDict((inv_key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + + word_embeddings = word_embeddings[:, : config.vocab_size] + state_dict["transformer.wte.weight"] = word_embeddings + state_dict["lm_head.weight"] = word_embeddings + + # LayerNorm + def inv_key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub( + r"^transformer.layers.(\d+).norm(1|2).(weight|bias)", + r"transformer.h.\1.ln_\2.\3", + key, + ) + return key + + state_dict = OrderedDict((inv_key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLPs + def inv_key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc1.weight", + r"transformer.h.\1.mlp.c_fc.weight", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc2.weight", + r"transformer.h.\1.mlp.c_proj.weight", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc1.bias", + r"transformer.h.\1.mlp.c_fc.bias", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc2.bias", + r"transformer.h.\1.mlp.c_proj.bias", + key, + ) + return key + + state_dict = OrderedDict((inv_key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for d in range(config.num_hidden_layers): + embed_dim = config.n_embd + head_dim = embed_dim // config.n_head + + Wqkv_weight = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.weight") + q, k, v = torch.split( + Wqkv_weight, [embed_dim, head_dim * config.n_head, head_dim * config.n_head], dim=0 + ) + c_attn_weight = torch.cat((q, k[:head_dim], v[:head_dim]), dim=0) + state_dict[f"transformer.h.{d}.attn.c_attn.weight"] = c_attn_weight + + # Same deal with the bias + Wqkv_bias = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.bias") + q, k, v = torch.split( + Wqkv_bias, [embed_dim, head_dim * config.n_head, head_dim * config.n_head], dim=0 + ) + c_attn_bias = torch.cat((q, k[:head_dim], v[:head_dim]), dim=0) + state_dict[f"transformer.h.{d}.attn.c_attn.bias"] = c_attn_bias + + def inv_key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).mixer.out_proj.weight", + r"transformer.h.\1.attn.c_proj.weight", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mixer.out_proj.bias", + r"transformer.h.\1.attn.c_proj.bias", + key, + ) + return key + + state_dict = OrderedDict((inv_key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def bigcode_config_to_gpt2_config(bigcode_config: GPTBigCodeConfig) -> GPT2Config: + return GPT2Config( + activation_function=bigcode_config.activation_function, + attn_pdrop=bigcode_config.attn_pdrop, + bos_token_id=bigcode_config.bos_token_id, + embd_pdrop=bigcode_config.embd_pdrop, + eos_token_id=bigcode_config.eos_token_id, + initializer_range=bigcode_config.initializer_range, + layer_norm_epsilon=bigcode_config.layer_norm_epsilon, + max_batch_size=bigcode_config.max_batch_size, + max_sequence_length=bigcode_config.max_sequence_length, + model_type=bigcode_config.model_type, + multi_query=bigcode_config.multi_query, + n_embd=bigcode_config.n_embd, + n_head=bigcode_config.n_head, + n_inner=bigcode_config.n_inner, + n_layer=bigcode_config.n_layer, + n_positions=bigcode_config.n_positions, + resid_pdrop=bigcode_config.resid_pdrop, + scale_attn_weights=bigcode_config.scale_attn_weights, + summary_activation=bigcode_config.summary_activation, + summary_first_dropout=bigcode_config.summary_first_dropout, + summary_proj_to_labels=bigcode_config.summary_proj_to_labels, + summary_type=bigcode_config.summary_type, + summary_use_proj=bigcode_config.summary_use_proj, + use_cache=bigcode_config.use_cache, + vocab_size=bigcode_config.vocab_size, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/btlm.py b/lib/python3.11/site-packages/flash_attn/models/btlm.py new file mode 100644 index 0000000000000000000000000000000000000000..295e12062320be819dd835de4a866607650431b2 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/btlm.py @@ -0,0 +1,102 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import json +import re +from pathlib import Path + +from collections import OrderedDict + +import torch +import torch.nn.functional as F + +from einops import rearrange +from transformers import GPT2Config, AutoConfig, PretrainedConfig + + +def remap_state_dict_hf_btlm(state_dict, config): + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^transformer.wpe.", "transformer.embeddings.position_embeddings.", key) + + if "transformer.wpe.weight" in state_dict: + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.wte.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub(r"^transformer.h.(\d+).ln_(1|2).(weight|bias)", r"transformer.layers.\1.norm\2.\3", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for d in range(config.num_hidden_layers): + W1 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc.weight") + W3 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc2.weight") + state_dict[f"transformer.layers.{d}.mlp.fc1.weight"] = torch.cat([W1.t(), W3.t()], dim=0) + b1 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc.bias") + b3 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc2.bias") + state_dict[f"transformer.layers.{d}.mlp.fc1.bias"] = torch.cat([b1, b3], dim=0) + W2 = state_dict.pop(f"transformer.h.{d}.mlp.c_proj.weight") + state_dict[f"transformer.layers.{d}.mlp.fc2.weight"] = W2.t() + + def key_mapping_mlp(key): + key = re.sub(r"^transformer.h.(\d+).mlp.c_proj.bias", r"transformer.layers.\1.mlp.fc2.bias", key) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for d in range(config.num_hidden_layers): + Wqkv = state_dict.pop(f"transformer.h.{d}.attn.c_attn.weight") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = Wqkv.t() + Wout = state_dict.pop(f"transformer.h.{d}.attn.c_proj.weight") + state_dict[f"transformer.layers.{d}.mixer.out_proj.weight"] = Wout.t() + state_dict.pop(f"transformer.relative_pe.slopes") # We don't store the Alibi slopes + + def key_mapping_attn(key): + key = re.sub(r"^transformer.h.(\d+).attn.c_attn.bias", r"transformer.layers.\1.mixer.Wqkv.bias", key) + key = re.sub( + r"^transformer.h.(\d+).attn.c_proj.bias", r"transformer.layers.\1.mixer.out_proj.bias", key + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def btlm_config_to_gpt2_config(btlm_config: PretrainedConfig) -> GPT2Config: + return GPT2Config( + vocab_size=btlm_config.vocab_size, + n_positions=0 if btlm_config.position_embedding_type == "alibi" else btlm_config.n_positions, + n_embd=btlm_config.hidden_size, + n_layer=btlm_config.num_hidden_layers, + n_head=btlm_config.num_attention_heads, + n_inner=btlm_config.n_inner, + activation_function=btlm_config.activation_function, + resid_pdrop=btlm_config.resid_pdrop, + embd_pdrop=btlm_config.embd_pdrop, + attn_pdrop=btlm_config.attn_pdrop, + layer_norm_epsilon=btlm_config.layer_norm_epsilon, + initializer_range=btlm_config.initializer_range, + bos_token_id=btlm_config.bos_token_id, + eos_token_id=btlm_config.eos_token_id, + # These are new arguments not in the original GPT2Config + use_alibi=btlm_config.position_embedding_type == "alibi", + use_flash_attn=btlm_config.position_embedding_type == "alibi", # Alibi code path requires flash_attn + mup_width_scale=btlm_config.mup_width_scale, + mup_embeddings_multiplier=btlm_config.mup_embeddings_scale, + mup_output_multiplier=btlm_config.mup_output_alpha, + mup_scale_qk_dot_by_d=btlm_config.mup_scale_qk_dot_by_d, + mlp_multiple_of=1, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/falcon.py b/lib/python3.11/site-packages/flash_attn/models/falcon.py new file mode 100644 index 0000000000000000000000000000000000000000..4b02ec7727740eaa9ca70a7f0ca64df94fff4c3a --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/falcon.py @@ -0,0 +1,143 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from einops import rearrange +from transformers import FalconConfig, GPT2Config + + +def remap_state_dict_hf_falcon(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^transformer.h.", "transformer.layers.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + # Word embedding + def key_mapping_emb(key): + return re.sub( + r"^transformer.word_embeddings.", "transformer.embeddings.word_embeddings.", key + ) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + output_embeddings_bias = state_dict.pop("lm_head.bias") + state_dict["lm_head.bias"] = F.pad( + output_embeddings_bias, (0, vocab_size - output_embeddings_bias.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.", r"transformer.layers.\1.norm1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + key = re.sub(r"^transformer.layers.(\d+).ln_attn.", r"transformer.layers.\1.norm1.", key) + key = re.sub(r"^transformer.layers.(\d+).ln_mlp.", r"transformer.layers.\1.norm2.", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_h_to_4h.", r"transformer.layers.\1.mlp.fc1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_4h_to_h.", r"transformer.layers.\1.mlp.fc2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).self_attention.query_key_value.", + r"transformer.layers.\1.mixer.Wqkv.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attention.dense.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", 1) + headdim = config.hidden_size // n_head + for l in range(config.n_layer): + # The weights are stored in a different layout compared to our implementation + Wqkv = rearrange( + state_dict.pop(f"transformer.layers.{l}.mixer.Wqkv.weight"), + "(group ratio headdim) ... -> group ratio headdim ...", + ratio=n_head // n_head_kv + 2, + headdim=headdim, + ) + Wq = rearrange(Wqkv[:, :-2], "group ratio headdim ... -> (group ratio headdim) ...") + Wk = rearrange(Wqkv[:, [-2]], "group ratio headdim ... -> (group ratio headdim) ...") + Wv = rearrange(Wqkv[:, [-1]], "group ratio headdim ... -> (group ratio headdim) ...") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + + return state_dict + + +def falcon_config_to_gpt2_config(falcon_config: FalconConfig) -> GPT2Config: + # The 40b config uses "n_head_kv" instead of "num_kv_heads" + n_head_kv = getattr( + falcon_config, + "n_head_kv", + 1 if getattr(falcon_config, "multi_query", False) else falcon_config.n_head, + ) + # HACK: the 40b config has 2 LN per layer instead of 1, but that's not reflected in the config. + # So we have to infer it from the number of heads in the key/value block + parallel_block_tied_norm = n_head_kv == 1 + return GPT2Config( + vocab_size=falcon_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=falcon_config.hidden_size, + n_layer=falcon_config.n_layer, + n_head=falcon_config.n_head, + n_inner=falcon_config.hidden_size * 4, + activation_function="gelu", + resid_pdrop=falcon_config.hidden_dropout, + embd_pdrop=0.0, # There doesn't seem to be any embedding dropout + attn_pdrop=falcon_config.attention_dropout, + layer_norm_epsilon=falcon_config.layer_norm_epsilon, + initializer_range=falcon_config.initializer_range, + bos_token_id=falcon_config.bos_token_id, + eos_token_id=falcon_config.eos_token_id, + # These are new arguments not in the original GPT2Config + parallel_block=falcon_config.parallel_attn, + n_head_kv=n_head_kv, + parallel_block_tied_norm=parallel_block_tied_norm, + rotary_emb_fraction=1.0, + rotary_emb_interleaved=False, + tie_word_embeddings=True, + qkv_proj_bias=falcon_config.bias, + out_proj_bias=falcon_config.bias, + mlp_fc1_bias=falcon_config.bias, + mlp_fc2_bias=falcon_config.bias, + lm_head_bias=False, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/gpt.py b/lib/python3.11/site-packages/flash_attn/models/gpt.py new file mode 100644 index 0000000000000000000000000000000000000000..3539f8f901695b29454358972d65031f4c4fabeb --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/gpt.py @@ -0,0 +1,1080 @@ +# Copyright (c) 2024, Tri Dao. + +import logging +import math +import re +from collections import OrderedDict, namedtuple +from collections.abc import Sequence +from functools import partial +from typing import Dict, List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers import GPT2Config + +from flash_attn.models.bigcode import remap_state_dict_hf_bigcode +from flash_attn.models.falcon import remap_state_dict_hf_falcon +from flash_attn.models.gpt_neox import remap_state_dict_hf_gpt_neox +from flash_attn.models.gptj import remap_state_dict_hf_gptj +from flash_attn.models.llama import remap_state_dict_hf_llama +from flash_attn.models.opt import remap_state_dict_hf_opt +from flash_attn.modules.block import Block, ParallelBlock +from flash_attn.modules.embedding import GPT2Embeddings, ParallelGPT2Embeddings +from flash_attn.modules.mha import MHA, ParallelMHA +from flash_attn.modules.mlp import ( + FusedMLP, + GatedMlp, + Mlp, + ParallelFusedMLP, + ParallelGatedMlp, + ParallelMLP, +) +from flash_attn.ops.activations import sqrelu_fwd +from flash_attn.utils.distributed import ( + all_gather, + all_gather_raw, + get_dim_for_local_rank, + sync_shared_params, +) +from flash_attn.utils.generation import GenerationMixin +from flash_attn.utils.pretrained import state_dict_from_pretrained + +try: + from flash_attn.ops.fused_dense import ColumnParallelLinear +except ImportError: + ColumnParallelLinear = None + +try: + from flash_attn.ops.triton.mlp import FusedDenseSqreluDense +except ImportError: + FusedDenseSqreluDense = None + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn, RMSNorm +except ImportError: + layer_norm_fn, RMSNorm = None, None + +logger = logging.getLogger(__name__) + + +def create_mixer_cls(config, layer_idx=None, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) + attn_scale_power = 0.5 if not getattr(config, "mup_scale_qk_dot_by_d", False) else 1.0 + softmax_scale = 1.0 if not config.scale_attn_weights else (head_dim ** (-attn_scale_power)) + softmax_scale *= getattr(config, "mup_attn_multiplier", 1.0) + if config.scale_attn_by_inverse_layer_idx: + assert layer_idx is not None + softmax_scale /= float(layer_idx + 1) + dwconv = getattr(config, "attn_dwconv", False) + if dwconv: + assert process_group is None, "TensorParallel MHA does not support dwconv yet" + qkv_proj_bias = getattr(config, "qkv_proj_bias", True) + out_proj_bias = getattr(config, "out_proj_bias", True) + rotary_emb_dim = int(getattr(config, "rotary_emb_fraction", 0.0) * head_dim) + rotary_emb_base = getattr(config, "rotary_emb_base", 10000.0) + rotary_emb_scale_base = getattr(config, "rotary_emb_scale_base", None) + rotary_emb_interleaved = getattr(config, "rotary_emb_interleaved", False) + use_alibi = getattr(config, "use_alibi", False) + window_size = getattr(config, "window_size", (-1, -1)) + use_flash_attn = getattr(config, "use_flash_attn", False) + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if not fused_bias_fc: + assert process_group is None, "TensorParallel MHA requires fused_bias_fc" + mha_cls = MHA if process_group is None else ParallelMHA + serial_kwargs = ( + {"fused_bias_fc": fused_bias_fc, "dwconv": dwconv} if process_group is None else {} + ) + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + num_heads_kv = getattr(config, "n_head_kv", None) + mixer_cls = partial( + mha_cls, + num_heads=config.num_attention_heads, + num_heads_kv=num_heads_kv, + qkv_proj_bias=qkv_proj_bias, + out_proj_bias=out_proj_bias, + dropout=config.attn_pdrop, + softmax_scale=softmax_scale, + causal=True, + layer_idx=layer_idx, + rotary_emb_dim=rotary_emb_dim, + rotary_emb_base=rotary_emb_base, + rotary_emb_scale_base=rotary_emb_scale_base, + rotary_emb_interleaved=rotary_emb_interleaved, + use_alibi=use_alibi, + window_size=window_size, + use_flash_attn=use_flash_attn, + **serial_kwargs, + **parallel_kwargs, + **factory_kwargs, + ) + return mixer_cls + + +def create_mlp_cls(config, layer_idx=None, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + mlp_fc1_bias = getattr(config, "mlp_fc1_bias", True) + mlp_fc2_bias = getattr(config, "mlp_fc2_bias", True) + fused_mlp = getattr(config, "fused_mlp", False) + if fused_mlp: + assert config.activation_function in [ + "gelu_new", + "gelu_fast", + "gelu_approx", + "gelu_pytorch_tanh", + "relu", + "sqrelu", + ] + fused_dense_sqrelu_dense = getattr(config, "fused_dense_sqrelu_dense", False) + if fused_dense_sqrelu_dense: + assert config.activation_function == "sqrelu", ( + "fused_dense_sqrelu_dense only " "supports approximate activation_function sqrelu" + ) + assert not (fused_dense_sqrelu_dense and fused_mlp) + if not fused_mlp and not fused_dense_sqrelu_dense: + assert config.activation_function in [ + "gelu", + "gelu_new", + "gelu_fast", + "gelu_approx", + "gelu_pytorch_tanh", + "relu", + "sqrelu", + "glu", + "swiglu", + "geglu", + ] + if config.activation_function in ["glu", "swiglu", "geglu"]: + activation = ( + F.sigmoid + if config.activation_function == "glu" + else (F.silu if config.activation_function == "swiglu" else F.gelu) + ) + mlp_cls = GatedMlp if process_group is None else ParallelGatedMlp + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + mlp_multiple_of = getattr(config, "mlp_multiple_of", 128) + mlp_cls = partial( + mlp_cls, + hidden_features=config.n_inner, + activation=activation, + bias1=mlp_fc1_bias, + bias2=mlp_fc2_bias, + multiple_of=mlp_multiple_of, + **parallel_kwargs, + **factory_kwargs, + ) + else: + if config.activation_function == "relu": + activation = partial(F.relu, inplace=True) + elif config.activation_function == "sqrelu": + activation = sqrelu_fwd + else: + approximate = ( + "tanh" + if config.activation_function + in ["gelu_new", "gelu_fast", "gelu_approx", "gelu_pytorch_tanh"] + else "none" + ) + activation = partial(F.gelu, approximate=approximate) + mlp_cls = Mlp if process_group is None else ParallelMLP + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + mlp_cls = partial( + mlp_cls, + hidden_features=config.n_inner, + activation=activation, + bias1=mlp_fc1_bias, + bias2=mlp_fc2_bias, + **parallel_kwargs, + **factory_kwargs, + ) + else: + mlp_checkpoint_lvl = getattr(config, "mlp_checkpoint_lvl", 0) + # mlp_checkpoint_lvl could be a list, which contains the checkpoint_lvl for each layer + if isinstance(mlp_checkpoint_lvl, Sequence): + assert layer_idx is not None + mlp_checkpoint_lvl = mlp_checkpoint_lvl[layer_idx] + if fused_mlp: + if FusedMLP is None: + raise ImportError("fused_dense is not installed") + activation = ( + "gelu_approx" + if config.activation_function + in ["gelu_new", "gelu_fast", "gelu_approx", "gelu_pytorch_tanh"] + else config.activation_function + ) + mlp_cls = FusedMLP if process_group is None else ParallelFusedMLP + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + mlp_cls = partial( + mlp_cls, + hidden_features=config.n_inner, + activation=activation, + checkpoint_lvl=mlp_checkpoint_lvl, + bias1=mlp_fc1_bias, + bias2=mlp_fc2_bias, + **parallel_kwargs, + **factory_kwargs, + ) + elif fused_dense_sqrelu_dense: + if process_group is not None: + assert fused_mlp, "Tensor Parallel is not implemented for FusedDenseSqreluDense" + assert FusedDenseSqreluDense is not None + mlp_cls = partial( + FusedDenseSqreluDense, + hidden_features=config.n_inner, + checkpoint_lvl=mlp_checkpoint_lvl, + **factory_kwargs, + ) + else: + raise RuntimeError("MLP type not supported") + return mlp_cls + + +def create_block(config, layer_idx=None, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + sequence_parallel = getattr(config, "sequence_parallel", True) + mixer_cls = create_mixer_cls(config, layer_idx, process_group=process_group, **factory_kwargs) + mlp_cls = create_mlp_cls(config, layer_idx, process_group=process_group, **factory_kwargs) + use_rms_norm = getattr(config, "rms_norm", False) + norm_cls = partial( + nn.LayerNorm if not use_rms_norm else RMSNorm, + eps=config.layer_norm_epsilon, + **factory_kwargs, + ) + # TD [2022-07-30]: Force residual in fp32, seems to make fp16 training more stable + residual_in_fp32 = getattr(config, "residual_in_fp32", False) + resid_dropout1 = config.resid_pdrop if layer_idx is None or layer_idx > 0 else config.embd_pdrop + prenorm = getattr(config, "prenorm", True) + parallel_block = getattr(config, "parallel_block", False) + if not parallel_block: + block = Block( + config.hidden_size, + mixer_cls, + mlp_cls, + norm_cls=norm_cls, + prenorm=prenorm, + resid_dropout1=resid_dropout1, + resid_dropout2=config.resid_pdrop, + fused_dropout_add_ln=getattr(config, "fused_dropout_add_ln", False), + residual_in_fp32=residual_in_fp32, + sequence_parallel=sequence_parallel and process_group is not None, + mark_shared_params=process_group is not None, + ) + else: + assert prenorm + block = ParallelBlock( + config.hidden_size, + mixer_cls, + mlp_cls, + norm_cls=norm_cls, + resid_dropout1=resid_dropout1, + resid_dropout2=config.resid_pdrop, + tied_norm=getattr(config, "parallel_block_tied_norm", False), + fused_dropout_add_ln=getattr(config, "fused_dropout_add_ln", False), + residual_in_fp32=residual_in_fp32, + sequence_parallel=sequence_parallel and process_group is not None, + mark_shared_params=process_group is not None, + ) + block.layer_idx = layer_idx + return block + + +class GPTPreTrainedModel(nn.Module): + """An abstract class to handle weights initialization and + a simple interface for dowloading and loading pretrained models. + """ + + def __init__(self, config, *inputs, **kwargs): + super().__init__() + if not isinstance(config, GPT2Config): + raise ValueError( + "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. " + "To create a model from a Google pretrained model use " + "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( + self.__class__.__name__, self.__class__.__name__ + ) + ) + self.config = config + + @classmethod + def from_pretrained( + cls, + model_name, + config, + *args, + strict=True, + device=None, + dtype=None, + world_size=1, + rank=0, + **kwargs, + ): + """ + Instantiate a GPTPreTrainedModel from a pre-trained model file or a pytorch state dict. + Download and cache the pre-trained model file if needed. + """ + # Instantiate model. + model = cls(config, *args, device=device, dtype=dtype, **kwargs) + # Load state_dict in cpu because we already initialized the model in GPU, and we don't + # want extra stuff taking up more GPU memory + state_dict = state_dict_from_pretrained(model_name, device="cpu", dtype=dtype) + if model_name.startswith("gpt2"): + state_dict = remap_state_dict_hf_gpt2(state_dict, config) + elif model_name.startswith("facebook/opt"): + state_dict = remap_state_dict_hf_opt(state_dict, config) + elif model_name.startswith("EleutherAI/gpt-j-") or model_name.startswith( + "togethercomputer/GPT-JT-" + ): + state_dict = remap_state_dict_hf_gptj(state_dict, config) + elif ( + model_name.startswith("EleutherAI/gpt-neox-") + or model_name.startswith("EleutherAI/pythia-") + or model_name.startswith("togethercomputer/RedPajama-INCITE-") + ): + state_dict = remap_state_dict_hf_gpt_neox(state_dict, config) + elif model_name.startswith("tiiuae/falcon-"): + state_dict = remap_state_dict_hf_falcon(state_dict, config) + elif model_name.startswith("meta-llama/Llama-"): + state_dict = remap_state_dict_hf_llama(state_dict, config) + elif model_name.startswith("bigcode/") or model_name.startswith("WizardLM/"): + state_dict = remap_state_dict_hf_bigcode(state_dict, config) + else: + raise NotImplementedError(f"Model {model_name} not supported") + if world_size > 1: + state_dict = shard_state_dict_tp(state_dict, config, world_size, rank) + load_return = model.load_state_dict(state_dict, strict=strict) + logger.info(load_return) + return model + + +# https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454 +def _init_weights( + module, n_layer, initializer_range=0.02, mup_width_scale=1.0, rescale_prenorm_residual=True +): + mup_init_scale = math.sqrt(mup_width_scale) + if isinstance(module, nn.Linear): + nn.init.normal_(module.weight, std=initializer_range * mup_init_scale) + optim_cfg = getattr(module.weight, "_optim", {}) + optim_cfg.update({"lr_multiplier": mup_width_scale}) + setattr(module.weight, "_optim", optim_cfg) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, std=initializer_range) + + if rescale_prenorm_residual: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + for name, p in module.named_parameters(): + if name in ["out_proj.weight", "fc2.weight"]: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + nn.init.normal_( + p, mean=0.0, std=initializer_range * mup_init_scale / math.sqrt(2 * n_layer) + ) + + +class GPTModel(GPTPreTrainedModel): + def __init__(self, config: GPT2Config, process_group=None, device=None, dtype=None): + super().__init__(config) + factory_kwargs = {"device": device, "dtype": dtype} + self.process_group = process_group + self.sequence_parallel = getattr(config, "sequence_parallel", True) + assert config.activation_function in [ + "gelu", + "gelu_new", + "gelu_fast", + "gelu_approx", + "gelu_pytorch_tanh", + "relu", + "sqrelu", + "glu", + "swiglu", + "geglu", + ] + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + self.embeddings_multiplier = getattr(config, "mup_embeddings_multiplier", 1.0) + # TD [2022-07-30]: Force residual in fp32, seems to make fp16 training more stable + self.residual_in_fp32 = getattr(config, "residual_in_fp32", False) + # These 2 options are for OPT-350m + self.prenorm = getattr(config, "prenorm", True) + use_rms_norm = getattr(config, "rms_norm", False) + word_embed_proj_dim = getattr(config, "word_embed_proj_dim", None) + # For GPT-J, GPT-NeoX + self.parallel_block = getattr(config, "parallel_block", False) + + if process_group is None: + self.embeddings = GPT2Embeddings( + config.hidden_size, + vocab_size, + config.max_position_embeddings, + word_embed_proj_dim=word_embed_proj_dim, + **factory_kwargs, + ) + else: + self.embeddings = ParallelGPT2Embeddings( + config.hidden_size, + vocab_size, + config.max_position_embeddings, + process_group=process_group, + sequence_parallel=self.sequence_parallel, + **factory_kwargs, + ) + + # We change the order of dropout, residual and layer norm: + # Instead of LN -> Attn / MLP -> Dropout -> Add, we do: + # Dropout -> Add -> LN -> Attn / MLP, returning both the residual branch (output of Add) and + # the main branch (output of MLP). The model definition is unchanged, but the mapping of the + # nn.Dropout probabilities are changed. + # This is for performance reason: we can fuse dropout + add + layer_norm. + self.layers = nn.ModuleList( + [ + create_block(config, layer_idx=i, process_group=process_group, **factory_kwargs) + for i in range(config.num_hidden_layers) + ] + ) + rotary_emb_fraction = getattr(config, "rotary_emb_fraction", 0.0) + if rotary_emb_fraction > 0.0: # Tie all the RotaryEmbedding modules to share the same cos/sin cache + for layer in self.layers[1:]: + layer.mixer.rotary_emb = self.layers[0].mixer.rotary_emb + + self.fused_dropout_add_ln = getattr(config, "fused_dropout_add_ln", False) + if self.fused_dropout_add_ln: + if layer_norm_fn is None: + raise ImportError("Triton is not installed") + if self.prenorm: + self.drop_f = nn.Dropout(config.resid_pdrop) + norm_cls = nn.LayerNorm if not use_rms_norm else RMSNorm + self.ln_f = norm_cls( + config.hidden_size, eps=config.layer_norm_epsilon, **factory_kwargs + ) + if process_group is not None: + for p in self.ln_f.parameters(): + # Mark the norm parameters as "shared_params" so that we sync their values at init. + p._shared_params = True + # Mark the norm params as "sequence_parallel" so we run all-reduce on their grads. + if self.sequence_parallel: + p._sequence_parallel = True + + self.apply( + partial( + _init_weights, + n_layer=config.num_hidden_layers, + initializer_range=config.initializer_range, + mup_width_scale=getattr(config, "mup_width_scale", 1.0), + ) + ) + self.tie_weights() + + def tie_weights(self): + if self.process_group is not None: + sync_shared_params(self, self.process_group) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return { + i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + for i, layer in enumerate(self.layers) + } + + def forward(self, input_ids, position_ids=None, inference_params=None): + # If using Tensor Parallel with sequence parallel, we combine the batch and the seqlen + # dimensions so that we can split on it easily, in case of small batch size. + # Only the attention layers need to know the seqlen. + embedding_kwargs = ( + {"combine_batch_seqlen_dim": True} + if self.process_group is not None and self.sequence_parallel + else {} + ) + hidden_states = self.embeddings(input_ids, position_ids=position_ids, **embedding_kwargs) + if self.embeddings_multiplier != 1.0: + hidden_states = hidden_states * self.embeddings_multiplier + if self.parallel_block: + hidden_states2 = None + residual = None + mixer_kwargs = ( + {"seqlen": input_ids.shape[1]} + if self.process_group is not None and self.sequence_parallel + else {} + ) + if inference_params is not None: + mixer_kwargs["inference_params"] = inference_params + for layer in self.layers: + if self.prenorm: + if not self.parallel_block: + hidden_states, residual = layer( + hidden_states, residual, mixer_kwargs=mixer_kwargs + ) + else: + hidden_states, hidden_states2, residual = layer( + hidden_states, hidden_states2, residual, mixer_kwargs=mixer_kwargs + ) + else: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + if self.prenorm: + if not self.fused_dropout_add_ln: + dropped = self.drop_f(hidden_states) + if not self.parallel_block: + residual = (dropped + residual) if residual is not None else dropped + else: + dropped2 = self.drop_f(hidden_states2) + residual = ( + (residual + dropped + dropped2) + if residual is not None + else dropped + dropped2 + ) + hidden_states = self.ln_f(residual.to(dtype=self.ln_f.weight.dtype)) + else: + # Set prenorm=False here since we don't need the residual + hidden_states = layer_norm_fn( + hidden_states, + self.ln_f.weight, + self.ln_f.bias, + residual=residual, + x1=None if not self.parallel_block else hidden_states2, + eps=self.ln_f.eps, + dropout_p=self.drop_f.p if self.training else 0.0, + prenorm=False, + is_rms_norm=isinstance(self.ln_f, RMSNorm) + ) + return hidden_states + + +class GPTLMHeadModel(GPTPreTrainedModel, GenerationMixin): + def __init__(self, config: GPT2Config, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__(config) + self.process_group = process_group + self.transformer = GPTModel(config, process_group=process_group, **factory_kwargs) + self.tie_word_embeddings = getattr(config, "tie_word_embeddings", True) + lm_head_bias = getattr(config, "lm_head_bias", False) + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + # This option is for OPT-350m + word_embed_proj_dim = getattr(config, "word_embed_proj_dim", None) + embed_dim = config.n_embd if word_embed_proj_dim is None else word_embed_proj_dim + if word_embed_proj_dim is not None: + self.project_out = nn.Linear(config.n_embd, embed_dim, bias=False, **factory_kwargs) + else: + self.project_out = None + mup_width_scale = getattr(config, "mup_width_scale", 1.0) + mup_output_multiplier = getattr(config, "mup_output_multiplier", 1.0) + self.output_scale = mup_output_multiplier * mup_width_scale + if process_group is None: + self.lm_head = nn.Linear(embed_dim, vocab_size, bias=lm_head_bias, **factory_kwargs) + else: + if ColumnParallelLinear is None: + raise ImportError("fused_dense_lib is not installed") + self.lm_head = ColumnParallelLinear( + embed_dim, + vocab_size, + process_group, + bias=lm_head_bias, + sequence_parallel=getattr(config, "sequence_parallel", True), + **factory_kwargs, + ) + self.norm_head = getattr(config, "norm_head", False) + # Initialize weights and apply final processing + self.apply( + partial( + _init_weights, + n_layer=config.num_hidden_layers, + initializer_range=config.initializer_range, + mup_width_scale=mup_width_scale, + ) + ) + self.tie_weights() + + def tie_weights(self): + if self.tie_word_embeddings: + self.lm_head.weight = self.transformer.embeddings.word_embeddings.weight + if self.process_group is not None: + sync_shared_params(self, self.process_group) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.transformer.allocate_inference_cache( + batch_size, max_seqlen, dtype=dtype, **kwargs + ) + + def forward(self, input_ids, position_ids=None, inference_params=None, num_last_tokens=0): + """ + input_ids: (batch, seqlen) int tensor + inference_params: for generation. Adapted from Megatron-LM (and Apex) + https://github.com/NVIDIA/apex/blob/3ff1a10f72ec07067c4e44759442329804ac5162/apex/transformer/testing/standalone_transformer_lm.py#L470 + num_last_tokens: if > 0, only return the logits for the last n tokens + """ + assert ( + input_ids.ndim == 2 + ), f"Expected `input_ids` to have shape [b, slen], but got shape {input_ids.shape}" + b, slen = input_ids.shape + hidden_states = self.transformer( + input_ids, position_ids=position_ids, inference_params=inference_params + ) + if inference_params is not None: + assert hidden_states.ndim == 3, "sequence_parallel is not supported in generation mode" + if num_last_tokens > 0: + hidden_states = hidden_states[:, -num_last_tokens:] + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + if self.output_scale != 1.0: + hidden_states = hidden_states * self.output_scale + if not self.norm_head: + lm_logits = self.lm_head(hidden_states) + else: + lm_head_weight = F.normalize(self.lm_head.weight) + if isinstance(self.lm_head, ColumnParallelLinear) and self.lm_head.sequence_parallel: + hidden_states = all_gather(hidden_states, self.lm_head.process_group) + lm_logits = F.linear(hidden_states, lm_head_weight, bias=self.lm_head.bias) + # During inference, we want the full logit for sampling + if isinstance(self.lm_head, ColumnParallelLinear) and inference_params is not None: + lm_logits, _ = all_gather_raw(lm_logits, self.lm_head.process_group) + lm_logits = rearrange(lm_logits, "(n b) ... d -> b ... (n d)", b=b) + CausalLMOutput = namedtuple("CausalLMOutput", ["logits"]) + return CausalLMOutput(logits=lm_logits) + + def load_state_dict(self, state_dict, strict=True): + # Remapping from our checkpoints that used a different ordering of layers in the block + # Previous: Attn / MLP -> Dropout -> Add -> LN + # Current: Dropout -> Add -> LN -> Attn / MLP + if "transformer.ln_0.weight" in state_dict: + n_layers = len(self.transformer.layers) + ln_weight = state_dict.pop(f"transformer.layers.{n_layers - 1}.norm2.weight") + ln_bias = state_dict.pop(f"transformer.layers.{n_layers - 1}.norm2.bias") + state_dict["transformer.ln_f.weight"] = ln_weight + state_dict["transformer.ln_f.bias"] = ln_bias + for l in reversed(range(n_layers)): + ln_weight = state_dict.pop(f"transformer.layers.{l}.norm1.weight") + ln_bias = state_dict.pop(f"transformer.layers.{l}.norm1.bias") + state_dict[f"transformer.layers.{l}.norm2.weight"] = ln_weight + state_dict[f"transformer.layers.{l}.norm2.bias"] = ln_bias + if l > 0: + ln_weight = state_dict.pop(f"transformer.layers.{l - 1}.norm2.weight") + ln_bias = state_dict.pop(f"transformer.layers.{l - 1}.norm2.bias") + state_dict[f"transformer.layers.{l}.norm1.weight"] = ln_weight + state_dict[f"transformer.layers.{l}.norm1.bias"] = ln_bias + ln_weight = state_dict.pop("transformer.ln_0.weight") + ln_bias = state_dict.pop("transformer.ln_0.bias") + state_dict[f"transformer.layers.0.norm1.weight"] = ln_weight + state_dict[f"transformer.layers.0.norm1.bias"] = ln_bias + return super().load_state_dict(state_dict, strict=strict) + + +def shard_state_dict_tp(state_dict, config, world_size, rank): + """Convert the state_dict of a standard GPT model to the state_dict of a GPT model + with tensor parallel. + + This function modifies state_dict in place. + """ + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + assert vocab_size % world_size == 0 + assert config.hidden_size % world_size == 0 + inner_dim = config.n_inner if config.n_inner is not None else 4 * config.hidden_size + assert inner_dim % world_size == 0 + + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", n_head) + + embed_dim = config.hidden_size + head_dim = embed_dim // n_head + + def shard_first_dim(state_dict, key): + if key in state_dict: + x = state_dict[key] + dim = x.shape[0] // world_size + state_dict[key] = x[rank * dim : (rank + 1) * dim] + + def shard_last_dim(state_dict, key, multiple_of=1): + if key in state_dict: + x = state_dict[key] + dim_each_rank = [ + get_dim_for_local_rank(x.size(-1), world_size, local_rank, multiple_of) + for local_rank in range(world_size) + ] + beg, end = tuple(sum(dim_each_rank[:pos]) for pos in (rank, rank + 1)) + state_dict[key] = x[..., beg:end] + + def shard_gatedmlp_fc1_dim(state_dict, key): + if key in state_dict: + x = state_dict[key] + dim = x.shape[0] // world_size // 2 + state_dict[key] = rearrange( + rearrange(x, "(two o) ... -> two o ...", two=2)[:, rank * dim : (rank + 1) * dim], + "two o ... -> (two o) ...", + ) + + def shard_qkv_headdim(state_dict, key): + if key in state_dict: + n_head_each_rank = [ + get_dim_for_local_rank(n_head, world_size, local_rank) + for local_rank in range(world_size) + ] + n_head_kv_each_rank = [ + get_dim_for_local_rank(n_head_kv, world_size, local_rank) + for local_rank in range(world_size) + ] + + beg_n_head = sum(n_head_each_rank[:rank]) + end_n_head = sum(n_head_each_rank[: rank + 1]) + + beg_n_head_kv = sum(n_head_kv_each_rank[:rank]) + end_n_head_kv = sum(n_head_kv_each_rank[: rank + 1]) + + if n_head_kv == n_head: + x = rearrange(state_dict[key], "(three d) ... -> three d ...", three=3) + state_dict[key] = rearrange( + x[:, beg_n_head * head_dim : end_n_head * head_dim], + "three d ... -> (three d) ...", + ) + else: + x = rearrange( + state_dict[key], + "(nheadqkv headdim) ... -> nheadqkv headdim ...", + nheadqkv=n_head + 2 * n_head_kv, + ) + state_dict[key] = rearrange( + torch.cat( + [ + x[beg_n_head:end_n_head], + x[n_head + beg_n_head_kv : n_head + end_n_head_kv], + x[ + n_head + + n_head_kv + + beg_n_head_kv : n_head + + n_head_kv + + end_n_head_kv + ], + ], + dim=0, + ), + "nheadqkv headdim ... -> (nheadqkv headdim) ...", + ) + + shard_first_dim(state_dict, "transformer.embeddings.word_embeddings.weight") + if "lm_head.weight" in state_dict: + shard_first_dim(state_dict, "lm_head.weight") + if "transformer.embeddings.position_embeddings.weight" in state_dict: + shard_last_dim(state_dict, "transformer.embeddings.position_embeddings.weight") + for i in range(config.num_hidden_layers): + shard_qkv_headdim(state_dict, f"transformer.layers.{i}.mixer.Wqkv.weight") + shard_qkv_headdim(state_dict, f"transformer.layers.{i}.mixer.Wqkv.bias") + shard_last_dim( + state_dict, f"transformer.layers.{i}.mixer.out_proj.weight", multiple_of=head_dim + ) + if rank != 0: + state_dict.pop(f"transformer.layers.{i}.mixer.out_proj.bias", None) + if config.activation_function in ["glu", "swiglu", "geglu"]: + shard_gatedmlp_fc1_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.weight") + shard_gatedmlp_fc1_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.bias") + else: + shard_first_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.weight") + shard_first_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.bias") + shard_last_dim(state_dict, f"transformer.layers.{i}.mlp.fc2.weight") + if rank != 0: + state_dict.pop(f"transformer.layers.{i}.mlp.fc2.bias", None) + return state_dict + + +def combine_state_dicts_tp(state_dicts: List[Dict[str, torch.Tensor]], config: GPT2Config): + """Convert the list of sharded state_dict of a GPT model with tensor parallel to + the state_dict of a standard GPT model. + + This function is meant to be the "reverse" of shard_state_dict_tp. + + Precondition: + - state_dicts should be ordered in the same way as the shards were created. + """ + world_size = len(state_dicts) + keys = state_dicts[0].keys() + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + assert vocab_size % world_size == 0 + assert config.hidden_size % world_size == 0 + inner_dim = config.n_inner if config.n_inner is not None else 4 * config.hidden_size + assert inner_dim % world_size == 0 + assert config.hidden_size % config.n_head == 0 + headdim = config.hidden_size // config.n_head + + # Sometimes the word embeddings are sharded on the 0th dim, sometimes on the 1st dim. + # vocab_size // world_size coordinates are nonzero. + def combine_word_embeddings(state_dicts, state_dict, key): + dim = 0 if state_dicts[0][key].shape[0] == vocab_size // world_size else 1 + state_dict[key] = torch.cat([s[key] for s in state_dicts], dim=dim) + + def combine_dim(state_dicts, state_dict, key, dim=-1): + if key in state_dict: + state_dict[key] = torch.cat([s[key] for s in state_dicts], dim=dim) + + def combine_qkv_headdim(state_dicts, state_dict, key): + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", n_head) + if key in state_dict: + if n_head_kv == n_head: + xs = [ + rearrange(s[key], "(three d) ... -> three d ...", three=3) for s in state_dicts + ] + state_dict[key] = rearrange(torch.cat(xs, dim=1), "three d ... -> (three d) ...") + else: + n_head_each_rank = [ + get_dim_for_local_rank(n_head, world_size, local_rank) + for local_rank in range(world_size) + ] + n_head_kv_each_rank = [ + get_dim_for_local_rank(n_head_kv, world_size, local_rank) + for local_rank in range(world_size) + ] + xs = [ + rearrange( + s[key], + "(nheadqkv headdim) ... -> nheadqkv headdim ...", + nheadqkv=rank_n_head + 2 * rank_n_head_kv, + headdim=headdim, + ) + for s, rank_n_head, rank_n_head_kv in zip( + state_dicts, n_head_each_rank, n_head_kv_each_rank + ) + ] + wq = torch.cat([x[: n_head_each_rank[rank]] for rank, x in enumerate(xs)], dim=0) + wk = torch.cat( + [ + x[ + n_head_each_rank[rank] : n_head_each_rank[rank] + + n_head_kv_each_rank[rank] + ] + for rank, x in enumerate(xs) + ], + dim=0, + ) + wv = torch.cat( + [ + x[n_head_each_rank[rank] + n_head_kv_each_rank[rank] :] + for rank, x in enumerate(xs) + ], + dim=0, + ) + wqkv = torch.cat( + [wq, wk, wv], + dim=0, + ) + state_dict[key] = rearrange( + wqkv, + "nheadqkv headdim ... -> (nheadqkv headdim) ...", + ) + + def combine_gated_mlp(state_dicts, state_dict, key): + if key in state_dict: + xs = [rearrange(s[key], "(two d) ... -> two d ...", two=2) for s in state_dicts] + state_dict[key] = rearrange(torch.cat(xs, dim=1), "two d ... -> (two d) ...") + + state_dict = state_dicts[0].copy() # don't modify state_dict[0] inplace + combine_word_embeddings( + state_dicts, state_dict, "transformer.embeddings.word_embeddings.weight" + ) + if "lm_head.weight" in state_dict: + combine_word_embeddings(state_dicts, state_dict, "lm_head.weight") + if "transformer.embeddings.position_embeddings.weight" in state_dict: + combine_dim( + state_dicts, state_dict, "transformer.embeddings.position_embeddings.weight", -1 + ) + mlp_combine_fn = ( + combine_gated_mlp + if config.activation_function in ["glu", "swiglu", "geglu"] + else partial(combine_dim, dim=0) + ) + for i in range(config.num_hidden_layers): + combine_qkv_headdim(state_dicts, state_dict, f"transformer.layers.{i}.mixer.Wqkv.weight") + combine_qkv_headdim(state_dicts, state_dict, f"transformer.layers.{i}.mixer.Wqkv.bias") + combine_dim(state_dicts, state_dict, f"transformer.layers.{i}.mixer.out_proj.weight", -1) + mlp_combine_fn(state_dicts, state_dict, f"transformer.layers.{i}.mlp.fc1.weight") + combine_dim(state_dicts, state_dict, f"transformer.layers.{i}.mlp.fc1.bias", 0) + combine_dim(state_dicts, state_dict, f"transformer.layers.{i}.mlp.fc2.weight", -1) + return state_dict + + +def remap_state_dict_hf_gpt2(state_dict, config): + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^wpe.", "transformer.embeddings.position_embeddings.", key) + + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("wte.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub(r"^h.(\d+).ln_(1|2).(weight|bias)", r"transformer.layers.\1.norm\2.\3", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for d in range(config.num_hidden_layers): + W1 = state_dict.pop(f"h.{d}.mlp.c_fc.weight") + state_dict[f"transformer.layers.{d}.mlp.fc1.weight"] = W1.t() + W2 = state_dict.pop(f"h.{d}.mlp.c_proj.weight") + state_dict[f"transformer.layers.{d}.mlp.fc2.weight"] = W2.t() + + def key_mapping_mlp(key): + key = re.sub(r"^h.(\d+).mlp.c_fc.bias", r"transformer.layers.\1.mlp.fc1.bias", key) + key = re.sub(r"^h.(\d+).mlp.c_proj.bias", r"transformer.layers.\1.mlp.fc2.bias", key) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for d in range(config.num_hidden_layers): + state_dict.pop(f"h.{d}.attn.bias", None) # We don't store this bias + Wqkv = state_dict.pop(f"h.{d}.attn.c_attn.weight") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = Wqkv.t() + Wout = state_dict.pop(f"h.{d}.attn.c_proj.weight") + state_dict[f"transformer.layers.{d}.mixer.out_proj.weight"] = Wout.t() + + def key_mapping_attn(key): + key = re.sub(r"^h.(\d+).attn.c_attn.bias", r"transformer.layers.\1.mixer.Wqkv.bias", key) + key = re.sub( + r"^h.(\d+).attn.c_proj.bias", r"transformer.layers.\1.mixer.out_proj.bias", key + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def remap_state_dict_megatron(state_dict, config): + def key_mapping_transformer(key): + key = re.sub(r"^language_model.encoder.", "transformer.", key) + key = re.sub(r"^language_model.", "transformer.", key) + return key + + state_dict = OrderedDict((key_mapping_transformer(k), v) for k, v in state_dict.items()) + + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^wpe.", "transformer.embeddings.position_embeddings.", key) + + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embedding.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.final_layernorm.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.(weight|bias)", + r"transformer.layers.\1.norm1.\2", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.(weight|bias)", + r"transformer.layers.\1.norm2.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_h_to_4h.(weight|bias)", + r"transformer.layers.\1.mlp.fc1.\2", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_4h_to_h.(weight|bias)", + r"transformer.layers.\1.mlp.fc2.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).self_attention.rotary_emb.inv_freq", + r"transformer.layers.\1.mixer.rotary_emb.inv_freq", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attention.query_key_value.(weight|bias)", + r"transformer.layers.\1.mixer.Wqkv.\2", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attention.dense.(weight|bias)", + r"transformer.layers.\1.mixer.out_proj.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + # Megatron stores Wqkv as ((nheads 3 headdim), hidden_dim) + # while we store Wqkv as ((3 nheads headdim), hidden_dim) + headdim = config.hidden_size // config.num_attention_heads + for d in range(config.num_hidden_layers): + Wqkv = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.weight") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = rearrange( + Wqkv, + "(nheads three headdim) ... -> (three nheads headdim) ...", + three=3, + headdim=headdim, + ) + bqkv = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.bias") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.bias"] = rearrange( + bqkv, "(nheads three headdim) -> (three nheads headdim)", three=3, headdim=headdim + ) + + return state_dict diff --git a/lib/python3.11/site-packages/flash_attn/models/gpt_neox.py b/lib/python3.11/site-packages/flash_attn/models/gpt_neox.py new file mode 100644 index 0000000000000000000000000000000000000000..c3894044172260a25c9c561fbaac8add91db5b23 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/gpt_neox.py @@ -0,0 +1,124 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from einops import rearrange +from transformers import GPT2Config, GPTNeoXConfig + + +def remap_state_dict_hf_gpt_neox(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^gpt_neox.", "transformer.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + # Word embedding + def key_mapping_emb(key): + return re.sub(r"^transformer.embed_in.", "transformer.embeddings.word_embeddings.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings", False): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("embed_out.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.final_layer_norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.", r"transformer.layers.\1.norm1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_h_to_4h.", r"transformer.layers.\1.mlp.fc1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_4h_to_h.", r"transformer.layers.\1.mlp.fc2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + # We don't store these biases + state_dict.pop(f"transformer.layers.{l}.attention.bias") + state_dict.pop(f"transformer.layers.{l}.attention.masked_bias") + # We don't store these + state_dict.pop(f"transformer.layers.{l}.attention.rotary_emb.inv_freq", None) + # GPT-NeoX stores Wqkv as ((nheads 3 headdim), hidden_dim) + # while we store Wqkv as ((3 nheads headdim), hidden_dim) + headdim = config.hidden_size // config.num_attention_heads + Wqkv = state_dict.pop(f"transformer.layers.{l}.attention.query_key_value.weight") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = rearrange( + Wqkv, + "(nheads three headdim) ... -> (three nheads headdim) ...", + three=3, + headdim=headdim, + ) + bqkv = state_dict.pop(f"transformer.layers.{l}.attention.query_key_value.bias") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.bias"] = rearrange( + bqkv, "(nheads three headdim) -> (three nheads headdim)", three=3, headdim=headdim + ) + + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).attention.dense.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def gpt_neox_config_to_gpt2_config(gpt_neox_config: GPTNeoXConfig) -> GPT2Config: + assert gpt_neox_config.rotary_emb_base == 10000 + return GPT2Config( + vocab_size=gpt_neox_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=gpt_neox_config.hidden_size, + n_layer=gpt_neox_config.num_hidden_layers, + n_head=gpt_neox_config.num_attention_heads, + n_inner=gpt_neox_config.intermediate_size, + activation_function=gpt_neox_config.hidden_act, + resid_pdrop=0.0, # No dropout + embd_pdrop=0.0, + attn_pdrop=0.0, + layer_norm_epsilon=gpt_neox_config.layer_norm_eps, + initializer_range=gpt_neox_config.initializer_range, + bos_token_id=gpt_neox_config.bos_token_id, + eos_token_id=gpt_neox_config.eos_token_id, + # These are new arguments not in the original GPT2Config + prenorm=True, + parallel_block=gpt_neox_config.use_parallel_residual, + parallel_block_tied_norm=False, + rotary_emb_fraction=gpt_neox_config.rotary_pct, + tie_word_embeddings=gpt_neox_config.tie_word_embeddings, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/gptj.py b/lib/python3.11/site-packages/flash_attn/models/gptj.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2330d79ce5b78a1229351956da20d88e356083 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/gptj.py @@ -0,0 +1,109 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPTJConfig + + +def remap_state_dict_hf_gptj(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^transformer.h.", "transformer.layers.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + # Word embedding + def key_mapping_emb(key): + return re.sub(r"^transformer.wte.", "transformer.embeddings.word_embeddings.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + output_embeddings_bias = state_dict.pop("lm_head.bias") + state_dict["lm_head.bias"] = F.pad( + output_embeddings_bias, (0, vocab_size - output_embeddings_bias.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + return re.sub(r"^transformer.layers.(\d+).ln_1.", r"transformer.layers.\1.norm1.", key) + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc_in.", r"transformer.layers.\1.mlp.fc1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc_out.", r"transformer.layers.\1.mlp.fc2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"transformer.layers.{l}.attn.q_proj.weight") + Wk = state_dict.pop(f"transformer.layers.{l}.attn.k_proj.weight") + Wv = state_dict.pop(f"transformer.layers.{l}.attn.v_proj.weight") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + # We don't store these biases + state_dict.pop(f"transformer.layers.{l}.attn.bias") + state_dict.pop(f"transformer.layers.{l}.attn.masked_bias") + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).attn.out_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def gptj_config_to_gpt2_config(gptj_config: GPTJConfig) -> GPT2Config: + headdim = gptj_config.n_embd // gptj_config.n_head + return GPT2Config( + vocab_size=gptj_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=gptj_config.n_embd, + n_layer=gptj_config.n_layer, + n_head=gptj_config.n_head, + n_inner=gptj_config.n_inner, + activation_function=gptj_config.activation_function, + resid_pdrop=gptj_config.resid_pdrop, + embd_pdrop=gptj_config.embd_pdrop, + attn_pdrop=gptj_config.attn_pdrop, + layer_norm_epsilon=gptj_config.layer_norm_epsilon, + initializer_range=gptj_config.initializer_range, + bos_token_id=gptj_config.bos_token_id, + eos_token_id=gptj_config.eos_token_id, + # These are new arguments not in the original GPT2Config + prenorm=True, + parallel_block=True, + parallel_block_tied_norm=True, + rotary_emb_fraction=gptj_config.rotary_dim / headdim, + rotary_emb_interleaved=True, + tie_word_embeddings=False, + qkv_proj_bias=False, + out_proj_bias=False, + lm_head_bias=True, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/llama.py b/lib/python3.11/site-packages/flash_attn/models/llama.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb51d17e27c1eeb5f09293b773cda8f4d81233 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/llama.py @@ -0,0 +1,422 @@ +# Copyright (c) 2023, Tri Dao. + +import json +import math +import os +import re +from collections import OrderedDict +from pathlib import Path +from typing import Dict, List, Union + +import torch +import torch.nn.functional as F +from sentencepiece import SentencePieceProcessor +from transformers import GPT2Config, LlamaConfig + +from einops import rearrange + + +def remap_state_dict_meta_llama( + state_dict: Dict[str, torch.Tensor], config: GPT2Config +) -> Dict[str, torch.Tensor]: + """Convert the state_dict in Meta format to standard GPT format. + + This function modifies state_dict in place. + """ + + def key_mapping_layers(key): + return f"transformer.{key}" if not key.startswith("output.") else key + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + + # Word embedding + def key_mapping_emb(key): + return re.sub( + r"^transformer.tok_embeddings.", "transformer.embeddings.word_embeddings.", key + ) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("output.weight") + # Need to recompute vocab_size since LLaMa shards the word embeddings and output embeddings + # differently. + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).attention_norm.", + r"transformer.layers.\1.norm1.", + key, + ) + key = re.sub(r"^transformer.layers.(\d+).ffn_norm.", r"transformer.layers.\1.norm2.", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for l in range(config.n_layer): + w1 = state_dict.pop(f"transformer.layers.{l}.feed_forward.w1.weight") + w3 = state_dict.pop(f"transformer.layers.{l}.feed_forward.w3.weight") + # Our ordering is different + state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat([w3, w1], dim=0) + + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).feed_forward.w2.", + r"transformer.layers.\1.mlp.fc2.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"transformer.layers.{l}.attention.wq.weight") + Wk = state_dict.pop(f"transformer.layers.{l}.attention.wk.weight") + Wv = state_dict.pop(f"transformer.layers.{l}.attention.wv.weight") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + # We don't store these + state_dict.pop(f"transformer.layers.{l}.attention.inner_attention.rope.freqs", None) + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).attention.wo.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + state_dict.pop("transformer.rope.freqs", None) + + return state_dict + + +def remap_state_dict_hf_llama( + state_dict: Dict[str, torch.Tensor], config: GPT2Config +) -> Dict[str, torch.Tensor]: + """Convert the state_dict in Hugging Face format to standard GPT format. + + This function modifies state_dict in place. + """ + + # Embedding + def key_mapping_emb(key): + return re.sub(r"^model.embed_tokens.", "transformer.embeddings.word_embeddings.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + + # LM head + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # Need to recompute vocab_size since LLaMa shards the word embeddings and output embeddings + # differently. + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # MLP + for l in range(config.n_layer): + # Fusing weights this way based on difference in the following: + # https://github.com/huggingface/transformers/blob/b42010bb1d3cbf262d27e0a328661885be46dfdb/src/transformers/models/llama/modeling_llama.py#L220 + # https://github.com/Dao-AILab/flash-attention/blob/c60851a8253257eb970e06a022c82517a8033e8c/flash_attn/modules/mlp.py#L115 + w1 = state_dict.pop(f"model.layers.{l}.mlp.gate_proj.weight") + w3 = state_dict.pop(f"model.layers.{l}.mlp.up_proj.weight") + state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat([w3, w1], dim=0) + + def key_mapping_mlp(key): + return re.sub( + r"^model.layers.(\d+).mlp.down_proj.", + r"transformer.layers.\1.mlp.fc2.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^model.norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^model.layers.(\d+).input_layernorm.", + r"transformer.layers.\1.norm1.", + key, + ) + key = re.sub( + r"^model.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + def inv_permute(w): + # Inverse of permute implemented in: + # https://github.com/huggingface/transformers/blob/b42010bb1d3cbf262d27e0a328661885be46dfdb/src/transformers/models/llama/convert_llama_weights_to_hf.py#L114 + return rearrange( + w, "(h two d) n -> (h d two) n", d=config.n_embd // config.n_head // 2, two=2 + ) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"model.layers.{l}.self_attn.q_proj.weight") + Wk = state_dict.pop(f"model.layers.{l}.self_attn.k_proj.weight") + Wv = state_dict.pop(f"model.layers.{l}.self_attn.v_proj.weight") + + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat( + [inv_permute(Wq), inv_permute(Wk), Wv], dim=0 + ) + # We don't store these + state_dict.pop(f"model.layers.{l}.self_attn.rotary_emb.inv_freq", None) + + def key_mapping_attn(key): + return re.sub( + r"^model.layers.(\d+).self_attn.o_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + return state_dict + + +def inv_remap_state_dict_hf_llama( + state_dict: Dict[str, torch.Tensor], config: GPT2Config +) -> Dict[str, torch.Tensor]: + """Convert the state_dict in standard GPT format to Hugging Face format. + + This function is meant to be the inverse of remap_state_dict_hf_llama, up to a + multiplier pad in the embedding and lm_head. That is if the original embedding + isn't a multiple of pad_vocab_size_multiple, then + inv_remap_state_dict_hf_llama(remap_state_dict_hf_llama(state_dict)) != state_dict. + + This function modifies state_dict in place. + """ + + # Embedding + def key_mapping_emb(key): + return re.sub(r"^transformer.embeddings.word_embeddings.", "model.embed_tokens.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("model.embed_tokens.weight") + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["model.embed_tokens.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + + # LM head + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["model.embed_tokens.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # MLP + for l in range(config.n_layer): + w3, w1 = torch.chunk( + state_dict.pop(f"transformer.layers.{l}.mlp.fc1.weight"), chunks=2, dim=0 + ) + state_dict[f"model.layers.{l}.mlp.gate_proj.weight"] = w1 + state_dict[f"model.layers.{l}.mlp.up_proj.weight"] = w3 + + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).mlp.fc2.", + r"model.layers.\1.mlp.down_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.", r"model.norm.", key) + key = re.sub( + r"^transformer.layers.(\d+).norm1.", + r"model.layers.\1.input_layernorm.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).norm2.", + r"model.layers.\1.post_attention_layernorm.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + def permute(w): + return rearrange( + w, "(h d two) n -> (h two d) n", d=config.n_embd // config.n_head // 2, two=2 + ) + + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", n_head) + + embed_dim = config.hidden_size + head_dim = embed_dim // n_head + + q_dim = n_head * head_dim + k_dim = v_dim = n_head_kv * head_dim + + # Attention + for l in range(config.n_layer): + Wqkv = state_dict.pop(f"transformer.layers.{l}.mixer.Wqkv.weight") + Wq = Wqkv[:q_dim] + Wk = Wqkv[q_dim : q_dim + k_dim] + Wv = Wqkv[q_dim + k_dim : q_dim + k_dim + v_dim] + state_dict[f"model.layers.{l}.self_attn.q_proj.weight"] = permute(Wq) + state_dict[f"model.layers.{l}.self_attn.k_proj.weight"] = permute(Wk) + state_dict[f"model.layers.{l}.self_attn.v_proj.weight"] = Wv + state_dict.pop(f"transformer.layers.{l}.attention.inner_attention.rope.freqs", None) + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).mixer.out_proj.", + r"model.layers.\1.self_attn.o_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + return state_dict + + +def config_from_meta_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str +) -> LlamaConfig: + """Load a LlamaConfig from a checkpoint path.""" + with open(Path(checkpoint_path) / model_name / "params.json") as f: + params = json.load(f) + config = LlamaConfig( + hidden_size=params["dim"], + intermediate_size=None, + num_attention_heads=params["n_heads"], + num_hidden_layers=params["n_layers"], + rms_norm_eps=params["norm_eps"], + num_key_value_heads=params.get("n_kv_heads", None), + ) + multiple_of = params.get("multiple_of", 1) + ffn_dim_multiplier = params.get("ffn_dim_multiplier", None) + + # Compute the hidden dimension of the MLP + # https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/model.py#L224 + intermediate_size = 4 * config.hidden_size + # https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/model.py#L195-L199 + intermediate_size = int(2 * intermediate_size / 3) + # custom dim factor multiplier + if ffn_dim_multiplier is not None: + intermediate_size = int(ffn_dim_multiplier * intermediate_size) + intermediate_size = multiple_of * ((intermediate_size + multiple_of - 1) // multiple_of) + + config.intermediate_size = intermediate_size + if "rope_theta" in params: + config.rotary_emb_base = params["rope_theta"] + config.vocab_size = 32000 + # some CodeLLaMa have vocab_size 32000, some 32016 + # Sadly it's not specified in the `params.json` file :( + tokenizer = Path(checkpoint_path) / model_name / "tokenizer.model" + if tokenizer.is_file(): + config.vocab_size = SentencePieceProcessor(str(tokenizer)).vocab_size() + return config + + +def config_from_hf_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str +) -> LlamaConfig: + return LlamaConfig.from_pretrained(Path(checkpoint_path) / f"{model_name}-hf" / "config.json") + + +def config_from_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str, checkpoint_format="meta" +) -> LlamaConfig: + if checkpoint_format == "meta": + return config_from_meta_checkpoint(checkpoint_path, model_name) + else: + return config_from_hf_checkpoint(checkpoint_path, model_name) + + +def state_dicts_from_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str +) -> List[dict]: + # Need to sort, otherwise we mess up the ordering and the weights are wrong + return [ + torch.load(path, map_location="cpu") + for path in sorted((Path(checkpoint_path) / model_name).glob("consolidated.*.pth")) + ] + + +def llama_config_to_gpt2_config(llama_config: LlamaConfig) -> GPT2Config: + return GPT2Config( + vocab_size=llama_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=llama_config.hidden_size, + n_layer=llama_config.num_hidden_layers, + n_head=llama_config.num_attention_heads, + n_inner=llama_config.intermediate_size, + activation_function="swiglu", # Hardcode since HF calls it 'silu' + # Llama doesn't have dropout, idk if it's because they only release the inference code + resid_pdrop=0.0, + embd_pdrop=0.0, + attn_pdrop=0.0, + layer_norm_epsilon=llama_config.rms_norm_eps, + initializer_range=llama_config.initializer_range, + bos_token_id=llama_config.bos_token_id, + eos_token_id=llama_config.eos_token_id, + # These are new arguments not in the original GPT2Config + pad_token_id=llama_config.pad_token_id, # Idk if this does anything + rms_norm=True, + rotary_emb_fraction=1.0, + rotary_emb_interleaved=True, + tie_word_embeddings=False, + qkv_proj_bias=False, + out_proj_bias=False, + mlp_fc1_bias=False, + mlp_fc2_bias=False, + rotary_emb_base=getattr(llama_config, "rotary_emb_base", 10000.0), + n_head_kv=llama_config.num_key_value_heads, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/opt.py b/lib/python3.11/site-packages/flash_attn/models/opt.py new file mode 100644 index 0000000000000000000000000000000000000000..501f9eb6cf44be86aeb77a4e0f35048255850c30 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/opt.py @@ -0,0 +1,116 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from transformers import GPT2Config, OPTConfig + + +def remap_state_dict_hf_opt(state_dict, config): + def key_mapping_model(key): + key = re.sub(r"^model.decoder.", "transformer.", key) + # The OPT-350m model uses '^decoder' instead of '^model.decoder' + key = re.sub(r"^decoder.", "transformer.", key) + return key + + state_dict = OrderedDict((key_mapping_model(k), v) for k, v in state_dict.items()) + # Word embedding and position embedding + def key_mapping_emb(key): + key = re.sub(r"^transformer.embed_tokens.", "transformer.embeddings.word_embeddings.", key) + # The OPT-350m model uses has project_in and project_out + key = re.sub(r"^transformer.project_in.", "transformer.embeddings.project_in.", key) + key = re.sub(r"^transformer.project_out.", "project_out.", key) + key = re.sub( + r"^transformer.embed_positions.", "transformer.embeddings.position_embeddings.", key + ) + return key + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + # OPT uses the first 2 indices of pos_emb for padding tokens + pos_embeddings = state_dict.pop("transformer.embeddings.position_embeddings.weight") + state_dict["transformer.embeddings.position_embeddings.weight"] = pos_embeddings[2:] + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.final_layer_norm.", r"transformer.ln_f.", key) + # The OPT-175B checkpoint calls this 'decoder.layer_norm' instead of 'decoder.final_layer_norm' + key = re.sub(r"^transformer.layer_norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).self_attn_layer_norm.", r"transformer.layers.\1.norm1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).final_layer_norm.", r"transformer.layers.\1.norm2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).fc(1|2).", r"transformer.layers.\1.mlp.fc\2.", key + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"transformer.layers.{l}.self_attn.q_proj.weight") + Wk = state_dict.pop(f"transformer.layers.{l}.self_attn.k_proj.weight") + Wv = state_dict.pop(f"transformer.layers.{l}.self_attn.v_proj.weight") + bq = state_dict.pop(f"transformer.layers.{l}.self_attn.q_proj.bias") + bk = state_dict.pop(f"transformer.layers.{l}.self_attn.k_proj.bias") + bv = state_dict.pop(f"transformer.layers.{l}.self_attn.v_proj.bias") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + state_dict[f"transformer.layers.{l}.mixer.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0) + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).self_attn.out_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def opt_config_to_gpt2_config(opt_config: OPTConfig) -> GPT2Config: + assert opt_config.layerdrop == 0.0 + assert opt_config.layer_norm_elementwise_affine + word_embed_proj_dim = ( + None + if opt_config.word_embed_proj_dim == opt_config.hidden_size + else opt_config.word_embed_proj_dim + ) + return GPT2Config( + vocab_size=opt_config.vocab_size, + n_positions=opt_config.max_position_embeddings, + n_embd=opt_config.hidden_size, + n_layer=opt_config.num_hidden_layers, + n_head=opt_config.num_attention_heads, + n_inner=opt_config.ffn_dim, + activation_function=opt_config.activation_function, + resid_pdrop=opt_config.dropout, + # HF's implementation of OPT doesn't seem to have embedding dropout + embd_pdrop=opt_config.dropout, + attn_pdrop=opt_config.attention_dropout, + initializer_range=opt_config.init_std, + bos_token_id=opt_config.bos_token_id, + eos_token_id=opt_config.eos_token_id, + # These are new arguments not in the original GPT2Config + prenorm=opt_config.do_layer_norm_before, + word_embed_proj_dim=word_embed_proj_dim, + ) diff --git a/lib/python3.11/site-packages/flash_attn/models/vit.py b/lib/python3.11/site-packages/flash_attn/models/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..4602fd7414d251e40f9d42250c23cc974d596661 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/models/vit.py @@ -0,0 +1,373 @@ +# Copyright (c) 2022, Tri Dao. +# Inspired by / adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py +import math +import re +from collections import OrderedDict +from copy import deepcopy +from functools import partial + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from timm.models.helpers import named_apply +from torch.nn.init import trunc_normal_ +from torchvision.ops import StochasticDepth + +from flash_attn.layers.patch_embed import PatchEmbed +from flash_attn.modules.block import Block +from flash_attn.modules.mha import MHA +from flash_attn.modules.mlp import FusedMLP, Mlp + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn +except ImportError: + layer_norm_fn = None + + +def create_mixer_cls( + num_heads, qkv_bias, attn_drop, use_flash_attn, fused_bias_fc, cross_attn=False +): + mixer_cls = partial( + MHA, + num_heads=num_heads, + cross_attn=cross_attn, + qkv_proj_bias=qkv_bias, + dropout=attn_drop, + fused_bias_fc=fused_bias_fc, + use_flash_attn=use_flash_attn, + ) + return mixer_cls + + +def create_mlp_cls(embed_dim, mlp_ratio, act_layer, fused_mlp): + inner_dim = int(embed_dim * mlp_ratio) + if not fused_mlp: + mlp_cls = partial(Mlp, hidden_features=inner_dim, activation=act_layer()) + else: + mlp_cls = partial(FusedMLP, hidden_features=inner_dim) + return mlp_cls + + +def create_block( + embed_dim, + num_heads, + mlp_ratio, + qkv_bias, + drop_rate, + attn_drop_rate, + drop_path1, + drop_path2, + norm_layer, + act_layer, + use_flash_attn, + fused_bias_fc, + fused_mlp, + fused_dropout_add_ln, + layer_idx=None, + n_layer=None, + last_layer_subset=False, +): + mixer_cls = create_mixer_cls( + num_heads, + qkv_bias, + attn_drop_rate, + use_flash_attn, + fused_bias_fc, + cross_attn=(last_layer_subset and layer_idx == n_layer - 1), + ) + mlp_cls = create_mlp_cls(embed_dim, mlp_ratio, act_layer, fused_mlp) + # TD [2022-10-15]: Force residual in fp32 in case of DeepSpeed + block = Block( + embed_dim, + mixer_cls, + mlp_cls, + norm_cls=norm_layer, + prenorm=True, + resid_dropout1=drop_rate, + resid_dropout2=drop_rate, + drop_path1=drop_path1, + drop_path2=drop_path2, + fused_dropout_add_ln=fused_dropout_add_ln, + residual_in_fp32=True, + ) + return block + + +class VisionTransformer(nn.Module): + """Vision Transformer + A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` + - https://arxiv.org/abs/2010.11929 + """ + + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + num_classes=1000, + global_pool="token", + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + init_values=None, + class_token=True, + no_embed_class=False, + pre_norm=False, + fc_norm=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + weight_init="", + embed_layer=PatchEmbed, + norm_layer=None, + act_layer=None, + use_flash_attn=False, + fused_bias_fc=False, + fused_mlp=False, + fused_dropout_add_ln=False, + ): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + num_classes (int): number of classes for classification head + global_pool (str): type of global pooling for final sequence (default: 'token') + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + init_values: (float): layer-scale init values + class_token (bool): use class token + fc_norm (Optional[bool]): pre-fc norm after pool, set if global_pool == 'avg' if None (default: None) + drop_rate (float): dropout rate + attn_drop_rate (float): attention dropout rate + drop_path_rate (float): stochastic depth rate + weight_init (str): weight init scheme + embed_layer (nn.Module): patch embedding layer + norm_layer: (nn.Module): normalization layer + act_layer: (nn.Module): MLP activation layer + """ + super().__init__() + assert global_pool == "token", "Only support pooling with CLS token" + assert class_token + assert init_values is None, "LayerScale is not supported yet" + assert weight_init == "" + assert fc_norm is None + # pre_norm seems redundant, as there's a LayerNorm right at the start of each block, idk + assert not pre_norm + use_fc_norm = global_pool == "avg" if fc_norm is None else fc_norm + norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) + act_layer = act_layer or nn.GELU + + self.num_classes = num_classes + self.global_pool = global_pool + self.num_features = ( + self.embed_dim + ) = embed_dim # num_features for consistency with other models + self.num_prefix_tokens = 1 if class_token else 0 + self.no_embed_class = no_embed_class + + patch_embed_extra_kwargs = ( + {"fused_bias_fc": fused_bias_fc} if embed_layer is PatchEmbed else {} + ) + self.patch_embed = embed_layer( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + bias=not pre_norm, # disable bias if pre-norm is used (e.g. CLIP) + **patch_embed_extra_kwargs, + ) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if class_token else None + embed_len = num_patches if no_embed_class else num_patches + self.num_prefix_tokens + self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * 0.02) + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + + # We change the order of dropout, residual and layer norm: + # Instead of LN -> Attn / MLP -> Dropout -> Add, we do: + # Dropout -> Add -> LN -> Attn / MLP, returning both the residual branch (output of Add) and + # the main branch (output of MLP). The model definition is unchanged, but the mapping of the + # nn.Dropout probabilities are changed. + # This is for performance reason: we can fuse dropout + add + layer_norm. + self.blocks = nn.ModuleList( + [ + create_block( + embed_dim, + num_heads, + mlp_ratio, + qkv_bias, + drop_rate, + attn_drop_rate, + drop_path1=dpr[i - 1] if i > 0 else 0.0, + drop_path2=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + use_flash_attn=use_flash_attn, + fused_bias_fc=fused_bias_fc, + fused_mlp=fused_mlp, + fused_dropout_add_ln=fused_dropout_add_ln, + layer_idx=i, + n_layer=depth, + last_layer_subset=(global_pool == "token"), + ) + for i in range(depth) + ] + ) + + self.dropout = nn.Dropout(p=drop_rate) + self.drop_path = StochasticDepth(p=dpr[-1], mode="row") + self.norm = norm_layer(embed_dim) + + self.fused_dropout_add_ln = fused_dropout_add_ln + if self.fused_dropout_add_ln and layer_norm_fn is None: + raise ImportError("Triton is not installed") + + # Classifier Head + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + self.init_weights(weight_init) + + def init_weights(self, mode=""): + assert mode == "" + trunc_normal_(self.pos_embed, std=0.02) + if self.cls_token is not None: + nn.init.normal_(self.cls_token, std=1e-6) + named_apply(init_weights_vit_timm, self) + + def _init_weights(self, m): + # this fn left here for compat with downstream users + init_weights_vit_timm(m) + + @torch.jit.ignore + def no_weight_decay(self): + return {"pos_embed", "cls_token"} + + def _pos_embed(self, x): + if self.no_embed_class: + # deit-3, updated JAX (big vision) + # position embedding does not overlap with class token, add then concat + x = x + self.pos_embed + if self.cls_token is not None: + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + else: + # original timm, JAX, and deit vit impl + # pos_embed has entry for class token, concat then add + if self.cls_token is not None: + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + x = x + self.pos_embed + return x + + def forward_features(self, x, all_tokens=True): + """ + If all_tokens==False and self.global_pool == 'token', we only return the features for the + cls token. + """ + x = self.patch_embed(x) + hidden_states = self._pos_embed(x) + residual = None + if self.global_pool != "token" or all_tokens: + # if True: + for block in self.blocks: + hidden_states, residual = block(hidden_states, residual) + else: + for block in self.blocks[:-1]: + hidden_states, residual = block(hidden_states, residual) + # For the last layer, we only want the 1st token of the output. So we do cross-attention + # where the query is the 1st token and the key/value is the whole sequence. + hidden_states, residual = self.blocks[-1]( + hidden_states, residual, mixer_subset=slice(0, 1) + ) + if not self.fused_dropout_add_ln: + residual = self.drop_path(self.dropout(hidden_states)) + residual + hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype)) + else: + if self.drop_path.p == 0 or not self.training: + rowscale = None + else: + rowscale = self.drop_path( + torch.ones( + hidden_states.shape[:-1], + device=hidden_states.device, + dtype=hidden_states.dtype, + ) + ) + # Set prenorm=False here since we don't need to the residual + hidden_states = layer_norm_fn( + hidden_states, + self.norm.weight, + self.norm.bias, + residual=residual, + eps=self.norm.eps, + dropout_p=self.dropout.p if self.training else 0.0, + rowscale=rowscale, + prenorm=False, + ) + return hidden_states + + def forward_head(self, x, pre_logits: bool = False): + if self.global_pool: + x = x[:, self.num_prefix_tokens :].mean(dim=1) if self.global_pool == "avg" else x[:, 0] + return x if pre_logits else self.head(x) + + def forward(self, x): + x = self.forward_features(x, all_tokens=False) + x = self.forward_head(x) + return x + + def load_state_dict(self, state_dict, strict=True): + patch_embed_weight = state_dict["patch_embed.proj.weight"] + if patch_embed_weight.dim() == 4: + # convert from Conv2d to Linear + state_dict["patch_embed.proj.weight"] = rearrange( + patch_embed_weight, "o c h w -> o (c h w)" + ) + + def key_mapping_attn(key): + key = re.sub(r"^blocks.(\d+).attn.qkv.", r"blocks.\1.mixer.Wqkv.", key) + key = re.sub(r"^blocks.(\d+).attn.proj.", r"blocks.\1.mixer.out_proj.", key) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + n_layer = len(self.blocks) + # Convert from Wqkv to Wq and Wkv for cross attention (last layer) + if ( + self.blocks[-1].mixer.cross_attn + and f"blocks.{n_layer - 1}.mixer.Wqkv.weight" in state_dict + ): + Wqkv = state_dict.pop(f"blocks.{n_layer - 1}.mixer.Wqkv.weight") + bqkv = state_dict.pop(f"blocks.{n_layer - 1}.mixer.Wqkv.bias") + state_dict[f"blocks.{n_layer - 1}.mixer.Wq.weight"] = Wqkv[: self.embed_dim] + state_dict[f"blocks.{n_layer - 1}.mixer.Wkv.weight"] = Wqkv[self.embed_dim :] + state_dict[f"blocks.{n_layer - 1}.mixer.Wq.bias"] = bqkv[: self.embed_dim] + state_dict[f"blocks.{n_layer - 1}.mixer.Wkv.bias"] = bqkv[self.embed_dim :] + return super().load_state_dict(state_dict, strict=strict) + + +def init_weights_vit_timm(module: nn.Module, name: str = ""): + """ViT weight initialization, original timm impl (for reproducibility)""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif hasattr(module, "init_weights"): + module.init_weights() + + +def vit_base_patch16_224(pretrained=False, **kwargs): + """ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). + ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer. + """ + assert not pretrained + model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) + model = VisionTransformer(**model_kwargs) + return model diff --git a/lib/python3.11/site-packages/flash_attn/modules/__init__.py b/lib/python3.11/site-packages/flash_attn/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/flash_attn/modules/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..763b4ccaeb83986b3bd065b32bb91dfe98f0ab0d Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/modules/__pycache__/block.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/block.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..088a3d840f47e13bf5a014cda977465d3a189dd0 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/block.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/modules/__pycache__/embedding.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/embedding.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c59feb9b295656923980741264dae4eb0de99af8 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/embedding.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/modules/__pycache__/mha.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/mha.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5da668830cc323db6eabc34edbc8d68cb9e5d735 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/mha.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/modules/__pycache__/mlp.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/mlp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ebcdadb6ee3330511f007688999388890a4a5e1 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/modules/__pycache__/mlp.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/modules/block.py b/lib/python3.11/site-packages/flash_attn/modules/block.py new file mode 100644 index 0000000000000000000000000000000000000000..be8e8b864b600220068c2ec16aba5e2f1a81c121 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/modules/block.py @@ -0,0 +1,397 @@ +# Copyright (c) 2024, Tri Dao. + +from functools import partial +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torchvision.ops import StochasticDepth + +from flash_attn.modules.mha import MHA +from flash_attn.modules.mlp import Mlp + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn, RMSNorm +except ImportError: + layer_norm_fn, RMSNorm = None, None + + +class Block(nn.Module): + def __init__( + self, + dim, + mixer_cls=None, + mlp_cls=None, + norm_cls=nn.LayerNorm, + dropout_cls=nn.Dropout, + prenorm=True, + resid_dropout1=0.0, + resid_dropout2=0.0, + drop_path1=0.0, + drop_path2=0.0, + fused_dropout_add_ln=False, + return_residual=False, + residual_in_fp32=False, + sequence_parallel=False, + mark_shared_params=False, + ): + """ + For prenorm=True, this Block has a slightly different structure compared to a regular + prenorm Transformer block. + The standard block is: LN -> MHA -> Dropout -> Add -> LN -> MLP -> Dropout -> Add. + [Ref: https://arxiv.org/abs/2002.04745] + Here we have: Dropout -> Add -> LN -> MHA -> Dropout -> Add -> LN -> MLP, returning both + the hidden_states (output of the MLP) and the residual. + This is for performance reasons, as we can fuse the dropout, add and LayerNorm. + The residual needs to be provided (except for the very first block). + + For prenorm=False, this Block has the same structure as a regular postnorm Transformer + block: MHA -> Dropout -> Add -> LN -> MLP -> Dropout -> Add -> LN. + + return_residual: whether each of the sub-layers (mixer and mlp) will return the residual. + This is for performance reason: for post-norm architecture, returning the input allows us + to fuse the backward of nn.Linear with the residual connection. + """ + super().__init__() + self.prenorm = prenorm + self.fused_dropout_add_ln = fused_dropout_add_ln + self.return_residual = return_residual + self.residual_in_fp32 = residual_in_fp32 + if self.residual_in_fp32: + assert self.prenorm, "residual_in_fp32 is only compatible with prenorm=True" + if mixer_cls is None: + mixer_cls = partial(MHA, num_heads=dim // 64) + if mlp_cls is None: + mlp_cls = partial(Mlp, hidden_features=4 * dim) + self.mixer = mixer_cls(dim) + self.dropout1 = dropout_cls(resid_dropout1) + self.drop_path1 = StochasticDepth(drop_path1, mode="row") + self.norm1 = norm_cls(dim) + self.mlp = mlp_cls(dim) + if not isinstance(self.mlp, nn.Identity): + self.dropout2 = dropout_cls(resid_dropout2) + self.drop_path2 = StochasticDepth(drop_path2, mode="row") + self.norm2 = norm_cls(dim) + + if self.fused_dropout_add_ln: + assert layer_norm_fn is not None, "Triton is not installed" + assert isinstance(self.norm1, (nn.LayerNorm, RMSNorm)) and isinstance( + self.dropout1, nn.Dropout + ) + + # TD [2023-01-07]: TODO: During training, if sequence_parallel is False and dropout != 0.0, + # then the input to each worker in the tensor parallel group will be different. + # This would produce wrong outputs? Somehow we'd need to sync the RNG state across workers. + # For now this is not an issue because we always use sequence_parallel=True during training + # and only use sequence_parallel=False during inference. + + # Mark the norm parameters as "sequence_parallel" so that we run all-reduce on their grads. + if sequence_parallel: + for p in self.norm1.parameters(): + p._sequence_parallel = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._sequence_parallel = True + # Mark the norm parameters as "shared_params" so that we sync their values at init. + if mark_shared_params: + for p in self.norm1.parameters(): + p._shared_params = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._shared_params = True + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + + def forward( + self, + hidden_states: Tensor, + residual: Optional[Tensor] = None, + mixer_subset=None, + mixer_kwargs=None, + ): + r"""Pass the input through the encoder layer. + + Args: + hidden_states: the sequence to the encoder layer (required). + residual: if postnorm, residual=None, If prenorm, hidden_states = Attn/MLP(LN(residual)) + mixer_subset: for cross-attention only. If not None, will take a subset of x + before applying the query projection. Useful for e.g., ViT where we only care + about the CLS token in the last layer. + """ + if self.prenorm: + if not self.fused_dropout_add_ln: + dropped = self.drop_path1(self.dropout1(hidden_states)) + residual = (dropped + residual) if residual is not None else dropped + hidden_states = self.norm1(residual.to(dtype=self.norm1.weight.dtype)) + if self.residual_in_fp32: + residual = residual.to(torch.float32) + else: + if self.drop_path1.p == 0 or not self.training: + rowscale1 = None + else: + rowscale1 = self.drop_path1( + torch.ones( + hidden_states.shape[:-1], + device=hidden_states.device, + dtype=hidden_states.dtype, + ) + ) + hidden_states, residual = layer_norm_fn( + hidden_states, + self.norm1.weight, + self.norm1.bias, + residual=residual, + eps=self.norm1.eps, + dropout_p=self.dropout1.p if self.training else 0.0, + rowscale=rowscale1, + prenorm=True, + residual_in_fp32=self.residual_in_fp32, + is_rms_norm=isinstance(self.norm1, RMSNorm) + ) + if mixer_kwargs is None: + mixer_kwargs = {} + if mixer_subset is not None: + mixer_kwargs["mixer_subset"] = mixer_subset + hidden_states = self.mixer(hidden_states, **mixer_kwargs) + if mixer_subset is not None: + residual = residual[:, mixer_subset] + if not isinstance(self.mlp, nn.Identity): + if not self.fused_dropout_add_ln: + dropped = self.drop_path2(self.dropout2(hidden_states)) + residual = (dropped + residual) if residual is not None else dropped + hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype)) + if self.residual_in_fp32: + residual = residual.to(torch.float32) + else: + if self.drop_path2.p == 0 or not self.training: + rowscale2 = None + else: + rowscale2 = self.drop_path2( + torch.ones( + hidden_states.shape[:-1], + device=hidden_states.device, + dtype=hidden_states.dtype, + ) + ) + hidden_states, residual = layer_norm_fn( + hidden_states, + self.norm2.weight, + self.norm2.bias, + residual=residual, + eps=self.norm2.eps, + dropout_p=self.dropout2.p if self.training else 0.0, + rowscale=rowscale2, + prenorm=True, + residual_in_fp32=self.residual_in_fp32, + is_rms_norm=isinstance(self.norm2, RMSNorm) + ) + hidden_states = self.mlp(hidden_states) + return hidden_states, residual + else: + assert residual is None + mixer_out = self.mixer( + hidden_states, **(mixer_kwargs if mixer_kwargs is not None else {}) + ) + if self.return_residual: # mixer out is actually a pair here + mixer_out, hidden_states = mixer_out + if not self.fused_dropout_add_ln: + hidden_states = self.norm1( + (self.drop_path1(self.dropout1(mixer_out)) + hidden_states).to( + dtype=self.norm1.weight.dtype + ) + ) + else: + if self.drop_path1.p == 0 or not self.training: + rowscale1 = None + else: + rowscale1 = self.drop_path1( + torch.ones( + mixer_out.shape[:-1], device=mixer_out.device, dtype=mixer_out.dtype + ) + ) + hidden_states = layer_norm_fn( + mixer_out, + self.norm1.weight, + self.norm1.bias, + residual=hidden_states, + eps=self.norm1.eps, + dropout_p=self.dropout1.p if self.training else 0.0, + rowscale=rowscale1, + prenorm=False, + is_rms_norm=isinstance(self.norm1, RMSNorm) + ) + if not isinstance(self.mlp, nn.Identity): + mlp_out = self.mlp(hidden_states) + if self.return_residual: # mlp out is actually a pair here + mlp_out, hidden_states = mlp_out + if not self.fused_dropout_add_ln: + hidden_states = self.norm2( + (self.drop_path2(self.dropout2(mlp_out)) + hidden_states).to( + dtype=self.norm2.weight.dtype + ) + ) + else: + if self.drop_path2.p == 0 or not self.training: + rowscale2 = None + else: + rowscale2 = self.drop_path2( + torch.ones( + mlp_out.shape[:-1], device=mlp_out.device, dtype=mlp_out.dtype + ) + ) + hidden_states = layer_norm_fn( + mlp_out, + self.norm2.weight, + self.norm2.bias, + residual=hidden_states, + eps=self.norm2.eps, + dropout_p=self.dropout2.p if self.training else 0.0, + rowscale=rowscale2, + prenorm=False, + is_rms_norm=isinstance(self.norm2, RMSNorm) + ) + return hidden_states + + +class ParallelBlock(nn.Module): + """The attention (mixer) and MLP blocks are done in parallel, similar to GPT-J, GPT-NeoX, + and PaLM. + """ + + def __init__( + self, + dim, + mixer_cls=None, + mlp_cls=None, + norm_cls=nn.LayerNorm, + dropout_cls=nn.Dropout, + resid_dropout1=0.0, + resid_dropout2=0.0, + tied_norm=False, + fused_dropout_add_ln=False, + residual_in_fp32=False, + sequence_parallel=False, + mark_shared_params=False, + ): + """ + This Block has a slightly different structure compared to a regular + prenorm Transformer block. + The standard block is: LN -> MHA / MLP -> Dropout -> Add. + [Ref: https://arxiv.org/abs/2002.04745] + Here we have: Dropout -> Add -> LN -> MHA / MLP, returning both + the hidden_states (output1 of the MHA / MLP) and the residual. + This is for performance reasons, as we can fuse the dropout, add and LayerNorm. + The residual needs to be provided (except for the very first block). + """ + super().__init__() + self.tied_norm = tied_norm + self.fused_dropout_add_ln = fused_dropout_add_ln + self.residual_in_fp32 = residual_in_fp32 + if mixer_cls is None: + mixer_cls = partial(MHA, num_heads=dim // 64) + if mlp_cls is None: + mlp_cls = partial(Mlp, hidden_features=4 * dim) + self.mixer = mixer_cls(dim) + self.dropout1 = dropout_cls(resid_dropout1) + self.norm1 = norm_cls(dim) + self.mlp = mlp_cls(dim) + self.dropout2 = dropout_cls(resid_dropout2) + if not self.tied_norm: + self.norm2 = norm_cls(dim) + + if self.fused_dropout_add_ln: + assert layer_norm_fn is not None, "Triton is not installed" + assert isinstance(self.norm1, (nn.LayerNorm, RMSNorm)) and isinstance( + self.dropout1, nn.Dropout + ) + + # TD [2023-01-07]: TODO: During training, if sequence_parallel is False and dropout != 0.0, + # then the input to each worker in the tensor parallel group will be different. + # This would produce wrong outputs? Somehow we'd need to sync the RNG state across workers. + # For now this is not an issue because we always use sequence_parallel=True during training + # and only use sequence_parallel=False during inference. + + # Mark the norm parameters as "sequence_parallel" so that we run all-reduce on their grads. + if sequence_parallel: + for p in self.norm1.parameters(): + p._sequence_parallel = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._sequence_parallel = True + # Mark the norm parameters as "shared_params" so that we sync their values at init. + if mark_shared_params: + for p in self.norm1.parameters(): + p._shared_params = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._shared_params = True + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + + def forward( + self, + hidden_states1: Tensor, + hidden_states2: Optional[Tensor] = None, + residual: Optional[Tensor] = None, + mixer_kwargs=None, + ): + r"""Pass the input through the encoder layer. + + Args: + hidden_states1: the output of the previous attention (mixer) or embedding layer. + hidden_states2: the output of the previous MLP layer (if None, will use hidden_states1). + residual. + """ + # TODO: Ideally we should only do the allgather / allreduce once for + # the Linear to MLP & Attention + if not self.fused_dropout_add_ln: + dropped1 = self.dropout1(hidden_states1) + # For the very 1st block, we only want 1 dropout, not two different dropouts + if hidden_states2 is not None: + dropped2 = self.dropout2(hidden_states2) + residual = ( + (residual + dropped1 + dropped2) + if residual is not None + else dropped1 + dropped2 + ) + else: + residual = (residual + dropped1) if residual is not None else dropped1 + hidden_states1 = self.norm1(residual.to(dtype=self.norm1.weight.dtype)) + hidden_states2 = ( + self.norm2(residual.to(dtype=self.norm2.weight.dtype)) + if not self.tied_norm + else hidden_states1 + ) + if self.residual_in_fp32: + residual = residual.to(torch.float32) + else: + weight2, bias2 = ( + (self.norm2.weight, self.norm2.bias) if not self.tied_norm else (None, None) + ) + hidden_states1, *rest, residual = layer_norm_fn( + hidden_states1, + self.norm1.weight, + self.norm1.bias, + residual=residual, + x1=hidden_states2, + weight1=weight2, + bias1=bias2, + eps=self.norm1.eps, + dropout_p=self.dropout1.p if self.training else 0.0, + prenorm=True, + residual_in_fp32=self.residual_in_fp32, + is_rms_norm=isinstance(self.norm1, RMSNorm) + ) + if self.tied_norm: + hidden_states2 = hidden_states1 + else: + hidden_states2, = rest + if mixer_kwargs is None: + mixer_kwargs = {} + hidden_states1 = self.mixer(hidden_states1, **mixer_kwargs) + hidden_states2 = self.mlp(hidden_states2) + return hidden_states1, hidden_states2, residual diff --git a/lib/python3.11/site-packages/flash_attn/modules/embedding.py b/lib/python3.11/site-packages/flash_attn/modules/embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..33587d09413dbab5edccfa3806fca829a6f9f9da --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/modules/embedding.py @@ -0,0 +1,216 @@ +# Copyright (c) 2022, Tri Dao. + +import torch +import torch.nn as nn +from einops import rearrange +from torch import Tensor + +from flash_attn.utils.distributed import all_reduce, reduce_scatter + + +class GPT2Embeddings(nn.Module): + def __init__( + self, + embed_dim, + vocab_size, + max_position_embeddings, + padding_idx=None, + word_embed_proj_dim=None, + device=None, + dtype=None, + ): + """ + If max_position_embeddings <= 0, there's no position embeddings + If word_embe_proj_dim is not None (e.g., OPT-350m), we embed to that dimension + the project up to embed_dim + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + if word_embed_proj_dim is None: + self.word_embeddings = nn.Embedding( + vocab_size, embed_dim, padding_idx=padding_idx, **factory_kwargs + ) + self.project_in = None + else: + self.word_embeddings = nn.Embedding( + vocab_size, word_embed_proj_dim, padding_idx=padding_idx, **factory_kwargs + ) + self.project_in = nn.Linear( + word_embed_proj_dim, embed_dim, bias=False, **factory_kwargs + ) + self.max_position_embeddings = max_position_embeddings + if self.max_position_embeddings > 0: + self.position_embeddings = nn.Embedding( + max_position_embeddings, embed_dim, **factory_kwargs + ) + + def forward(self, input_ids, position_ids=None): + """ + input_ids: (batch, seqlen) + position_ids: (batch, seqlen) + """ + batch_size, seqlen = input_ids.shape + embeddings = self.word_embeddings(input_ids) + if self.project_in is not None: + embeddings = self.project_in(embeddings) + if self.max_position_embeddings > 0: + if position_ids is None: + position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device) + position_embeddings = self.position_embeddings(position_ids) + embeddings = embeddings + position_embeddings + return embeddings + + +class BertEmbeddings(nn.Module): + def __init__( + self, + embed_dim, + vocab_size, + max_position_embeddings, + type_vocab_size, + padding_idx=None, + device=None, + dtype=None, + ): + """ + If max_position_embeddings <= 0, there's no position embeddings + If type_vocab_size <= 0, there's no token type embeddings + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.word_embeddings = nn.Embedding( + vocab_size, embed_dim, padding_idx=padding_idx, **factory_kwargs + ) + self.max_position_embeddings = max_position_embeddings + self.type_vocab_size = type_vocab_size + if self.max_position_embeddings > 0: + self.position_embeddings = nn.Embedding( + max_position_embeddings, embed_dim, **factory_kwargs + ) + if self.type_vocab_size > 0: + self.token_type_embeddings = nn.Embedding(type_vocab_size, embed_dim, **factory_kwargs) + + def forward(self, input_ids, position_ids=None, token_type_ids=None): + """ + input_ids: (batch, seqlen) + position_ids: (batch, seqlen) + token_type_ids: (batch, seqlen) + """ + batch_size, seqlen = input_ids.shape + embeddings = self.word_embeddings(input_ids) + if self.max_position_embeddings > 0: + if position_ids is None: + position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device) + position_embeddings = self.position_embeddings(position_ids) + embeddings = embeddings + position_embeddings + if self.type_vocab_size > 0: + if token_type_ids is None: + token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device) + token_type_embeddings = self.token_type_embeddings(token_type_ids) + embeddings = embeddings + token_type_embeddings + return embeddings + + +class VocabParallelEmbedding(nn.Embedding): + def __init__(self, num_embeddings, *args, process_group=None, padding_idx=None, **kwargs): + self.process_group = process_group + if process_group is not None: + world_size = torch.distributed.get_world_size(process_group) + if num_embeddings % world_size != 0: + raise ValueError( + f"num_embeddings ({num_embeddings}) must be divisible by " + f"world_size ({world_size})" + ) + if world_size > 1 and padding_idx is not None: + raise RuntimeError("ParallelEmbedding does not support padding_idx") + else: + world_size = 1 + super().__init__(num_embeddings // world_size, *args, padding_idx=padding_idx, **kwargs) + + def forward(self, input: Tensor) -> Tensor: + if self.process_group is None: + return super().forward(input) + else: + rank = torch.distributed.get_rank(self.process_group) + vocab_size = self.num_embeddings + vocab_start_index, vocab_end_index = rank * vocab_size, (rank + 1) * vocab_size + # Create a mask of valid vocab ids (1 means it needs to be masked). + input_ids_mask = (input < vocab_start_index) | (input >= vocab_end_index) + input = input - vocab_start_index + input[input_ids_mask] = 0 + embeddings = super().forward(input) + embeddings[input_ids_mask] = 0.0 + return embeddings + + +class ColumnParallelEmbedding(nn.Embedding): + def __init__(self, num_embeddings, embedding_dim, *args, process_group=None, **kwargs): + self.process_group = process_group + if process_group is not None: + world_size = torch.distributed.get_world_size(process_group) + if embedding_dim % world_size != 0: + raise ValueError( + f"embedding_dim ({embedding_dim}) must be divisible by " + f"world_size ({world_size})" + ) + else: + world_size = 1 + super().__init__(num_embeddings, embedding_dim // world_size, *args, **kwargs) + + +class ParallelGPT2Embeddings(nn.Module): + def __init__( + self, + embed_dim, + vocab_size, + max_position_embeddings, + process_group, + padding_idx=None, + sequence_parallel=True, + device=None, + dtype=None, + ): + """ + If max_position_embeddings <= 0, there's no position embeddings + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.process_group = process_group + self.sequence_parallel = sequence_parallel + self.word_embeddings = VocabParallelEmbedding( + vocab_size, + embed_dim, + padding_idx=padding_idx, + process_group=process_group, + **factory_kwargs, + ) + self.max_position_embeddings = max_position_embeddings + if self.max_position_embeddings > 0: + self.position_embeddings = ColumnParallelEmbedding( + max_position_embeddings, embed_dim, process_group=process_group, **factory_kwargs + ) + + def forward(self, input_ids, position_ids=None, combine_batch_seqlen_dim=False): + """ + input_ids: (batch, seqlen) + position_ids: (batch, seqlen) + """ + batch_size, seqlen = input_ids.shape + world_size = torch.distributed.get_world_size(self.process_group) + embeddings = self.word_embeddings(input_ids) + if self.max_position_embeddings > 0: + if position_ids is None: + position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device) + position_embeddings = self.position_embeddings(position_ids) + if world_size <= 1: + embeddings = embeddings + position_embeddings + else: + partition_dim = self.position_embeddings.embedding_dim + rank = torch.distributed.get_rank(self.process_group) + embeddings[ + ..., rank * partition_dim : (rank + 1) * partition_dim + ] += position_embeddings + if combine_batch_seqlen_dim: + embeddings = rearrange(embeddings, "b s d -> (b s) d") + reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce + return embeddings if world_size <= 1 else reduce_fn(embeddings, self.process_group) diff --git a/lib/python3.11/site-packages/flash_attn/modules/mha.py b/lib/python3.11/site-packages/flash_attn/modules/mha.py new file mode 100644 index 0000000000000000000000000000000000000000..77640c2b239ac729cad79ce3b2504e0eeacb5f73 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/modules/mha.py @@ -0,0 +1,1020 @@ +# Copyright (c) 2023, Tri Dao. + +import math +from functools import partial + +import torch +import torch.nn as nn +from einops import rearrange, repeat + +from flash_attn.utils.distributed import get_dim_for_local_rank + +try: + from flash_attn import ( + flash_attn_kvpacked_func, + flash_attn_qkvpacked_func, + flash_attn_varlen_kvpacked_func, + flash_attn_varlen_qkvpacked_func, + flash_attn_with_kvcache, + ) +except ImportError: + flash_attn_varlen_qkvpacked_func, flash_attn_varlen_kvpacked_func = None, None + flash_attn_qkvpacked_func, flash_attn_kvpacked_func = None, None + flash_attn_with_kvcache = None + +try: + from flash_attn.ops.fused_dense import ColumnParallelLinear, FusedDense, RowParallelLinear +except ImportError: + FusedDense, ColumnParallelLinear, RowParallelLinear = None, None, None + +try: + from flash_attn.layers.rotary import RotaryEmbedding +except ImportError: + RotaryEmbedding = None + + +# From https://github.com/ofirpress/attention_with_linear_biases/blob/4b92f28a005ead2567abe2359f633e73e08f3833/fairseq/models/transformer.py#L742 +def get_alibi_slopes(nheads): + def get_slopes_power_of_2(nheads): + start = 2 ** (-(2 ** -(math.log2(nheads) - 3))) + ratio = start + return [start * ratio**i for i in range(nheads)] + + if math.log2(nheads).is_integer(): + return get_slopes_power_of_2(nheads) + else: + closest_power_of_2 = 2 ** math.floor(math.log2(nheads)) + return ( + get_slopes_power_of_2(closest_power_of_2) + + get_alibi_slopes(2 * closest_power_of_2)[0::2][: nheads - closest_power_of_2] + ) + + +class FlashSelfAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__( + self, + causal=False, + softmax_scale=None, + attention_dropout=0.0, + window_size=(-1, -1), + alibi_slopes=None, + deterministic=False, + ): + super().__init__() + assert flash_attn_varlen_qkvpacked_func is not None, "FlashAttention is not installed" + assert flash_attn_qkvpacked_func is not None, "FlashAttention is not installed" + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + self.register_buffer("alibi_slopes", alibi_slopes, persistent=False) + self.window_size = window_size + self.deterministic = deterministic + + def forward(self, qkv, causal=None, cu_seqlens=None, max_seqlen=None): + """Implements the multihead softmax attention. + Arguments + --------- + qkv: The tensor containing the query, key, and value. + If cu_seqlens is None and max_seqlen is None, then qkv has shape (B, S, 3, H, D). + If cu_seqlens is not None and max_seqlen is not None, then qkv has shape + (total, 3, H, D), where total is the sum of the sequence lengths in the batch. + causal: if passed, will override self.causal + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into qkv. + max_seqlen: int. Maximum sequence length in the batch. + Returns: + -------- + out: (total, H, D) if cu_seqlens is not None and max_seqlen is not None, + else (B, S, H, D). + """ + assert qkv.dtype in [torch.float16, torch.bfloat16] + assert qkv.is_cuda + causal = self.causal if causal is None else causal + unpadded = cu_seqlens is not None + if self.alibi_slopes is not None: + self.alibi_slopes = self.alibi_slopes.to(torch.float32) + if unpadded: + assert cu_seqlens.dtype == torch.int32 + assert max_seqlen is not None + assert isinstance(max_seqlen, int) + return flash_attn_varlen_qkvpacked_func( + qkv, + cu_seqlens, + max_seqlen, + self.drop.p if self.training else 0.0, + softmax_scale=self.softmax_scale, + causal=causal, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + else: + return flash_attn_qkvpacked_func( + qkv, + self.drop.p if self.training else 0.0, + softmax_scale=self.softmax_scale, + causal=causal, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + + +class FlashCrossAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__( + self, + causal=False, + softmax_scale=None, + attention_dropout=0.0, + alibi_slopes=None, + window_size=(-1, -1), + deterministic=False, + ): + super().__init__() + assert flash_attn_varlen_kvpacked_func is not None, "FlashAttention is not installed" + assert flash_attn_kvpacked_func is not None, "FlashAttention is not installed" + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + self.register_buffer("alibi_slopes", alibi_slopes, persistent=False) + self.window_size = window_size + self.deterministic = deterministic + + def forward( + self, + q, + kv, + causal=None, + cu_seqlens=None, + max_seqlen=None, + cu_seqlens_k=None, + max_seqlen_k=None, + ): + """Implements the multihead softmax attention. + Arguments + --------- + q: The tensor containing the query. (B, Sq, H, D) + kv: The tensor containing the key and value. (B, Sk, 2, H_k, D) + causal: if passed, will override self.causal + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + max_seqlen: int. Maximum sequence length in the batch of q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_k: int. Maximum sequence length in the batch of k and v. + """ + assert q.dtype in [torch.float16, torch.bfloat16] + assert q.is_cuda and kv.is_cuda + causal = self.causal if causal is None else causal + unpadded = cu_seqlens is not None + if self.alibi_slopes is not None: + self.alibi_slopes = self.alibi_slopes.to(torch.float32) + if unpadded: + assert cu_seqlens.dtype == torch.int32 + assert max_seqlen is not None + assert isinstance(max_seqlen, int) + assert cu_seqlens_k is not None + assert cu_seqlens_k.dtype == torch.int32 + assert max_seqlen_k is not None + assert isinstance(max_seqlen_k, int) + return flash_attn_varlen_kvpacked_func( + q, + kv, + cu_seqlens, + cu_seqlens_k, + max_seqlen, + max_seqlen_k, + self.drop.p if self.training else 0.0, + softmax_scale=self.softmax_scale, + causal=causal, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + else: + batch_size, seqlen_q = q.shape[0], q.shape[1] + seqlen_k = kv.shape[1] + assert kv.shape[0] == batch_size and kv.shape[4] == q.shape[3] + return flash_attn_kvpacked_func( + q, + kv, + self.drop.p if self.training else 0.0, + causal=causal, + softmax_scale=self.softmax_scale, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + + +class SelfAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0): + super().__init__() + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + + def forward(self, qkv, causal=None, key_padding_mask=None): + """Implements the multihead softmax attention. + Arguments + --------- + qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) + causal: if passed, will override self.causal + key_padding_mask: boolean mask to apply to the attention weights. True means to keep, + False means to mask out. (B, S) + """ + batch_size, seqlen = qkv.shape[0], qkv.shape[1] + causal = self.causal if causal is None else causal + q, k, v = qkv.unbind(dim=2) + softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1]) + scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale) + if key_padding_mask is not None: + padding_mask = torch.full( + (batch_size, seqlen), -10000.0, dtype=scores.dtype, device=scores.device + ) + padding_mask.masked_fill_(key_padding_mask, 0.0) + # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess) + scores = scores + rearrange(padding_mask, "b s -> b 1 1 s") + if causal: + # "triu_tril_cuda_template" not implemented for 'BFloat16' + # So we have to construct the mask in float + causal_mask = torch.triu( + torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1 + ) + # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess) + scores = scores + causal_mask.to(dtype=scores.dtype) + attention = torch.softmax(scores, dim=-1, dtype=v.dtype) + attention_drop = self.drop(attention) + output = torch.einsum("bhts,bshd->bthd", attention_drop, v) + return output + + +class CrossAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0): + super().__init__() + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + + def forward(self, q, kv, causal=None, key_padding_mask=None): + """Implements the multihead softmax attention. + Arguments + --------- + q: The tensor containing the query. (B, Sq, H, D) + kv: The tensor containing the key and value. (B, Sk, 2, H_k, D) + causal: if passed, will override self.causal + key_padding_mask: boolean mask to apply to the attention weights. True means to keep, + False means to mask out. (B, Sk) + """ + batch_size, seqlen_q = q.shape[0], q.shape[1] + causal = self.causal if causal is None else causal + seqlen_k = kv.shape[1] + assert kv.shape[0] == batch_size and kv.shape[4] == q.shape[3] + if kv.shape[3] != q.shape[2]: # MQA/GQA + kv = repeat(kv, "... hkv d -> ... (hkv g) d", g=q.shape[2] // kv.shape[3]) + k, v = kv.unbind(dim=2) + softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1]) + scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale) + if key_padding_mask is not None: + padding_mask = torch.full( + (batch_size, seqlen_k), -10000.0, dtype=scores.dtype, device=scores.device + ) + padding_mask.masked_fill_(key_padding_mask, 0.0) + # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess) + scores = scores + rearrange(padding_mask, "b s -> b 1 1 s") + if causal: + # causal mask needs to take into account the difference between seqlen_q and seqlen_k + row_idx = rearrange( + torch.arange(seqlen_q, device=q.device, dtype=torch.long), "s -> s 1" + ) + col_idx = torch.arange(seqlen_k, device=kv.device, dtype=torch.long) + sk = ( + seqlen_k + if key_padding_mask is None + else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1") + ) + causal_mask = col_idx > row_idx + sk - seqlen_q + scores = scores.masked_fill(causal_mask, -10000.0) + attention = torch.softmax(scores, dim=-1, dtype=v.dtype) + attention_drop = self.drop(attention) + output = torch.einsum("bhts,bshd->bthd", attention_drop, v) + return output + + +class LinearResidual(nn.Linear): + """Wrap nn.Linear to return the residual as well. For compatibility with FusedDense.""" + + def forward(self, input: torch.Tensor) -> torch.Tensor: + return super().forward(input), input + + +def _update_kv_cache(kv, inference_params, layer_idx): + """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)""" + # Pre-allocate memory for key-values for inference. + num_heads, head_dim = kv.shape[-2:] + if layer_idx not in inference_params.key_value_memory_dict: + kv_cache = torch.empty( + inference_params.max_batch_size, + inference_params.max_seqlen, + 2, + num_heads, + head_dim, + dtype=kv.dtype, + device=kv.device, + ) + inference_params.key_value_memory_dict[layer_idx] = kv_cache + else: + kv_cache = inference_params.key_value_memory_dict[layer_idx] + # Adjust key and value for inference + batch_start = inference_params.batch_size_offset + batch_end = batch_start + kv.shape[0] + sequence_start = inference_params.seqlen_offset + sequence_end = sequence_start + kv.shape[1] + assert batch_end <= kv_cache.shape[0] + assert sequence_end <= kv_cache.shape[1] + assert kv_cache is not None + kv_cache[batch_start:batch_end, sequence_start:sequence_end, ...] = kv + return kv_cache[batch_start:batch_end, :sequence_end, ...] + + +class MHA(nn.Module): + """Multi-head self-attention and cross-attention""" + + def __init__( + self, + embed_dim, + num_heads, + num_heads_kv=None, + cross_attn=False, + qkv_proj_bias=True, + out_proj_bias=True, + dropout=0.0, + softmax_scale=None, + causal=False, + layer_idx=None, + dwconv=False, + rotary_emb_dim=0, + rotary_emb_base=10000.0, + rotary_emb_scale_base=None, + rotary_emb_interleaved=False, + use_alibi=False, + window_size=(-1, -1), + fused_bias_fc=False, + use_flash_attn=False, + return_residual=False, + checkpointing=False, + device=None, + dtype=None, + ) -> None: + """ + num_heads_kv: can be used to toggle MQA / GQA. If None, use num_heads. + return_residual: whether to return the input x along with the output. This is for + performance reason: for post-norm architecture, returning the input allows us + to fuse the backward of nn.Linear with the residual connection. + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.embed_dim = embed_dim + self.cross_attn = cross_attn + self.causal = causal + self.layer_idx = layer_idx + self.dwconv = dwconv + self.rotary_emb_dim = rotary_emb_dim + self.use_flash_attn = use_flash_attn + self.return_residual = return_residual + self.checkpointing = checkpointing + if use_alibi: + assert use_flash_attn, "ALiBi code path requires flash_attn" + alibi_slopes = torch.tensor(get_alibi_slopes(num_heads), device=device) + else: + alibi_slopes = None + if window_size != (-1, -1): + assert use_flash_attn, "Local (sliding window) attention code path requires flash_attn" + + self.num_heads = num_heads + self.num_heads_kv = num_heads_kv if num_heads_kv is not None else num_heads + assert ( + self.num_heads % self.num_heads_kv == 0 + ), "num_heads must be divisible by num_heads_kv" + assert self.embed_dim % num_heads == 0, "embed_dim must be divisible by num_heads" + self.head_dim = self.embed_dim // num_heads + qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv) + kv_dim = 2 * self.head_dim * self.num_heads_kv + + if self.rotary_emb_dim > 0: + assert not cross_attn, "MHA with rotary embedding does not support cross-attention yet" + assert RotaryEmbedding is not None, "rotary_emb is not installed" + self.rotary_emb = RotaryEmbedding( + self.rotary_emb_dim, + base=rotary_emb_base, + scale_base=rotary_emb_scale_base, + interleaved=rotary_emb_interleaved, + device=device, + ) + + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + linear_resid_cls = ( + LinearResidual if not fused_bias_fc else partial(FusedDense, return_residual=True) + ) + wqkv_cls = linear_cls if not self.return_residual else linear_resid_cls + inner_attn_cls = ( + partial(FlashSelfAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else SelfAttention + ) + inner_cross_attn_cls = ( + partial(FlashCrossAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else CrossAttention + ) + if not self.cross_attn: + self.Wqkv = wqkv_cls(embed_dim, qkv_dim, bias=qkv_proj_bias, **factory_kwargs) + else: + self.Wq = linear_cls(embed_dim, embed_dim, bias=qkv_proj_bias, **factory_kwargs) + self.Wkv = wqkv_cls(embed_dim, kv_dim, bias=qkv_proj_bias, **factory_kwargs) + if self.dwconv: + if self.num_heads_kv == self.num_heads: + self.dwconv_qkv = nn.Conv1d( + qkv_dim, qkv_dim, kernel_size=3, padding=2, groups=qkv_dim + ) + else: + self.dwconv_q = nn.Conv1d( + embed_dim, embed_dim, kernel_size=3, padding=2, groups=embed_dim + ) + self.dwconv_kv = nn.Conv1d(kv_dim, kv_dim, kernel_size=3, padding=2, groups=kv_dim) + self.inner_attn = inner_attn_cls( + causal=causal, + softmax_scale=softmax_scale, + attention_dropout=dropout, + ) + self.inner_cross_attn = inner_cross_attn_cls( + causal=causal, softmax_scale=softmax_scale, attention_dropout=dropout + ) + self.out_proj = linear_cls(embed_dim, embed_dim, bias=out_proj_bias, **factory_kwargs) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None): + dtype = self.out_proj.weight.dtype if dtype is None else dtype + device = self.out_proj.weight.device + return torch.empty( + batch_size, + max_seqlen, + 2, + self.num_heads_kv, + self.head_dim, + dtype=dtype, + device=device, + ) + + def _update_kv_cache(self, kv, inference_params): + """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)""" + assert not self.dwconv, "Generation does not support dwconv yet" + assert self.layer_idx is not None, "Generation requires layer_idx in the constructor" + return _update_kv_cache(kv, inference_params, self.layer_idx) + + def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params): + """ + Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention. + q: (batch_size, seqlen_q, nheads, head_dim) + kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim) + """ + assert inference_params is not None and inference_params.seqlen_offset > 0 + assert self.use_flash_attn + if self.rotary_emb_dim > 0: + assert self.rotary_emb.scale is None, "This code path does not support xPos" + self.rotary_emb._update_cos_sin_cache( + inference_params.max_seqlen, device=q.device, dtype=q.dtype + ) + rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached + else: + rotary_cos, rotary_sin = None, None + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + context = flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + rotary_cos=rotary_cos, + rotary_sin=rotary_sin, + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False, + alibi_slopes=alibi_slopes, + ) + return context + + def _update_kvcache_attention(self, q, kv, inference_params): + """Write kv to inference_params, then do attention""" + if ( + inference_params.seqlen_offset == 0 + or flash_attn_with_kvcache is None + or not self.use_flash_attn + ): + # TODO: this only uses seqlen_offset and not lengths_per_sample. + kv = self._update_kv_cache(kv, inference_params) + return self.inner_cross_attn(q, kv) + else: + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + return flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + alibi_slopes=alibi_slopes, + ) + + def forward( + self, + x, + x_kv=None, + key_padding_mask=None, + cu_seqlens=None, + max_seqlen=None, + mixer_subset=None, + inference_params=None, + **kwargs, + ): + """ + Arguments: + x: (batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim) if + cu_seqlens is None and max_seqlen is None, else (total, hidden_dim) where total + is the is the sum of the sequence lengths in the batch. + x_kv: (batch, seqlen, hidden_dim), only applicable for cross-attention. If None, use x. + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into x. Only applicable when using + FlashAttention. + max_seqlen: int. Maximum sequence length in the batch. + key_padding_mask: boolean mask, True means to keep, False means to mask out. + (batch, seqlen). Only applicable when not using FlashAttention. + mixer_subset: for cross-attention only. If not None, will take a subset of x + before applying the query projection. Useful for e.g., ViT where we only care + about the CLS token in the last layer. + inference_params: for generation. Adapted from Megatron-LM (and Apex) + https://github.com/NVIDIA/apex/blob/3ff1a10f72ec07067c4e44759442329804ac5162/apex/transformer/testing/standalone_transformer_lm.py#L470 + """ + if cu_seqlens is not None: + assert max_seqlen is not None + assert key_padding_mask is None + assert self.use_flash_attn + assert not self.dwconv + assert self.rotary_emb_dim == 0 + if key_padding_mask is not None: + assert cu_seqlens is None + assert max_seqlen is None + assert not self.use_flash_attn + if inference_params is not None: + assert key_padding_mask is None + assert cu_seqlens is None and max_seqlen is None + assert not self.dwconv + + kwargs = ( + {"cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen, **kwargs} + if self.use_flash_attn + else {"key_padding_mask": key_padding_mask, **kwargs} + ) + seqlen_offset = ( + 0 + if inference_params is None + else ( + inference_params.lengths_per_sample + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + ) + rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None + batch, seqlen = x.shape[:2] + if not self.cross_attn and self.num_heads_kv == self.num_heads: + assert x_kv is None and mixer_subset is None + if not self.return_residual: + qkv = self.Wqkv(x) + else: + qkv, x = self.Wqkv(x) + if self.dwconv: + qkv = rearrange( + self.dwconv_qkv(rearrange(qkv, "b s d -> b d s"))[..., :-2], "b d s -> b s d" + ).contiguous() + qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim) + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + qkv = self.rotary_emb( + qkv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_attn(qkv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, **kwargs) + else: + context = self._update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + context = self._apply_rotary_update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + if self.cross_attn: + if not self.return_residual: + q = self.Wq(x if mixer_subset is None else x[:, mixer_subset]) + kv = self.Wkv(x_kv if x_kv is not None else x) + else: + if x_kv is not None: + kv, x_kv = self.Wkv(x_kv) + else: + kv, x = self.Wkv(x) + q = self.Wq(x if mixer_subset is None else x[:, mixer_subset]) + else: + assert self.num_heads_kv != self.num_heads + if not self.return_residual: + qkv = self.Wqkv(x) + else: + qkv, x = self.Wqkv(x) + q = qkv[..., : self.num_heads * self.head_dim] + kv = qkv[..., self.num_heads * self.head_dim :] + q = rearrange(q, "... (h d) -> ... h d", d=self.head_dim) + kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim) + if self.dwconv: + q = rearrange( + self.dwconv_q(rearrange(q, "b s d -> b d s"))[..., :-2], "b d s -> b s d" + ).contiguous() + kv = rearrange( + self.dwconv_kv(rearrange(kv, "b s d -> b d s"))[..., :-2], "b d s -> b s d" + ).contiguous() + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + q, kv = self.rotary_emb( + q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_cross_attn(q, kv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint( + self.inner_cross_attn, q, kv, **kwargs + ) + else: + context = self._update_kvcache_attention(q, kv, inference_params) + else: + context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params) + out = self.out_proj(rearrange(context, "... h d -> ... (h d)")) + return out if not self.return_residual else (out, x) + + +class ParallelMHA(nn.Module): + """Multi-head self-attention and cross-attention""" + + def __init__( + self, + embed_dim, + num_heads, + process_group, + num_heads_kv=None, + qkv_proj_bias=True, + out_proj_bias=True, + dropout=0.0, + softmax_scale=None, + causal=False, + layer_idx=None, + rotary_emb_dim=0, + rotary_emb_base=10000.0, + rotary_emb_scale_base=None, + rotary_emb_interleaved=False, + use_alibi=False, + window_size=(-1, -1), + use_flash_attn=False, + checkpointing=False, + sequence_parallel=True, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.embed_dim = embed_dim + self.causal = causal + self.layer_idx = layer_idx + self.rotary_emb_dim = rotary_emb_dim + self.use_flash_attn = use_flash_attn + self.checkpointing = checkpointing + self.process_group = process_group + self.world_size = process_group.size() + self.local_rank = torch.distributed.get_rank(process_group) + + self.num_heads = num_heads + assert self.embed_dim % self.num_heads == 0, "embed_dim must be divisible by num_heads" + + self.num_heads_kv = num_heads_kv if num_heads_kv is not None else num_heads + assert ( + self.num_heads % self.num_heads_kv == 0 + ), "num_heads must be divisible by num_heads_kv" + + self.num_heads_per_rank = get_dim_for_local_rank( + self.num_heads, self.world_size, self.local_rank + ) + self.num_heads_kv_per_rank = get_dim_for_local_rank( + self.num_heads_kv, self.world_size, self.local_rank + ) + self.head_dim = self.embed_dim // num_heads + qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv) + + if use_alibi: + assert use_flash_attn, "ALiBi code path requires flash_attn" + num_heads_local = math.ceil(self.num_heads / self.world_size) + alibi_slopes = torch.tensor( + get_alibi_slopes(num_heads)[ + self.local_rank * num_heads_local : (self.local_rank + 1) * num_heads_local + ], + device=device, + ) + else: + alibi_slopes = None + if window_size != (-1, -1): + assert use_flash_attn, "Local (sliding window) attention code path requires flash_attn" + + if self.rotary_emb_dim > 0: + assert RotaryEmbedding is not None, "rotary_emb is not installed" + self.rotary_emb = RotaryEmbedding( + self.rotary_emb_dim, + base=rotary_emb_base, + scale_base=rotary_emb_scale_base, + interleaved=rotary_emb_interleaved, + device=device, + ) + + if ColumnParallelLinear is None or RowParallelLinear is None: + raise ImportError("fused_dense is not installed") + self.Wqkv = ColumnParallelLinear( + embed_dim, + qkv_dim, + process_group, + bias=qkv_proj_bias, + sequence_parallel=sequence_parallel, + multiple_of=self.head_dim * (self.num_heads // self.num_heads_kv + 2), + **factory_kwargs, + ) + inner_attn_cls = ( + partial(FlashSelfAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else SelfAttention + ) + inner_cross_attn_cls = ( + partial(FlashCrossAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else CrossAttention + ) + self.inner_attn = inner_attn_cls( + causal=causal, softmax_scale=softmax_scale, attention_dropout=dropout + ) + self.inner_cross_attn = inner_cross_attn_cls( + causal=causal, softmax_scale=softmax_scale, attention_dropout=dropout + ) + self.out_proj = RowParallelLinear( + embed_dim, + embed_dim, + process_group, + bias=out_proj_bias, + sequence_parallel=sequence_parallel, + multiple_of=self.head_dim, + **factory_kwargs, + ) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None): + dtype = self.out_proj.weight.dtype if dtype is None else dtype + device = self.out_proj.weight.device + return torch.empty( + batch_size, + max_seqlen, + 2, + self.num_heads_kv_per_rank, + self.head_dim, + dtype=dtype, + device=device, + ) + + def _update_kv_cache(self, kv, inference_params): + """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)""" + assert self.layer_idx is not None, "Generation requires layer_idx in the constructor" + return _update_kv_cache(kv, inference_params, self.layer_idx) + + def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params): + """ + Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention. + q: (batch_size, seqlen_q, nheads, head_dim) + kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim) + """ + assert inference_params is not None and inference_params.seqlen_offset > 0 + assert self.use_flash_attn + if self.rotary_emb_dim > 0: + assert self.rotary_emb.scale is None, "This code path does not support xPos" + self.rotary_emb._update_cos_sin_cache( + inference_params.max_seqlen, device=q.device, dtype=q.dtype + ) + rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached + else: + rotary_cos, rotary_sin = None, None + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + context = flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + rotary_cos=rotary_cos, + rotary_sin=rotary_sin, + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False, + alibi_slopes=alibi_slopes, + ) + return context + + def _update_kvcache_attention(self, q, kv, inference_params): + """Write kv to inference_params, then do attention""" + if inference_params.seqlen_offset == 0 or not self.use_flash_attn: + # TODO: this only uses seqlen_offset and not lengths_per_sample. + kv = self._update_kv_cache(kv, inference_params) + return self.inner_cross_attn(q, kv) + else: + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + context = flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + alibi_slopes=alibi_slopes, + ) + return context + + def forward(self, x, seqlen=None, inference_params=None, **kwargs): + """ + Arguments: + x: (batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim) if seqlen=None. + If seqlen is not None, x is (batch * seqlen, hidden_dim). This is so that when we + split x during sequence parallel, we split the batch * seqlen dimension + (in case batch is small). + """ + qkv = self.Wqkv(x) + if seqlen is not None: + qkv = rearrange(qkv, "(b s) ... -> b s ...", s=seqlen) + seqlen_offset = ( + 0 + if inference_params is None + else ( + inference_params.lengths_per_sample + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + ) + rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None + if self.num_heads_kv == self.num_heads: + qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, d=self.head_dim) + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + qkv = self.rotary_emb( + qkv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_attn(qkv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, **kwargs) + else: + context = self._update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + context = self._apply_rotary_update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + q = rearrange( + qkv[..., : self.num_heads_per_rank * self.head_dim], + "... (h d) -> ... h d", + d=self.head_dim, + ) + kv = rearrange( + qkv[..., self.num_heads_per_rank * self.head_dim :], + "... (two hkv d) -> ... two hkv d", + two=2, + d=self.head_dim, + ) + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + q, kv = self.rotary_emb( + q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_cross_attn(q, kv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint( + self.inner_cross_attn, q, kv, **kwargs + ) + else: + context = self._update_kvcache_attention(q, kv, inference_params) + else: + context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params) + context = rearrange(context, "b s h d -> b s (h d)") + if seqlen is not None: + context = rearrange(context, "b s d -> (b s) d") + out = self.out_proj(context) + return out diff --git a/lib/python3.11/site-packages/flash_attn/modules/mlp.py b/lib/python3.11/site-packages/flash_attn/modules/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..23584d3098a245bcb2b09653bdf0f426eb63bde2 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/modules/mlp.py @@ -0,0 +1,191 @@ +# Copyright (c) 2023, Tri Dao. + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.distributed import ProcessGroup + + +try: + from flash_attn.ops.activations import swiglu +except ImportError: + swiglu = None + +try: + from flash_attn.ops.fused_dense import ColumnParallelLinear, RowParallelLinear +except ImportError: + ColumnParallelLinear, RowParallelLinear = None, None + +try: + from flash_attn.ops.fused_dense import FusedMLP, ParallelFusedMLP +except ImportError: + FusedMLP, ParallelFusedMLP = None, None + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation=F.gelu, + bias1=True, + bias2=True, + return_residual=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features if out_features is not None else in_features + hidden_features = hidden_features if hidden_features is not None else in_features * 4 + self.return_residual = return_residual + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs) + self.activation = activation + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x): + y = self.fc1(x) + y = self.activation(y) + y = self.fc2(y) + return y if not self.return_residual else (y, x) + + +class ParallelMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation=F.gelu, + process_group: ProcessGroup = None, + sequence_parallel=True, + bias1=True, + bias2=True, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + assert ColumnParallelLinear is not None, "Need to install fused_dense" + assert RowParallelLinear is not None, "Need to install fused_dense" + out_features = out_features if out_features is not None else in_features + hidden_features = hidden_features if hidden_features is not None else in_features * 4 + self.fc1 = ColumnParallelLinear( + in_features, + hidden_features, + process_group, + bias=bias1, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + self.activation = activation + self.fc2 = RowParallelLinear( + hidden_features, + out_features, + process_group, + bias=bias2, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + + def forward(self, x): + y = self.fc1(x) + y = self.activation(y) + y = self.fc2(y) + return y + + +class GatedMlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation=F.sigmoid, + bias1=True, + bias2=True, + multiple_of=128, + return_residual=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features if out_features is not None else in_features + hidden_features = ( + hidden_features if hidden_features is not None else int(8 * in_features / 3) + ) + hidden_features = (hidden_features + multiple_of - 1) // multiple_of * multiple_of + self.return_residual = return_residual + self.fc1 = nn.Linear(in_features, 2 * hidden_features, bias=bias1, **factory_kwargs) + self.activation = activation + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x): + y = self.fc1(x) + if self.activation == F.sigmoid: # Special case for GLU + y = F.glu(y, dim=-1) + elif self.activation == F.silu and swiglu is not None: # Special case for SwiGLU + y, gate = y.chunk(2, dim=-1) + y = swiglu(gate, y) + else: + y, gate = y.chunk(2, dim=-1) + y = y * self.activation(gate) + y = self.fc2(y) + return y if not self.return_residual else (y, x) + + +class ParallelGatedMlp(nn.Module): + """Parallel GatedMlp""" + + def __init__( + self, + in_features, + process_group, + hidden_features=None, + out_features=None, + activation=F.sigmoid, + bias1=True, + bias2=True, + multiple_of=128, + sequence_parallel=True, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features if out_features is not None else in_features + hidden_features = ( + hidden_features if hidden_features is not None else int(8 * in_features / 3) + ) + hidden_features = (hidden_features + multiple_of - 1) // multiple_of * multiple_of + if ColumnParallelLinear is None or RowParallelLinear is None: + raise ImportError("fused_dense is not installed") + self.fc1 = ColumnParallelLinear( + in_features, + 2 * hidden_features, + process_group, + bias=bias1, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + self.activation = activation + self.fc2 = RowParallelLinear( + hidden_features, + out_features, + process_group, + bias=bias2, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + + def forward(self, x): + y = self.fc1(x) + if self.activation == F.sigmoid: # Special case for GLU + y = F.glu(y, dim=-1) + else: + y, gate = y.chunk(2, dim=-1) + y = y * self.activation(gate) + y = self.fc2(y) + return y diff --git a/lib/python3.11/site-packages/flash_attn/ops/__init__.py b/lib/python3.11/site-packages/flash_attn/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/flash_attn/ops/activations.py b/lib/python3.11/site-packages/flash_attn/ops/activations.py new file mode 100644 index 0000000000000000000000000000000000000000..7c09649fc41e12d5a360c5672825d8380bc7ec80 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/activations.py @@ -0,0 +1,135 @@ +# Copied from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/model/layers/activations.py +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# 1/sqrt(2*pi)-> 0.3989423 +# 1/sqrt(2) -> 0.70710678 +# sqrt(2/pi) -> 0.79788456 + +# this function is tanh approximation of gelu +# actual gelu is: +# x * 0.5 * (1.0 + torch.erf(x * 0.70710678)) +@torch.jit.script +def bias_gelu(y, bias): + x = bias + y + return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=y.dtype) + + +# gradient of tanh approximation of gelu +# gradient of actual gelu is: +# 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x) +@torch.jit.script +def bias_gelu_back(g, y, bias): + """Assume that y has shape (B, D) and bias has shape (D)""" + x = bias + y + tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)) + # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243 + ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * ( + 1 + tanh_out + ) + grad_y = ff * g + return grad_y.to(dtype=y.dtype), grad_y.sum(dim=(0), dtype=bias.dtype) + + +class GeLUFunction(torch.autograd.Function): + @staticmethod + # bias is an optional argument + def forward(ctx, input, bias): + ctx.save_for_backward(input, bias) + return bias_gelu(input, bias) + + @staticmethod + def backward(ctx, grad_output): + input, bias = ctx.saved_tensors + tmp = bias_gelu_back(grad_output, input, bias) + return tmp, tmp + + +bias_gelu_impl = GeLUFunction.apply + +# this function is tanh approximation of gelu +# actual gelu is: +# x * 0.5 * (1.0 + torch.erf(x * 0.70710678)) +@torch.jit.script +def gelu_fwd(x): + return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=x.dtype) + + +# gradient of tanh approximation of gelu +# gradient of actual gelu is: +# 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x) +@torch.jit.script +def gelu_bwd(g, x): + tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)) + # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243 + ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * ( + 1 + tanh_out + ) + return (ff * g).to(dtype=x.dtype) + + +class FastGeLUFunction(torch.autograd.Function): + @staticmethod + # bias is an optional argument + def forward(ctx, input): + ctx.save_for_backward(input) + return gelu_fwd(input) + + @staticmethod + def backward(ctx, grad_output): + (input,) = ctx.saved_tensors + tmp = gelu_bwd(grad_output, input) + return tmp + + +fast_gelu_impl = FastGeLUFunction.apply + + +@torch.jit.script +def relu_bwd(g, x): + return torch.where(x >= 0, g, 0.0).to(dtype=x.dtype) + + +@torch.jit.script +def sqrelu_fwd(x): + r = F.relu(x) + return (r * r).to(dtype=x.dtype) + + +@torch.jit.script +def sqrelu_bwd(g, x): + return (2.0 * g * F.relu(x)).to(dtype=x.dtype) + + +swiglu_fwd_codestring = """ +template T swiglu_fwd(T x, T y) { + return float(x) * float(y) / (1.0f + ::exp(-float(x))); +} +""" +swiglu_bwd_codestring = """ +template void swiglu_bwd(T x, T y, T g, T& dx, T& dy) { + float x_sigmoid = 1.0f / (1.0f + ::exp(-float(x))); + dx = x_sigmoid * (1 + float(x) * (1.0f - x_sigmoid)) * float(g) * float(y); + dy = float(x) * x_sigmoid * float(g); +} +""" +swiglu_fwd = torch.cuda.jiterator._create_jit_fn(swiglu_fwd_codestring) +swiglu_bwd = torch.cuda.jiterator._create_multi_output_jit_fn(swiglu_bwd_codestring, num_outputs=2) + + +class SwiGLUFunction(torch.autograd.Function): + + @staticmethod + def forward(ctx, x, y): + ctx.save_for_backward(x, y) + return swiglu_fwd(x, y) + + @staticmethod + def backward(ctx, dout): + x, y = ctx.saved_tensors + return swiglu_bwd(x, y, dout) + +swiglu = SwiGLUFunction.apply diff --git a/lib/python3.11/site-packages/flash_attn/ops/fused_dense.py b/lib/python3.11/site-packages/flash_attn/ops/fused_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..1e45b8e609812a1545781011141ec80f6dc3af0f --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/fused_dense.py @@ -0,0 +1,688 @@ +# Copyright (c) 2023, Tri Dao. +# Inspired by https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py +# We make it work with pytorch amp and with bfloat16. +# The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py +from functools import partial +from typing import Optional + +# import fused_dense_cuda # from apex +import fused_dense_lib as fused_dense_cuda +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torch.cuda.amp import custom_bwd, custom_fwd +from torch.distributed import ProcessGroup + +from flash_attn.ops.activations import gelu_bwd, relu_bwd, sqrelu_bwd, sqrelu_fwd +from flash_attn.utils.distributed import ( + all_gather_raw, + all_reduce, + all_reduce_raw, + reduce_scatter, + reduce_scatter_raw, +) + + +class FusedDenseFunc(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward( + ctx, x, weight, bias, return_residual=False, process_group=None, sequence_parallel=True + ): + """ + If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel + with sequence parallelism: we do an all_gather_raw of x before doing the matmul. + """ + ctx.compute_weight_gradient = weight.requires_grad + ctx.return_residual = return_residual + ctx.process_group = process_group + ctx.sequence_parallel = sequence_parallel + + if torch.is_autocast_enabled(): + x = x.to(dtype=torch.get_autocast_gpu_dtype()) + x = x.contiguous() + if process_group is not None and sequence_parallel: + # We want to kick off the all_gather early, before weight dtype conversion + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + else: + total_x = x + + if torch.is_autocast_enabled(): + weight = weight.to(dtype=torch.get_autocast_gpu_dtype()) + bias = bias.to(dtype=torch.get_autocast_gpu_dtype()) if bias is not None else None + weight = weight.contiguous() + if process_group is not None and sequence_parallel: + handle_x.wait() + batch_shape, n = total_x.shape[:-1], total_x.shape[-1] + batch_dim = batch_shape.numel() + # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174 + if min(batch_dim, n, *weight.shape) > 65535 * 32: + raise RuntimeError("fused_dense only supports matrix dims <= 2M") + output = F.linear(total_x, weight, bias) + if ctx.compute_weight_gradient: + ctx.save_for_backward(x, weight) + else: + ctx.save_for_backward(weight) + return output if not return_residual else (output, x) + + @staticmethod + @custom_bwd + def backward(ctx, grad_output, *args): + grad_output = grad_output.contiguous() + if ctx.return_residual: + (grad_input,) = args + grad_input = grad_input.contiguous() + process_group = ctx.process_group + sequence_parallel = ctx.sequence_parallel + if ctx.compute_weight_gradient: + x, weight = ctx.saved_tensors + if process_group is not None and sequence_parallel: + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + else: + total_x = x + else: + (weight,) = ctx.saved_tensors + total_x = None + batch_shape = grad_output.shape[:-1] + batch_dim = batch_shape.numel() + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + if ctx.needs_input_grad[0]: + if not ctx.return_residual: + grad_input = F.linear(grad_output, weight.t()) + else: + grad_input = torch.addmm( + grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_output, weight + ) + grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1]) + if process_group is not None: + reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw + grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True) + else: + grad_input = None + if ctx.needs_input_grad[1]: + assert ctx.compute_weight_gradient + if process_group is not None and sequence_parallel: + handle_x.wait() + grad_weight, grad_bias = fused_dense_cuda.linear_bias_wgrad( + total_x.reshape(batch_dim, total_x.shape[-1]), grad_output, ctx.needs_input_grad[2] + ) + else: + grad_weight = None + grad_bias = grad_output if ctx.needs_input_grad[2] else None + if process_group is not None and ctx.needs_input_grad[0]: + handle_grad_input.wait() + return grad_input, grad_weight, grad_bias, None, None, None + + +def fused_dense_func( + x: Tensor, + weight: Tensor, + bias: Optional[Tensor] = None, + return_residual: bool = False, + process_group: Optional[ProcessGroup] = None, + sequence_parallel: bool = True, +): + dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or ( + x.dtype == torch.float32 and torch.is_autocast_enabled() + ) + if x.is_cuda and weight.is_cuda and (bias is None or bias.is_cuda) and dtype_eligible: + return FusedDenseFunc.apply( + x, weight, bias, return_residual, process_group, sequence_parallel + ) + else: + assert process_group is None + out = F.linear(x, weight, bias) + return out if not return_residual else (out, x) + + +class FusedDense(nn.Linear): + def __init__( + self, + in_features: int, + out_features: int, + bias: bool = True, + return_residual: bool = False, + device=None, + dtype=None, + ) -> None: + super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype) + self.return_residual = return_residual + + def forward(self, x, process_group=None): + """ + If process_group is not None, we're doing Tensor Parallel with sequence parallelism: + we do an all_gather of x before doing the matmul. + """ + return fused_dense_func( + x, + self.weight, + self.bias, + return_residual=self.return_residual, + process_group=process_group, + ) + + +class ColumnParallelLinear(nn.Linear): + def __init__( + self, + in_features: int, + out_features: int, + process_group: ProcessGroup, + bias: bool = True, + sequence_parallel=True, + multiple_of=1, + device=None, + dtype=None, + ) -> None: + world_size = torch.distributed.get_world_size(process_group) + if out_features % multiple_of: + raise ValueError(f"out_features ({out_features}) must be a multiple of {multiple_of}") + multiple = out_features // multiple_of + # We want to split @multiple across world_size, but it could be an uneven split + div = multiple // world_size + mod = multiple % world_size + # The first @mod ranks get @div + 1 copies, the rest get @div copies + local_multiple = div + int(torch.distributed.get_rank(process_group) < mod) + super().__init__( + in_features, local_multiple * multiple_of, bias=bias, device=device, dtype=dtype + ) + self.process_group = process_group + self.sequence_parallel = sequence_parallel + + def forward(self, x): + # If self.sequence_parallel is True, we're doing Tensor Parallel with sequence parallelism: + # we do an all_gather of x before doing the matmul. + # If not, then the input is already gathered. + return fused_dense_func( + x, + self.weight, + self.bias, + process_group=self.process_group, + sequence_parallel=self.sequence_parallel, + ) + + +class RowParallelLinear(nn.Linear): + def __init__( + self, + in_features: int, + out_features: int, + process_group: ProcessGroup, + bias: bool = True, + sequence_parallel=True, + multiple_of=1, + device=None, + dtype=None, + ) -> None: + world_size = torch.distributed.get_world_size(process_group) + rank = torch.distributed.get_rank(process_group) + if in_features % multiple_of: + raise ValueError(f"in_features ({in_features}) must be a multiple of {multiple_of}") + multiple = in_features // multiple_of + # We want to split @multiple across world_size, but it could be an uneven split + div = multiple // world_size + mod = multiple % world_size + # The first @mod ranks get @div + 1 copies, the rest get @div copies + local_multiple = div + int(torch.distributed.get_rank(process_group) < mod) + # Only rank 0 will have bias + super().__init__( + local_multiple * multiple_of, + out_features, + bias=bias and rank == 0, + device=device, + dtype=dtype, + ) + self.process_group = process_group + self.sequence_parallel = sequence_parallel + + def forward(self, x): + """ + We're doing Tensor Parallel with sequence parallelism: we do the matmul and then + a reduce_scatter of the result. + """ + out = fused_dense_func(x, self.weight, self.bias) + reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce + return reduce_fn(out, self.process_group) + + +class FusedMLPFunc(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward( + ctx, + x, + weight1, + bias1, + weight2, + bias2, + activation="gelu_approx", + save_pre_act=True, + return_residual=False, + checkpoint_lvl=0, + heuristic=0, + process_group=None, + sequence_parallel=True, + ): + """ + If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel + with sequence parallelism: we do an all_gather of x before doing the matmul. + If sequence_parallel=False, then the input is already gathered. + + checkpoint_lvl: + 0: no recomputation in the bwd + 1: recompute gelu_out / relu_out in the bwd + 2: recompute pre_act and gelu_out / relu_out in the bwd + """ + assert -1 <= heuristic <= 4 + assert activation in ["gelu_approx", "relu", "sqrelu"] + if activation == "sqrelu": + assert heuristic == -1 + if not save_pre_act: + checkpoint_lvl = 2 + assert checkpoint_lvl in [0, 1, 2] + ctx.return_residual = return_residual + ctx.process_group = process_group + ctx.sequence_parallel = sequence_parallel + ctx.checkpoint_lvl = checkpoint_lvl + ctx.activation = activation + ctx.heuristic = heuristic + + if torch.is_autocast_enabled(): + x = x.to(dtype=torch.get_autocast_gpu_dtype()) + x = x.contiguous() + if process_group is not None and sequence_parallel: + # We want to kick off the all_gather early, before weight dtype conversion + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + else: + total_x = x + + if torch.is_autocast_enabled(): + dtype = torch.get_autocast_gpu_dtype() + weight1, weight2 = [a.to(dtype=dtype) for a in [weight1, weight2]] + bias1 = bias1.to(dtype=dtype) if bias1 is not None else None + bias2 = bias2.to(dtype=dtype) if bias2 is not None else None + weight1 = weight1.contiguous() + bias1 = bias1.contiguous() if bias1 is not None else None + weight2 = weight2.contiguous() + bias2 = bias2.contiguous() if bias2 is not None else None + if process_group is not None and sequence_parallel: + handle_x.wait() + batch_shape, n = total_x.shape[:-1], total_x.shape[-1] + batch_dim = batch_shape.numel() + # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174 + if min(batch_dim, n, *weight1.shape, *weight2.shape) > 65535 * 32: + raise RuntimeError("fused_dense only supports matrix dims <= 2M") + if heuristic == -1: + pre_act = F.linear(total_x, weight1, bias1) + activation_fn = ( + partial(F.gelu, approximate="tanh") + if activation == "gelu_approx" + else (sqrelu_fwd if activation == "sqrelu" else F.relu) + ) + with torch.jit.fuser("fuser2"): + output1 = activation_fn(pre_act) + # This is before adding bias1 + # pre_act = F.linear(total_x.reshape(batch_dim, n), weight1) + # with torch.jit.fuser('fuser2'): + # output1 = bias_gelu(pre_act, bias1) + else: + is_gelu = activation == "gelu_approx" + output1, *rest = fused_dense_cuda.linear_act_forward( + total_x.reshape(batch_dim, n), weight1, bias1, is_gelu, save_pre_act, heuristic + ) + if save_pre_act: + pre_act = rest[0] + output2 = F.linear(output1, weight2, bias2) + if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"): + # For RELU the pre_act is very small (just a bit-mask) so we just save it + ctx.save_for_backward(x, weight1, weight2, pre_act, output1) + elif checkpoint_lvl == 1: + ctx.save_for_backward(x, weight1, weight2, pre_act) + elif checkpoint_lvl == 2: + ctx.save_for_backward(x, weight1, weight2, bias1) + output2 = output2.reshape(*batch_shape, output2.shape[-1]) + return output2 if not return_residual else (output2, x) + + @staticmethod + @custom_bwd + def backward(ctx, grad_output, *args): + grad_output = grad_output.contiguous() + checkpoint_lvl = ctx.checkpoint_lvl + activation = ctx.activation + activation_fn = ( + partial(F.gelu, approximate="tanh") + if activation == "gelu_approx" + else (sqrelu_fwd if activation == "sqrelu" else F.relu) + ) + if ctx.return_residual: + (grad_input,) = args + grad_input = grad_input.contiguous() + process_group = ctx.process_group + sequence_parallel = ctx.sequence_parallel + x, weight1, weight2, *rest = ctx.saved_tensors + if process_group is None or not sequence_parallel: + total_x = x + batch_shape = grad_output.shape[:-1] + batch_dim = batch_shape.numel() + if checkpoint_lvl in [0, 1]: + if process_group is not None and sequence_parallel: + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"): + pre_act, output1 = rest + elif checkpoint_lvl == 1: + (pre_act,) = rest + with torch.jit.fuser("fuser2"): + output1 = activation_fn(pre_act) + elif checkpoint_lvl == 2: + (bias1,) = rest + if process_group is not None and sequence_parallel: + total_x, _ = all_gather_raw(x, process_group) + if ctx.heuristic == -1: + pre_act = F.linear(total_x, weight1, bias1) + with torch.jit.fuser("fuser2"): + output1 = activation_fn(pre_act) + else: + output1, pre_act = fused_dense_cuda.linear_act_forward( + total_x.reshape(batch_dim, total_x.shape[-1]), + weight1, + bias1, + activation == "gelu_approx", + True, + ctx.heuristic, + ) + + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + output1 = output1.reshape(batch_dim, output1.shape[-1]) + pre_act = pre_act.reshape(batch_dim, pre_act.shape[-1]) + if ctx.needs_input_grad[3]: + grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad( + output1, grad_output, ctx.needs_input_grad[4] + ) + else: + grad_weight2 = None + grad_bias2 = grad_output if ctx.needs_input_grad[4] else None + if ctx.heuristic == -1: + # grad_pre_act = matmul_dgelu(grad_output, weight2, pre_act) + grad_output1 = F.linear(grad_output, weight2.t()) + activation_grad_fn = ( + gelu_bwd + if activation == "gelu_approx" + else (sqrelu_bwd if activation == "sqrelu" else relu_bwd) + ) + with torch.jit.fuser("fuser2"): + grad_pre_act = activation_grad_fn(grad_output1, pre_act) + else: + # The cublasLt epilogue has to compute both gelu/relu grad and bias grad, we can't + # just compute gelu/relu grad + grad_pre_act, grad_bias1 = fused_dense_cuda.bias_act_linear_dgrad_bgrad( + weight2, grad_output, pre_act, activation == "gelu_approx", ctx.heuristic + ) + if not ctx.needs_input_grad[2]: + grad_bias1 = None + if ctx.needs_input_grad[0]: + if not ctx.return_residual: + grad_input = F.linear(grad_pre_act, weight1.t()) + else: + grad_input = torch.addmm( + grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_pre_act, weight1 + ) + grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1]) + if process_group is not None: + reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw + grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True) + else: + grad_input = None + if ctx.heuristic == -1: + if ctx.needs_input_grad[1]: + if process_group is not None and sequence_parallel and checkpoint_lvl != 2: + handle_x.wait() + grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_wgrad( + total_x.reshape(batch_dim, total_x.shape[-1]), + grad_pre_act, + ctx.needs_input_grad[2], + ) + else: + grad_weight1 = None + grad_bias1 = grad_pre_act if ctx.needs_input_grad[2] else None + else: + if ctx.needs_input_grad[1]: + if process_group is not None and sequence_parallel and checkpoint_lvl != 2: + handle_x.wait() + grad_weight1 = F.linear( + grad_pre_act.t(), total_x.reshape(batch_dim, total_x.shape[-1]).t() + ) + else: + grad_weight1 = None + if process_group is not None and ctx.needs_input_grad[0]: + handle_grad_input.wait() + return ( + grad_input, + grad_weight1, + grad_bias1, + grad_weight2, + grad_bias2, + None, + None, + None, + None, + None, + None, + None, + ) + + +def fused_mlp_func( + x: Tensor, + weight1: Tensor, + weight2: Tensor, + bias1: Optional[Tensor] = None, + bias2: Optional[Tensor] = None, + activation: str = "gelu_approx", + save_pre_act: bool = True, + return_residual: bool = False, + checkpoint_lvl: int = 0, + heuristic: int = 0, + process_group: Optional[ProcessGroup] = None, + sequence_parallel: bool = True, +): + assert activation in ["gelu_approx", "relu", "sqrelu"] + dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or ( + x.dtype == torch.float32 and torch.is_autocast_enabled() + ) + # If we save pre-activation, dimension must be divisible by 128 (relu) or 8 (gelu) + dim_eligible = not save_pre_act or (x.shape[-1] % (128 if activation == "relu" else 8) == 0) + if ( + x.is_cuda + and weight1.is_cuda + and weight2.is_cuda + and (bias1 is None or bias1.is_cuda) + and (bias2 is None or bias2.is_cuda) + and dtype_eligible + and dim_eligible + ): + return FusedMLPFunc.apply( + x, + weight1, + bias1, + weight2, + bias2, + activation, + save_pre_act, + return_residual, + checkpoint_lvl, + heuristic, + process_group, + sequence_parallel, + ) + else: + assert process_group is None + pre_act = F.linear(x, weight1, bias1) + activation_fn = ( + partial(F.gelu, approximate="tanh") + if activation == "gelu_approx" + else partial(F.relu, inplace=True) + ) + output1 = activation_fn(pre_act) + output2 = F.linear(output1, weight2, bias2) + return output2 if not return_residual else (output2, x) + + +class FusedMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + bias1=True, + bias2=True, + activation="gelu_approx", + return_residual=False, + checkpoint_lvl=0, + heuristic="auto", + device=None, + dtype=None, + ): + """ + If process_group is not None, we're doing Tensor Parallel with sequence parallelism: + we do an all_gather of x before doing the matmul, gelu, then matmul. + Finally we do a reduce_scatter of the output. + + checkpoint_lvl (increasing lvl means slower but more memory saving): + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute pre_act and gelu_out in the bwd + heuristic: + -1: don't fuse gemm + gelu (separate kernel) + 0..4: use this heuristic for the algo section in the fused gemm + gelu + 'auto': heuristic will be picked automatically: + For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf. + For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16. + For H100, we set heuristic=-1 for both fp16 and bf16 as the fused cuBlasLt implementation + is slower than the unfused version. + return_residual: whether to return the input x along with the output. This is for + performance reason: for post-norm architecture, returning the input allows us + to fuse the backward of nn.Linear with the residual connection. + """ + assert checkpoint_lvl in [0, 1, 2] + assert activation in ["gelu_approx", "relu", "sqrelu"] + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features * 4 + self.activation = activation + self.return_residual = return_residual + self.checkpoint_lvl = checkpoint_lvl + self.heuristic = heuristic if activation != "sqrelu" else -1 + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs) + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x, process_group=None): + dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype() + if self.heuristic == "auto": + if self.activation == "gelu_approx": + if torch.cuda.get_device_capability("cuda") == (9, 0): + heuristic = -1 + else: + cuda_ver = tuple(map(int, torch.version.cuda.split("."))) + heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1) + else: + heuristic = 0 + else: + heuristic = self.heuristic + out = fused_mlp_func( + x, + self.fc1.weight, + self.fc2.weight, + self.fc1.bias, + self.fc2.bias, + activation=self.activation, + save_pre_act=self.training, + return_residual=self.return_residual, + checkpoint_lvl=self.checkpoint_lvl, + heuristic=heuristic, + process_group=process_group, + ) + if self.return_residual: + out, x = out + if process_group is not None: + out = reduce_scatter(out, process_group) + return out if not self.return_residual else (out, x) + + +class ParallelFusedMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation="gelu_approx", + process_group: ProcessGroup = None, + bias1=True, + bias2=True, + sequence_parallel=True, + checkpoint_lvl=0, + heuristic="auto", + device=None, + dtype=None, + ): + """ + process_group is required. We're doing Tensor Parallel with sequence parallelism: + we do an all_gather of x before doing the matmul, gelu, then matmul. + Finally we do a reduce_scatter of the output. + + checkpoint_lvl (increasing lvl means slower but more memory saving): + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute pre_act and gelu_out in the bwd + heuristic: + -1: don't fuse gemm + gelu (separate kernel) + 0..4: use this heuristic for the algo section in the fused gemm + gelu + 'auto': heuristic will be picked automatically: + For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf. + For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16. + """ + assert checkpoint_lvl in [0, 1, 2] + assert activation in ["gelu_approx", "relu", "sqrelu"] + assert process_group is not None + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features * 4 + self.activation = activation + self.process_group = process_group + self.sequence_parallel = sequence_parallel + self.checkpoint_lvl = checkpoint_lvl + self.heuristic = heuristic if activation != "sqrelu" else -1 + self.fc1 = ColumnParallelLinear( + in_features, hidden_features, process_group, bias=bias1, **factory_kwargs + ) + self.fc2 = RowParallelLinear( + hidden_features, out_features, process_group, bias=bias2, **factory_kwargs + ) + + def forward(self, x): + dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype() + if self.heuristic == "auto": + if self.activation == "gelu_approx": + cuda_ver = tuple(map(int, torch.version.cuda.split("."))) + heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1) + else: + heuristic = 0 + else: + heuristic = self.heuristic + out = fused_mlp_func( + x, + self.fc1.weight, + self.fc2.weight, + self.fc1.bias, + self.fc2.bias, + activation=self.activation, + save_pre_act=self.training, + checkpoint_lvl=self.checkpoint_lvl, + heuristic=heuristic, + process_group=self.process_group, + sequence_parallel=self.sequence_parallel, + ) + reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce + return reduce_fn(out, self.process_group) diff --git a/lib/python3.11/site-packages/flash_attn/ops/layer_norm.py b/lib/python3.11/site-packages/flash_attn/ops/layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6cd798fd02844ef9cd3897f8ab95e490e638bf --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/layer_norm.py @@ -0,0 +1,800 @@ +# Copyright (c) 2022, Tri Dao. +# Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py + +import dropout_layer_norm +import torch +from torch.nn import init + + +def maybe_align(x, alignment_in_bytes=16): + """Assume that x already has last dim divisible by alignment_in_bytes""" + # TD [2023-07-04] I'm not 100% sure that clone will align the memory + # https://discuss.pytorch.org/t/how-to-ensure-that-tensor-data-ptr-is-aligned-to-16-bytes/183440 + return x if x.data_ptr() % alignment_in_bytes == 0 else x.clone() + + +def _dropout_add_layer_norm_forward( + x0, + residual, + gamma, + beta, + rowscale, + colscale, + dropout_p, + epsilon, + residual_in_fp32=False, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes""" + hidden_size = gamma.numel() + x0mat = x0.view((-1, hidden_size)) + residualmat = residual.view((-1, hidden_size)) if residual is not None else None + rowscale = rowscale.view(-1) if rowscale is not None else None + zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd( + x0mat, + residualmat, + gamma, + beta, + rowscale, + colscale, + None, + None, + dropout_p, + epsilon, + 1.0, + 0, + None, + residual_in_fp32, + is_rms_norm, + ) + # dmask is None if dropout_p == 0.0 + # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype + return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma + + +def _dropout_add_layer_norm_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + rowscale, + colscale, + dropout_p, + has_residual, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes + dx == None means that it was a post-norm architecture + (x = drop(x0) + residual was not returned in the fwd). + x0 must not be None if we have colscale. + """ + hidden_size = gamma.numel() + xmat = x.view((-1, hidden_size)) + dzmat = dz.view(xmat.shape) + dxmat = dx.view(xmat.shape) if dx is not None else None + x0mat = x0.view((-1, hidden_size)) if x0 is not None else None + rowscale = rowscale.view(-1) if rowscale is not None else None + if colscale is not None: + assert x0 is not None, "x0 is required to compute the gradient of colscale" + dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd( + dzmat, + dxmat, + xmat, + x0mat, + dmask, + mu, + rsigma, + gamma, + rowscale, + colscale, + None, + None, + dropout_p, + 1.0, + 0, + has_residual, + is_rms_norm, + ) + # dresidualmat is None if not has_residual + if colscale is None: + return dx0mat, dresidualmat, dgamma, dbeta + else: + dcolscale = rest[0] + return dx0mat, dresidualmat, dgamma, dbeta, dcolscale + + +def _dropout_add_layer_norm_subset_forward( + x0, + residual, + gamma, + beta, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32=False, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes""" + hidden_size = gamma.numel() + x0mat = x0.view((-1, hidden_size)) + residualmat = residual.view((-1, hidden_size)) if residual is not None else None + x0_subset = x0_subset.view(-1) if x0_subset is not None else None + out_subset = out_subset.view(-1) if out_subset is not None else None + zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd( + x0mat, + residualmat, + gamma, + beta, + None, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + None, + residual_in_fp32, + is_rms_norm, + ) + # dmask is None if dropout_p == 0.0 + # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype + return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma + + +def _dropout_add_layer_norm_subset_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + colscale, + x0_subset, + out_subset, + dropout_p, + rowscale_const, + x0_numrows, + has_residual, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes + dx == None means that it was a post-norm architecture + (x = drop(x0) + residual was not returned in the fwd). + x0 must not be None if we have colscale. + """ + hidden_size = gamma.numel() + xmat = x.view((-1, hidden_size)) + dzmat = dz.view(-1, hidden_size) + dxmat = dx.view(xmat.shape) if dx is not None else None + x0mat = x0.view((-1, hidden_size)) if x0 is not None else None + x0_subset = x0_subset.view(-1) if x0_subset is not None else None + out_subset = out_subset.view(-1) if out_subset is not None else None + if colscale is not None: + assert x0 is not None, "x0 is required to compute the gradient of colscale" + dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd( + dzmat, + dxmat, + xmat, + x0mat, + dmask, + mu, + rsigma, + gamma, + None, + colscale, + x0_subset, + out_subset, + dropout_p, + rowscale_const, + x0_numrows, + has_residual, + is_rms_norm, + ) + # dresidualmat is None if not has_residual + if colscale is None: + return dx0mat, dresidualmat, dgamma, dbeta + else: + dcolscale = rest[0] + return dx0mat, dresidualmat, dgamma, dbeta, dcolscale + + +def _dropout_add_layer_norm_parallel_residual_forward( + x0, + x1, + residual, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + residual_in_fp32=False, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes""" + hidden_size = gamma0.numel() + x0mat = x0.view((-1, hidden_size)) + x1mat = x1.view((-1, hidden_size)) if x1 is not None else None + residualmat = residual.view((-1, hidden_size)) if residual is not None else None + ( + z0mat, + z1mat, + xmat, + dmask0, + dmask1, + mu, + rsigma, + ) = dropout_layer_norm.dropout_add_ln_parallel_residual_fwd( + x0mat, + x1mat, + residualmat, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + None, + residual_in_fp32, + is_rms_norm, + ) + # dmask0 and dmask1 are None if dropout_p == 0.0 + # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype + return z0mat, z1mat, xmat if xmat is not None else x0mat, dmask0, dmask1, mu, rsigma + + +def _dropout_add_layer_norm_parallel_residual_backward( + dz0, + dz1, + dx, + x, + dmask0, + dmask1, + mu, + rsigma, + gamma0, + gamma1, + dropout_p, + has_x1, + has_residual, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes + dx == None means that it was a post-norm architecture + (x = drop(x0) + residual was not returned in the fwd). + """ + hidden_size = gamma0.numel() + xmat = x.view((-1, hidden_size)) + dz0mat = dz0.view(xmat.shape) + dz1mat = dz1.view(xmat.shape) if dz1 is not None else None + dxmat = dx.view(xmat.shape) if dx is not None else None + ( + dx0mat, + dx1mat, + dresidualmat, + dgamma0, + dbeta0, + dgamma1, + dbeta1, + *rest, + ) = dropout_layer_norm.dropout_add_ln_parallel_residual_bwd( + dz0mat, + dz1mat, + dxmat, + xmat, + dmask0, + dmask1, + mu, + rsigma, + gamma0, + gamma1, + dropout_p, + has_x1, + has_residual, + is_rms_norm, + ) + # dresidualmat is None if not has_residual + return dx0mat, dx1mat, dresidualmat, dgamma0, dbeta0, dgamma1, dbeta1 + + +class DropoutAddLayerNormFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x0, + residual, + gamma, + beta, + rowscale, + colscale, + dropout_p, + epsilon, + residual_in_fp32=False, + prenorm=False, + is_rms_norm=False, + return_dmask=False, + ): + x0 = maybe_align(x0.contiguous(), 16) + residual = maybe_align(residual.contiguous(), 16) if residual is not None else None + gamma = maybe_align(gamma.contiguous(), 16) + beta = maybe_align(beta.contiguous(), 16) if beta is not None else None + rowscale = maybe_align(rowscale.contiguous(), 16) if rowscale is not None else None + colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None + zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_forward( + x0, + residual, + gamma, + beta, + rowscale, + colscale, + dropout_p, + epsilon, + residual_in_fp32, + is_rms_norm, + ) + # Only need to save x0 if we need to compute gradient wrt colscale + x0_saved = x0 if colscale is not None else None + ctx.save_for_backward( + xmat.view(x0.shape), x0_saved, dmask, gamma, mu, rsigma, rowscale, colscale + ) + ctx.prenorm = prenorm + ctx.dropout_p = dropout_p + ctx.has_residual = residual is not None + ctx.is_rms_norm = is_rms_norm + ctx.has_beta = beta is not None + if not return_dmask: + return ( + zmat.view(x0.shape) if not prenorm else (zmat.view(x0.shape), xmat.view(x0.shape)) + ) + else: + dmask = ( + dmask.view(x0.shape) + if dropout_p > 0.0 + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + ctx.mark_non_differentiable(dmask) + return ( + (zmat.view(x0.shape), dmask) + if not prenorm + else (zmat.view(x0.shape), xmat.view(x0.shape), dmask) + ) + + @staticmethod + def backward(ctx, dz, *args): + # assert dz.is_contiguous() + dz = maybe_align(dz.contiguous(), 16) # this happens! + dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None + x, x0, dmask, gamma, mu, rsigma, rowscale, colscale = ctx.saved_tensors + # x0 is None if colscale is None + dropout_p = ctx.dropout_p + has_residual = ctx.has_residual + dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + rowscale, + colscale, + dropout_p, + has_residual, + ctx.is_rms_norm, + ) + dx0 = dx0mat.view(x.shape) + dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None + dcolscale = rest[0] if colscale is not None else None + return ( + dx0, + dresidual, + dgamma, + dbeta if ctx.has_beta else None, + None, + dcolscale, + None, + None, + None, + None, + None, + None, + ) + + +class DropoutAddLayerNormSubsetFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x0, + residual, + gamma, + beta, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32=False, + prenorm=False, + is_rms_norm=False, + return_dmask=False, + ): + x0 = maybe_align(x0.contiguous(), 16) + residual = maybe_align(residual.contiguous(), 16) if residual is not None else None + gamma = maybe_align(gamma.contiguous(), 16) + beta = maybe_align(beta.contiguous(), 16) if beta is not None else None + colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None + zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_subset_forward( + x0, + residual, + gamma, + beta, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32, + is_rms_norm, + ) + # Only need to save x0 if we need to compute gradient wrt colscale + x0_saved = x0 if colscale is not None else None + x_shape = (-1, *x0.shape[1:]) + ctx.save_for_backward( + xmat.view(x_shape), x0_saved, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset + ) + ctx.prenorm = prenorm + ctx.dropout_p = dropout_p + ctx.rowscale_const = rowscale_const + ctx.x0_numrows = x0.shape[:-1].numel() + ctx.has_residual = residual is not None + ctx.is_rms_norm = is_rms_norm + ctx.has_beta = beta is not None + z_shape = (-1, *x0.shape[1:]) + if not return_dmask: + return zmat.view(z_shape) if not prenorm else (zmat.view(z_shape), xmat.view(x0.shape)) + else: + z = zmat.view(z_shape) + dmask = ( + dmask.view(x0.shape) + if dropout_p > 0.0 + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + ctx.mark_non_differentiable(dmask) + return (z, dmask) if not prenorm else (z, xmat.view(x_shape), dmask) + + @staticmethod + def backward(ctx, dz, *args): + # assert dz.is_contiguous() + dz = maybe_align(dz.contiguous(), 16) # this happens! + dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None + x, x0, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset = ctx.saved_tensors + # x0 is None if colscale is None + dropout_p = ctx.dropout_p + has_residual = ctx.has_residual + dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_subset_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + colscale, + x0_subset, + out_subset, + dropout_p, + ctx.rowscale_const, + ctx.x0_numrows, + has_residual, + ctx.is_rms_norm, + ) + dx0 = dx0mat.view(-1, *x.shape[1:]) + dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None + dcolscale = rest[0] if colscale is not None else None + return ( + dx0, + dresidual, + dgamma, + dbeta if ctx.has_beta else None, + dcolscale, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + ) + + +class DropoutAddLayerNormParallelResidualFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x0, + x1, + residual, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + residual_in_fp32=False, + prenorm=False, + is_rms_norm=False, + return_dmask=False, + ): + x0 = maybe_align(x0.contiguous(), 16) + x1 = maybe_align(x1.contiguous(), 16) if x1 is not None else None + residual = maybe_align(residual.contiguous(), 16) if residual is not None else None + gamma0 = maybe_align(gamma0.contiguous(), 16) + beta0 = maybe_align(beta0.contiguous(), 16) if beta0 is not None else None + gamma1 = maybe_align(gamma1.contiguous(), 16) if gamma1 is not None else None + beta1 = maybe_align(beta1.contiguous(), 16) if beta1 is not None else None + ( + z0mat, + z1mat, + xmat, + dmask0, + dmask1, + mu, + rsigma, + ) = _dropout_add_layer_norm_parallel_residual_forward( + x0, + x1, + residual, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + residual_in_fp32, + is_rms_norm, + ) + ctx.save_for_backward(xmat.view(x0.shape), dmask0, dmask1, gamma0, gamma1, mu, rsigma) + ctx.prenorm = prenorm + ctx.dropout_p = dropout_p + ctx.has_x1 = x1 is not None + ctx.has_residual = residual is not None + ctx.is_rms_norm = is_rms_norm + ctx.has_beta = beta0 is not None + z = (z0mat.view(x0.shape), z1mat.view(x0.shape) if z1mat is not None else None) + if not return_dmask: + return z if not prenorm else (*z, xmat.view(x0.shape)) + else: + dmask0 = ( + dmask0.view(x0.shape) + if dropout_p > 0.0 + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + dmask1 = ( + dmask1.view(x0.shape) + if dropout_p > 0.0 and x1 is not None + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + ctx.mark_non_differentiable(dmask0) + ctx.mark_non_differentiable(dmask1) + return ( + (*z, dmask0, dmask1) if not prenorm else (*z, xmat.view(x0.shape), dmask0, dmask1) + ) + + @staticmethod + def backward(ctx, dz0, dz1, *args): + dz0 = maybe_align(dz0.contiguous(), 16) # this happens! + dz1 = maybe_align(dz1.contiguous(), 16) if dz1 is not None else None + dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None + x, dmask0, dmask1, gamma0, gamma1, mu, rsigma = ctx.saved_tensors + dropout_p = ctx.dropout_p + has_x1 = ctx.has_x1 + has_residual = ctx.has_residual + ( + dx0mat, + dx1mat, + dresidualmat, + dgamma0, + dbeta0, + dgamma1, + dbeta1, + ) = _dropout_add_layer_norm_parallel_residual_backward( + dz0, + dz1, + dx, + x, + dmask0, + dmask1, + mu, + rsigma, + gamma0, + gamma1, + dropout_p, + has_x1, + has_residual, + ctx.is_rms_norm, + ) + dx0 = dx0mat.view(x.shape) + dx1 = dx1mat.view(x.shape) if dx1mat is not None else None + dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None + return ( + dx0, + dx1, + dresidual, + dgamma0, + dbeta0 if ctx.has_beta else None, + dgamma1, + dbeta1 if ctx.has_beta else None, + None, + None, + None, + None, + None, + None, + ) + + +def layer_norm(x, weight, bias, epsilon): + return DropoutAddLayerNormFn.apply(x, None, weight, bias, None, None, 0.0, epsilon, False) + + +def dropout_add_layer_norm( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + rowscale=None, + layerscale=None, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormFn.apply( + x0, + residual, + weight, + bias, + rowscale, + layerscale, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + False, + return_dropout_mask, + ) + + +def dropout_add_layer_norm_subset( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + layerscale=None, + x0_subset=None, + out_subset=None, + rowscale_const=1.0, + out_numrows=0, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormSubsetFn.apply( + x0, + residual, + weight, + bias, + layerscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32, + prenorm, + False, + return_dropout_mask, + ) + + +def dropout_add_layer_norm_parallel_residual( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormParallelResidualFn.apply( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + False, + return_dropout_mask, + ) + + +class DropoutAddLayerNorm(torch.nn.Module): + def __init__( + self, + hidden_size, + prenorm=False, + p=0.0, + eps=1e-5, + residual_in_fp32=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.prenorm = prenorm + self.p = p + self.eps = eps + self.residual_in_fp32 = residual_in_fp32 + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.bias = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.reset_parameters() + + def reset_parameters(self): + init.ones_(self.weight) + init.zeros_(self.bias) + + def forward(self, x0, residual=None): + return dropout_add_layer_norm( + x0, + residual, + self.weight, + self.bias, + self.p if self.training else 0.0, + self.eps, + prenorm=self.prenorm, + residual_in_fp32=self.residual_in_fp32, + ) diff --git a/lib/python3.11/site-packages/flash_attn/ops/rms_norm.py b/lib/python3.11/site-packages/flash_attn/ops/rms_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..068348d61290e3839dd082b540d898578ba1e8e2 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/rms_norm.py @@ -0,0 +1,174 @@ +# Copyright (c) 2022, Tri Dao. +# Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py + +import torch +from torch.nn import init + +from flash_attn.ops.layer_norm import ( + DropoutAddLayerNormFn, + DropoutAddLayerNormParallelResidualFn, + DropoutAddLayerNormSubsetFn, +) + + +def rms_norm(x, weight, epsilon): + return DropoutAddLayerNormFn.apply( + x, None, weight, None, None, None, 0.0, epsilon, False, False, True + ) + + +def dropout_add_rms_norm( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + rowscale=None, + layerscale=None, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormFn.apply( + x0, + residual, + weight, + bias, + rowscale, + layerscale, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + True, + return_dropout_mask, + ) + + +def dropout_add_rms_norm_subset( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + layerscale=None, + x0_subset=None, + out_subset=None, + rowscale_const=1.0, + out_numrows=0, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormSubsetFn.apply( + x0, + residual, + weight, + bias, + layerscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32, + prenorm, + True, + return_dropout_mask, + ) + + +def dropout_add_rms_norm_parallel_residual( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormParallelResidualFn.apply( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + True, + return_dropout_mask, + ) + + +class RMSNorm(torch.nn.Module): + def __init__(self, hidden_size, eps=1e-5, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.eps = eps + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + init.ones_(self.weight) + + def forward(self, x): + return rms_norm(x, self.weight, self.eps) + + +class DropoutAddRMSNorm(torch.nn.Module): + def __init__( + self, + hidden_size, + prenorm=False, + p=0.0, + eps=1e-5, + residual_in_fp32=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.prenorm = prenorm + self.p = p + self.eps = eps + self.residual_in_fp32 = residual_in_fp32 + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + init.ones_(self.weight) + + def forward(self, x0, residual=None): + return dropout_add_rms_norm( + x0, + residual, + self.weight, + None, + self.p if self.training else 0.0, + self.eps, + prenorm=self.prenorm, + residual_in_fp32=self.residual_in_fp32, + ) diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__init__.py b/lib/python3.11/site-packages/flash_attn/ops/triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/__init__.py @@ -0,0 +1 @@ + diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ed2e9d55e764e2f45f6e4fb16ec66b85e4f753 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/cross_entropy.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/cross_entropy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf26dc88c6f080c1859dda0defaa894f1718242c Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/cross_entropy.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/k_activations.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/k_activations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70dbf1eee0a407147e8a2d71e8301d82f4cf3dc2 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/k_activations.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/layer_norm.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/layer_norm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..816139e9f869a51e4e85da8de59966eb3bb8c19f Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/layer_norm.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/linear.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..602a340be60b8ca32be2dd4763408a6f46ee34ac Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/linear.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/mlp.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/mlp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad62f47d5f821fe777049605331d6cddeaf4226e Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/mlp.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/rotary.cpython-311.pyc b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/rotary.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd2d4d75454a0ed2ef7a831ef8e7a5a3ed36cc47 Binary files /dev/null and b/lib/python3.11/site-packages/flash_attn/ops/triton/__pycache__/rotary.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/cross_entropy.py b/lib/python3.11/site-packages/flash_attn/ops/triton/cross_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..7b0315b9793a8935dc507ed1b71b6e9d44e3b689 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/cross_entropy.py @@ -0,0 +1,329 @@ +# Copyright (c) 2023, Tri Dao. + +from typing import Tuple, Optional, Union + +import torch +import torch.nn.functional as F + +import triton +import triton.language as tl + +# `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for +# `_all_gather_base` and `_reduce_scatter_base`. They require the most recent +# version of PyTorch. The following 2 lines are for backward compatibility with +# older PyTorch. +if "all_gather_into_tensor" not in dir(torch.distributed): + torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base + + +@triton.heuristics( + { + "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0, + } +) +@triton.jit +def cross_entropy_fwd_kernel( + loss_ptr, # data ptrs + lse_ptr, + z_loss_ptr, + logits_ptr, + labels_ptr, + smoothing, + logit_scale, + lse_square_scale, + ignore_index, + total_classes, + class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes + n_cols, # shapes + logits_row_stride, # strides + BLOCK_SIZE: tl.constexpr, + HAS_SMOOTHING: tl.constexpr, + # if SPLIT (e.g. tensor parallel), don't include the LSE in the loss since it's not the final LSE + SPLIT: tl.constexpr, + PRECOMPUTED_LSE: tl.constexpr, # If LSE is already computed (also no smoothing and logit_scale == 1.0) +): + row_idx = tl.program_id(0) + logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64) + sum_logits = 0.0 # For smoothing + if not PRECOMPUTED_LSE: + # Statistics for online softmax + m_i = -float("inf") + l_i = 0.0 + for col_offset in range(0, n_cols, BLOCK_SIZE): + cols = col_offset + tl.arange(0, BLOCK_SIZE) + logits = tl.load(logits_ptr + cols, mask=cols < n_cols, other=-float("inf")).to( + tl.float32 + ) * logit_scale + if HAS_SMOOTHING: + sum_logits += tl.sum(tl.where(cols < n_cols, logits, 0.0)) + m_i_new = tl.maximum(m_i, tl.max(logits)) + l_i = tl.exp(m_i - m_i_new) * l_i + tl.sum(tl.exp(logits - m_i_new)) + m_i = m_i_new + lse = tl.log(l_i) + m_i + tl.store(lse_ptr + row_idx, lse) + else: + lse = tl.load(lse_ptr + row_idx) + label_idx = tl.load(labels_ptr + row_idx) + if label_idx == ignore_index: + loss = 0.0 + z_loss = 0.0 + else: + label_idx -= class_start_idx + if label_idx >= 0 and label_idx < n_cols: + logits_label = tl.load(logits_ptr + label_idx) * logit_scale + if HAS_SMOOTHING: + loss = ( + (lse if not SPLIT else 0.0) + - smoothing * sum_logits / total_classes + - (1 - smoothing) * logits_label + ) + else: + loss = (lse if not SPLIT else 0.0) - logits_label + else: + # If label is out of bounds, we set the CE loss to 0.0. But we still want the smoothing loss + if HAS_SMOOTHING: + loss = smoothing * ((lse if not SPLIT else 0.0) - sum_logits / total_classes) + else: + loss = 0.0 + if not SPLIT: + z_loss = lse_square_scale * lse * lse + loss += z_loss + else: + z_loss = 0.0 + tl.store(loss_ptr + row_idx, loss) + if not SPLIT: + tl.store(z_loss_ptr + row_idx, z_loss) + + +@triton.heuristics( + { + "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0, + } +) +@triton.jit +def cross_entropy_bwd_kernel( + dlogits_ptr, # data ptrs + dloss_ptr, + logits_ptr, + lse_ptr, + labels_ptr, + smoothing, + logit_scale, + lse_square_scale, + ignore_index, + total_classes, + class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes + n_cols, # shapes + logits_row_stride, # strides + dlogits_row_stride, + dloss_row_stride, + BLOCK_SIZE: tl.constexpr, + HAS_SMOOTHING: tl.constexpr, +): + row_idx = tl.program_id(0) + col_block_idx = tl.program_id(1) + logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64) + dlogits_ptr = dlogits_ptr + row_idx * dlogits_row_stride.to(tl.int64) + col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + label_idx = tl.load(labels_ptr + row_idx) + if label_idx != ignore_index: + dloss = tl.load(dloss_ptr + row_idx * dloss_row_stride) + else: + dloss = 0.0 + logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf")).to( + tl.float32 + ) * logit_scale + lse = tl.load(lse_ptr + row_idx) + probs = tl.exp(logits - lse) + probs += 2.0 * lse_square_scale * lse * probs + label_idx -= class_start_idx + if HAS_SMOOTHING: + smooth_positive = 1.0 - smoothing + smooth_negative = smoothing / total_classes + probs = tl.where(col_offsets == label_idx, probs - smooth_positive, probs) - smooth_negative + else: + probs = tl.where(col_offsets == label_idx, probs - 1.0, probs) + tl.store(dlogits_ptr + col_offsets, (dloss * logit_scale) * probs, mask=col_offsets < n_cols) + + +class CrossEntropyLoss(torch.autograd.Function): + + @staticmethod + def forward( + ctx, + logits, + labels, + precomputed_lse=None, + smoothing=0.0, + logit_scale=1.0, + lse_square_scale=0.0, + ignore_index=-100, + inplace_backward=False, + process_group=None, + ): + # For some reason Triton generates wrong code when labels has dtype long and its address + # is not aligned to 16 bytes. The ld.global.b64 seems to load the wrong label index. + if labels.dtype == torch.long and labels.data_ptr() % 16 != 0: + labels = F.pad(labels, (0, 1))[..., :-1] + assert labels.data_ptr() % 16 == 0 + n_rows, n_cols = logits.shape + assert labels.shape == (n_rows,) + world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group) + total_classes = world_size * n_cols + rank = 0 if process_group is None else torch.distributed.get_rank(process_group) + class_start_idx = rank * n_cols + use_precomputed_lse = precomputed_lse is not None and logit_scale == 1.0 and smoothing == 0.0 + + if logits.stride(-1) != 1: + logits = logits.contiguous() + MAX_BLOCK_SIZE = 16 * 1024 + BLOCK_SIZE = min(triton.next_power_of_2(n_cols), MAX_BLOCK_SIZE) + num_warps = ( + 4 + if BLOCK_SIZE < 2048 + else (8 if BLOCK_SIZE < 8192 else (16 if BLOCK_SIZE < 128 * 1024 else 32)) + ) + losses = torch.empty(n_rows, dtype=torch.float, device=logits.device) + if use_precomputed_lse: + assert precomputed_lse.shape == (n_rows,) + lse = precomputed_lse.contiguous() + else: + lse = torch.empty(n_rows, dtype=torch.float, device=logits.device) + z_losses = torch.empty(n_rows, dtype=torch.float, device=logits.device) + # Need this, otherwise Triton tries to launch from cuda:0 and we get + # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?) + with torch.cuda.device(logits.device.index): + cross_entropy_fwd_kernel[(n_rows,)]( + losses, # data ptrs + lse, + z_losses, + logits, + labels, + smoothing, + logit_scale, + lse_square_scale, + ignore_index, + total_classes, + class_start_idx, + n_cols, # shapes + logits.stride(0), # strides + BLOCK_SIZE=BLOCK_SIZE, # constants + SPLIT=world_size > 1, + PRECOMPUTED_LSE=use_precomputed_lse, + num_warps=num_warps, + ) + + if world_size > 1: + # If there's no smoothing, if labels are in the vocab of this partition, losses contains + # - predicted logit, and 0 otherwise. + # If there's smoothing=0.1, for labels in the vocab of this partition, losses contains + # -0.9 * predicted logit - 0.1 * sum logit / total_classes. + # For labels not in the vocab of this partition, losses contains + # -0.1 * sum logit / total_classes. + if world_size > 1: + lse_allgather = torch.empty(world_size, n_rows, dtype=lse.dtype, device=lse.device) + torch.distributed.all_gather_into_tensor(lse_allgather, lse, group=process_group) + handle_losses = torch.distributed.all_reduce( + losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True + ) + lse = torch.logsumexp(lse_allgather, dim=0) + handle_losses.wait() + # After the allreduce, if there's no smoothing, the total losses are - predicted_logit, + # we just have to add the (global) lse. + # If there's smoothing=0.1, the total losses are + # -0.9 * predicted_logit - 0.1 * sum logit / total_classes. + # Again, we just have to add the (global) lse. + losses += lse + if lse_square_scale != 0.0: + z_losses = lse_square_scale * lse.square() + z_losses.masked_fill_(labels == ignore_index, 0.0) + losses += z_losses + else: + z_losses = torch.zeros_like(losses) + losses.masked_fill_(labels == ignore_index, 0.0) + + ctx.save_for_backward(logits, lse, labels) + ctx.mark_non_differentiable(z_losses) + ctx.smoothing = smoothing + ctx.logit_scale = logit_scale + ctx.lse_square_scale = lse_square_scale + ctx.ignore_index = ignore_index + ctx.total_classes = total_classes + ctx.class_start_idx = class_start_idx + ctx.inplace_backward = inplace_backward + return losses, z_losses + + @staticmethod + def backward(ctx, grad_losses, grad_z_losses): + del grad_z_losses # z_losses are only for logging. + + logits, lse, labels = ctx.saved_tensors + dlogits = logits if ctx.inplace_backward else torch.empty_like(logits) + n_rows, n_cols = logits.shape + BLOCK_SIZE = min(triton.next_power_of_2(n_cols), 4 * 1024) + num_warps = 4 if BLOCK_SIZE < 2048 else (8 if BLOCK_SIZE < 8192 else 16) + grid = lambda META: (n_rows, triton.cdiv(n_cols, META["BLOCK_SIZE"])) # noqa + # Need this, otherwise Triton tries to launch from cuda:0 and we get + # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?) + with torch.cuda.device(logits.device.index): + cross_entropy_bwd_kernel[grid]( + dlogits, # data ptrs + grad_losses, + logits, + lse, + labels, + ctx.smoothing, + ctx.logit_scale, + ctx.lse_square_scale, + ctx.ignore_index, + ctx.total_classes, + ctx.class_start_idx, + n_cols, # shapes + logits.stride(0), # strides + dlogits.stride(0), + grad_losses.stride(0), + BLOCK_SIZE=BLOCK_SIZE, # constants + num_warps=num_warps, + ) + return dlogits, None, None, None, None, None, None, None, None, None + + +def cross_entropy_loss( + logits: torch.Tensor, + labels: torch.Tensor, + precomputed_lse: Optional[torch.Tensor] = None, + label_smoothing: float = 0.0, + logit_scale: float = 1.0, + lse_square_scale: float = 0.0, + ignore_index=-100, + inplace_backward: bool = False, + process_group=None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Arguments: + logits: (batch, vocab_size) + labels: (batch,) + label_smoothing: float + logit_scale: float. Multiply logits by this scale before calculating the loss. + lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss. + This is also referred to as "z-loss". + ignore_index: int. If labels == ignore_index, the loss is set to 0.0. + inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits. + This saves memory. + process_group: if not None, we're doing Tensor Parallel: each process is responsible for + one part of the vocab. The loss will be aggregated across processes. + Returns: + losses: (batch,), float + z_losses: (batch,), float + """ + return CrossEntropyLoss.apply( + logits, + labels, + precomputed_lse, + label_smoothing, + logit_scale, + lse_square_scale, + ignore_index, + inplace_backward, + process_group, + ) diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/k_activations.py b/lib/python3.11/site-packages/flash_attn/ops/triton/k_activations.py new file mode 100644 index 0000000000000000000000000000000000000000..efb83c358eb4a85d069ee340a3c83f418f9a805b --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/k_activations.py @@ -0,0 +1,162 @@ +# Adapted from https://github.com/facebookresearch/xformers/blob/main/xformers/triton/k_activations.py +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import math +from enum import Enum +from typing import Optional + +import triton +import triton.language as tl + +_sqrt2pi = math.sqrt(2.0 / math.pi) +_sqrt1_2 = math.sqrt(1.0 / 2) +_gaussian_pdf_normalization = 1.0 / math.sqrt(2 * math.pi) + + +class Activation(str, Enum): + SquaredReLU = "squared_relu" + GeLU = "gelu" + GeLUApprox = "gelu_approx" + LeakyReLU = "leaky_relu" + ReLU = "relu" + + +def get_triton_activation_kernel(activation: Optional[Activation]): + return ( + { + Activation.ReLU: relu, + Activation.LeakyReLU: leaky_relu, + Activation.GeLU: gelu, + Activation.GeLUApprox: gelu_approx, + Activation.SquaredReLU: squared_relu, + }[activation] + if activation + else None + ) + + +def get_triton_activation_bwd_kernel(activation: Optional[Activation]): + return ( + { + Activation.ReLU: relu_grad, + Activation.LeakyReLU: leaky_relu_grad, + Activation.GeLU: gelu_grad, + Activation.GeLUApprox: gelu_approx_grad, + Activation.SquaredReLU: squared_relu_grad, + }[activation] + if activation + else None + ) + + +@triton.jit +def tanh(x): + # Tanh is just a scaled sigmoid + return 2 * tl.sigmoid(2 * x) - 1 + + +@triton.jit +def cosh(x): + exp_x = tl.exp(x) + return (exp_x + 1.0 / exp_x) * 0.5 + + +# a Triton implementation of the most used activations +# See for instance http://arxiv.org/abs/1606.08415 for an overview + +# ReLU +@triton.jit +def relu(x): + """ + ReLU_ activation function + + .. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html + """ + zero = 0.0 + return tl.where(x >= 0, x, zero.to(x.dtype)) + + +@triton.jit +def relu_grad(x): + # ReLU is different from other activations + # in that it does not require the input to retrospectively compute its gradient + # here the input is the downstream gradient, and we return the upstream gradient directly + zero = 0.0 + one = 1.0 + return tl.where(x >= 0, one.to(x.dtype), zero.to(x.dtype)) + + +@triton.jit +def squared_relu(x): + """ + Squared ReLU activation, as proposed in the Primer_ paper. + + .. _Primer: https://arxiv.org/abs/2109.08668 + """ + x_ = relu(x) + return (x_ * x_).to(x.dtype) + + +@triton.jit +def squared_relu_grad(x): + return tl.where(x >= 0, 2.0 * x, 0.0) + + +# Leaky ReLU +@triton.jit +def leaky_relu(x): + """ + LeakyReLU_ activation + + .. _LeakyReLU: https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html + """ + scale = 0.01 + 0.0 + scale = scale.to(x.dtype) + return tl.where(x >= 0, x, scale * x) + + +@triton.jit +def leaky_relu_grad(x): + min_grad = 0.01 + max_grad = 1 + + min_grad = min_grad.to(x.dtype) + max_grad = max_grad.to(x.dtype) + + return tl.where(x >= 0, max_grad, min_grad) + + +@triton.jit +def gelu(x): + """Gaussian Error Linear Unit (GELU)""" + return x * 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2)) + + +@triton.jit +def gelu_grad(x): + cdf = 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2)) + pdf = tl.exp(-0.5 * x * x) * _gaussian_pdf_normalization + return cdf + x * pdf + + +@triton.jit +def gelu_approx(x): + """ + GeLU_ activation - Gaussian error linear unit, with tanh approximation + + .. _GeLU: https://arxiv.org/pdf/1606.08415.pdf + """ + return 0.5 * x * (1.0 + tanh(_sqrt2pi * x * (1.0 + 0.044715 * x * x))) + + +@triton.jit +def gelu_approx_grad(x): + # CREDITS: Fast implementation proposed in + # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/fused_bias_gelu.py#L30 + tanh_out = tanh(0.79788456 * x * (1 + 0.044715 * x * x)) + return 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * ( + 1 + tanh_out + ) diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/layer_norm.py b/lib/python3.11/site-packages/flash_attn/ops/triton/layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..addffe1f18585b59a8c22f20d3708ffb46d6bf34 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/layer_norm.py @@ -0,0 +1,1112 @@ +# Copyright (c) 2024, Tri Dao. +# Implement dropout + residual + layer_norm / rms_norm. + +# Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html +# For the backward pass, we keep weight_grad and bias_grad in registers and accumulate. +# This is faster for dimensions up to 8k, but after that it's much slower due to register spilling. +# The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine. + +import math + +import torch +import torch.nn.functional as F +from torch.cuda.amp import custom_fwd, custom_bwd + +import triton +import triton.language as tl + + +def layer_norm_ref( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + dropout_mask=None, + dropout_mask1=None, + upcast=False, +): + dtype = x.dtype + if upcast: + x = x.float() + weight = weight.float() + bias = bias.float() if bias is not None else None + residual = residual.float() if residual is not None else residual + x1 = x1.float() if x1 is not None else None + weight1 = weight1.float() if weight1 is not None else None + bias1 = bias1.float() if bias1 is not None else None + if x1 is not None: + assert rowscale is None, "rowscale is not supported with parallel LayerNorm" + if rowscale is not None: + x = x * rowscale[..., None] + if dropout_p > 0.0: + if dropout_mask is not None: + x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p) + else: + x = F.dropout(x, p=dropout_p) + if x1 is not None: + if dropout_mask1 is not None: + x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p) + else: + x1 = F.dropout(x1, p=dropout_p) + if x1 is not None: + x = x + x1 + if residual is not None: + x = (x + residual).to(x.dtype) + out = F.layer_norm(x.to(weight.dtype), x.shape[-1:], weight=weight, bias=bias, eps=eps).to( + dtype + ) + if weight1 is None: + return out if not prenorm else (out, x) + else: + out1 = F.layer_norm( + x.to(weight1.dtype), x.shape[-1:], weight=weight1, bias=bias1, eps=eps + ).to(dtype) + return (out, out1) if not prenorm else (out, out1, x) + + +def rms_norm_ref( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + dropout_mask=None, + dropout_mask1=None, + upcast=False, +): + dtype = x.dtype + if upcast: + x = x.float() + weight = weight.float() + bias = bias.float() if bias is not None else None + residual = residual.float() if residual is not None else residual + x1 = x1.float() if x1 is not None else None + weight1 = weight1.float() if weight1 is not None else None + bias1 = bias1.float() if bias1 is not None else None + if x1 is not None: + assert rowscale is None, "rowscale is not supported with parallel LayerNorm" + if rowscale is not None: + x = x * rowscale[..., None] + if dropout_p > 0.0: + if dropout_mask is not None: + x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p) + else: + x = F.dropout(x, p=dropout_p) + if x1 is not None: + if dropout_mask1 is not None: + x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p) + else: + x1 = F.dropout(x1, p=dropout_p) + if x1 is not None: + x = x + x1 + if residual is not None: + x = (x + residual).to(x.dtype) + rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps) + out = ((x * rstd * weight) + bias if bias is not None else (x * rstd * weight)).to(dtype) + if weight1 is None: + return out if not prenorm else (out, x) + else: + out1 = ((x * rstd * weight1) + bias1 if bias1 is not None else (x * rstd * weight1)).to( + dtype + ) + return (out, out1) if not prenorm else (out, out1, x) + + +@triton.autotune( + configs=[ + triton.Config({}, num_warps=1), + triton.Config({}, num_warps=2), + triton.Config({}, num_warps=4), + triton.Config({}, num_warps=8), + triton.Config({}, num_warps=16), + triton.Config({}, num_warps=32), + ], + key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS"], +) +# @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None}) +# @triton.heuristics({"HAS_RESIDUAL": lambda args: args["RESIDUAL"] is not None}) +@triton.heuristics({"HAS_X1": lambda args: args["X1"] is not None}) +@triton.heuristics({"HAS_W1": lambda args: args["W1"] is not None}) +@triton.heuristics({"HAS_B1": lambda args: args["B1"] is not None}) +@triton.jit +def _layer_norm_fwd_1pass_kernel( + X, # pointer to the input + Y, # pointer to the output + W, # pointer to the weights + B, # pointer to the biases + RESIDUAL, # pointer to the residual + X1, + W1, + B1, + Y1, + RESIDUAL_OUT, # pointer to the residual + ROWSCALE, + SEEDS, # Dropout seeds for each row + DROPOUT_MASK, + Mean, # pointer to the mean + Rstd, # pointer to the 1/std + stride_x_row, # how much to increase the pointer when moving by 1 row + stride_y_row, + stride_res_row, + stride_res_out_row, + stride_x1_row, + stride_y1_row, + M, # number of rows in X + N, # number of columns in X + eps, # epsilon to avoid division by zero + dropout_p, # Dropout probability + IS_RMS_NORM: tl.constexpr, + BLOCK_N: tl.constexpr, + HAS_RESIDUAL: tl.constexpr, + STORE_RESIDUAL_OUT: tl.constexpr, + HAS_BIAS: tl.constexpr, + HAS_DROPOUT: tl.constexpr, + STORE_DROPOUT_MASK: tl.constexpr, + HAS_ROWSCALE: tl.constexpr, + HAS_X1: tl.constexpr, + HAS_W1: tl.constexpr, + HAS_B1: tl.constexpr, +): + # Map the program id to the row of X and Y it should compute. + row = tl.program_id(0) + X += row * stride_x_row + Y += row * stride_y_row + if HAS_RESIDUAL: + RESIDUAL += row * stride_res_row + if STORE_RESIDUAL_OUT: + RESIDUAL_OUT += row * stride_res_out_row + if HAS_X1: + X1 += row * stride_x1_row + if HAS_W1: + Y1 += row * stride_y1_row + # Compute mean and variance + cols = tl.arange(0, BLOCK_N) + x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32) + if HAS_ROWSCALE: + rowscale = tl.load(ROWSCALE + row).to(tl.float32) + x *= rowscale + if HAS_DROPOUT: + # Compute dropout mask + # 7 rounds is good enough, and reduces register pressure + keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + x = tl.where(keep_mask, x / (1.0 - dropout_p), 0.0) + if STORE_DROPOUT_MASK: + tl.store(DROPOUT_MASK + row * N + cols, keep_mask, mask=cols < N) + if HAS_X1: + x1 = tl.load(X1 + cols, mask=cols < N, other=0.0).to(tl.float32) + if HAS_ROWSCALE: + rowscale = tl.load(ROWSCALE + M + row).to(tl.float32) + x1 *= rowscale + if HAS_DROPOUT: + # Compute dropout mask + # 7 rounds is good enough, and reduces register pressure + keep_mask = ( + tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + ) + x1 = tl.where(keep_mask, x1 / (1.0 - dropout_p), 0.0) + if STORE_DROPOUT_MASK: + tl.store(DROPOUT_MASK + (M + row) * N + cols, keep_mask, mask=cols < N) + x += x1 + if HAS_RESIDUAL: + residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32) + x += residual + if STORE_RESIDUAL_OUT: + tl.store(RESIDUAL_OUT + cols, x, mask=cols < N) + if not IS_RMS_NORM: + mean = tl.sum(x, axis=0) / N + tl.store(Mean + row, mean) + xbar = tl.where(cols < N, x - mean, 0.0) + var = tl.sum(xbar * xbar, axis=0) / N + else: + xbar = tl.where(cols < N, x, 0.0) + var = tl.sum(xbar * xbar, axis=0) / N + rstd = 1 / tl.sqrt(var + eps) + tl.store(Rstd + row, rstd) + # Normalize and apply linear transformation + mask = cols < N + w = tl.load(W + cols, mask=mask).to(tl.float32) + if HAS_BIAS: + b = tl.load(B + cols, mask=mask).to(tl.float32) + x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd + y = x_hat * w + b if HAS_BIAS else x_hat * w + # Write output + tl.store(Y + cols, y, mask=mask) + if HAS_W1: + w1 = tl.load(W1 + cols, mask=mask).to(tl.float32) + if HAS_B1: + b1 = tl.load(B1 + cols, mask=mask).to(tl.float32) + y1 = x_hat * w1 + b1 if HAS_B1 else x_hat * w1 + tl.store(Y1 + cols, y1, mask=mask) + + +def _layer_norm_fwd( + x, + weight, + bias, + eps, + residual=None, + x1=None, + weight1=None, + bias1=None, + dropout_p=0.0, + rowscale=None, + out_dtype=None, + residual_dtype=None, + is_rms_norm=False, + return_dropout_mask=False, + out=None, + residual_out=None +): + if residual is not None: + residual_dtype = residual.dtype + M, N = x.shape + assert x.stride(-1) == 1 + if residual is not None: + assert residual.stride(-1) == 1 + assert residual.shape == (M, N) + assert weight.shape == (N,) + assert weight.stride(-1) == 1 + if bias is not None: + assert bias.stride(-1) == 1 + assert bias.shape == (N,) + if x1 is not None: + assert x1.shape == x.shape + assert rowscale is None + assert x1.stride(-1) == 1 + if weight1 is not None: + assert weight1.shape == (N,) + assert weight1.stride(-1) == 1 + if bias1 is not None: + assert bias1.shape == (N,) + assert bias1.stride(-1) == 1 + if rowscale is not None: + assert rowscale.is_contiguous() + assert rowscale.shape == (M,) + # allocate output + if out is None: + out = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype) + else: + assert out.shape == x.shape + assert out.stride(-1) == 1 + if weight1 is not None: + y1 = torch.empty_like(out) + assert y1.stride(-1) == 1 + else: + y1 = None + if ( + residual is not None + or (residual_dtype is not None and residual_dtype != x.dtype) + or dropout_p > 0.0 + or rowscale is not None + or x1 is not None + ): + if residual_out is None: + residual_out = torch.empty( + M, N, device=x.device, dtype=residual_dtype if residual_dtype is not None else x.dtype + ) + else: + assert residual_out.shape == x.shape + assert residual_out.stride(-1) == 1 + else: + residual_out = None + mean = torch.empty((M,), dtype=torch.float32, device=x.device) if not is_rms_norm else None + rstd = torch.empty((M,), dtype=torch.float32, device=x.device) + if dropout_p > 0.0: + seeds = torch.randint( + 2**32, (M if x1 is None else 2 * M,), device=x.device, dtype=torch.int64 + ) + else: + seeds = None + if return_dropout_mask and dropout_p > 0.0: + dropout_mask = torch.empty(M if x1 is None else 2 * M, N, device=x.device, dtype=torch.bool) + else: + dropout_mask = None + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_N: + raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.") + with torch.cuda.device(x.device.index): + _layer_norm_fwd_1pass_kernel[(M,)]( + x, + out, + weight, + bias, + residual, + x1, + weight1, + bias1, + y1, + residual_out, + rowscale, + seeds, + dropout_mask, + mean, + rstd, + x.stride(0), + out.stride(0), + residual.stride(0) if residual is not None else 0, + residual_out.stride(0) if residual_out is not None else 0, + x1.stride(0) if x1 is not None else 0, + y1.stride(0) if y1 is not None else 0, + M, + N, + eps, + dropout_p, + is_rms_norm, + BLOCK_N, + residual is not None, + residual_out is not None, + bias is not None, + dropout_p > 0.0, + dropout_mask is not None, + rowscale is not None, + ) + # residual_out is None if residual is None and residual_dtype == input_dtype and dropout_p == 0.0 + if dropout_mask is not None and x1 is not None: + dropout_mask, dropout_mask1 = dropout_mask.tensor_split(2, dim=0) + else: + dropout_mask1 = None + return ( + out, + y1, + mean, + rstd, + residual_out if residual_out is not None else x, + seeds, + dropout_mask, + dropout_mask1, + ) + + +@triton.autotune( + configs=[ + triton.Config({}, num_warps=1), + triton.Config({}, num_warps=2), + triton.Config({}, num_warps=4), + triton.Config({}, num_warps=8), + triton.Config({}, num_warps=16), + triton.Config({}, num_warps=32), + ], + key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS", "HAS_DROPOUT"], +) +# @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None}) +# @triton.heuristics({"HAS_DRESIDUAL": lambda args: args["DRESIDUAL"] is not None}) +# @triton.heuristics({"STORE_DRESIDUAL": lambda args: args["DRESIDUAL_IN"] is not None}) +@triton.heuristics({"HAS_ROWSCALE": lambda args: args["ROWSCALE"] is not None}) +@triton.heuristics({"HAS_DY1": lambda args: args["DY1"] is not None}) +@triton.heuristics({"HAS_DX1": lambda args: args["DX1"] is not None}) +@triton.heuristics({"HAS_B1": lambda args: args["DB1"] is not None}) +@triton.heuristics({"RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None}) +@triton.jit +def _layer_norm_bwd_kernel( + X, # pointer to the input + W, # pointer to the weights + B, # pointer to the biases + Y, # pointer to the output to be recomputed + DY, # pointer to the output gradient + DX, # pointer to the input gradient + DW, # pointer to the partial sum of weights gradient + DB, # pointer to the partial sum of biases gradient + DRESIDUAL, + W1, + DY1, + DX1, + DW1, + DB1, + DRESIDUAL_IN, + ROWSCALE, + SEEDS, + Mean, # pointer to the mean + Rstd, # pointer to the 1/std + stride_x_row, # how much to increase the pointer when moving by 1 row + stride_y_row, + stride_dy_row, + stride_dx_row, + stride_dres_row, + stride_dy1_row, + stride_dx1_row, + stride_dres_in_row, + M, # number of rows in X + N, # number of columns in X + eps, # epsilon to avoid division by zero + dropout_p, + rows_per_program, + IS_RMS_NORM: tl.constexpr, + BLOCK_N: tl.constexpr, + HAS_DRESIDUAL: tl.constexpr, + STORE_DRESIDUAL: tl.constexpr, + HAS_BIAS: tl.constexpr, + HAS_DROPOUT: tl.constexpr, + HAS_ROWSCALE: tl.constexpr, + HAS_DY1: tl.constexpr, + HAS_DX1: tl.constexpr, + HAS_B1: tl.constexpr, + RECOMPUTE_OUTPUT: tl.constexpr, +): + # Map the program id to the elements of X, DX, and DY it should compute. + row_block_id = tl.program_id(0) + row_start = row_block_id * rows_per_program + # Do not early exit if row_start >= M, because we need to write DW and DB + cols = tl.arange(0, BLOCK_N) + mask = cols < N + X += row_start * stride_x_row + if HAS_DRESIDUAL: + DRESIDUAL += row_start * stride_dres_row + if STORE_DRESIDUAL: + DRESIDUAL_IN += row_start * stride_dres_in_row + DY += row_start * stride_dy_row + DX += row_start * stride_dx_row + if HAS_DY1: + DY1 += row_start * stride_dy1_row + if HAS_DX1: + DX1 += row_start * stride_dx1_row + if RECOMPUTE_OUTPUT: + Y += row_start * stride_y_row + w = tl.load(W + cols, mask=mask).to(tl.float32) + if RECOMPUTE_OUTPUT and HAS_BIAS: + b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32) + if HAS_DY1: + w1 = tl.load(W1 + cols, mask=mask).to(tl.float32) + dw = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_BIAS: + db = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_DY1: + dw1 = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_B1: + db1 = tl.zeros((BLOCK_N,), dtype=tl.float32) + row_end = min((row_block_id + 1) * rows_per_program, M) + for row in range(row_start, row_end): + # Load data to SRAM + x = tl.load(X + cols, mask=mask, other=0).to(tl.float32) + dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32) + if HAS_DY1: + dy1 = tl.load(DY1 + cols, mask=mask, other=0).to(tl.float32) + if not IS_RMS_NORM: + mean = tl.load(Mean + row) + rstd = tl.load(Rstd + row) + # Compute dx + xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd + xhat = tl.where(mask, xhat, 0.0) + if RECOMPUTE_OUTPUT: + y = xhat * w + b if HAS_BIAS else xhat * w + tl.store(Y + cols, y, mask=mask) + wdy = w * dy + dw += dy * xhat + if HAS_BIAS: + db += dy + if HAS_DY1: + wdy += w1 * dy1 + dw1 += dy1 * xhat + if HAS_B1: + db1 += dy1 + if not IS_RMS_NORM: + c1 = tl.sum(xhat * wdy, axis=0) / N + c2 = tl.sum(wdy, axis=0) / N + dx = (wdy - (xhat * c1 + c2)) * rstd + else: + c1 = tl.sum(xhat * wdy, axis=0) / N + dx = (wdy - xhat * c1) * rstd + if HAS_DRESIDUAL: + dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32) + dx += dres + # Write dx + if STORE_DRESIDUAL: + tl.store(DRESIDUAL_IN + cols, dx, mask=mask) + if HAS_DX1: + if HAS_DROPOUT: + keep_mask = ( + tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + ) + dx1 = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0) + else: + dx1 = dx + tl.store(DX1 + cols, dx1, mask=mask) + if HAS_DROPOUT: + keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + dx = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0) + if HAS_ROWSCALE: + rowscale = tl.load(ROWSCALE + row).to(tl.float32) + dx *= rowscale + tl.store(DX + cols, dx, mask=mask) + + X += stride_x_row + if HAS_DRESIDUAL: + DRESIDUAL += stride_dres_row + if STORE_DRESIDUAL: + DRESIDUAL_IN += stride_dres_in_row + if RECOMPUTE_OUTPUT: + Y += stride_y_row + DY += stride_dy_row + DX += stride_dx_row + if HAS_DY1: + DY1 += stride_dy1_row + if HAS_DX1: + DX1 += stride_dx1_row + tl.store(DW + row_block_id * N + cols, dw, mask=mask) + if HAS_BIAS: + tl.store(DB + row_block_id * N + cols, db, mask=mask) + if HAS_DY1: + tl.store(DW1 + row_block_id * N + cols, dw1, mask=mask) + if HAS_B1: + tl.store(DB1 + row_block_id * N + cols, db1, mask=mask) + + +def _layer_norm_bwd( + dy, + x, + weight, + bias, + eps, + mean, + rstd, + dresidual=None, + dy1=None, + weight1=None, + bias1=None, + seeds=None, + dropout_p=0.0, + rowscale=None, + has_residual=False, + has_x1=False, + is_rms_norm=False, + x_dtype=None, + recompute_output=False, +): + M, N = x.shape + assert x.stride(-1) == 1 + assert dy.stride(-1) == 1 + assert dy.shape == (M, N) + if dresidual is not None: + assert dresidual.stride(-1) == 1 + assert dresidual.shape == (M, N) + assert weight.shape == (N,) + assert weight.stride(-1) == 1 + if bias is not None: + assert bias.stride(-1) == 1 + assert bias.shape == (N,) + if dy1 is not None: + assert weight1 is not None + assert dy1.shape == dy.shape + assert dy1.stride(-1) == 1 + if weight1 is not None: + assert weight1.shape == (N,) + assert weight1.stride(-1) == 1 + if bias1 is not None: + assert bias1.shape == (N,) + assert bias1.stride(-1) == 1 + if seeds is not None: + assert seeds.is_contiguous() + assert seeds.shape == (M if not has_x1 else M * 2,) + if rowscale is not None: + assert rowscale.is_contiguous() + assert rowscale.shape == (M,) + # allocate output + dx = ( + torch.empty_like(x) + if x_dtype is None + else torch.empty(M, N, dtype=x_dtype, device=x.device) + ) + dresidual_in = ( + torch.empty_like(x) + if has_residual + and (dx.dtype != x.dtype or dropout_p > 0.0 or rowscale is not None or has_x1) + else None + ) + dx1 = torch.empty_like(dx) if (has_x1 and dropout_p > 0.0) else None + y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None + if recompute_output: + assert weight1 is None, "recompute_output is not supported with parallel LayerNorm" + + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_N: + raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.") + sm_count = torch.cuda.get_device_properties(x.device).multi_processor_count + _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device) + _db = ( + torch.empty((sm_count, N), dtype=torch.float32, device=bias.device) + if bias is not None + else None + ) + _dw1 = torch.empty_like(_dw) if weight1 is not None else None + _db1 = torch.empty_like(_db) if bias1 is not None else None + rows_per_program = math.ceil(M / sm_count) + grid = (sm_count,) + with torch.cuda.device(x.device.index): + _layer_norm_bwd_kernel[grid]( + x, + weight, + bias, + y, + dy, + dx, + _dw, + _db, + dresidual, + weight1, + dy1, + dx1, + _dw1, + _db1, + dresidual_in, + rowscale, + seeds, + mean, + rstd, + x.stride(0), + 0 if not recompute_output else y.stride(0), + dy.stride(0), + dx.stride(0), + dresidual.stride(0) if dresidual is not None else 0, + dy1.stride(0) if dy1 is not None else 0, + dx1.stride(0) if dx1 is not None else 0, + dresidual_in.stride(0) if dresidual_in is not None else 0, + M, + N, + eps, + dropout_p, + rows_per_program, + is_rms_norm, + BLOCK_N, + dresidual is not None, + dresidual_in is not None, + bias is not None, + dropout_p > 0.0, + ) + dw = _dw.sum(0).to(weight.dtype) + db = _db.sum(0).to(bias.dtype) if bias is not None else None + dw1 = _dw1.sum(0).to(weight1.dtype) if weight1 is not None else None + db1 = _db1.sum(0).to(bias1.dtype) if bias1 is not None else None + # Don't need to compute dresidual_in separately in this case + if has_residual and dx.dtype == x.dtype and dropout_p == 0.0 and rowscale is None: + dresidual_in = dx + if has_x1 and dropout_p == 0.0: + dx1 = dx + return ( + (dx, dw, db, dresidual_in, dx1, dw1, db1) + if not recompute_output + else (dx, dw, db, dresidual_in, dx1, dw1, db1, y) + ) + + +class LayerNormFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, + return_dropout_mask=False, + out=None, + residual_out=None + ): + x_shape_og = x.shape + # reshape input data into 2D tensor + x = x.reshape(-1, x.shape[-1]) + if x.stride(-1) != 1: + x = x.contiguous() + if residual is not None: + assert residual.shape == x_shape_og + residual = residual.reshape(-1, residual.shape[-1]) + if residual.stride(-1) != 1: + residual = residual.contiguous() + if x1 is not None: + assert x1.shape == x_shape_og + assert rowscale is None, "rowscale is not supported with parallel LayerNorm" + x1 = x1.reshape(-1, x1.shape[-1]) + if x1.stride(-1) != 1: + x1 = x1.contiguous() + weight = weight.contiguous() + if bias is not None: + bias = bias.contiguous() + if weight1 is not None: + weight1 = weight1.contiguous() + if bias1 is not None: + bias1 = bias1.contiguous() + if rowscale is not None: + rowscale = rowscale.reshape(-1).contiguous() + residual_dtype = ( + residual.dtype + if residual is not None + else (torch.float32 if residual_in_fp32 else None) + ) + if out is not None: + out = out.reshape(-1, out.shape[-1]) + if residual_out is not None: + residual_out = residual_out.reshape(-1, residual_out.shape[-1]) + y, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd( + x, + weight, + bias, + eps, + residual, + x1, + weight1, + bias1, + dropout_p=dropout_p, + rowscale=rowscale, + residual_dtype=residual_dtype, + is_rms_norm=is_rms_norm, + return_dropout_mask=return_dropout_mask, + out=out, + residual_out=residual_out + ) + ctx.save_for_backward( + residual_out, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd + ) + ctx.x_shape_og = x_shape_og + ctx.eps = eps + ctx.dropout_p = dropout_p + ctx.is_rms_norm = is_rms_norm + ctx.has_residual = residual is not None + ctx.has_x1 = x1 is not None + ctx.prenorm = prenorm + ctx.x_dtype = x.dtype + y = y.reshape(x_shape_og) + y1 = y1.reshape(x_shape_og) if y1 is not None else None + residual_out = residual_out.reshape(x_shape_og) if residual_out is not None else None + dropout_mask = dropout_mask.reshape(x_shape_og) if dropout_mask is not None else None + dropout_mask1 = dropout_mask1.reshape(x_shape_og) if dropout_mask1 is not None else None + if not return_dropout_mask: + if weight1 is None: + return y if not prenorm else (y, residual_out) + else: + return (y, y1) if not prenorm else (y, y1, residual_out) + else: + if weight1 is None: + return ( + (y, dropout_mask, dropout_mask1) + if not prenorm + else (y, residual_out, dropout_mask, dropout_mask1) + ) + else: + return ( + (y, y1, dropout_mask, dropout_mask1) + if not prenorm + else (y, y1, residual_out, dropout_mask, dropout_mask1) + ) + + @staticmethod + def backward(ctx, dy, *args): + x, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd = ctx.saved_tensors + dy = dy.reshape(-1, dy.shape[-1]) + if dy.stride(-1) != 1: + dy = dy.contiguous() + assert dy.shape == x.shape + if weight1 is not None: + dy1, args = args[0], args[1:] + dy1 = dy1.reshape(-1, dy1.shape[-1]) + if dy1.stride(-1) != 1: + dy1 = dy1.contiguous() + assert dy1.shape == x.shape + else: + dy1 = None + if ctx.prenorm: + dresidual = args[0] + dresidual = dresidual.reshape(-1, dresidual.shape[-1]) + if dresidual.stride(-1) != 1: + dresidual = dresidual.contiguous() + assert dresidual.shape == x.shape + else: + dresidual = None + dx, dw, db, dresidual_in, dx1, dw1, db1 = _layer_norm_bwd( + dy, + x, + weight, + bias, + ctx.eps, + mean, + rstd, + dresidual, + dy1, + weight1, + bias1, + seeds, + ctx.dropout_p, + rowscale, + ctx.has_residual, + ctx.has_x1, + ctx.is_rms_norm, + x_dtype=ctx.x_dtype, + ) + return ( + dx.reshape(ctx.x_shape_og), + dw, + db, + dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None, + dx1.reshape(ctx.x_shape_og) if dx1 is not None else None, + dw1, + db1, + None, + None, + None, + None, + None, + None, + None, + None, + None, + ) + + +def layer_norm_fn( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, + return_dropout_mask=False, + out=None, + residual_out=None +): + return LayerNormFn.apply( + x, + weight, + bias, + residual, + x1, + weight1, + bias1, + eps, + dropout_p, + rowscale, + prenorm, + residual_in_fp32, + is_rms_norm, + return_dropout_mask, + out, + residual_out + ) + + +def rms_norm_fn( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, + out=None, + residual_out=None +): + return LayerNormFn.apply( + x, + weight, + bias, + residual, + x1, + weight1, + bias1, + eps, + dropout_p, + rowscale, + prenorm, + residual_in_fp32, + True, + return_dropout_mask, + out, + residual_out + ) + + +class RMSNorm(torch.nn.Module): + + def __init__(self, hidden_size, eps=1e-5, dropout_p=0.0, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.eps = eps + if dropout_p > 0.0: + self.drop = torch.nn.Dropout(dropout_p) + else: + self.drop = None + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + torch.nn.init.ones_(self.weight) + + def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False): + return rms_norm_fn( + x, + self.weight, + self.bias, + residual=residual, + eps=self.eps, + dropout_p=self.drop.p if self.drop is not None and self.training else 0.0, + prenorm=prenorm, + residual_in_fp32=residual_in_fp32, + ) + + +class LayerNormLinearFn(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward( + ctx, + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, + ): + x_shape_og = x.shape + # reshape input data into 2D tensor + x = x.reshape(-1, x.shape[-1]) + if x.stride(-1) != 1: + x = x.contiguous() + if residual is not None: + assert residual.shape == x_shape_og + residual = residual.reshape(-1, residual.shape[-1]) + if residual.stride(-1) != 1: + residual = residual.contiguous() + norm_weight = norm_weight.contiguous() + if norm_bias is not None: + norm_bias = norm_bias.contiguous() + residual_dtype = ( + residual.dtype + if residual is not None + else (torch.float32 if residual_in_fp32 else None) + ) + y, _, mean, rstd, residual_out, *rest = _layer_norm_fwd( + x, + norm_weight, + norm_bias, + eps, + residual, + out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype(), + residual_dtype=residual_dtype, + is_rms_norm=is_rms_norm, + ) + y = y.reshape(x_shape_og) + dtype = torch.get_autocast_gpu_dtype() if torch.is_autocast_enabled() else y.dtype + linear_weight = linear_weight.to(dtype) + linear_bias = linear_bias.to(dtype) if linear_bias is not None else None + out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias) + # We don't store y, will be recomputed in the backward pass to save memory + ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd) + ctx.x_shape_og = x_shape_og + ctx.eps = eps + ctx.is_rms_norm = is_rms_norm + ctx.has_residual = residual is not None + ctx.prenorm = prenorm + ctx.x_dtype = x.dtype + ctx.linear_bias_is_none = linear_bias is None + return out if not prenorm else (out, residual_out.reshape(x_shape_og)) + + @staticmethod + @custom_bwd + def backward(ctx, dout, *args): + x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors + dout = dout.reshape(-1, dout.shape[-1]) + dy = F.linear(dout, linear_weight.t()) + dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0) + if dy.stride(-1) != 1: + dy = dy.contiguous() + assert dy.shape == x.shape + if ctx.prenorm: + dresidual = args[0] + dresidual = dresidual.reshape(-1, dresidual.shape[-1]) + if dresidual.stride(-1) != 1: + dresidual = dresidual.contiguous() + assert dresidual.shape == x.shape + else: + dresidual = None + dx, dnorm_weight, dnorm_bias, dresidual_in, _, _, _, y = _layer_norm_bwd( + dy, + x, + norm_weight, + norm_bias, + ctx.eps, + mean, + rstd, + dresidual=dresidual, + has_residual=ctx.has_residual, + is_rms_norm=ctx.is_rms_norm, + x_dtype=ctx.x_dtype, + recompute_output=True, + ) + dlinear_weight = torch.einsum("bo,bi->oi", dout, y) + return ( + dx.reshape(ctx.x_shape_og), + dnorm_weight, + dnorm_bias, + dlinear_weight, + dlinear_bias, + dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None, + None, + None, + None, + None, + ) + + +def layer_norm_linear_fn( + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, +): + return LayerNormLinearFn.apply( + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual, + eps, + prenorm, + residual_in_fp32, + is_rms_norm, + ) diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/linear.py b/lib/python3.11/site-packages/flash_attn/ops/triton/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..a8966dbc345ab0e593df0124451ee7be3dae131a --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/linear.py @@ -0,0 +1,594 @@ +# Adapted from https://github.com/ELS-RD/kernl/blob/main/src/kernl/implementations/linear_layer.py +# and https://github.com/openai/triton/blob/master/python/triton/ops/matmul.py +from typing import Optional + +import torch +import triton +import triton.language as tl +from triton.ops.matmul_perf_model import early_config_prune, estimate_matmul_time + +from flash_attn.ops.triton.k_activations import ( + gelu, + gelu_approx, + gelu_approx_grad, + gelu_grad, + squared_relu, + squared_relu_grad, +) + +# CREDITS: Initially inspired by the Triton tutorial on matrix multiplications + + +def init_to_zero(name): + return lambda nargs: nargs[name].zero_() + + +def get_configs_io_bound(): + configs = [] + for num_stages in [2, 3, 4, 5, 6]: + for block_m in [16, 32]: + for block_k in [32, 64]: + for block_n in [32, 64, 128, 256]: + num_warps = 2 if block_n <= 64 else 4 + configs.append( + triton.Config( + { + "BLOCK_M": block_m, + "BLOCK_N": block_n, + "BLOCK_K": block_k, + "SPLIT_K": 1, + }, + num_stages=num_stages, + num_warps=num_warps, + ) + ) + # split_k not used + # for split_k in [2, 4, 8, 16]: + # configs.append(triton.Config( + # {'BLOCK_M': block_m, 'BLOCK_N': block_n, 'BLOCK_K': block_k, 'SPLIT_K': split_k}, + # num_stages=num_stages, num_warps=num_warps, pre_hook=init_to_zero('C'))) + return configs + + +@triton.autotune( + configs=[ + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + # good for int8 + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=4, + num_warps=4, + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + ] + + get_configs_io_bound(), + key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"], + prune_configs_by={ + "early_config_prune": early_config_prune, + "perf_model": estimate_matmul_time, + "top_k": 10, + }, +) +@triton.heuristics( + { + "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0, + } +) +@triton.jit +def kernel_fwd( + C, # Pointers to matrices + ACT_INPUT, + A, + B, + bias, + # Matrix dimensions + M, + N, + K, + CACHE_KEY_M, + CACHE_KEY_N, + CACHE_KEY_K, + # The stride variables represent how much to increase the ptr by when moving by 1 + # element in a particular dimension. E.g. stride_am is how much to increase a_ptr + # by to get the element one row down (A has M rows) + stride_cm, + # stride_cn, # Assume that stride_cn == 1 + stride_am, + stride_ak, + stride_bn, + stride_bk, + # Meta-parameters + BLOCK_M: tl.constexpr, + GROUP_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_K: tl.constexpr, + # split k not used, not performant with activation, kept because early_config_prune is expecting it + SPLIT_K: tl.constexpr, + EVEN_K: tl.constexpr, + A_ROWMAJOR: tl.constexpr, + B_COLMAJOR: tl.constexpr, + BIAS: tl.constexpr, + SAVE_ACT_INPUT: tl.constexpr, + ACTIVATION: tl.constexpr, +): + + """ + Kernel for computing Out = activation(A x W + C) + - Input has shape (M, K) + - Weight has shape (K, N) + - Bias has shape (N,) + - Output has shape (M, N) + - ActInputs (optional) has shape (M, N) + 'ActInputs' optionally saves the A x W + C intermediate for backward computations + This kernel will consolidate over K + """ + + pid = tl.program_id(axis=0) + + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + # now compute the block that each program will go through + # rm (resp. rn) denotes a range of indices + # for rows (resp. col) of C + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + # trick to avoid masking on M and N axis + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + + if A_ROWMAJOR: + A = A + (ram[:, None] * stride_am + rk[None, :]) + else: + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + if B_COLMAJOR: + B = B + (rk[:, None] + rbn[None, :] * stride_bn) + else: + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.0) + b = tl.load(B, mask=rk[:, None] < k, other=0.0) + acc += tl.dot(a, b) + + if A_ROWMAJOR: + A += BLOCK_K + else: + A += BLOCK_K * stride_ak + if B_COLMAJOR: + B += BLOCK_K + else: + B += BLOCK_K * stride_bk + + # Putting bias after the matmul (instead of before) is faster, idk why + if BIAS: + bias = tl.load(bias + rn, mask=rn < N, other=0.0).to(tl.float32) + acc += bias[None, :] + + # optional: save the activation inputs + if SAVE_ACT_INPUT: + # act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] * stride_cn + act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] + tl.store(act_in_ptrs, acc) + + # optional: fused activation (while the data is in shared memory) + if ACTIVATION == "gelu": + acc = gelu(acc) + elif ACTIVATION == "gelu_approx": + acc = gelu_approx(acc) + elif ACTIVATION == "squared_relu": + acc = squared_relu(acc) + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + # write back result + # C = C + rm[:, None] * stride_cm + rn[None, :] * stride_cn + C = C + rm[:, None] * stride_cm + rn[None, :] + mask = (rm < M)[:, None] & (rn < N)[None, :] + tl.store(C, acc) + + +def triton_linear_act( + x: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor] = None, + activation: str = "id", + save_act_input: bool = False, +) -> torch.Tensor: + """ + Compute e = activation(x @ weight.T + bias). + This wrapper kicks the `kernel_fwd` Triton kernel + :param x: input tensor + :param weight: weight matrix + :param bias: an optional bias tensor + :param activation: Activation name. Needs to be a Triton kernel. + :param act_input: an optional tensor to save the activation inputs (for backward) + :return: result tensor + """ + # if torch.is_autocast_enabled(): + # dtype = torch.get_autocast_gpu_dtype() + # x, weight, bias = [a.to(dtype=dtype) for a in [x, weight, bias]] + + assert activation in ["id", "gelu", "gelu_approx", "squared_relu"] + + batch_shape, n = x.shape[:-1], x.shape[-1] + batch_dim = batch_shape.numel() + x_reshaped = x.reshape(batch_dim, n) + + if x_reshaped.stride(0) > 1 and x_reshaped.stride(1) > 1: + x_reshaped = x_reshaped.contiguous() + if weight.stride(0) > 1 and weight.stride(1) > 1: + weight = weight.contiguous() + bias = bias.contiguous() if bias is not None else None + + assert ( + x.dtype == weight.dtype + ), f"Input and weight must have the same dtype, got {x.dtype} and {weight.dtype}" + if bias is not None: + assert ( + x.dtype == bias.dtype + ), f"Input and bias must have the same dtype, got {x.dtype} and {bias.dtype}" + assert ( + x_reshaped.shape[1] == weight.shape[1] + ), f"Incompatible dimensions: {x_reshaped.shape} - {weight.shape}" + + assert ( + bias is None or bias.shape[0] == weight.shape[0] + ), "Incompatible dimensions in between weight and bias" + + M, K = x_reshaped.shape + N, K = weight.shape + + output = torch.empty((M, N), device=x.device, dtype=x.dtype) + act_input = torch.empty_like(output) if save_act_input else None + + # 1D launch kernel where each block gets its own program. + grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa + + kernel_fwd[grid]( + output, + act_input, + x_reshaped, + weight, # data ptrs + bias if bias is not None else x, # auto skip bias if not present + M, # shapes + N, + K, + M // 32, # key for triton cache (limit number of compilations) + N // 32, + K // 32, + stride_cm=output.stride(0), # strides + # stride_cn=output.stride(1), + stride_am=x_reshaped.stride(0), + stride_ak=x_reshaped.stride(1), + stride_bk=weight.stride(1), + stride_bn=weight.stride(0), + BIAS=bias is not None, # optional fused bias + SAVE_ACT_INPUT=save_act_input, # optional save activation inputs + ACTIVATION=activation, # optional fused activation + A_ROWMAJOR=x_reshaped.stride(1) == 1, + B_COLMAJOR=weight.stride(1) == 1, + GROUP_M=8, # speed optimization: group the programs + ) + + if not save_act_input: + return output.reshape(*batch_shape, output.shape[-1]) + else: + return ( + output.reshape(*batch_shape, output.shape[-1]), + act_input.reshape(*batch_shape, act_input.shape[-1]), + ) + + +@triton.autotune( + configs=[ + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + # good for int8 + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=4, + num_warps=4, + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + ] + + get_configs_io_bound(), + key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"], + prune_configs_by={ + "early_config_prune": early_config_prune, + "perf_model": estimate_matmul_time, + "top_k": 10, + }, +) +@triton.heuristics( + { + "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0, + } +) +@triton.jit +def kernel_bwd( + C, # Pointers to matrices + ACT_INPUT, + A, + B, + # Matrix dimensions + M, + N, + K, + CACHE_KEY_M, + CACHE_KEY_N, + CACHE_KEY_K, + # The stride variables represent how much to increase the ptr by when moving by 1 + # element in a particular dimension. E.g. stride_am is how much to increase a_ptr + # by to get the element one row down (A has M rows) + stride_cm, + # stride_cn, # Assume that stride_cn == 1 + stride_am, + stride_ak, + stride_bk, + stride_bn, + # Meta-parameters + BLOCK_M: tl.constexpr, + GROUP_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_K: tl.constexpr, + # split k not used, not performant with activation, kept because early_config_prune is expecting it + SPLIT_K: tl.constexpr, + EVEN_K: tl.constexpr, + ACTIVATION: tl.constexpr, +): + + """ + Kernel for computing Out = activation(A x W + C) + - Input has shape (M, K) + - Weight has shape (K, N) + - Output has shape (M, N) + - ActInputs (optional) has shape (M, N) + 'ActInputs' optionally saves the A x W + C intermediate for backward computations + This kernel will consolidate over K + """ + + pid = tl.program_id(axis=0) + + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + # now compute the block that each program will go through + # rm (resp. rn) denotes a range of indices + # for rows (resp. col) of C + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + # trick to avoid masking on M and N axis + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.0) + b = tl.load(B, mask=rk[:, None] < k, other=0.0) + acc += tl.dot(a, b) + + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + # optional: fused activation (while the data is in shared memory) + if ACTIVATION != "id": + act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] + act_input = tl.load(act_in_ptrs).to(acc.dtype) + if ACTIVATION == "gelu": + acc *= gelu_grad(act_input) + elif ACTIVATION == "gelu_approx": + acc *= gelu_approx_grad(act_input) + elif ACTIVATION == "squared_relu": + acc *= squared_relu_grad(act_input) + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + # write back result + C = C + rm[:, None] * stride_cm + rn[None, :] + mask = (rm < M)[:, None] & (rn < N)[None, :] + tl.store(C, acc, mask=mask) + + +def triton_dgrad_act( + grad_output: torch.Tensor, + weight: torch.Tensor, + activation: str = "id", + act_input: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Compute e = activation(grad_output @ weight + bias). + This wrapper kicks the `kernel_fwd` Triton kernel + :param grad_output: input tensor + :param weight: weight matrix + :param activation: Activation name. Needs to be a Triton kernel. + :param act_input: an optional tensor to save the activation inputs (for backward) + :return: result tensor + """ + assert activation in ["id", "gelu", "gelu_approx", "squared_relu"] + + batch_shape, n = grad_output.shape[:-1], grad_output.shape[-1] + batch_dim = batch_shape.numel() + grad_output_reshaped = grad_output.reshape(batch_dim, n) + + if grad_output_reshaped.stride(0) > 1 and grad_output_reshaped.stride(1) > 1: + grad_output_reshaped = grad_output_reshaped.contiguous() + if weight.stride(0) > 1 and weight.stride(1) > 1: + weight = weight.contiguous() + + assert ( + grad_output.dtype == weight.dtype + ), f"grad_output and weight must have the same dtype, got {grad_output.dtype} and {weight.dtype}" + assert ( + grad_output_reshaped.shape[1] == weight.shape[0] + ), f"Incompatible dimensions: {grad_output_reshaped.shape} - {weight.shape}" + if activation != "id": + assert act_input is not None, f"act_input is required for activation {activation}" + + # M, N, K in bwd are different from M, N, K in fwd + M, K = grad_output_reshaped.shape + K, N = weight.shape + + grad_input = torch.empty((M, N), device=grad_output.device, dtype=grad_output.dtype) + + # 1D launch kernel where each block gets its own program. + grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa + + kernel_bwd[grid]( + grad_input, + act_input, + grad_output_reshaped, + weight, # data ptrs + M, # shapes + N, + K, + M // 32, # key for triton cache (limit number of compilations) + N // 32, + K // 32, + stride_cm=grad_input.stride(0), # strides + # stride_cn=grad_input.stride(1), + stride_am=grad_output_reshaped.stride(0), + stride_ak=grad_output_reshaped.stride(1), + stride_bk=weight.stride(0), + stride_bn=weight.stride(1), + ACTIVATION=activation, # optional fused activation + GROUP_M=8, # speed optimization: group the programs + ) + + return grad_input.reshape(*batch_shape, grad_input.shape[-1]) diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/mlp.py b/lib/python3.11/site-packages/flash_attn/ops/triton/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..b795310f1c8afc8203124597bb6ca70f1af7ed11 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/mlp.py @@ -0,0 +1,149 @@ +# The triton fused matmul + sqrelu is faster for fp16 but slower for bf16, compared +# to naive implementation. +import fused_dense_lib as fused_dense_cuda +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.cuda.amp import custom_bwd, custom_fwd + +from flash_attn.ops.activations import sqrelu_bwd, sqrelu_fwd +from flash_attn.ops.triton.linear import triton_dgrad_act, triton_linear_act + + +class FusedDenseSqreluDenseFunc(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward(ctx, x, weight1, bias1, weight2, bias2, checkpoint_lvl=0): + """checkpoint_lvl: + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute act_input and gelu_out in the bwd + """ + if torch.is_autocast_enabled(): + dtype = torch.get_autocast_gpu_dtype() + x, weight1, bias1, weight2, bias2 = [ + a.to(dtype=dtype) for a in [x, weight1, bias1, weight2, bias2] + ] + is_bf16 = x.dtype == torch.bfloat16 + assert checkpoint_lvl in [0, 1, 2] + x = x.contiguous() + weight1 = weight1.contiguous() + bias1 = bias1.contiguous() + weight2 = weight2.contiguous() + bias2 = bias2.contiguous() + batch_shape, n = x.shape[:-1], x.shape[-1] + batch_dim = batch_shape.numel() + if is_bf16: + act_input = fused_dense_cuda.linear_bias_forward( + x.reshape(batch_dim, n), weight1, bias1 + ) + output1 = sqrelu_fwd(act_input) + else: + save_act_input = checkpoint_lvl != 2 + result = triton_linear_act( + x.reshape(batch_dim, n), + weight1, + bias1, + activation="squared_relu", + save_act_input=save_act_input, + ) + if save_act_input: + output1, act_input = result + else: + output1 = result + output2 = fused_dense_cuda.linear_bias_forward(output1, weight2, bias2) + ctx.checkpoint_lvl = checkpoint_lvl + if checkpoint_lvl == 0: + ctx.save_for_backward(x, weight1, bias1, weight2, act_input, output1) + elif checkpoint_lvl == 1: + ctx.save_for_backward(x, weight1, bias1, weight2, act_input) + elif checkpoint_lvl == 2: + ctx.save_for_backward(x, weight1, bias1, weight2) + return output2.reshape(*batch_shape, output2.shape[-1]) + + @staticmethod + @custom_bwd + def backward(ctx, grad_output): + grad_output = grad_output.contiguous() + checkpoint_lvl = ctx.checkpoint_lvl + x, weight1, bias1, weight2, *rest = ctx.saved_tensors + batch_shape, n = x.shape[:-1], x.shape[-1] + batch_dim = batch_shape.numel() + is_bf16 = x.dtype == torch.bfloat16 + if checkpoint_lvl == 0: + act_input, output1 = rest + elif checkpoint_lvl == 1: + (act_input,) = rest + output1 = sqrelu_fwd(act_input) + elif checkpoint_lvl == 2: + if is_bf16: + act_input = fused_dense_cuda.linear_bias_forward( + x.reshape(batch_dim, n), weight1, bias1 + ) + output1 = sqrelu_fwd(act_input) + else: + output1, act_input = triton_linear_act( + x.reshape(batch_dim, n), + weight1, + bias1, + activation="squared_relu", + save_act_input=True, + ) + + if is_bf16: + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output) + grad_output1 = grad_output @ weight2 + grad_act_input = sqrelu_bwd(grad_output1, act_input) + grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward( + x.reshape(batch_dim, n), weight1, grad_act_input + ) + else: + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output) + grad_act_input = triton_dgrad_act( + grad_output, weight2, activation="squared_relu", act_input=act_input + ) + grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward( + x.reshape(batch_dim, n), weight1, grad_act_input + ) + return grad_input.reshape_as(x), grad_weight1, grad_bias1, grad_weight2, grad_bias2, None + + +fused_dense_sqrelu_dense_function = FusedDenseSqreluDenseFunc.apply + + +class FusedDenseSqreluDense(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + bias1=True, + bias2=True, + checkpoint_lvl=0, + device=None, + dtype=None, + ): + """ + checkpoint_lvl (increasing lvl means slower but more memory saving): + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute gelu_in and gelu_out in the bwd + """ + assert checkpoint_lvl in [0, 1, 2] + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features * 4 + assert bias1 == True, "DenseSqreluDense module without bias is currently not supported" + assert bias2 == True, "DenseSqreluDense module without bias is currently not supported" + self.checkpoint_lvl = checkpoint_lvl + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs) + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x): + assert x.is_cuda + return fused_dense_sqrelu_dense_function( + x, self.fc1.weight, self.fc1.bias, self.fc2.weight, self.fc2.bias, self.checkpoint_lvl + ) diff --git a/lib/python3.11/site-packages/flash_attn/ops/triton/rotary.py b/lib/python3.11/site-packages/flash_attn/ops/triton/rotary.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee56d647738cb1c74e2b0a341e7ae7bef85f966 --- /dev/null +++ b/lib/python3.11/site-packages/flash_attn/ops/triton/rotary.py @@ -0,0 +1,227 @@ +# Copyright (c) 2023, Tri Dao. + +from typing import Optional, Union + +import torch + +import triton +import triton.language as tl + + +@triton.jit +def rotary_kernel( + OUT, # Pointers to matrices + X, + COS, + SIN, + CU_SEQLENS, + SEQLEN_OFFSETS, # this could be int or a pointer + # Matrix dimensions + seqlen, + rotary_dim, + seqlen_ro, + # strides + stride_out_batch, + stride_out_seqlen, + stride_out_nheads, + stride_out_headdim, + stride_x_batch, + stride_x_seqlen, + stride_x_nheads, + stride_x_headdim, + # Meta-parameters + BLOCK_K: tl.constexpr, + IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr, + IS_VARLEN: tl.constexpr, + INTERLEAVED: tl.constexpr, + CONJUGATE: tl.constexpr, + BLOCK_M: tl.constexpr, +): + pid_m = tl.program_id(axis=0) + pid_batch = tl.program_id(axis=1) + pid_head = tl.program_id(axis=2) + rotary_dim_half = rotary_dim // 2 + + if not IS_VARLEN: + X = X + pid_batch * stride_x_batch + pid_head * stride_x_nheads + OUT = OUT + pid_batch * stride_out_batch + pid_head * stride_out_nheads + else: + start_idx = tl.load(CU_SEQLENS + pid_batch) + seqlen = tl.load(CU_SEQLENS + pid_batch + 1) - start_idx + X = X + start_idx * stride_x_seqlen + pid_head * stride_x_nheads + OUT = OUT + start_idx * stride_out_seqlen + pid_head * stride_out_nheads + + if pid_m * BLOCK_M >= seqlen: + return + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + if not IS_SEQLEN_OFFSETS_TENSOR: + rm_cs = rm + SEQLEN_OFFSETS + else: + rm_cs = rm + tl.load(SEQLEN_OFFSETS + pid_batch) + rk = tl.arange(0, BLOCK_K) + rk_half = tl.arange(0, BLOCK_K // 2) + + if not INTERLEAVED: + # Load the 1st and 2nd halves of X, do calculation, then store to 1st and 2nd halves of OUT + X = X + (rm[:, None] * stride_x_seqlen + rk_half[None, :] * stride_x_headdim) + COS = COS + (rm_cs[:, None] * rotary_dim_half + rk_half[None, :]) + SIN = SIN + (rm_cs[:, None] * rotary_dim_half + rk_half[None, :]) + cos = tl.load( + COS, mask=(rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < rotary_dim_half), other=1.0 + ).to(tl.float32) + sin = tl.load( + SIN, mask=(rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < rotary_dim_half), other=0.0 + ).to(tl.float32) + x0 = tl.load( + X, mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half), other=0.0 + ).to(tl.float32) + x1 = tl.load( + X + rotary_dim_half * stride_x_headdim, + mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half), + other=0.0, + ).to(tl.float32) + if CONJUGATE: + sin = -sin + o0 = x0 * cos - x1 * sin + o1 = x0 * sin + x1 * cos + # write back result + OUT = OUT + (rm[:, None] * stride_out_seqlen + rk_half[None, :] * stride_out_headdim) + tl.store(OUT, o0, mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half)) + tl.store( + OUT + rotary_dim_half * stride_out_headdim, + o1, + mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half), + ) + else: + # We don't want to load X[0, 2, 4, ...] and X[1, 3, 5, ...] separately since both are slow. + # Instead, we load x0 = X[0, 1, 2, 3, ...] and x1 = X[1, 0, 3, 2, ...]. + # Loading x0 will be fast but x1 will be slow. + # Then we load cos = COS[0, 0, 1, 1, ...] and sin = SIN[0, 0, 1, 1, ...]. + # Then we do the calculation and use tl.where to pick put the right outputs for the even + # and for the odd indices. + rk_swap = rk + ((rk + 1) % 2) * 2 - 1 # 1, 0, 3, 2, 5, 4, ... + rk_repeat = tl.arange(0, BLOCK_K) // 2 + X0 = X + (rm[:, None] * stride_x_seqlen + rk[None, :] * stride_x_headdim) + X1 = X + (rm[:, None] * stride_x_seqlen + rk_swap[None, :] * stride_x_headdim) + COS = COS + (rm_cs[:, None] * rotary_dim_half + rk_repeat[None, :]) + SIN = SIN + (rm_cs[:, None] * rotary_dim_half + rk_repeat[None, :]) + cos = tl.load( + COS, + mask=(rm_cs[:, None] < seqlen_ro) & (rk_repeat[None, :] < rotary_dim_half), + other=1.0, + ).to(tl.float32) + sin = tl.load( + SIN, + mask=(rm_cs[:, None] < seqlen_ro) & (rk_repeat[None, :] < rotary_dim_half), + other=0.0, + ).to(tl.float32) + x0 = tl.load(X0, mask=(rm[:, None] < seqlen) & (rk[None, :] < rotary_dim), other=0.0).to( + tl.float32 + ) + x1 = tl.load( + X1, mask=(rm[:, None] < seqlen) & (rk_swap[None, :] < rotary_dim), other=0.0 + ).to(tl.float32) + if CONJUGATE: + sin = -sin + x0_cos = x0 * cos + x1_sin = x1 * sin + out = tl.where(rk[None, :] % 2 == 0, x0_cos - x1_sin, x0_cos + x1_sin) + OUT = OUT + (rm[:, None] * stride_out_seqlen + rk[None, :] * stride_out_headdim) + tl.store(OUT, out, mask=(rm[:, None] < seqlen) & (rk[None, :] < rotary_dim)) + + +def apply_rotary( + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + seqlen_offsets: Union[int, torch.Tensor] = 0, + cu_seqlens: Optional[torch.Tensor] = None, + max_seqlen: Optional[int] = None, + interleaved=False, + inplace=False, + conjugate=False, +) -> torch.Tensor: + """ + Arguments: + x: (batch, seqlen, nheads, headdim) if cu_seqlens is None + else (total_seqlen, nheads, headdim). + cos: (seqlen_ro, rotary_dim / 2) + sin: (seqlen_ro, rotary_dim / 2) + seqlen_offsets: integer or integer tensor of size (batch,) + cu_seqlens: (batch + 1,) or None + max_seqlen: int + Returns: + y: (batch, seqlen, nheads, headdim) + """ + is_varlen = cu_seqlens is not None + if not is_varlen: + batch, seqlen, nheads, headdim = x.shape + else: + assert max_seqlen is not None, "If cu_seqlens is passed in, then max_seqlen must be passed" + total_seqlen, nheads, headdim = x.shape + batch_p_1 = cu_seqlens.shape[0] + batch = batch_p_1 - 1 + seqlen = max_seqlen + seqlen_ro, rotary_dim = cos.shape + assert sin.shape == cos.shape + rotary_dim *= 2 + assert rotary_dim <= headdim, "rotary_dim must be <= headdim" + assert headdim <= 256, "Only support headdim <= 256" + assert seqlen_ro >= seqlen, "seqlen_ro must be >= seqlen" + + assert ( + cos.dtype == sin.dtype + ), f"cos and sin must have the same dtype, got {cos.dtype} and {sin.dtype}" + assert ( + x.dtype == cos.dtype + ), f"Input and cos/sin must have the same dtype, got {x.dtype} and {cos.dtype}" + + cos, sin = cos.contiguous(), sin.contiguous() + if isinstance(seqlen_offsets, torch.Tensor): + assert seqlen_offsets.shape == (batch,) + assert seqlen_offsets.dtype in [torch.int32, torch.int64] + seqlen_offsets = seqlen_offsets.contiguous() + else: + assert seqlen_offsets + seqlen <= seqlen_ro + + output = torch.empty_like(x) if not inplace else x + if rotary_dim < headdim and not inplace: + output[..., rotary_dim:].copy_(x[..., rotary_dim:]) + + BLOCK_K = ( + 32 + if rotary_dim <= 32 + else (64 if rotary_dim <= 64 else (128 if rotary_dim <= 128 else 256)) + ) + grid = lambda META: (triton.cdiv(seqlen, META["BLOCK_M"]), batch, nheads) # noqa + BLOCK_M = 4 if interleaved else (8 if rotary_dim <= 128 else 4) + + # Need this, otherwise Triton tries to launch from cuda:0 and we get + # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?) + with torch.cuda.device(x.device.index): + rotary_kernel[grid]( + output, # data ptrs + x, + cos, + sin, + cu_seqlens, + seqlen_offsets, + seqlen, # shapes + rotary_dim, + seqlen_ro, + output.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0 + output.stride(-3), # seqlen_stride or total_seqlen_stride + output.stride(-2), # nheads_stride + output.stride(-1), # headdim_stride + x.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0 + x.stride(-3), # seqlen stride or total_seqlen_stride + x.stride(-2), # nheads stride + x.stride(-1), # headdim stride + BLOCK_K, + isinstance(seqlen_offsets, torch.Tensor), + is_varlen, + interleaved, + conjugate, + BLOCK_M, + ) + return output diff --git a/lib/python3.11/site-packages/multipart/__init__.py b/lib/python3.11/site-packages/multipart/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..53c08d28d0ee974896a3fd4cc26e90d1e6592119 --- /dev/null +++ b/lib/python3.11/site-packages/multipart/__init__.py @@ -0,0 +1,38 @@ +# Copyright 2012, Andrew Dunham +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This only works if using a file system, other loaders not implemented. + +import importlib.util +import sys +import warnings +from pathlib import Path + +for p in sys.path: + file_path = Path(p, "multipart.py") + try: + if file_path.is_file(): + spec = importlib.util.spec_from_file_location("multipart", file_path) + assert spec is not None, f"{file_path} found but not loadable!" + module = importlib.util.module_from_spec(spec) + sys.modules["multipart"] = module + assert spec.loader is not None, f"{file_path} must be loadable!" + spec.loader.exec_module(module) + break + except PermissionError: + pass +else: + warnings.warn("Please use `import python_multipart` instead.", PendingDeprecationWarning, stacklevel=2) + from python_multipart import * + from python_multipart import __all__, __version__ diff --git a/lib/python3.11/site-packages/multipart/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/multipart/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3886d4258082118d312df6504ebfd34f522e8b9a Binary files /dev/null and b/lib/python3.11/site-packages/multipart/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/multipart/__pycache__/decoders.cpython-311.pyc b/lib/python3.11/site-packages/multipart/__pycache__/decoders.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b433cbfe6a7ffed4c3c21064224302b1cc77bf97 Binary files /dev/null and b/lib/python3.11/site-packages/multipart/__pycache__/decoders.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/multipart/__pycache__/exceptions.cpython-311.pyc b/lib/python3.11/site-packages/multipart/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3920e5781b02ab088dbcf7a5ca86e7fed1b9b852 Binary files /dev/null and b/lib/python3.11/site-packages/multipart/__pycache__/exceptions.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/multipart/__pycache__/multipart.cpython-311.pyc b/lib/python3.11/site-packages/multipart/__pycache__/multipart.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4155067a0c01442ddbd69d5aae024bf9d8dd0ad2 Binary files /dev/null and b/lib/python3.11/site-packages/multipart/__pycache__/multipart.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/multipart/decoders.py b/lib/python3.11/site-packages/multipart/decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..31acdfbf1d69a0a13dcde2742fdeb6ff04e98e7d --- /dev/null +++ b/lib/python3.11/site-packages/multipart/decoders.py @@ -0,0 +1 @@ +from python_multipart.decoders import * diff --git a/lib/python3.11/site-packages/multipart/exceptions.py b/lib/python3.11/site-packages/multipart/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..36815d1980abcf496bf63b0ac93525053111dc79 --- /dev/null +++ b/lib/python3.11/site-packages/multipart/exceptions.py @@ -0,0 +1 @@ +from python_multipart.exceptions import * diff --git a/lib/python3.11/site-packages/multipart/multipart.py b/lib/python3.11/site-packages/multipart/multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf567dfc297e9e97c10073b2022efc993e39b93 --- /dev/null +++ b/lib/python3.11/site-packages/multipart/multipart.py @@ -0,0 +1 @@ +from python_multipart.multipart import * diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/INSTALLER b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/METADATA b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ad8407757d7731d6c7ebf6aa6f61e792eb8eb644 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/METADATA @@ -0,0 +1,1140 @@ +Metadata-Version: 2.4 +Name: orjson +Version: 3.11.9 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: License :: OSI Approved :: MIT License +Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Rust +Classifier: Typing :: Typed +License-File: LICENSE-APACHE +License-File: LICENSE-MIT +License-File: LICENSE-MPL-2.0 +Summary: Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy +License-Expression: MPL-2.0 AND (Apache-2.0 OR MIT) +Requires-Python: >=3.10 +Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM +Project-URL: changelog, https://github.com/ijl/orjson/blob/master/CHANGELOG.md +Project-URL: documentation, https://github.com/ijl/orjson +Project-URL: source, https://github.com/ijl/orjson + +# orjson + +orjson is a fast, correct JSON library for Python. It +[benchmarks](https://github.com/ijl/orjson?tab=readme-ov-file#performance) as the fastest Python +library for JSON and is more correct than the standard json library or other +third-party libraries. It serializes +[dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass), +[datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime), +[numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy), and +[UUID](https://github.com/ijl/orjson?tab=readme-ov-file#uuid) instances natively. + +[orjson.dumps()](https://github.com/ijl/orjson?tab=readme-ov-file#serialize) is +something like 10x as fast as `json`, serializes +common types and subtypes, has a `default` parameter for the caller to specify +how to serialize arbitrary types, and has a number of flags controlling output. + +[orjson.loads()](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize) +is something like 2x as fast as `json`, and is strictly compliant with UTF-8 and +RFC 8259 ("The JavaScript Object Notation (JSON) Data Interchange Format"). + +Reading from and writing to files, line-delimited JSON files, and so on is +not provided by the library. + +orjson supports CPython 3.10, 3.11, 3.12, 3.13, 3.14, and 3.15. + +It distributes amd64/x86_64/x64, i686/x86, aarch64/arm64/armv8, arm7, +ppc64le/POWER8, and s390x wheels for Linux, amd64 and aarch64 wheels +for macOS, and amd64, i686, and aarch64 wheels for Windows. + +Wheels published to PyPI for amd64 run on x86-64-v1 (2003) +or later, but will at runtime use AVX-512 if available for a +significant performance benefit; aarch64 wheels run on ARMv8-A (2011) or +later. + +orjson does not and will not support PyPy, embedded Python builds for +Android/iOS, or PEP 554 subinterpreters. + +orjson may support PEP 703 free-threading when it is stable. + +Releases follow semantic versioning and serializing a new object type +without an opt-in flag is considered a breaking change. + +orjson contains source code licensed under the Mozilla Public License 2.0, +Apache 2.0, and MIT licenses. The repository from which PyPI artifacts are +published is [github.com/ijl/orjson](https://github.com/ijl/orjson) and an +alternative repository is [codeberg.org/ijl/orjson](https://codeberg.org/ijl/orjson). +There is no open issue tracker or pull requests due to signal-to-noise ratio. +There is a [CHANGELOG](https://github.com/ijl/orjson/blob/master/CHANGELOG.md) +available in the repository. + +1. [Usage](https://github.com/ijl/orjson?tab=readme-ov-file#usage) + 1. [Install](https://github.com/ijl/orjson?tab=readme-ov-file#install) + 2. [Quickstart](https://github.com/ijl/orjson?tab=readme-ov-file#quickstart) + 3. [Migrating](https://github.com/ijl/orjson?tab=readme-ov-file#migrating) + 4. [Serialize](https://github.com/ijl/orjson?tab=readme-ov-file#serialize) + 1. [default](https://github.com/ijl/orjson?tab=readme-ov-file#default) + 2. [option](https://github.com/ijl/orjson?tab=readme-ov-file#option) + 3. [Fragment](https://github.com/ijl/orjson?tab=readme-ov-file#fragment) + 5. [Deserialize](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize) +2. [Types](https://github.com/ijl/orjson?tab=readme-ov-file#types) + 1. [dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass) + 2. [datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime) + 3. [enum](https://github.com/ijl/orjson?tab=readme-ov-file#enum) + 4. [float](https://github.com/ijl/orjson?tab=readme-ov-file#float) + 5. [int](https://github.com/ijl/orjson?tab=readme-ov-file#int) + 6. [numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy) + 7. [str](https://github.com/ijl/orjson?tab=readme-ov-file#str) + 8. [uuid](https://github.com/ijl/orjson?tab=readme-ov-file#uuid) +3. [Testing](https://github.com/ijl/orjson?tab=readme-ov-file#testing) +4. [Performance](https://github.com/ijl/orjson?tab=readme-ov-file#performance) + 1. [Latency](https://github.com/ijl/orjson?tab=readme-ov-file#latency) + 2. [Reproducing](https://github.com/ijl/orjson?tab=readme-ov-file#reproducing) +5. [Questions](https://github.com/ijl/orjson?tab=readme-ov-file#questions) +6. [Packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging) +7. [License](https://github.com/ijl/orjson?tab=readme-ov-file#license) + +## Usage + +### Install + +To install a wheel from PyPI, install the `orjson` package. + +In `requirements.in` or `requirements.txt` format, specify: + +```txt +orjson >= 3.10,<4 +``` + +In `pyproject.toml` format, specify: + +```toml +orjson = "^3.10" +``` + +To build a wheel, see [packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging). + +### Quickstart + +This is an example of serializing, with options specified, and deserializing: + +```python +>>> import orjson, datetime, numpy +>>> data = { + "type": "job", + "created_at": datetime.datetime(1970, 1, 1), + "status": "🆗", + "payload": numpy.array([[1, 2], [3, 4]]), +} +>>> orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY) +b'{"type":"job","created_at":"1970-01-01T00:00:00+00:00","status":"\xf0\x9f\x86\x97","payload":[[1,2],[3,4]]}' +>>> orjson.loads(_) +{'type': 'job', 'created_at': '1970-01-01T00:00:00+00:00', 'status': '🆗', 'payload': [[1, 2], [3, 4]]} +``` + +### Migrating + +orjson version 3 serializes more types than version 2. Subclasses of `str`, +`int`, `dict`, and `list` are now serialized. This is faster and more similar +to the standard library. It can be disabled with +`orjson.OPT_PASSTHROUGH_SUBCLASS`.`dataclasses.dataclass` instances +are now serialized by default and cannot be customized in a +`default` function unless `option=orjson.OPT_PASSTHROUGH_DATACLASS` is +specified. `uuid.UUID` instances are serialized by default. +For any type that is now serialized, +implementations in a `default` function and options enabling them can be +removed but do not need to be. There was no change in deserialization. + +To migrate from the standard library, the largest difference is that +`orjson.dumps` returns `bytes` and `json.dumps` returns a `str`. + +Users with `dict` objects using non-`str` keys should specify `option=orjson.OPT_NON_STR_KEYS`. + +`sort_keys` is replaced by `option=orjson.OPT_SORT_KEYS`. + +`indent` is replaced by `option=orjson.OPT_INDENT_2` and other levels of indentation are not +supported. + +`ensure_ascii` is probably not relevant today and UTF-8 characters cannot be +escaped to ASCII. + +### Serialize + +```python +def dumps( + __obj: Any, + default: Optional[Callable[[Any], Any]] = ..., + option: Optional[int] = ..., +) -> bytes: ... +``` + +`dumps()` serializes Python objects to JSON. + +It natively serializes +`str`, `dict`, `list`, `tuple`, `int`, `float`, `bool`, `None`, +`dataclasses.dataclass`, `typing.TypedDict`, `datetime.datetime`, +`datetime.date`, `datetime.time`, `uuid.UUID`, `numpy.ndarray`, and +`orjson.Fragment` instances. It supports arbitrary types through `default`. It +serializes subclasses of `str`, `int`, `dict`, `list`, +`dataclasses.dataclass`, and `enum.Enum`. It does not serialize subclasses +of `tuple` to avoid serializing `namedtuple` objects as arrays. To avoid +serializing subclasses, specify the option `orjson.OPT_PASSTHROUGH_SUBCLASS`. + +The output is a `bytes` object containing UTF-8. + +The global interpreter lock (GIL) is held for the duration of the call. + +It raises `JSONEncodeError` on an unsupported type. This exception message +describes the invalid object with the error message +`Type is not JSON serializable: ...`. To fix this, specify +[default](https://github.com/ijl/orjson?tab=readme-ov-file#default). + +It raises `JSONEncodeError` on a `str` that contains invalid UTF-8. + +It raises `JSONEncodeError` on an integer that exceeds 64 bits by default or, +with `OPT_STRICT_INTEGER`, 53 bits. + +It raises `JSONEncodeError` if a `dict` has a key of a type other than `str`, +unless `OPT_NON_STR_KEYS` is specified. + +It raises `JSONEncodeError` if the output of `default` recurses to handling by +`default` more than 254 levels deep. + +It raises `JSONEncodeError` on circular references. + +It raises `JSONEncodeError` if a `tzinfo` on a datetime object is +unsupported. + +`JSONEncodeError` is a subclass of `TypeError`. This is for compatibility +with the standard library. + +If the failure was caused by an exception in `default` then +`JSONEncodeError` chains the original exception as `__cause__`. + +#### default + +To serialize a subclass or arbitrary types, specify `default` as a +callable that returns a supported type. `default` may be a function, +lambda, or callable class instance. To specify that a type was not +handled by `default`, raise an exception such as `TypeError`. + +```python +>>> import orjson, decimal +>>> +def default(obj): + if isinstance(obj, decimal.Decimal): + return str(obj) + raise TypeError + +>>> orjson.dumps(decimal.Decimal("0.0842389659712649442845")) +JSONEncodeError: Type is not JSON serializable: decimal.Decimal +>>> orjson.dumps(decimal.Decimal("0.0842389659712649442845"), default=default) +b'"0.0842389659712649442845"' +>>> orjson.dumps({1, 2}, default=default) +orjson.JSONEncodeError: Type is not JSON serializable: set +``` + +The `default` callable may return an object that itself +must be handled by `default` up to 254 times before an exception +is raised. + +It is important that `default` raise an exception if a type cannot be handled. +Python otherwise implicitly returns `None`, which appears to the caller +like a legitimate value and is serialized: + +```python +>>> import orjson, json +>>> +def default(obj): + if isinstance(obj, decimal.Decimal): + return str(obj) + +>>> orjson.dumps({"set":{1, 2}}, default=default) +b'{"set":null}' +>>> json.dumps({"set":{1, 2}}, default=default) +'{"set":null}' +``` + +#### option + +To modify how data is serialized, specify `option`. Each `option` is an integer +constant in `orjson`. To specify multiple options, mask them together, e.g., +`option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC`. + +##### OPT_APPEND_NEWLINE + +Append `\n` to the output. This is a convenience and optimization for the +pattern of `dumps(...) + "\n"`. `bytes` objects are immutable and this +pattern copies the original contents. + +```python +>>> import orjson +>>> orjson.dumps([]) +b"[]" +>>> orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE) +b"[]\n" +``` + +##### OPT_INDENT_2 + +Pretty-print output with an indent of two spaces. This is equivalent to +`indent=2` in the standard library. Pretty printing is slower and the output +larger. This option is compatible with all other options. + +```python +>>> import orjson +>>> orjson.dumps({"a": "b", "c": {"d": True}, "e": [1, 2]}) +b'{"a":"b","c":{"d":true},"e":[1,2]}' +>>> orjson.dumps( + {"a": "b", "c": {"d": True}, "e": [1, 2]}, + option=orjson.OPT_INDENT_2 +) +b'{\n "a": "b",\n "c": {\n "d": true\n },\n "e": [\n 1,\n 2\n ]\n}' +``` + +If displayed, the indentation and linebreaks appear like this: + +```json +{ + "a": "b", + "c": { + "d": true + }, + "e": [ + 1, + 2 + ] +} +``` + +This measures serializing the github.json fixture as compact (52KiB) or +pretty (64KiB): + +| Library | compact (ms) | pretty (ms) | vs. orjson | +|-----------|----------------|---------------|--------------| +| orjson | 0.01 | 0.02 | 1 | +| json | 0.13 | 0.54 | 34 | + +This measures serializing the citm_catalog.json fixture, more of a worst +case due to the amount of nesting and newlines, as compact (489KiB) or +pretty (1.1MiB): + +| Library | compact (ms) | pretty (ms) | vs. orjson | +|-----------|----------------|---------------|--------------| +| orjson | 0.25 | 0.45 | 1 | +| json | 3.01 | 24.42 | 54.4 | + +This can be reproduced using the `pyindent` script. + +##### OPT_NAIVE_UTC + +Serialize `datetime.datetime` objects without a `tzinfo` as UTC. This +has no effect on `datetime.datetime` objects that have `tzinfo` set. + +```python +>>> import orjson, datetime +>>> orjson.dumps( + datetime.datetime(1970, 1, 1, 0, 0, 0), + ) +b'"1970-01-01T00:00:00"' +>>> orjson.dumps( + datetime.datetime(1970, 1, 1, 0, 0, 0), + option=orjson.OPT_NAIVE_UTC, + ) +b'"1970-01-01T00:00:00+00:00"' +``` + +##### OPT_NON_STR_KEYS + +Serialize `dict` keys of type other than `str`. This allows `dict` keys +to be one of `str`, `int`, `float`, `bool`, `None`, `datetime.datetime`, +`datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. For comparison, +the standard library serializes `str`, `int`, `float`, `bool` or `None` by +default. orjson benchmarks as being faster at serializing non-`str` keys +than other libraries. This option is slower for `str` keys than the default. + +```python +>>> import orjson, datetime, uuid +>>> orjson.dumps( + {uuid.UUID("7202d115-7ff3-4c81-a7c1-2a1f067b1ece"): [1, 2, 3]}, + option=orjson.OPT_NON_STR_KEYS, + ) +b'{"7202d115-7ff3-4c81-a7c1-2a1f067b1ece":[1,2,3]}' +>>> orjson.dumps( + {datetime.datetime(1970, 1, 1, 0, 0, 0): [1, 2, 3]}, + option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC, + ) +b'{"1970-01-01T00:00:00+00:00":[1,2,3]}' +``` + +These types are generally serialized how they would be as +values, e.g., `datetime.datetime` is still an RFC 3339 string and respects +options affecting it. The exception is that `int` serialization does not +respect `OPT_STRICT_INTEGER`. + +This option has the risk of creating duplicate keys. This is because non-`str` +objects may serialize to the same `str` as an existing key, e.g., +`{"1": true, 1: false}`. The last key to be inserted to the `dict` will be +serialized last and a JSON deserializer will presumably take the last +occurrence of a key (in the above, `false`). The first value will be lost. + +This option is compatible with `orjson.OPT_SORT_KEYS`. If sorting is used, +note the sort is unstable and will be unpredictable for duplicate keys. + +```python +>>> import orjson, datetime +>>> orjson.dumps( + {"other": 1, datetime.date(1970, 1, 5): 2, datetime.date(1970, 1, 3): 3}, + option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS +) +b'{"1970-01-03":3,"1970-01-05":2,"other":1}' +``` + +This measures serializing 589KiB of JSON comprising a `list` of 100 `dict` +in which each `dict` has both 365 randomly-sorted `int` keys representing epoch +timestamps as well as one `str` key and the value for each key is a +single integer. In "str keys", the keys were converted to `str` before +serialization, and orjson still specifes `option=orjson.OPT_NON_STR_KEYS` +(which is always somewhat slower). + +| Library | str keys (ms) | int keys (ms) | int keys sorted (ms) | +|-----------|-----------------|-----------------|------------------------| +| orjson | 0.5 | 0.93 | 2.08 | +| json | 2.72 | 3.59 | | + +json is blank because it +raises `TypeError` on attempting to sort before converting all keys to `str`. +This can be reproduced using the `pynonstr` script. + +##### OPT_OMIT_MICROSECONDS + +Do not serialize the `microsecond` field on `datetime.datetime` and +`datetime.time` instances. + +```python +>>> import orjson, datetime +>>> orjson.dumps( + datetime.datetime(1970, 1, 1, 0, 0, 0, 1), + ) +b'"1970-01-01T00:00:00.000001"' +>>> orjson.dumps( + datetime.datetime(1970, 1, 1, 0, 0, 0, 1), + option=orjson.OPT_OMIT_MICROSECONDS, + ) +b'"1970-01-01T00:00:00"' +``` + +##### OPT_PASSTHROUGH_DATACLASS + +Passthrough `dataclasses.dataclass` instances to `default`. This allows +customizing their output but is much slower. + + +```python +>>> import orjson, dataclasses +>>> +@dataclasses.dataclass +class User: + id: str + name: str + password: str + +def default(obj): + if isinstance(obj, User): + return {"id": obj.id, "name": obj.name} + raise TypeError + +>>> orjson.dumps(User("3b1", "asd", "zxc")) +b'{"id":"3b1","name":"asd","password":"zxc"}' +>>> orjson.dumps(User("3b1", "asd", "zxc"), option=orjson.OPT_PASSTHROUGH_DATACLASS) +TypeError: Type is not JSON serializable: User +>>> orjson.dumps( + User("3b1", "asd", "zxc"), + option=orjson.OPT_PASSTHROUGH_DATACLASS, + default=default, + ) +b'{"id":"3b1","name":"asd"}' +``` + +##### OPT_PASSTHROUGH_DATETIME + +Passthrough `datetime.datetime`, `datetime.date`, and `datetime.time` instances +to `default`. This allows serializing datetimes to a custom format, e.g., +HTTP dates: + +```python +>>> import orjson, datetime +>>> +def default(obj): + if isinstance(obj, datetime.datetime): + return obj.strftime("%a, %d %b %Y %H:%M:%S GMT") + raise TypeError + +>>> orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}) +b'{"created_at":"1970-01-01T00:00:00"}' +>>> orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME) +TypeError: Type is not JSON serializable: datetime.datetime +>>> orjson.dumps( + {"created_at": datetime.datetime(1970, 1, 1)}, + option=orjson.OPT_PASSTHROUGH_DATETIME, + default=default, + ) +b'{"created_at":"Thu, 01 Jan 1970 00:00:00 GMT"}' +``` + +This does not affect datetimes in `dict` keys if using OPT_NON_STR_KEYS. + +##### OPT_PASSTHROUGH_SUBCLASS + +Passthrough subclasses of builtin types to `default`. + +```python +>>> import orjson +>>> +class Secret(str): + pass + +def default(obj): + if isinstance(obj, Secret): + return "******" + raise TypeError + +>>> orjson.dumps(Secret("zxc")) +b'"zxc"' +>>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS) +TypeError: Type is not JSON serializable: Secret +>>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default) +b'"******"' +``` + +This does not affect serializing subclasses as `dict` keys if using +OPT_NON_STR_KEYS. + +##### OPT_SERIALIZE_DATACLASS + +This is deprecated and has no effect in version 3. In version 2 this was +required to serialize `dataclasses.dataclass` instances. For more, see +[dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass). + +##### OPT_SERIALIZE_NUMPY + +Serialize `numpy.ndarray` instances. For more, see +[numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy). + +##### OPT_SERIALIZE_UUID + +This is deprecated and has no effect in version 3. In version 2 this was +required to serialize `uuid.UUID` instances. For more, see +[UUID](https://github.com/ijl/orjson?tab=readme-ov-file#UUID). + +##### OPT_SORT_KEYS + +Serialize `dict` keys in sorted order. The default is to serialize in an +unspecified order. This is equivalent to `sort_keys=True` in the standard +library. + +This can be used to ensure the order is deterministic for hashing or tests. +It has a substantial performance penalty and is not recommended in general. + +```python +>>> import orjson +>>> orjson.dumps({"b": 1, "c": 2, "a": 3}) +b'{"b":1,"c":2,"a":3}' +>>> orjson.dumps({"b": 1, "c": 2, "a": 3}, option=orjson.OPT_SORT_KEYS) +b'{"a":3,"b":1,"c":2}' +``` + +This measures serializing the twitter.json fixture unsorted and sorted: + +| Library | unsorted (ms) | sorted (ms) | vs. orjson | +|-----------|-----------------|---------------|--------------| +| orjson | 0.11 | 0.3 | 1 | +| json | 1.36 | 1.93 | 6.4 | + +The benchmark can be reproduced using the `pysort` script. + +The sorting is not collation/locale-aware: + +```python +>>> import orjson +>>> orjson.dumps({"a": 1, "ä": 2, "A": 3}, option=orjson.OPT_SORT_KEYS) +b'{"A":3,"a":1,"\xc3\xa4":2}' +``` + +This is the same sorting behavior as the standard library. + +`dataclass` also serialize as maps but this has no effect on them. + +##### OPT_STRICT_INTEGER + +Enforce 53-bit limit on integers. The limit is otherwise 64 bits, the same as +the Python standard library. For more, see [int](https://github.com/ijl/orjson?tab=readme-ov-file#int). + +##### OPT_UTC_Z + +Serialize a UTC timezone on `datetime.datetime` instances as `Z` instead +of `+00:00`. + +```python +>>> import orjson, datetime, zoneinfo +>>> orjson.dumps( + datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")), + ) +b'"1970-01-01T00:00:00+00:00"' +>>> orjson.dumps( + datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")), + option=orjson.OPT_UTC_Z + ) +b'"1970-01-01T00:00:00Z"' +``` + +#### Fragment + +`orjson.Fragment` includes already-serialized JSON in a document. This is an +efficient way to include JSON blobs from a cache, JSONB field, or separately +serialized object without first deserializing to Python objects via `loads()`. + +```python +>>> import orjson +>>> orjson.dumps({"key": "zxc", "data": orjson.Fragment(b'{"a": "b", "c": 1}')}) +b'{"key":"zxc","data":{"a": "b", "c": 1}}' +``` + +It does no reformatting: `orjson.OPT_INDENT_2` will not affect a +compact blob nor will a pretty-printed JSON blob be rewritten as compact. + +The input must be `bytes` or `str` and given as a positional argument. + +This raises `orjson.JSONEncodeError` if a `str` is given and the input is +not valid UTF-8. It otherwise does no validation and it is possible to +write invalid JSON. This does not escape characters. The implementation is +tested to not crash if given invalid strings or invalid JSON. + +### Deserialize + +```python +def loads(__obj: Union[bytes, bytearray, memoryview, str]) -> Any: ... +``` + +`loads()` deserializes JSON to Python objects. It deserializes to `dict`, +`list`, `int`, `float`, `str`, `bool`, and `None` objects. + +`bytes`, `bytearray`, `memoryview`, and `str` input are accepted. If the input +exists as a `memoryview`, `bytearray`, or `bytes` object, it is recommended to +pass these directly rather than creating an unnecessary `str` object. That is, +`orjson.loads(b"{}")` instead of `orjson.loads(b"{}".decode("utf-8"))`. This +has lower memory usage and lower latency. + +The input must be valid UTF-8. + +orjson maintains a cache of map keys for the duration of the process. This +causes a net reduction in memory usage by avoiding duplicate strings. The +keys must be at most 64 bytes to be cached and 2048 entries are stored. + +The global interpreter lock (GIL) is held for the duration of the call. + +It raises `JSONDecodeError` if given an invalid type or invalid +JSON. This includes if the input contains `NaN`, `Infinity`, or `-Infinity`, +which the standard library allows, but is not valid JSON. + +It raises `JSONDecodeError` if a combination of array or object recurses +1024 levels deep. + +It raises `JSONDecodeError` if unable to allocate a buffer large enough +to parse the document. + +`JSONDecodeError` is a subclass of `json.JSONDecodeError` and `ValueError`. +This is for compatibility with the standard library. + +## Types + +### dataclass + +orjson serializes instances of `dataclasses.dataclass` natively. It serializes +instances 40-50x as fast as other libraries and avoids a severe slowdown seen +in other libraries compared to serializing `dict`. + +It is supported to pass all variants of dataclasses, including dataclasses +using `__slots__`, frozen dataclasses, those with optional or default +attributes, and subclasses. There is a performance benefit to not +using `__slots__`. + +| Library | dict (ms) | dataclass (ms) | vs. orjson | +|-----------|-------------|------------------|--------------| +| orjson | 0.43 | 0.95 | 1 | +| json | 5.81 | 38.32 | 40 | + +This measures serializing 555KiB of JSON, orjson natively and other libraries +using `default` to serialize the output of `dataclasses.asdict()`. This can be +reproduced using the `pydataclass` script. + +Dataclasses are serialized as maps, with every attribute serialized and in +the order given on class definition: + +```python +>>> import dataclasses, orjson, typing + +@dataclasses.dataclass +class Member: + id: int + active: bool = dataclasses.field(default=False) + +@dataclasses.dataclass +class Object: + id: int + name: str + members: typing.List[Member] + +>>> orjson.dumps(Object(1, "a", [Member(1, True), Member(2)])) +b'{"id":1,"name":"a","members":[{"id":1,"active":true},{"id":2,"active":false}]}' +``` + +### datetime + +orjson serializes `datetime.datetime` objects to +[RFC 3339](https://tools.ietf.org/html/rfc3339) format, +e.g., "1970-01-01T00:00:00+00:00". This is a subset of ISO 8601 and is +compatible with `isoformat()` in the standard library. + +```python +>>> import orjson, datetime, zoneinfo +>>> orjson.dumps( + datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=zoneinfo.ZoneInfo("Australia/Adelaide")) +) +b'"2018-12-01T02:03:04.000009+10:30"' +>>> orjson.dumps( + datetime.datetime(2100, 9, 1, 21, 55, 2).replace(tzinfo=zoneinfo.ZoneInfo("UTC")) +) +b'"2100-09-01T21:55:02+00:00"' +>>> orjson.dumps( + datetime.datetime(2100, 9, 1, 21, 55, 2) +) +b'"2100-09-01T21:55:02"' +``` + +`datetime.datetime` supports instances with a `tzinfo` that is `None`, +`datetime.timezone.utc`, a timezone instance from the standard library `zoneinfo` +module, or a timezone instance from the third-party `pendulum`, `pytz`, or +`dateutil`/`arrow` libraries. + +It is fastest to use the standard library's `zoneinfo.ZoneInfo` for timezones. + +`datetime.time` objects must not have a `tzinfo`. + +```python +>>> import orjson, datetime +>>> orjson.dumps(datetime.time(12, 0, 15, 290)) +b'"12:00:15.000290"' +``` + +`datetime.date` objects will always serialize. + +```python +>>> import orjson, datetime +>>> orjson.dumps(datetime.date(1900, 1, 2)) +b'"1900-01-02"' +``` + +Errors with `tzinfo` result in `JSONEncodeError` being raised. + +To disable serialization of `datetime` objects specify the option +`orjson.OPT_PASSTHROUGH_DATETIME`. + +To use "Z" suffix instead of "+00:00" to indicate UTC ("Zulu") time, use the option +`orjson.OPT_UTC_Z`. + +To assume datetimes without timezone are UTC, use the option `orjson.OPT_NAIVE_UTC`. + +### enum + +orjson serializes enums natively. Options apply to their values. + +```python +>>> import enum, datetime, orjson +>>> +class DatetimeEnum(enum.Enum): + EPOCH = datetime.datetime(1970, 1, 1, 0, 0, 0) +>>> orjson.dumps(DatetimeEnum.EPOCH) +b'"1970-01-01T00:00:00"' +>>> orjson.dumps(DatetimeEnum.EPOCH, option=orjson.OPT_NAIVE_UTC) +b'"1970-01-01T00:00:00+00:00"' +``` + +Enums with members that are not supported types can be serialized using +`default`: + +```python +>>> import enum, orjson +>>> +class Custom: + def __init__(self, val): + self.val = val + +def default(obj): + if isinstance(obj, Custom): + return obj.val + raise TypeError + +class CustomEnum(enum.Enum): + ONE = Custom(1) + +>>> orjson.dumps(CustomEnum.ONE, default=default) +b'1' +``` + +### float + +orjson serializes and deserializes double precision floats with no loss of +precision and consistent rounding. + +`orjson.dumps()` serializes Nan, Infinity, and -Infinity, which are not +compliant JSON, as `null`: + +```python +>>> import orjson, json +>>> orjson.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) +b'[null,null,null]' +>>> json.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) +'[NaN, Infinity, -Infinity]' +``` + +### int + +orjson serializes and deserializes 64-bit integers by default. The range +supported is a signed 64-bit integer's minimum (-9223372036854775807) to +an unsigned 64-bit integer's maximum (18446744073709551615). This +is widely compatible, but there are implementations +that only support 53-bits for integers, e.g., +web browsers. For those implementations, `dumps()` can be configured to +raise a `JSONEncodeError` on values exceeding the 53-bit range. + +```python +>>> import orjson +>>> orjson.dumps(9007199254740992) +b'9007199254740992' +>>> orjson.dumps(9007199254740992, option=orjson.OPT_STRICT_INTEGER) +JSONEncodeError: Integer exceeds 53-bit range +>>> orjson.dumps(-9007199254740992, option=orjson.OPT_STRICT_INTEGER) +JSONEncodeError: Integer exceeds 53-bit range +``` + +### numpy + +orjson natively serializes `numpy.ndarray` and individual +`numpy.float64`, `numpy.float32`, `numpy.float16` (`numpy.half`), +`numpy.int64`, `numpy.int32`, `numpy.int16`, `numpy.int8`, +`numpy.uint64`, `numpy.uint32`, `numpy.uint16`, `numpy.uint8`, +`numpy.uintp`, `numpy.intp`, `numpy.datetime64`, and `numpy.bool` +instances. + +orjson is compatible with both numpy v1 and v2. + +orjson is faster than all compared libraries at serializing +numpy instances. Serializing numpy data requires specifying +`option=orjson.OPT_SERIALIZE_NUMPY`. + +```python +>>> import orjson, numpy +>>> orjson.dumps( + numpy.array([[1, 2, 3], [4, 5, 6]]), + option=orjson.OPT_SERIALIZE_NUMPY, +) +b'[[1,2,3],[4,5,6]]' +``` + +The array must be a contiguous C array (`C_CONTIGUOUS`) and one of the +supported datatypes. + +Note a difference between serializing `numpy.float32` using `ndarray.tolist()` +or `orjson.dumps(..., option=orjson.OPT_SERIALIZE_NUMPY)`: `tolist()` converts +to a `double` before serializing and orjson's native path does not. This +can result in different rounding. + +`numpy.datetime64` instances are serialized as RFC 3339 strings and +datetime options affect them. + +```python +>>> import orjson, numpy +>>> orjson.dumps( + numpy.datetime64("2021-01-01T00:00:00.172"), + option=orjson.OPT_SERIALIZE_NUMPY, +) +b'"2021-01-01T00:00:00.172000"' +>>> orjson.dumps( + numpy.datetime64("2021-01-01T00:00:00.172"), + option=( + orjson.OPT_SERIALIZE_NUMPY | + orjson.OPT_NAIVE_UTC | + orjson.OPT_OMIT_MICROSECONDS + ), +) +b'"2021-01-01T00:00:00+00:00"' +``` + +If an array is not a contiguous C array, contains an unsupported datatype, +or contains a `numpy.datetime64` using an unsupported representation +(e.g., picoseconds), orjson falls through to `default`. In `default`, +`obj.tolist()` can be specified. + +If an array is not in the native endianness, e.g., an array of big-endian values +on a little-endian system, `orjson.JSONEncodeError` is raised. + +If an array is malformed, `orjson.JSONEncodeError` is raised. + +This measures serializing 92MiB of JSON from an `numpy.ndarray` with +dimensions of `(50000, 100)` and `numpy.float64` values: + +| Library | Latency (ms) | RSS diff (MiB) | vs. orjson | +|-----------|----------------|------------------|--------------| +| orjson | 105 | 105 | 1 | +| json | 1,481 | 295 | 14.2 | + +This measures serializing 100MiB of JSON from an `numpy.ndarray` with +dimensions of `(100000, 100)` and `numpy.int32` values: + +| Library | Latency (ms) | RSS diff (MiB) | vs. orjson | +|-----------|----------------|------------------|--------------| +| orjson | 68 | 119 | 1 | +| json | 684 | 501 | 10.1 | + +This measures serializing 105MiB of JSON from an `numpy.ndarray` with +dimensions of `(100000, 200)` and `numpy.bool` values: + +| Library | Latency (ms) | RSS diff (MiB) | vs. orjson | +|-----------|----------------|------------------|--------------| +| orjson | 50 | 125 | 1 | +| json | 573 | 398 | 11.5 | + +In these benchmarks, orjson serializes natively and `json` serializes +`ndarray.tolist()` via `default`. The RSS column measures peak memory +usage during serialization. This can be reproduced using the `pynumpy` script. + +orjson does not have an installation or compilation dependency on numpy. The +implementation is independent, reading `numpy.ndarray` using +`PyArrayInterface`. + +### str + +orjson is strict about UTF-8 conformance. This is stricter than the standard +library's json module, which will serialize and deserialize UTF-16 surrogates, +e.g., "\ud800", that are invalid UTF-8. + +If `orjson.dumps()` is given a `str` that does not contain valid UTF-8, +`orjson.JSONEncodeError` is raised. If `loads()` receives invalid UTF-8, +`orjson.JSONDecodeError` is raised. + +```python +>>> import orjson, json +>>> orjson.dumps('\ud800') +JSONEncodeError: str is not valid UTF-8: surrogates not allowed +>>> json.dumps('\ud800') +'"\\ud800"' +>>> orjson.loads('"\\ud800"') +JSONDecodeError: unexpected end of hex escape at line 1 column 8: line 1 column 1 (char 0) +>>> json.loads('"\\ud800"') +'\ud800' +``` + +To make a best effort at deserializing bad input, first decode `bytes` using +the `replace` or `lossy` argument for `errors`: + +```python +>>> import orjson +>>> orjson.loads(b'"\xed\xa0\x80"') +JSONDecodeError: str is not valid UTF-8: surrogates not allowed +>>> orjson.loads(b'"\xed\xa0\x80"'.decode("utf-8", "replace")) +'���' +``` + +### uuid + +orjson serializes `uuid.UUID` instances to +[RFC 4122](https://tools.ietf.org/html/rfc4122) format, e.g., +"f81d4fae-7dec-11d0-a765-00a0c91e6bf6". + +``` python +>>> import orjson, uuid +>>> orjson.dumps(uuid.uuid5(uuid.NAMESPACE_DNS, "python.org")) +b'"886313e1-3b8a-5372-9b90-0c9aee199e5d"' +``` + +## Testing + +The library has comprehensive tests. There are tests against fixtures in the +[JSONTestSuite](https://github.com/nst/JSONTestSuite) and +[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) +repositories. It is tested to not crash against the +[Big List of Naughty Strings](https://github.com/minimaxir/big-list-of-naughty-strings). +It is tested to not leak memory. It is tested to not crash +against and not accept invalid UTF-8. There are integration tests +exercising the library's use in web servers (gunicorn using multiprocess/forked +workers) and when multithreaded. + +orjson is the most correct of the compared libraries. This graph shows how each +library handles a combined 342 JSON fixtures from the +[JSONTestSuite](https://github.com/nst/JSONTestSuite) and +[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) tests: + +| Library | Invalid JSON documents not rejected | Valid JSON documents not deserialized | +|------------|---------------------------------------|-----------------------------------------| +| orjson | 0 | 0 | +| json | 17 | 0 | + +This shows that all libraries deserialize valid JSON but only orjson +correctly rejects the given invalid JSON fixtures. Errors are largely due to +accepting invalid strings and numbers. + +The graph above can be reproduced using the `pycorrectness` script. + +## Performance + +Serialization and deserialization performance of orjson is consistently better +than the standard library's `json`. The graphs below illustrate a few commonly +used documents. + +### Latency + +![Serialization](doc/serialization.png) + +![Deserialization](doc/deserialization.png) + +#### twitter.json serialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 0.1 | 8453 | 1 | +| json | 1.3 | 765 | 11.1 | + +#### twitter.json deserialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 0.5 | 1889 | 1 | +| json | 2.2 | 453 | 4.2 | + +#### github.json serialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 0.01 | 103693 | 1 | +| json | 0.13 | 7648 | 13.6 | + +#### github.json deserialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 0.04 | 23264 | 1 | +| json | 0.1 | 10430 | 2.2 | + +#### citm_catalog.json serialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 0.3 | 3975 | 1 | +| json | 3 | 338 | 11.8 | + +#### citm_catalog.json deserialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 1.3 | 781 | 1 | +| json | 4 | 250 | 3.1 | + +#### canada.json serialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 2.5 | 399 | 1 | +| json | 29.8 | 33 | 11.9 | + +#### canada.json deserialization + +| Library | Median latency (milliseconds) | Operations per second | Relative (latency) | +|-----------|---------------------------------|-------------------------|----------------------| +| orjson | 3 | 333 | 1 | +| json | 18 | 55 | 6 | + +### Reproducing + +The above was measured using Python 3.11.10 in a Fedora 42 container on an +x86-64-v4 machine using the +`orjson-3.10.11-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl` +artifact on PyPI. The latency results can be reproduced using the `pybench` script. + +## Questions + +### Will it deserialize to dataclasses, UUIDs, decimals, etc or support object_hook? + +No. This requires a schema specifying what types are expected and how to +handle errors etc. This is addressed by data validation libraries a +level above this. + +### Will it serialize to `str`? + +No. `bytes` is the correct type for a serialized blob. + +### Will it support NDJSON or JSONL? + +No. [orjsonl](https://github.com/umarbutler/orjsonl) may be appropriate. + +### Will it support JSON5 or RJSON? + +No, it supports RFC 8259. + +### How do I depend on orjson in a Rust project? + +orjson is only shipped as a Python module. The project should depend on +`orjson` in its own Python requirements and should obtain pointers to +functions and objects using the normal `PyImport_*` APIs. + +## Packaging + +To package orjson requires at least [Rust](https://www.rust-lang.org/) 1.95, +a C compiler, and the [maturin](https://github.com/PyO3/maturin) build tool. +The recommended build command is: + +```sh +maturin build --release --strip +``` + +The project's own CI tests against `nightly-2026-05-01` and stable 1.95. It +is prudent to pin the nightly version because that channel can introduce +breaking changes. There is a significant performance benefit to using +nightly. + +orjson is tested on native hardware for amd64, aarch64, and i686 on Linux. It is +cross-compiled and may be tested via emulation for arm7, ppc64le, and s390x. It +is tested for aarch64 on macOS and cross-compiles for amd64. For +Windows it is tested on amd64, i686, and aarch64. + +There are no runtime dependencies other than libc. + +The source distribution on PyPI contains all dependencies' source and can be +built without network access. The file can be downloaded from +`https://files.pythonhosted.org/packages/source/o/orjson/orjson-${version}.tar.gz`. + +orjson's tests are included in the source distribution on PyPI. The tests +require only `pytest`. There are optional packages such as `pytz` and `numpy` +listed in `test/requirements.txt` and used in ~10% of tests. Not having these +dependencies causes the tests needing them to skip. Tests can be run +with `pytest -q test`. + +## License + +orjson was written by ijl <>, copyright 2018 - 2026, with +some source files available under the Mozilla Public License 2.0 and some +available under your choice of the Apache 2 license or MIT license. + diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/RECORD b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..52320bf6d693751babaca2d8dcf815d10b0a78a8 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/RECORD @@ -0,0 +1,13 @@ +orjson-3.11.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +orjson-3.11.9.dist-info/METADATA,sha256=KIpNYW5og375gFm7cQWbeRC3IVm3t60odci7gUY8GIc,41968 +orjson-3.11.9.dist-info/RECORD,, +orjson-3.11.9.dist-info/WHEEL,sha256=qcptoZlhfIXMX79vtSlJjktSxXjWW-Zv9r2eVf661bI,147 +orjson-3.11.9.dist-info/licenses/LICENSE-APACHE,sha256=pg7qgXUUUxZo1-AHZXMUSf4U0FnTJJ4LyTs23kX3WfI,10847 +orjson-3.11.9.dist-info/licenses/LICENSE-MIT,sha256=I_GOA9xJ35FiL-KnYXZJdATkbO2KcV2dK2enRGVxzKM,1023 +orjson-3.11.9.dist-info/licenses/LICENSE-MPL-2.0,sha256=ZqMQfVrWoFiqt1PqrCBHzLLtDjlGXdD-WETaPjANUXI,16727 +orjson-3.11.9.dist-info/sboms/orjson.cyclonedx.json,sha256=06wA1_ydZLshb0SeqWsxoUcMHCx58cLT8VSiwJ3W-Vc,33096 +orjson/__init__.py,sha256=ejoFsSgbZapQVMNTh_vlvJkwW_lLnsd3SmzUpvWxSPU,693 +orjson/__init__.pyi,sha256=ApTAgpg75i1fKjyi5QwAkB2eP0w73IJFNaqKSx70ASE,876 +orjson/__pycache__/__init__.cpython-311.pyc,, +orjson/orjson.cpython-311-x86_64-linux-gnu.so,sha256=o4YjVDUHZnzzVD8-8R8qsna71nHWxm3jB1mLMK7ei7Q,245880 +orjson/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/WHEEL b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ed35e5a15c1a9fc28265b0fffe9fc5d50aab9c42 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: maturin (1.13.1) +Root-Is-Purelib: false +Tag: cp311-cp311-manylinux_2_17_x86_64 +Tag: cp311-cp311-manylinux2014_x86_64 diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-APACHE b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-APACHE new file mode 100644 index 0000000000000000000000000000000000000000..16fe87b06e802f094b3fbb0894b137bca2b16ef1 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-MIT b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-MIT new file mode 100644 index 0000000000000000000000000000000000000000..31aa79387f27e730e33d871925e152e35e428031 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-MPL-2.0 b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-MPL-2.0 new file mode 100644 index 0000000000000000000000000000000000000000..ee6256cdb62a765749a71aae3abea32884301cd1 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/licenses/LICENSE-MPL-2.0 @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/lib/python3.11/site-packages/orjson-3.11.9.dist-info/sboms/orjson.cyclonedx.json b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/sboms/orjson.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..6d9273a866d3cdbbee0e4f37a796ecf39254afd7 --- /dev/null +++ b/lib/python3.11/site-packages/orjson-3.11.9.dist-info/sboms/orjson.cyclonedx.json @@ -0,0 +1,1079 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:f15a880a-5fbc-4974-ba3c-8131a66d4657", + "metadata": { + "timestamp": "2026-05-06T14:56:43.500928236Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.9" + } + ], + "authors": [ + { + "name": "ijl", + "email": "ijl@mailbox.org" + } + ], + "component": { + "type": "library", + "bom-ref": "path+file:///__w/orjson/orjson#3.11.9", + "author": "ijl ", + "name": "orjson", + "version": "3.11.9", + "description": "Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy", + "scope": "required", + "licenses": [ + { + "expression": "MPL-2.0 AND (Apache-2.0 OR MIT)" + } + ], + "purl": "pkg:cargo/orjson@3.11.9?download_url=file://.", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/ijl/orjson" + } + ], + "components": [ + { + "type": "library", + "bom-ref": "path+file:///__w/orjson/orjson#3.11.9 bin-target-0", + "name": "orjson", + "version": "3.11.9", + "purl": "pkg:cargo/orjson@3.11.9?download_url=file://.#src/lib.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:all_targets", + "value": "true" + } + ] + }, + "components": [ + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#associative-cache@3.0.1", + "author": "Nick Fitzgerald ", + "name": "associative-cache", + "version": "3.0.1", + "description": "A generic N-way associative cache with fixed-size capacity and random or least recently used (LRU) replacement.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "138b4febdc7d0135523c55358c97361fd45089bc65fe859ef21a58d0892deb00" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/associative-cache@3.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/associative-cache" + }, + { + "type": "vcs", + "url": "https://github.com/fitzgen/associative-cache" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytecount@0.6.9", + "author": "Andre Bogus , Joshua Landau ", + "name": "bytecount", + "version": "0.6.9", + "description": "count occurrences of a given byte, or the number of UTF-8 code points, in a byte slice, fast", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bytecount@0.6.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/llogiq/bytecount" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "author": "Carl Lerche , Sean McArthur ", + "name": "bytes", + "version": "1.11.1", + "description": "Types and traits for working with bytes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/bytes@1.11.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/bytes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "author": "Alex Crichton ", + "name": "cc", + "version": "1.2.61", + "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cc@1.2.61", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cc" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cc-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "author": "Alex Crichton ", + "name": "cfg-if", + "version": "1.0.4", + "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cfg-if@1.0.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/cfg-if" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "author": "Henri Sivonen ", + "name": "encoding_rs", + "version": "0.8.35", + "description": "A Gecko-oriented implementation of the Encoding Standard", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" + } + ], + "licenses": [ + { + "expression": "(Apache-2.0 OR MIT) AND BSD-3-Clause" + } + ], + "purl": "pkg:cargo/encoding_rs@0.8.35", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/encoding_rs/" + }, + { + "type": "website", + "url": "https://docs.rs/encoding_rs/" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/encoding_rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "name": "find-msvc-tools", + "version": "0.1.9", + "description": "Find windows-specific tools, read MSVC versions from the registry and from COM interfaces", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/find-msvc-tools@0.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/find-msvc-tools" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "author": "David Tolnay ", + "name": "itoa", + "version": "1.0.18", + "description": "Fast integer primitive to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itoa@1.0.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itoa" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/itoa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoap@1.0.1", + "author": "Ryohei Machida ", + "name": "itoap", + "version": "1.0.1", + "description": "Even faster functions for printing integers with decimal format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/itoap@1.0.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/Kogia-sima/itoap" + }, + { + "type": "vcs", + "url": "https://github.com/Kogia-sima/itoap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#jiff@0.2.24", + "author": "Andrew Gallant ", + "name": "jiff", + "version": "0.2.24", + "description": "A date-time library that encourages you to jump into the pit of success. This library is heavily inspired by the Temporal project. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f00b5dbd620d61dfdcb6007c9c1f6054ebd75319f163d886a9055cec1155073d" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/jiff@0.2.24", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/jiff" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/jiff" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "author": "The Rust Project Developers", + "name": "libc", + "version": "0.2.186", + "description": "Raw FFI bindings to platform libraries like libc.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/libc@0.2.186", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/libc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "author": "Andrew Gallant , bluss", + "name": "memchr", + "version": "2.8.0", + "description": "Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for 1, 2 or 3 byte search and single substring search. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/memchr@2.8.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/memchr/" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/memchr" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/memchr" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#no-panic@0.1.36", + "author": "David Tolnay ", + "name": "no-panic", + "version": "0.1.36", + "description": "Attribute macro to require that the compiler prove a function can't ever panic.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f967505aabc8af5752d098c34146544a43684817cdba8f9725b292530cabbf53" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/no-panic@0.1.36", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/no-panic" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/no-panic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "author": "Aleksey Kladov ", + "name": "once_cell", + "version": "1.21.4", + "description": "Single assignment cells and lazy values.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell@1.21.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/once_cell" + }, + { + "type": "vcs", + "url": "https://github.com/matklad/once_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "author": "David Tolnay , Alex Crichton ", + "name": "proc-macro2", + "version": "1.0.106", + "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2@1.0.106", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/proc-macro2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-build-config", + "version": "0.28.3", + "description": "Build configuration for the PyO3 ecosystem", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-build-config@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-ffi", + "version": "0.28.3", + "description": "Python-API bindings for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-ffi@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "other", + "url": "python" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "author": "David Tolnay ", + "name": "quote", + "version": "1.0.45", + "description": "Quasi-quoting macro quote!(...)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quote@1.0.45", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quote/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/quote" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde", + "version": "1.0.228", + "description": "A generic serialization/deserialization framework", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_core", + "version": "1.0.228", + "description": "Serde traits only, with no support for derive -- use the `serde` crate instead", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_core@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_core" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_json", + "version": "1.0.149", + "description": "A JSON serialization file format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_json@1.0.149", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_json" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/json" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0", + "author": "comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg ", + "name": "shlex", + "version": "1.3.0", + "description": "Split a string into shell words, like Python's shlex.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/shlex@1.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/comex/rust-shlex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5", + "author": "Hans Kratz ", + "name": "simdutf8", + "version": "0.1.5", + "description": "SIMD-accelerated UTF-8 validation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/simdutf8@0.1.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/simdutf8/" + }, + { + "type": "website", + "url": "https://github.com/rusticstuff/simdutf8" + }, + { + "type": "vcs", + "url": "https://github.com/rusticstuff/simdutf8" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "author": "David Tolnay ", + "name": "syn", + "version": "2.0.117", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@2.0.117", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", + "author": "Dan Gohman ", + "name": "target-lexicon", + "version": "0.13.5", + "description": "LLVM target triple types", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception" + } + ], + "purl": "pkg:cargo/target-lexicon@0.13.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/target-lexicon/" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/target-lexicon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24", + "author": "David Tolnay ", + "name": "unicode-ident", + "version": "1.0.24", + "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + } + ], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0) AND Unicode-3.0" + } + ], + "purl": "pkg:cargo/unicode-ident@1.0.24", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-ident" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unicode-ident" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#xxhash-rust@0.8.15", + "author": "Douman ", + "name": "xxhash-rust", + "version": "0.8.15", + "description": "Implementation of xxhash", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" + } + ], + "licenses": [ + { + "expression": "BSL-1.0" + } + ], + "purl": "pkg:cargo/xxhash-rust@0.8.15", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/DoumanAsh/xxhash-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21", + "author": "David Tolnay ", + "name": "zmij", + "version": "1.0.21", + "description": "A double-to-string conversion algorithm based on Schubfach and yy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zmij@1.0.21", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/zmij" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/zmij" + } + ] + } + ], + "dependencies": [ + { + "ref": "path+file:///__w/orjson/orjson#3.11.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#associative-cache@3.0.1", + "registry+https://github.com/rust-lang/crates.io-index#bytecount@0.6.9", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "registry+https://github.com/rust-lang/crates.io-index#itoap@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#jiff@0.2.24", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5", + "registry+https://github.com/rust-lang/crates.io-index#xxhash-rust@0.8.15", + "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#associative-cache@3.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytecount@0.6.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoap@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#jiff@0.2.24" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#no-panic@0.1.36", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#xxhash-rust@0.8.15" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#no-panic@0.1.36" + ] + } + ] +} \ No newline at end of file diff --git a/lib/python3.11/site-packages/orjson/__init__.py b/lib/python3.11/site-packages/orjson/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a12ab65c6e434dbcf11a055cf271a946501250 --- /dev/null +++ b/lib/python3.11/site-packages/orjson/__init__.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright ijl (2023-2026) + +""" +Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy +""" + +from .orjson import * +from .orjson import __version__ + +__all__ = ( + "__version__", + "dumps", + "Fragment", + "JSONDecodeError", + "JSONEncodeError", + "loads", + "OPT_APPEND_NEWLINE", + "OPT_INDENT_2", + "OPT_NAIVE_UTC", + "OPT_NON_STR_KEYS", + "OPT_OMIT_MICROSECONDS", + "OPT_PASSTHROUGH_DATACLASS", + "OPT_PASSTHROUGH_DATETIME", + "OPT_PASSTHROUGH_SUBCLASS", + "OPT_SERIALIZE_DATACLASS", + "OPT_SERIALIZE_NUMPY", + "OPT_SERIALIZE_UUID", + "OPT_SORT_KEYS", + "OPT_STRICT_INTEGER", + "OPT_UTC_Z", +) diff --git a/lib/python3.11/site-packages/orjson/__init__.pyi b/lib/python3.11/site-packages/orjson/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9804cee53a5248f62bba23d7c3d07a151c701ff4 --- /dev/null +++ b/lib/python3.11/site-packages/orjson/__init__.pyi @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +# Copyright ijl (2019-2026), Eric Jolibois (2022), Anders Kaseorg (2020) + +import json +from collections.abc import Callable +from typing import Any + +__version__: str + +def dumps( + __obj: Any, + default: Callable[[Any], Any] | None = ..., + option: int | None = ..., +) -> bytes: ... +def loads(__obj: bytes | bytearray | memoryview | str) -> Any: ... + +class JSONDecodeError(json.JSONDecodeError): ... +class JSONEncodeError(TypeError): ... + +class Fragment(tuple): + contents: bytes | str + +OPT_APPEND_NEWLINE: int +OPT_INDENT_2: int +OPT_NAIVE_UTC: int +OPT_NON_STR_KEYS: int +OPT_OMIT_MICROSECONDS: int +OPT_PASSTHROUGH_DATACLASS: int +OPT_PASSTHROUGH_DATETIME: int +OPT_PASSTHROUGH_SUBCLASS: int +OPT_SERIALIZE_DATACLASS: int +OPT_SERIALIZE_NUMPY: int +OPT_SERIALIZE_UUID: int +OPT_SORT_KEYS: int +OPT_STRICT_INTEGER: int +OPT_UTC_Z: int diff --git a/lib/python3.11/site-packages/orjson/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/orjson/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..389a5edb1e31d8692393ff2ec0d26d55b82dafcb Binary files /dev/null and b/lib/python3.11/site-packages/orjson/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/orjson/py.typed b/lib/python3.11/site-packages/orjson/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/INSTALLER b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/METADATA b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..37cb00053d85735d9823ee5f8f8e1dbe5c59afa2 --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/METADATA @@ -0,0 +1,539 @@ +Metadata-Version: 2.4 +Name: propcache +Version: 0.5.2 +Summary: Accelerated property cache +Home-page: https://github.com/aio-libs/propcache +Author: Andrew Svetlov +Author-email: andrew.svetlov@gmail.com +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache-2.0 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Workflows, https://github.com/aio-libs/propcache/actions?query=branch:master +Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/propcache +Project-URL: Docs: Changelog, https://propcache.readthedocs.io/en/latest/changes/ +Project-URL: Docs: RTD, https://propcache.readthedocs.io +Project-URL: GitHub: issues, https://github.com/aio-libs/propcache/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/propcache +Keywords: cython,cext,propcache +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: NOTICE +Dynamic: license-file + +propcache +========= + +The module provides a fast implementation of cached properties for Python 3.10+. + +.. image:: https://github.com/aio-libs/propcache/actions/workflows/ci-cd.yml/badge.svg + :target: https://github.com/aio-libs/propcache/actions?query=workflow%3ACI + :align: right + +.. image:: https://codecov.io/gh/aio-libs/propcache/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/propcache + +.. image:: https://badge.fury.io/py/propcache.svg + :target: https://badge.fury.io/py/propcache + + +.. image:: https://readthedocs.org/projects/propcache/badge/?version=latest + :target: https://propcache.readthedocs.io + + +.. image:: https://img.shields.io/pypi/pyversions/propcache.svg + :target: https://pypi.python.org/pypi/propcache + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + +Introduction +------------ + +The API is designed to be nearly identical to the built-in ``functools.cached_property`` class, +except for the additional ``under_cached_property`` class which uses ``self._cache`` +instead of ``self.__dict__`` to store the cached values and prevents ``__set__`` from being called. + +For full documentation please read https://propcache.readthedocs.io. + +Installation +------------ + +:: + + $ pip install propcache + +The library is Python 3 only! + +PyPI contains binary wheels for Linux, Windows and MacOS. If you want to install +``propcache`` on another operating system where wheels are not provided, +the the tarball will be used to compile the library from +the source code. It requires a C compiler and and Python headers installed. + +To skip the compilation you must explicitly opt-in by using a PEP 517 +configuration setting ``pure-python``, or setting the ``PROPCACHE_NO_EXTENSIONS`` +environment variable to a non-empty value, e.g.: + +.. code-block:: console + + $ pip install propcache --config-settings=pure-python=false + +Please note that the pure-Python (uncompiled) version is much slower. However, +PyPy always uses a pure-Python implementation, and, as such, it is unaffected +by this variable. + + +API documentation +------------------ + +The documentation is located at https://propcache.readthedocs.io. + +Source code +----------- + +The project is hosted on GitHub_ + +Please file an issue on the `bug tracker +`_ if you have found a bug +or have some suggestion in order to improve the library. + +Discussion list +--------------- + +*aio-libs* google group: https://groups.google.com/forum/#!forum/aio-libs + +Feel free to post your questions and ideas here. + + +Authors and License +------------------- + +The ``propcache`` package is derived from ``yarl`` which is written by Andrew Svetlov. + +It's *Apache 2* licensed and freely available. + + +.. _GitHub: https://github.com/aio-libs/propcache + +========= +Changelog +========= + +.. + You should *NOT* be adding new change log entries to this file, this + file is managed by towncrier. You *may* edit previous change logs to + fix problems like typo corrections or such. + To add a new change log entry, please see + https://pip.pypa.io/en/latest/development/#adding-a-news-entry + we named the news folder "changes". + + WARNING: Don't drop the next directive! + +.. towncrier release notes start + +0.5.2 +===== + +*(2026-05-08)* + + +No significant changes. + + +---- + + +0.5.1 +===== + +*(2026-05-08)* + + +No significant changes. + + +---- + + +0.5.0 +===== + +*(2026-05-08)* + + +Features +-------- + +- Added support for newer type hints and remove ``Optional`` and ``Union`` from all annotations + -- by `@Vizonex `__ + + *Related issues and pull requests on GitHub:* + `#193 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Dropped support for Python 3.9 as it has reached end of life. + + *Related issues and pull requests on GitHub:* + `#216 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Changed the Cython build dependency from ``~= 3.1.0`` to ``>= 3.2.0``, + removing the upper version bound to avoid conflicts for downstream packagers + -- by `@jameshilliard `__ and `@gundalow `__. + + The upstream Cython version is pinned to 3.2.4 in the CI/CD environment. + + *Related issues and pull requests on GitHub:* + `#184 `__, `#188 `__, `#214 `__. + +- Start building and shipping riscv64 wheels + -- by `@justeph `__. + + *Related issues and pull requests on GitHub:* + `#194 `__. + +- The `PEP 517 `__ build backend now supports a new ``build-inplace`` + config setting (and ``PROPCACHE_BUILD_INPLACE`` environment variable) + for controlling whether to build the project in-tree or in a + temporary directory. It only affects wheels and is set up to build + in a temporary directory by default. It does not affect editable + wheel builds; they will keep being built in-tree regardless. + + Here's an example of using this setting: + + .. code-block:: console + + $ python -m build --config-setting=build-inplace=true + + Additionally, when building wheels in an automatically created + temporary directory, the build backend now normalizes the + respective file system path to a deterministic source checkout + directory by injecting the ``-ffile-prefix-map`` compiler option + into the ``CFLAGS`` environment variable, as suggested by known + `reproducible build practices + `__. + + The effect is that downstreams will get reproducible build results. + + *Related issues and pull requests on GitHub:* + `#218 `__. + + +---- + + +0.4.1 +===== + +*(2025-10-08)* + + +Bug fixes +--------- + +- Fixed reference leak caused by ``Py_INCREF`` because Cython has its own reference counter systems -- by `@Vizonex `__. + + *Related issues and pull requests on GitHub:* + `#162 `__. + + +Contributor-facing changes +-------------------------- + +- Fixes the default value for the ``os`` + parameter in ``reusable-build-wheel.yml`` + to be ``ubuntu-latest`` instead of + ``ubuntu``. + + *Related issues and pull requests on GitHub:* + `#155 `__. + + +---- + + +0.4.0 +===== + +*(2025-10-04)* + + +Features +-------- + +- Optimized propcache by replacing sentinel ``object`` for checking if + the ``object`` is ``NULL`` and changed ``dict`` API for + Python C-API -- by `@Vizonex `__. + + *Related issues and pull requests on GitHub:* + `#121 `__. + + +Contributor-facing changes +-------------------------- + +- Builds have been added for arm64 Windows + wheels and the ``reusable-build-wheel.yml`` + workflow has been modified to allow for + an OS value (``windows-11-arm``) which + does not include the ``-latest`` postfix + -- by `@finnagin `__. + + *Related issues and pull requests on GitHub:* + `#133 `__. + +- Added CI for CPython 3.14 -- by `@kumaraditya303 `__. + + *Related issues and pull requests on GitHub:* + `#140 `__. + + +---- + + +0.3.2 +===== + +*(2025-06-09)* + + +Improved documentation +---------------------- + +- Fixed incorrect decorator usage in the ``~propcache.api.under_cached_property`` example code -- by `@meanmail `__. + + *Related issues and pull requests on GitHub:* + `#109 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Updated to use Cython 3.1 universally across the build path -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#117 `__. + +- Made Cython line tracing opt-in via the ``with-cython-tracing`` build config setting -- by `@bdraco `__. + + Previously, line tracing was enabled by default in ``pyproject.toml``, which caused build issues for some users and made wheels nearly twice as slow. + + Now line tracing is only enabled when explicitly requested via ``pip install . --config-setting=with-cython-tracing=true`` or by setting the ``PROPCACHE_CYTHON_TRACING`` environment variable. + + *Related issues and pull requests on GitHub:* + `#118 `__. + + +---- + + +0.3.1 +===== + +*(2025-03-25)* + + +Bug fixes +--------- + +- Improved typing annotations, fixing some type errors under correct usage + and improving typing robustness generally -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#103 `__. + + +---- + + +0.3.0 +===== + +*(2025-02-20)* + + +Features +-------- + +- Implemented support for the free-threaded build of CPython 3.13 -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#84 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Started building wheels for the free-threaded build of CPython 3.13 -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#84 `__. + + +Contributor-facing changes +-------------------------- + +- GitHub Actions CI/CD is now configured to manage caching pip-ecosystem + dependencies using `re-actors/cache-python-deps`_ -- an action by + `@webknjaz `__ that takes into account ABI stability and the exact + version of Python runtime. + + .. _`re-actors/cache-python-deps`: + https://github.com/marketplace/actions/cache-python-deps + + *Related issues and pull requests on GitHub:* + `#93 `__. + + +---- + + +0.2.1 +===== + +*(2024-12-01)* + + +Bug fixes +--------- + +- Stopped implicitly allowing the use of Cython pre-release versions when + building the distribution package -- by `@ajsanchezsanz `__ and + `@markgreene74 `__. + + *Related commits on GitHub:* + `64df0a6 `__. + +- Fixed ``wrapped`` and ``func`` not being accessible in the Cython versions of ``propcache.api.cached_property`` and ``propcache.api.under_cached_property`` decorators -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#72 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Removed support for Python 3.8 as it has reached end of life -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#57 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Stopped implicitly allowing the use of Cython pre-release versions when + building the distribution package -- by `@ajsanchezsanz `__ and + `@markgreene74 `__. + + *Related commits on GitHub:* + `64df0a6 `__. + + +---- + + +0.2.0 +===== + +*(2024-10-07)* + + +Bug fixes +--------- + +- Fixed loading the C-extensions on Python 3.8 -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#26 `__. + + +Features +-------- + +- Improved typing for the ``propcache.api.under_cached_property`` decorator -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#38 `__. + + +Improved documentation +---------------------- + +- Added API documentation for the ``propcache.api.cached_property`` and ``propcache.api.under_cached_property`` decorators -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#16 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Moved ``propcache.api.under_cached_property`` and ``propcache.api.cached_property`` to `propcache.api` -- by `@bdraco `__. + + Both decorators remain importable from the top-level package, however importing from `propcache.api` is now the recommended way to use them. + + *Related issues and pull requests on GitHub:* + `#19 `__, `#24 `__, `#32 `__. + +- Converted project to use a src layout -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#22 `__, `#29 `__, `#37 `__. + + +---- + + +0.1.0 +===== + +*(2024-10-03)* + + +Features +-------- + +- Added ``armv7l`` wheels -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#5 `__. + + +---- + + +0.0.0 +===== + +*(2024-10-02)* + + +- Initial release. diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/RECORD b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b0587f12bb2f6ab1ac296d6ac0576343b5a3bcdf --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/RECORD @@ -0,0 +1,18 @@ +propcache-0.5.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +propcache-0.5.2.dist-info/METADATA,sha256=9TRJXN0vkVr45kl4PZX93LGgWhrBgYUPDJc8Cnj3u64,16496 +propcache-0.5.2.dist-info/RECORD,, +propcache-0.5.2.dist-info/WHEEL,sha256=M5wZqvm0RPz434ksvS2jyqHKJ9fsZFXCH8JlrvbFuNs,190 +propcache-0.5.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +propcache-0.5.2.dist-info/licenses/NOTICE,sha256=VtasbIEFwKUTBMIdsGDjYa-ajqCvmnXCOcKLXRNpODg,609 +propcache-0.5.2.dist-info/top_level.txt,sha256=pVF_GbqSAITPMiX27kfU3QP9-ufhRvkADmudDxWdF3w,10 +propcache/__init__.py,sha256=lNXqBAR5xSfCkeeYrdUBmpk154KWjPTdrh1rdqowtYE,965 +propcache/__pycache__/__init__.cpython-311.pyc,, +propcache/__pycache__/_helpers.cpython-311.pyc,, +propcache/__pycache__/_helpers_py.cpython-311.pyc,, +propcache/__pycache__/api.cpython-311.pyc,, +propcache/_helpers.py,sha256=68SQm6kETN8Mnt9Ol26LJYgHgmB0mKy1tp92888zN4k,1553 +propcache/_helpers_c.cpython-311-x86_64-linux-gnu.so,sha256=kTbMXRBnAgBktbnivhAP40EAlJwtcfY34ITprt1DizE,143792 +propcache/_helpers_c.pyx,sha256=kcJa1U5lh54TPCqAeZ0cVB7URcb3I8ZbJieOrkNhLQE,3265 +propcache/_helpers_py.py,sha256=G29pl3XJ8T0LqleQxYMTh9SwI3_UdG7r9KGcQwbi0pc,1910 +propcache/api.py,sha256=wvgB-ypkkI5uf72VVYl2NFGc_TnzUQA2CxC7dTlL5ak,179 +propcache/py.typed,sha256=ay5OMO475PlcZ_Fbun9maHW7Y6MBTk0UXL4ztHx3Iug,14 diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/WHEEL b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1c20eb80797cc99230ae524aa88695dd1a4d7ced --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/WHEEL @@ -0,0 +1,7 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp311-cp311-manylinux_2_17_x86_64 +Tag: cp311-cp311-manylinux2014_x86_64 +Tag: cp311-cp311-manylinux_2_28_x86_64 + diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/licenses/LICENSE b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/licenses/NOTICE b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/licenses/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..fa53b2b138df881c4c95239d0e4bede831b36ab5 --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/licenses/NOTICE @@ -0,0 +1,13 @@ + Copyright 2016-2021, Andrew Svetlov and aio-libs team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/lib/python3.11/site-packages/propcache-0.5.2.dist-info/top_level.txt b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c9accf6226df7e4011a41ac5d6014223685cfed --- /dev/null +++ b/lib/python3.11/site-packages/propcache-0.5.2.dist-info/top_level.txt @@ -0,0 +1 @@ +propcache diff --git a/lib/python3.11/site-packages/propcache/__init__.py b/lib/python3.11/site-packages/propcache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bbfd78a3628d5b0d12cda99195987d4e454d78da --- /dev/null +++ b/lib/python3.11/site-packages/propcache/__init__.py @@ -0,0 +1,32 @@ +"""propcache: An accelerated property cache for Python classes.""" + +from typing import TYPE_CHECKING + +_PUBLIC_API = ("cached_property", "under_cached_property") + +__version__ = "0.5.2" +__all__ = () + +# Imports have moved to `propcache.api` in 0.2.0+. +# This module is now a facade for the API. +if TYPE_CHECKING: + from .api import cached_property as cached_property # noqa: F401 + from .api import under_cached_property as under_cached_property # noqa: F401 + + +def _import_facade(attr: str) -> object: + """Import the public API from the `api` module.""" + if attr in _PUBLIC_API: + from . import api # pylint: disable=import-outside-toplevel + + return getattr(api, attr) + raise AttributeError(f"module '{__package__}' has no attribute '{attr}'") + + +def _dir_facade() -> list[str]: + """Include the public API in the module's dir() output.""" + return [*_PUBLIC_API, *globals().keys()] + + +__getattr__ = _import_facade +__dir__ = _dir_facade diff --git a/lib/python3.11/site-packages/propcache/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/propcache/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..063ef66c9e39a9405b55554e00fcd19cdc89d2b2 Binary files /dev/null and b/lib/python3.11/site-packages/propcache/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/propcache/__pycache__/_helpers.cpython-311.pyc b/lib/python3.11/site-packages/propcache/__pycache__/_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b22c5658fa278688dbc753da08ac654823795c3e Binary files /dev/null and b/lib/python3.11/site-packages/propcache/__pycache__/_helpers.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/propcache/__pycache__/_helpers_py.cpython-311.pyc b/lib/python3.11/site-packages/propcache/__pycache__/_helpers_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..001112d7d286b1c0b8bc37e46e98696e39fe9bb9 Binary files /dev/null and b/lib/python3.11/site-packages/propcache/__pycache__/_helpers_py.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/propcache/__pycache__/api.cpython-311.pyc b/lib/python3.11/site-packages/propcache/__pycache__/api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55e851adc58d2204f12d52bbb944b363b3c0f8e0 Binary files /dev/null and b/lib/python3.11/site-packages/propcache/__pycache__/api.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/propcache/_helpers.py b/lib/python3.11/site-packages/propcache/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..1e52895c151c952a100eeaab524fea2ef8d68f7e --- /dev/null +++ b/lib/python3.11/site-packages/propcache/_helpers.py @@ -0,0 +1,39 @@ +import os +import sys +from typing import TYPE_CHECKING + +__all__ = ("cached_property", "under_cached_property") + + +NO_EXTENSIONS = bool(os.environ.get("PROPCACHE_NO_EXTENSIONS")) # type: bool +if sys.implementation.name != "cpython": + NO_EXTENSIONS = True + + +# isort: off +if TYPE_CHECKING: + from ._helpers_py import cached_property as cached_property_py + from ._helpers_py import under_cached_property as under_cached_property_py + + cached_property = cached_property_py + under_cached_property = under_cached_property_py +elif not NO_EXTENSIONS: # pragma: no branch + try: + from ._helpers_c import cached_property as cached_property_c # type: ignore[attr-defined, unused-ignore] + from ._helpers_c import under_cached_property as under_cached_property_c # type: ignore[attr-defined, unused-ignore] + + cached_property = cached_property_c + under_cached_property = under_cached_property_c + except ImportError: # pragma: no cover + from ._helpers_py import cached_property as cached_property_py + from ._helpers_py import under_cached_property as under_cached_property_py + + cached_property = cached_property_py # type: ignore[assignment, misc] + under_cached_property = under_cached_property_py +else: + from ._helpers_py import cached_property as cached_property_py + from ._helpers_py import under_cached_property as under_cached_property_py + + cached_property = cached_property_py # type: ignore[assignment, misc] + under_cached_property = under_cached_property_py +# isort: on diff --git a/lib/python3.11/site-packages/propcache/_helpers_c.pyx b/lib/python3.11/site-packages/propcache/_helpers_c.pyx new file mode 100644 index 0000000000000000000000000000000000000000..9e9e5589b95954129e14083efaa17cdf1995fd4f --- /dev/null +++ b/lib/python3.11/site-packages/propcache/_helpers_c.pyx @@ -0,0 +1,103 @@ +# cython: language_level=3, freethreading_compatible=True +from types import GenericAlias + +from cpython.dict cimport PyDict_GetItem +from cpython.object cimport PyObject + + +cdef extern from "Python.h": + # Call a callable Python object callable with exactly + # 1 positional argument arg and no keyword arguments. + # Return the result of the call on success, or raise + # an exception and return NULL on failure. + PyObject* PyObject_CallOneArg( + object callable, object arg + ) except NULL + int PyDict_SetItem( + object dict, object key, PyObject* value + ) except -1 + void Py_DECREF(PyObject*) + + +cdef class under_cached_property: + """Use as a class method decorator. It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + + """ + + cdef readonly object wrapped + cdef object name + + def __init__(self, object wrapped): + self.wrapped = wrapped + self.name = wrapped.__name__ + + @property + def __doc__(self): + return self.wrapped.__doc__ + + def __get__(self, object inst, owner): + if inst is None: + return self + cdef dict cache = inst._cache + cdef PyObject* val = PyDict_GetItem(cache, self.name) + if val == NULL: + val = PyObject_CallOneArg(self.wrapped, inst) + PyDict_SetItem(cache, self.name, val) + Py_DECREF(val) + return val + + def __set__(self, inst, value): + raise AttributeError("cached property is read-only") + + __class_getitem__ = classmethod(GenericAlias) + + +cdef class cached_property: + """Use as a class method decorator. It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + + """ + + cdef readonly object func + cdef object name + + def __init__(self, func): + self.func = func + self.name = None + + @property + def __doc__(self): + return self.func.__doc__ + + def __set_name__(self, owner, object name): + if self.name is None: + self.name = name + elif name != self.name: + raise TypeError( + "Cannot assign the same cached_property to two different names " + f"({self.name!r} and {name!r})." + ) + + def __get__(self, inst, owner): + if inst is None: + return self + if self.name is None: + raise TypeError( + "Cannot use cached_property instance" + " without calling __set_name__ on it.") + cdef dict cache = inst.__dict__ + cdef PyObject* val = PyDict_GetItem(cache, self.name) + if val is NULL: + val = PyObject_CallOneArg(self.func, inst) + PyDict_SetItem(cache, self.name, val) + Py_DECREF(val) + return val + + __class_getitem__ = classmethod(GenericAlias) diff --git a/lib/python3.11/site-packages/propcache/_helpers_py.py b/lib/python3.11/site-packages/propcache/_helpers_py.py new file mode 100644 index 0000000000000000000000000000000000000000..db5b8d6378f040b4ca6619d43e36f4bfc65dacf3 --- /dev/null +++ b/lib/python3.11/site-packages/propcache/_helpers_py.py @@ -0,0 +1,64 @@ +"""Various helper functions.""" + +from __future__ import annotations + +import sys +from collections.abc import Callable, Mapping +from functools import cached_property +from typing import Any, Generic, Protocol, TypeVar, overload + +__all__ = ("under_cached_property", "cached_property") + + +if sys.version_info >= (3, 11): + from typing import Self +else: + Self = Any + +_T = TypeVar("_T") +# We use Mapping to make it possible to use TypedDict, but this isn't +# technically type safe as we need to assign into the dict. +_Cache = TypeVar("_Cache", bound=Mapping[str, Any]) + + +class _CacheImpl(Protocol[_Cache]): + _cache: _Cache + + +class under_cached_property(Generic[_T]): + """Use as a class method decorator. + + It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + """ + + def __init__(self, wrapped: Callable[[Any], _T]) -> None: + self.wrapped = wrapped + self.__doc__ = wrapped.__doc__ + self.name = wrapped.__name__ + + @overload + def __get__(self, inst: None, owner: type[object] | None = None) -> Self: ... + + @overload + def __get__( + self, inst: _CacheImpl[Any], owner: type[object] | None = None + ) -> _T: ... + + def __get__( + self, inst: _CacheImpl[Any] | None, owner: type[object] | None = None + ) -> _T | Self: + if inst is None: + return self + try: + return inst._cache[self.name] # type: ignore[no-any-return] + except KeyError: + val = self.wrapped(inst) + inst._cache[self.name] = val + return val + + def __set__(self, inst: _CacheImpl[Any], value: _T) -> None: + raise AttributeError("cached property is read-only") diff --git a/lib/python3.11/site-packages/propcache/api.py b/lib/python3.11/site-packages/propcache/api.py new file mode 100644 index 0000000000000000000000000000000000000000..22389e6337f8f77681b61de5e45d1ae6d474d39b --- /dev/null +++ b/lib/python3.11/site-packages/propcache/api.py @@ -0,0 +1,8 @@ +"""Public API of the property caching library.""" + +from ._helpers import cached_property, under_cached_property + +__all__ = ( + "cached_property", + "under_cached_property", +) diff --git a/lib/python3.11/site-packages/propcache/py.typed b/lib/python3.11/site-packages/propcache/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dcf2c804da5e19d617a03a6c68aa128d1d1f89a0 --- /dev/null +++ b/lib/python3.11/site-packages/propcache/py.typed @@ -0,0 +1 @@ +# Placeholder diff --git a/lib/python3.11/site-packages/pycparser-3.0.dist-info/INSTALLER b/lib/python3.11/site-packages/pycparser-3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser-3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/lib/python3.11/site-packages/pycparser-3.0.dist-info/METADATA b/lib/python3.11/site-packages/pycparser-3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b94a88bb3f4d9b5d41bd639b818f79c01dce4fd1 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser-3.0.dist-info/METADATA @@ -0,0 +1,244 @@ +Metadata-Version: 2.4 +Name: pycparser +Version: 3.0 +Summary: C parser in Python +Author-email: Eli Bendersky +Maintainer-email: Eli Bendersky +License-Expression: BSD-3-Clause +Project-URL: Homepage, https://github.com/eliben/pycparser +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Dynamic: license-file + +=============== +pycparser v3.00 +=============== + + +.. image:: https://github.com/eliben/pycparser/workflows/pycparser-tests/badge.svg + :align: center + :target: https://github.com/eliben/pycparser/actions + +---- + +.. contents:: + :backlinks: none + +.. sectnum:: + +Introduction +============ + +What is pycparser? +------------------ + +**pycparser** is a parser for the C language, written in pure Python. It is a +module designed to be easily integrated into applications that need to parse +C source code. + +What is it good for? +-------------------- + +Anything that needs C code to be parsed. The following are some uses for +**pycparser**, taken from real user reports: + +* C code obfuscator +* Front-end for various specialized C compilers +* Static code checker +* Automatic unit-test discovery +* Adding specialized extensions to the C language + +One of the most popular uses of **pycparser** is in the `cffi +`_ library, which uses it to parse the +declarations of C functions and types in order to auto-generate FFIs. + +**pycparser** is unique in the sense that it's written in pure Python - a very +high level language that's easy to experiment with and tweak. To people familiar +with Lex and Yacc, **pycparser**'s code will be simple to understand. It also +has no external dependencies (except for a Python interpreter), making it very +simple to install and deploy. + +Which version of C does pycparser support? +------------------------------------------ + +**pycparser** aims to support the full C99 language (according to the standard +ISO/IEC 9899). Some features from C11 are also supported, and patches to support +more are welcome. + +**pycparser** supports very few GCC extensions, but it's fairly easy to set +things up so that it parses code with a lot of GCC-isms successfully. See the +`FAQ `_ for more details. + +What grammar does pycparser follow? +----------------------------------- + +**pycparser** very closely follows the C grammar provided in Annex A of the C99 +standard (ISO/IEC 9899). + +How is pycparser licensed? +-------------------------- + +`BSD license `_. + +Contact details +--------------- + +For reporting problems with **pycparser** or submitting feature requests, please +open an `issue `_, or submit a +pull request. + + +Installing +========== + +Prerequisites +------------- + +**pycparser** is being tested with modern versions of Python on +Linux, macOS and Windows. See `the CI dashboard `__ +for details. + +**pycparser** has no external dependencies. + +Installation process +-------------------- + +The recommended way to install **pycparser** is with ``pip``:: + + > pip install pycparser + +Using +===== + +Interaction with the C preprocessor +----------------------------------- + +In order to be compilable, C code must be preprocessed by the C preprocessor - +``cpp``. A compatible ``cpp`` handles preprocessing directives like ``#include`` and +``#define``, removes comments, and performs other minor tasks that prepare the C +code for compilation. + +For all but the most trivial snippets of C code **pycparser**, like a C +compiler, must receive preprocessed C code in order to function correctly. If +you import the top-level ``parse_file`` function from the **pycparser** package, +it will interact with ``cpp`` for you, as long as it's in your PATH, or you +provide a path to it. + +Note also that you can use ``gcc -E`` or ``clang -E`` instead of ``cpp``. See +the ``using_gcc_E_libc.py`` example for more details. Windows users can download +and install a binary build of Clang for Windows `from this website +`_. + +What about the standard C library headers? +------------------------------------------ + +C code almost always ``#include``\s various header files from the standard C +library, like ``stdio.h``. While (with some effort) **pycparser** can be made to +parse the standard headers from any C compiler, it's much simpler to use the +provided "fake" standard includes for C11 in ``utils/fake_libc_include``. These +are standard C header files that contain only the bare necessities to allow +valid parsing of the files that use them. As a bonus, since they're minimal, it +can significantly improve the performance of parsing large C files. + +The key point to understand here is that **pycparser** doesn't really care about +the semantics of types. It only needs to know whether some token encountered in +the source is a previously defined type. This is essential in order to be able +to parse C correctly. + +See `this blog post +`_ +for more details. + +Note that the fake headers are not included in the ``pip`` package nor installed +via the package build (`#224 `_). + +Basic usage +----------- + +Take a look at the |examples|_ directory of the distribution for a few examples +of using **pycparser**. These should be enough to get you started. Please note +that most realistic C code samples would require running the C preprocessor +before passing the code to **pycparser**; see the previous sections for more +details. + +.. |examples| replace:: ``examples`` +.. _examples: examples + + +Advanced usage +-------------- + +The public interface of **pycparser** is well documented with comments in +``pycparser/c_parser.py``. For a detailed overview of the various AST nodes +created by the parser, see ``pycparser/_c_ast.cfg``. + +There's also a `FAQ available here `_. +In any case, you can always drop me an `email `_ for help. + + +Modifying +========= + +There are a few points to keep in mind when modifying **pycparser**: + +* The code for **pycparser**'s AST nodes is automatically generated from a + configuration file - ``_c_ast.cfg``, by ``_ast_gen.py``. If you modify the AST + configuration, make sure to re-generate the code. This can be done by running + the ``_ast_gen.py`` script (from the repository root or the + ``pycparser`` directory). +* Read the docstring in the constructor of the ``CParser`` class for details + on configuration and compatibility arguments. + + +Package contents +================ + +Once you unzip the ``pycparser`` package, you'll see the following files and +directories: + +README.rst: + This README file. + +LICENSE: + The pycparser license + +setup.py: + Legacy installation script (build metadata lives in ``pyproject.toml``). + +pyproject.toml: + Package metadata and build configuration. + +examples/: + A directory with some examples of using **pycparser** + +pycparser/: + The **pycparser** module source code. + +tests/: + Unit tests. + +utils/fake_libc_include: + Minimal standard C library include files that should allow to parse any C code. + Note that these headers now include C11 code, so they may not work when the + preprocessor is configured to an earlier C standard (like ``-std=c99``). + +utils/internal/: + Internal utilities for my own use. You probably don't need them. + + +Contributors +============ + +Some people have contributed to **pycparser** by opening issues on bugs they've +found and/or submitting patches. The list of contributors is in the CONTRIBUTORS +file in the source distribution. After **pycparser** moved to Github I stopped +updating this list because Github does a much better job at tracking +contributions. diff --git a/lib/python3.11/site-packages/pycparser-3.0.dist-info/RECORD b/lib/python3.11/site-packages/pycparser-3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..17d304b6a3fe6e19372806df35cc73ce97fa9683 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser-3.0.dist-info/RECORD @@ -0,0 +1,21 @@ +pycparser-3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pycparser-3.0.dist-info/METADATA,sha256=9UemCwq1TMLyQiE9H4eWCtgN991d_rmNF6RE1Iv7a5M,8229 +pycparser-3.0.dist-info/RECORD,, +pycparser-3.0.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92 +pycparser-3.0.dist-info/licenses/LICENSE,sha256=DIRjmTaep23de1xE_m0WSXQV_PAV9cu1CMJL-YuBxbE,1543 +pycparser-3.0.dist-info/top_level.txt,sha256=c-lPcS74L_8KoH7IE6PQF5ofyirRQNV4VhkbSFIPeWM,10 +pycparser/__init__.py,sha256=phViRyAuUmgqE4kNmaCqpm5WVEBIvzUSFapBv4XX3xo,2829 +pycparser/__pycache__/__init__.cpython-311.pyc,, +pycparser/__pycache__/_ast_gen.cpython-311.pyc,, +pycparser/__pycache__/ast_transforms.cpython-311.pyc,, +pycparser/__pycache__/c_ast.cpython-311.pyc,, +pycparser/__pycache__/c_generator.cpython-311.pyc,, +pycparser/__pycache__/c_lexer.cpython-311.pyc,, +pycparser/__pycache__/c_parser.cpython-311.pyc,, +pycparser/_ast_gen.py,sha256=ExH5Ym4pk7dQPEIkQr9RJim5feztdBQwSBPvpvE-5BM,11292 +pycparser/_c_ast.cfg,sha256=ld5ezE9yzIJFIVAUfw7ezJSlMi4nXKNCzfmqjOyQTNo,4255 +pycparser/ast_transforms.py,sha256=XwMsarc5aDddNWgIiKm4-jOWMRYib96yNQUo0_u28WA,5899 +pycparser/c_ast.py,sha256=uwkcZWHfXDQIw6WDvCL17iWM_-0R-URDqEMmPjXLOAc,32954 +pycparser/c_generator.py,sha256=RVKJPguv2CvovHHSfQkqimckUr9wGU9PofxCGj251QA,20661 +pycparser/c_lexer.py,sha256=B1VoqbYhPWkOJJWCem4OY4zj0IxrPktBZZFe2Y87kUg,25155 +pycparser/c_parser.py,sha256=3FBKGLjjlC3v8afwD_cnMR67ImoYIy73a4WKQR6hX7g,89798 diff --git a/lib/python3.11/site-packages/pycparser-3.0.dist-info/WHEEL b/lib/python3.11/site-packages/pycparser-3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..fbbd86cb272bc6e329803bf67f442f2a124caa95 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser-3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.10.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/lib/python3.11/site-packages/pycparser-3.0.dist-info/licenses/LICENSE b/lib/python3.11/site-packages/pycparser-3.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bee14a47d2d83f2d4e3aca6d5a41e587ebf3c516 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser-3.0.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +pycparser -- A C parser in Python + +Copyright (c) 2008-2022, Eli Bendersky +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of the copyright holder nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/python3.11/site-packages/pycparser-3.0.dist-info/top_level.txt b/lib/python3.11/site-packages/pycparser-3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc1c9e101ad9ccd943b359338ef42c342ebc84a1 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser-3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +pycparser diff --git a/lib/python3.11/site-packages/pycparser/__init__.py b/lib/python3.11/site-packages/pycparser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0606c03e205a154bb751de57fe8e03e277491fb0 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/__init__.py @@ -0,0 +1,99 @@ +# ----------------------------------------------------------------- +# pycparser: __init__.py +# +# This package file exports some convenience functions for +# interacting with pycparser +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ----------------------------------------------------------------- +__all__ = ["c_lexer", "c_parser", "c_ast"] +__version__ = "3.00" + +import io +from subprocess import check_output + +from . import c_parser + +CParser = c_parser.CParser + + +def preprocess_file(filename, cpp_path="cpp", cpp_args=""): + """Preprocess a file using cpp. + + filename: + Name of the file you want to preprocess. + + cpp_path: + cpp_args: + Refer to the documentation of parse_file for the meaning of these + arguments. + + When successful, returns the preprocessed file's contents. + Errors from cpp will be printed out. + """ + path_list = [cpp_path] + if isinstance(cpp_args, list): + path_list += cpp_args + elif cpp_args != "": + path_list += [cpp_args] + path_list += [filename] + + try: + # Note the use of universal_newlines to treat all newlines + # as \n for Python's purpose + text = check_output(path_list, universal_newlines=True) + except OSError as e: + raise RuntimeError( + "Unable to invoke 'cpp'. " + + "Make sure its path was passed correctly\n" + + f"Original error: {e}" + ) + + return text + + +def parse_file( + filename, use_cpp=False, cpp_path="cpp", cpp_args="", parser=None, encoding=None +): + """Parse a C file using pycparser. + + filename: + Name of the file you want to parse. + + use_cpp: + Set to True if you want to execute the C pre-processor + on the file prior to parsing it. + + cpp_path: + If use_cpp is True, this is the path to 'cpp' on your + system. If no path is provided, it attempts to just + execute 'cpp', so it must be in your PATH. + + cpp_args: + If use_cpp is True, set this to the command line arguments strings + to cpp. Be careful with quotes - it's best to pass a raw string + (r'') here. For example: + r'-I../utils/fake_libc_include' + If several arguments are required, pass a list of strings. + + encoding: + Encoding to use for the file to parse + + parser: + Optional parser object to be used instead of the default CParser + + When successful, an AST is returned. ParseError can be + thrown if the file doesn't parse successfully. + + Errors from cpp will be printed out. + """ + if use_cpp: + text = preprocess_file(filename, cpp_path, cpp_args) + else: + with io.open(filename, encoding=encoding) as f: + text = f.read() + + if parser is None: + parser = CParser() + return parser.parse(text, filename) diff --git a/lib/python3.11/site-packages/pycparser/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/pycparser/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c583752b4e1c02c6a4a06ff8ed2da7b3f2d75fd Binary files /dev/null and b/lib/python3.11/site-packages/pycparser/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pycparser/__pycache__/_ast_gen.cpython-311.pyc b/lib/python3.11/site-packages/pycparser/__pycache__/_ast_gen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..911ccb4255ec3afc5fa7051b7c32b30b1ccff653 Binary files /dev/null and b/lib/python3.11/site-packages/pycparser/__pycache__/_ast_gen.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pycparser/__pycache__/ast_transforms.cpython-311.pyc b/lib/python3.11/site-packages/pycparser/__pycache__/ast_transforms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c094a0fa11b6628b80ff3f5239dbba0870a4156 Binary files /dev/null and b/lib/python3.11/site-packages/pycparser/__pycache__/ast_transforms.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pycparser/__pycache__/c_ast.cpython-311.pyc b/lib/python3.11/site-packages/pycparser/__pycache__/c_ast.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d63158f0043a61d4ddf58e28637746aec2dc84cc Binary files /dev/null and b/lib/python3.11/site-packages/pycparser/__pycache__/c_ast.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pycparser/__pycache__/c_generator.cpython-311.pyc b/lib/python3.11/site-packages/pycparser/__pycache__/c_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa706e651a334b524553b1f58046fa0620934eba Binary files /dev/null and b/lib/python3.11/site-packages/pycparser/__pycache__/c_generator.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pycparser/__pycache__/c_lexer.cpython-311.pyc b/lib/python3.11/site-packages/pycparser/__pycache__/c_lexer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff451ae4378574aeeecece7ce71fbbef8eabe18c Binary files /dev/null and b/lib/python3.11/site-packages/pycparser/__pycache__/c_lexer.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pycparser/_ast_gen.py b/lib/python3.11/site-packages/pycparser/_ast_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..6df0b6a9b37e4cfc70a49c20c42b8a5e1828827c --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/_ast_gen.py @@ -0,0 +1,355 @@ +# ----------------------------------------------------------------- +# _ast_gen.py +# +# Generates the AST Node classes from a specification given in +# a configuration file. This module can also be run as a script to +# regenerate c_ast.py from _c_ast.cfg (from the repo root or the +# pycparser/ directory). Use 'make check' to reformat the generated +# file after running this script. +# +# The design of this module was inspired by astgen.py from the +# Python 2.5 code-base. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ----------------------------------------------------------------- +from string import Template +import os +from typing import IO + + +class ASTCodeGenerator: + def __init__(self, cfg_filename="_c_ast.cfg"): + """Initialize the code generator from a configuration + file. + """ + self.cfg_filename = cfg_filename + self.node_cfg = [ + NodeCfg(name, contents) + for (name, contents) in self.parse_cfgfile(cfg_filename) + ] + + def generate(self, file: IO[str]) -> None: + """Generates the code into file, an open file buffer.""" + src = Template(_PROLOGUE_COMMENT).substitute(cfg_filename=self.cfg_filename) + + src += _PROLOGUE_CODE + for node_cfg in self.node_cfg: + src += node_cfg.generate_source() + "\n\n" + + file.write(src) + + def parse_cfgfile(self, filename): + """Parse the configuration file and yield pairs of + (name, contents) for each node. + """ + with open(filename, "r") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + colon_i = line.find(":") + lbracket_i = line.find("[") + rbracket_i = line.find("]") + if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i: + raise RuntimeError(f"Invalid line in {filename}:\n{line}\n") + + name = line[:colon_i] + val = line[lbracket_i + 1 : rbracket_i] + vallist = [v.strip() for v in val.split(",")] if val else [] + yield name, vallist + + +class NodeCfg: + """Node configuration. + + name: node name + contents: a list of contents - attributes and child nodes + See comment at the top of the configuration file for details. + """ + + def __init__(self, name, contents): + self.name = name + self.all_entries = [] + self.attr = [] + self.child = [] + self.seq_child = [] + + for entry in contents: + clean_entry = entry.rstrip("*") + self.all_entries.append(clean_entry) + + if entry.endswith("**"): + self.seq_child.append(clean_entry) + elif entry.endswith("*"): + self.child.append(clean_entry) + else: + self.attr.append(entry) + + def generate_source(self): + src = self._gen_init() + src += "\n" + self._gen_children() + src += "\n" + self._gen_iter() + src += "\n" + self._gen_attr_names() + return src + + def _gen_init(self): + src = f"class {self.name}(Node):\n" + + if self.all_entries: + args = ", ".join(self.all_entries) + slots = ", ".join(f"'{e}'" for e in self.all_entries) + slots += ", 'coord', '__weakref__'" + arglist = f"(self, {args}, coord=None)" + else: + slots = "'coord', '__weakref__'" + arglist = "(self, coord=None)" + + src += f" __slots__ = ({slots})\n" + src += f" def __init__{arglist}:\n" + + for name in self.all_entries + ["coord"]: + src += f" self.{name} = {name}\n" + + return src + + def _gen_children(self): + src = " def children(self):\n" + + if self.all_entries: + src += " nodelist = []\n" + + for child in self.child: + src += f" if self.{child} is not None:\n" + src += f' nodelist.append(("{child}", self.{child}))\n' + + for seq_child in self.seq_child: + src += f" for i, child in enumerate(self.{seq_child} or []):\n" + src += f' nodelist.append((f"{seq_child}[{{i}}]", child))\n' + + src += " return tuple(nodelist)\n" + else: + src += " return ()\n" + + return src + + def _gen_iter(self): + src = " def __iter__(self):\n" + + if self.all_entries: + for child in self.child: + src += f" if self.{child} is not None:\n" + src += f" yield self.{child}\n" + + for seq_child in self.seq_child: + src += f" for child in (self.{seq_child} or []):\n" + src += " yield child\n" + + if not (self.child or self.seq_child): + # Empty generator + src += " return\n" + " yield\n" + else: + # Empty generator + src += " return\n" + " yield\n" + + return src + + def _gen_attr_names(self): + src = " attr_names = (" + "".join(f"{nm!r}, " for nm in self.attr) + ")" + return src + + +_PROLOGUE_COMMENT = r"""#----------------------------------------------------------------- +# ** ATTENTION ** +# This code was automatically generated from _c_ast.cfg +# +# Do not modify it directly. Modify the configuration file and +# run the generator again. +# ** ** *** ** ** +# +# pycparser: c_ast.py +# +# AST Node classes. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +#----------------------------------------------------------------- + +""" +_PROLOGUE_CODE = r''' +import sys +from typing import Any, ClassVar, IO, Optional + +def _repr(obj): + """ + Get the representation of an object, with dedicated pprint-like format for lists. + """ + if isinstance(obj, list): + return '[' + (',\n '.join((_repr(e).replace('\n', '\n ') for e in obj))) + '\n]' + else: + return repr(obj) + +class Node: + __slots__ = () + """ Abstract base class for AST nodes. + """ + attr_names: ClassVar[tuple[str, ...]] = () + coord: Optional[Any] + def __repr__(self): + """ Generates a python representation of the current node + """ + result = self.__class__.__name__ + '(' + + indent = '' + separator = '' + for name in self.__slots__[:-2]: + result += separator + result += indent + result += name + '=' + (_repr(getattr(self, name)).replace('\n', '\n ' + (' ' * (len(name) + len(self.__class__.__name__))))) + + separator = ',' + indent = '\n ' + (' ' * len(self.__class__.__name__)) + + result += indent + ')' + + return result + + def children(self): + """ A sequence of all children that are Nodes + """ + pass + + def show( + self, + buf: IO[str] = sys.stdout, + offset: int = 0, + attrnames: bool = False, + showemptyattrs: bool = True, + nodenames: bool = False, + showcoord: bool = False, + _my_node_name: Optional[str] = None, + ): + """ Pretty print the Node and all its attributes and + children (recursively) to a buffer. + + buf: + Open IO buffer into which the Node is printed. + + offset: + Initial offset (amount of leading spaces) + + attrnames: + True if you want to see the attribute names in + name=value pairs. False to only see the values. + + showemptyattrs: + False if you want to suppress printing empty attributes. + + nodenames: + True if you want to see the actual node names + within their parents. + + showcoord: + Do you want the coordinates of each Node to be + displayed. + """ + lead = ' ' * offset + if nodenames and _my_node_name is not None: + buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ') + else: + buf.write(lead + self.__class__.__name__+ ': ') + + if self.attr_names: + def is_empty(v): + v is None or (hasattr(v, '__len__') and len(v) == 0) + nvlist = [(n, getattr(self,n)) for n in self.attr_names \ + if showemptyattrs or not is_empty(getattr(self,n))] + if attrnames: + attrstr = ', '.join(f'{name}={value}' for name, value in nvlist) + else: + attrstr = ', '.join(f'{value}' for _, value in nvlist) + buf.write(attrstr) + + if showcoord: + buf.write(f' (at {self.coord})') + buf.write('\n') + + for (child_name, child) in self.children(): + child.show( + buf, + offset=offset + 2, + attrnames=attrnames, + showemptyattrs=showemptyattrs, + nodenames=nodenames, + showcoord=showcoord, + _my_node_name=child_name) + + +class NodeVisitor: + """ A base NodeVisitor class for visiting c_ast nodes. + Subclass it and define your own visit_XXX methods, where + XXX is the class name you want to visit with these + methods. + + For example: + + class ConstantVisitor(NodeVisitor): + def __init__(self): + self.values = [] + + def visit_Constant(self, node): + self.values.append(node.value) + + Creates a list of values of all the constant nodes + encountered below the given node. To use it: + + cv = ConstantVisitor() + cv.visit(node) + + Notes: + + * generic_visit() will be called for AST nodes for which + no visit_XXX method was defined. + * The children of nodes for which a visit_XXX was + defined will not be visited - if you need this, call + generic_visit() on the node. + You can use: + NodeVisitor.generic_visit(self, node) + * Modeled after Python's own AST visiting facilities + (the ast module of Python 3.0) + """ + + _method_cache = None + + def visit(self, node: Node): + """ Visit a node. + """ + + if self._method_cache is None: + self._method_cache = {} + + visitor = self._method_cache.get(node.__class__.__name__, None) + if visitor is None: + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + self._method_cache[node.__class__.__name__] = visitor + + return visitor(node) + + def generic_visit(self, node: Node): + """ Called if no explicit visitor function exists for a + node. Implements preorder visiting of the node. + """ + for _, c in node.children(): + self.visit(c) + +''' + + +if __name__ == "__main__": + base_dir = os.path.dirname(os.path.abspath(__file__)) + cfg_path = os.path.join(base_dir, "_c_ast.cfg") + out_path = os.path.join(base_dir, "c_ast.py") + ast_gen = ASTCodeGenerator(cfg_path) + with open(out_path, "w") as out: + ast_gen.generate(out) diff --git a/lib/python3.11/site-packages/pycparser/_c_ast.cfg b/lib/python3.11/site-packages/pycparser/_c_ast.cfg new file mode 100644 index 0000000000000000000000000000000000000000..0626533e8adf517da897ec047c8deb6ad41c38c9 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/_c_ast.cfg @@ -0,0 +1,195 @@ +#----------------------------------------------------------------- +# pycparser: _c_ast.cfg +# +# Defines the AST Node classes used in pycparser. +# +# Each entry is a Node sub-class name, listing the attributes +# and child nodes of the class: +# * - a child node +# ** - a sequence of child nodes +# - an attribute +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +#----------------------------------------------------------------- + +# ArrayDecl is a nested declaration of an array with the given type. +# dim: the dimension (for example, constant 42) +# dim_quals: list of dimension qualifiers, to support C99's allowing 'const' +# and 'static' within the array dimension in function declarations. +ArrayDecl: [type*, dim*, dim_quals] + +ArrayRef: [name*, subscript*] + +# op: =, +=, /= etc. +# +Assignment: [op, lvalue*, rvalue*] + +Alignas: [alignment*] + +BinaryOp: [op, left*, right*] + +Break: [] + +Case: [expr*, stmts**] + +Cast: [to_type*, expr*] + +# Compound statement in C99 is a list of block items (declarations or +# statements). +# +Compound: [block_items**] + +# Compound literal (anonymous aggregate) for C99. +# (type-name) {initializer_list} +# type: the typename +# init: InitList for the initializer list +# +CompoundLiteral: [type*, init*] + +# type: int, char, float, string, etc. +# +Constant: [type, value] + +Continue: [] + +# name: the variable being declared +# quals: list of qualifiers (const, volatile) +# funcspec: list function specifiers (i.e. inline in C99) +# storage: list of storage specifiers (extern, register, etc.) +# type: declaration type (probably nested with all the modifiers) +# init: initialization value, or None +# bitsize: bit field size, or None +# +Decl: [name, quals, align, storage, funcspec, type*, init*, bitsize*] + +DeclList: [decls**] + +Default: [stmts**] + +DoWhile: [cond*, stmt*] + +# Represents the ellipsis (...) parameter in a function +# declaration +# +EllipsisParam: [] + +# An empty statement (a semicolon ';' on its own) +# +EmptyStatement: [] + +# Enumeration type specifier +# name: an optional ID +# values: an EnumeratorList +# +Enum: [name, values*] + +# A name/value pair for enumeration values +# +Enumerator: [name, value*] + +# A list of enumerators +# +EnumeratorList: [enumerators**] + +# A list of expressions separated by the comma operator. +# +ExprList: [exprs**] + +# This is the top of the AST, representing a single C file (a +# translation unit in K&R jargon). It contains a list of +# "external-declaration"s, which is either declarations (Decl), +# Typedef or function definitions (FuncDef). +# +FileAST: [ext**] + +# for (init; cond; next) stmt +# +For: [init*, cond*, next*, stmt*] + +# name: Id +# args: ExprList +# +FuncCall: [name*, args*] + +# type (args) +# +FuncDecl: [args*, type*] + +# Function definition: a declarator for the function name and +# a body, which is a compound statement. +# There's an optional list of parameter declarations for old +# K&R-style definitions +# +FuncDef: [decl*, param_decls**, body*] + +Goto: [name] + +ID: [name] + +# Holder for types that are a simple identifier (e.g. the built +# ins void, char etc. and typedef-defined types) +# +IdentifierType: [names] + +If: [cond*, iftrue*, iffalse*] + +# An initialization list used for compound literals. +# +InitList: [exprs**] + +Label: [name, stmt*] + +# A named initializer for C99. +# The name of a NamedInitializer is a sequence of Nodes, because +# names can be hierarchical and contain constant expressions. +# +NamedInitializer: [name**, expr*] + +# a list of comma separated function parameter declarations +# +ParamList: [params**] + +PtrDecl: [quals, type*] + +Return: [expr*] + +StaticAssert: [cond*, message*] + +# name: struct tag name +# decls: declaration of members +# +Struct: [name, decls**] + +# type: . or -> +# name.field or name->field +# +StructRef: [name*, type, field*] + +Switch: [cond*, stmt*] + +# cond ? iftrue : iffalse +# +TernaryOp: [cond*, iftrue*, iffalse*] + +# A base type declaration +# +TypeDecl: [declname, quals, align, type*] + +# A typedef declaration. +# Very similar to Decl, but without some attributes +# +Typedef: [name, quals, storage, type*] + +Typename: [name, quals, align, type*] + +UnaryOp: [op, expr*] + +# name: union tag name +# decls: declaration of members +# +Union: [name, decls**] + +While: [cond*, stmt*] + +Pragma: [string] diff --git a/lib/python3.11/site-packages/pycparser/ast_transforms.py b/lib/python3.11/site-packages/pycparser/ast_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..1051737f65d106e23acf8685b57dfd12c811b934 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/ast_transforms.py @@ -0,0 +1,174 @@ +# ------------------------------------------------------------------------------ +# pycparser: ast_transforms.py +# +# Some utilities used by the parser to create a friendlier AST. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ + +from typing import Any, List, Tuple, cast + +from . import c_ast + + +def fix_switch_cases(switch_node: c_ast.Switch) -> c_ast.Switch: + """The 'case' statements in a 'switch' come out of parsing with one + child node, so subsequent statements are just tucked to the parent + Compound. Additionally, consecutive (fall-through) case statements + come out messy. This is a peculiarity of the C grammar. The following: + + switch (myvar) { + case 10: + k = 10; + p = k + 1; + return 10; + case 20: + case 30: + return 20; + default: + break; + } + + Creates this tree (pseudo-dump): + + Switch + ID: myvar + Compound: + Case 10: + k = 10 + p = k + 1 + return 10 + Case 20: + Case 30: + return 20 + Default: + break + + The goal of this transform is to fix this mess, turning it into the + following: + + Switch + ID: myvar + Compound: + Case 10: + k = 10 + p = k + 1 + return 10 + Case 20: + Case 30: + return 20 + Default: + break + + A fixed AST node is returned. The argument may be modified. + """ + assert isinstance(switch_node, c_ast.Switch) + if not isinstance(switch_node.stmt, c_ast.Compound): + return switch_node + + # The new Compound child for the Switch, which will collect children in the + # correct order + new_compound = c_ast.Compound([], switch_node.stmt.coord) + + # The last Case/Default node + last_case: c_ast.Case | c_ast.Default | None = None + + # Goes over the children of the Compound below the Switch, adding them + # either directly below new_compound or below the last Case as appropriate + # (for `switch(cond) {}`, block_items would have been None) + for child in switch_node.stmt.block_items or []: + if isinstance(child, (c_ast.Case, c_ast.Default)): + # If it's a Case/Default: + # 1. Add it to the Compound and mark as "last case" + # 2. If its immediate child is also a Case or Default, promote it + # to a sibling. + new_compound.block_items.append(child) + _extract_nested_case(child, new_compound.block_items) + last_case = new_compound.block_items[-1] + else: + # Other statements are added as children to the last case, if it + # exists. + if last_case is None: + new_compound.block_items.append(child) + else: + last_case.stmts.append(child) + + switch_node.stmt = new_compound + return switch_node + + +def _extract_nested_case( + case_node: c_ast.Case | c_ast.Default, stmts_list: List[c_ast.Node] +) -> None: + """Recursively extract consecutive Case statements that are made nested + by the parser and add them to the stmts_list. + """ + if isinstance(case_node.stmts[0], (c_ast.Case, c_ast.Default)): + nested = case_node.stmts.pop() + stmts_list.append(nested) + _extract_nested_case(cast(Any, nested), stmts_list) + + +def fix_atomic_specifiers( + decl: c_ast.Decl | c_ast.Typedef, +) -> c_ast.Decl | c_ast.Typedef: + """Atomic specifiers like _Atomic(type) are unusually structured, + conferring a qualifier upon the contained type. + + This function fixes a decl with atomic specifiers to have a sane AST + structure, by removing spurious Typename->TypeDecl pairs and attaching + the _Atomic qualifier in the right place. + """ + # There can be multiple levels of _Atomic in a decl; fix them until a + # fixed point is reached. + while True: + decl, found = _fix_atomic_specifiers_once(decl) + if not found: + break + + # Make sure to add an _Atomic qual on the topmost decl if needed. Also + # restore the declname on the innermost TypeDecl (it gets placed in the + # wrong place during construction). + typ: Any = decl + while not isinstance(typ, c_ast.TypeDecl): + try: + typ = typ.type + except AttributeError: + return decl + if "_Atomic" in typ.quals and "_Atomic" not in decl.quals: + decl.quals.append("_Atomic") + if typ.declname is None: + typ.declname = decl.name + + return decl + + +def _fix_atomic_specifiers_once( + decl: c_ast.Decl | c_ast.Typedef, +) -> Tuple[c_ast.Decl | c_ast.Typedef, bool]: + """Performs one 'fix' round of atomic specifiers. + Returns (modified_decl, found) where found is True iff a fix was made. + """ + parent: Any = decl + grandparent: Any = None + node: Any = decl.type + while node is not None: + if isinstance(node, c_ast.Typename) and "_Atomic" in node.quals: + break + try: + grandparent = parent + parent = node + node = node.type + except AttributeError: + # If we've reached a node without a `type` field, it means we won't + # find what we're looking for at this point; give up the search + # and return the original decl unmodified. + return decl, False + + assert isinstance(parent, c_ast.TypeDecl) + assert grandparent is not None + cast(Any, grandparent).type = node.type + if "_Atomic" not in node.type.quals: + node.type.quals.append("_Atomic") + return decl, True diff --git a/lib/python3.11/site-packages/pycparser/c_ast.py b/lib/python3.11/site-packages/pycparser/c_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f42af8a183ee61b9ff8f2d85c60cd3eb18afc4 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/c_ast.py @@ -0,0 +1,1341 @@ +# ----------------------------------------------------------------- +# ** ATTENTION ** +# This code was automatically generated from _c_ast.cfg +# +# Do not modify it directly. Modify the configuration file and +# run the generator again. +# ** ** *** ** ** +# +# pycparser: c_ast.py +# +# AST Node classes. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ----------------------------------------------------------------- + + +import sys +from typing import Any, ClassVar, IO, Optional + + +def _repr(obj): + """ + Get the representation of an object, with dedicated pprint-like format for lists. + """ + if isinstance(obj, list): + return "[" + (",\n ".join((_repr(e).replace("\n", "\n ") for e in obj))) + "\n]" + else: + return repr(obj) + + +class Node: + __slots__ = () + """ Abstract base class for AST nodes. + """ + attr_names: ClassVar[tuple[str, ...]] = () + coord: Optional[Any] + + def __repr__(self): + """Generates a python representation of the current node""" + result = self.__class__.__name__ + "(" + + indent = "" + separator = "" + for name in self.__slots__[:-2]: + result += separator + result += indent + result += ( + name + + "=" + + ( + _repr(getattr(self, name)).replace( + "\n", + "\n " + (" " * (len(name) + len(self.__class__.__name__))), + ) + ) + ) + + separator = "," + indent = "\n " + (" " * len(self.__class__.__name__)) + + result += indent + ")" + + return result + + def children(self): + """A sequence of all children that are Nodes""" + pass + + def show( + self, + buf: IO[str] = sys.stdout, + offset: int = 0, + attrnames: bool = False, + showemptyattrs: bool = True, + nodenames: bool = False, + showcoord: bool = False, + _my_node_name: Optional[str] = None, + ): + """Pretty print the Node and all its attributes and + children (recursively) to a buffer. + + buf: + Open IO buffer into which the Node is printed. + + offset: + Initial offset (amount of leading spaces) + + attrnames: + True if you want to see the attribute names in + name=value pairs. False to only see the values. + + showemptyattrs: + False if you want to suppress printing empty attributes. + + nodenames: + True if you want to see the actual node names + within their parents. + + showcoord: + Do you want the coordinates of each Node to be + displayed. + """ + lead = " " * offset + if nodenames and _my_node_name is not None: + buf.write(lead + self.__class__.__name__ + " <" + _my_node_name + ">: ") + else: + buf.write(lead + self.__class__.__name__ + ": ") + + if self.attr_names: + + def is_empty(v): + v is None or (hasattr(v, "__len__") and len(v) == 0) + + nvlist = [ + (n, getattr(self, n)) + for n in self.attr_names + if showemptyattrs or not is_empty(getattr(self, n)) + ] + if attrnames: + attrstr = ", ".join(f"{name}={value}" for name, value in nvlist) + else: + attrstr = ", ".join(f"{value}" for _, value in nvlist) + buf.write(attrstr) + + if showcoord: + buf.write(f" (at {self.coord})") + buf.write("\n") + + for child_name, child in self.children(): + child.show( + buf, + offset=offset + 2, + attrnames=attrnames, + showemptyattrs=showemptyattrs, + nodenames=nodenames, + showcoord=showcoord, + _my_node_name=child_name, + ) + + +class NodeVisitor: + """A base NodeVisitor class for visiting c_ast nodes. + Subclass it and define your own visit_XXX methods, where + XXX is the class name you want to visit with these + methods. + + For example: + + class ConstantVisitor(NodeVisitor): + def __init__(self): + self.values = [] + + def visit_Constant(self, node): + self.values.append(node.value) + + Creates a list of values of all the constant nodes + encountered below the given node. To use it: + + cv = ConstantVisitor() + cv.visit(node) + + Notes: + + * generic_visit() will be called for AST nodes for which + no visit_XXX method was defined. + * The children of nodes for which a visit_XXX was + defined will not be visited - if you need this, call + generic_visit() on the node. + You can use: + NodeVisitor.generic_visit(self, node) + * Modeled after Python's own AST visiting facilities + (the ast module of Python 3.0) + """ + + _method_cache = None + + def visit(self, node: Node): + """Visit a node.""" + + if self._method_cache is None: + self._method_cache = {} + + visitor = self._method_cache.get(node.__class__.__name__, None) + if visitor is None: + method = "visit_" + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + self._method_cache[node.__class__.__name__] = visitor + + return visitor(node) + + def generic_visit(self, node: Node): + """Called if no explicit visitor function exists for a + node. Implements preorder visiting of the node. + """ + for _, c in node.children(): + self.visit(c) + + +class ArrayDecl(Node): + __slots__ = ("type", "dim", "dim_quals", "coord", "__weakref__") + + def __init__(self, type, dim, dim_quals, coord=None): + self.type = type + self.dim = dim + self.dim_quals = dim_quals + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + if self.dim is not None: + nodelist.append(("dim", self.dim)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + if self.dim is not None: + yield self.dim + + attr_names = ("dim_quals",) + + +class ArrayRef(Node): + __slots__ = ("name", "subscript", "coord", "__weakref__") + + def __init__(self, name, subscript, coord=None): + self.name = name + self.subscript = subscript + self.coord = coord + + def children(self): + nodelist = [] + if self.name is not None: + nodelist.append(("name", self.name)) + if self.subscript is not None: + nodelist.append(("subscript", self.subscript)) + return tuple(nodelist) + + def __iter__(self): + if self.name is not None: + yield self.name + if self.subscript is not None: + yield self.subscript + + attr_names = () + + +class Assignment(Node): + __slots__ = ("op", "lvalue", "rvalue", "coord", "__weakref__") + + def __init__(self, op, lvalue, rvalue, coord=None): + self.op = op + self.lvalue = lvalue + self.rvalue = rvalue + self.coord = coord + + def children(self): + nodelist = [] + if self.lvalue is not None: + nodelist.append(("lvalue", self.lvalue)) + if self.rvalue is not None: + nodelist.append(("rvalue", self.rvalue)) + return tuple(nodelist) + + def __iter__(self): + if self.lvalue is not None: + yield self.lvalue + if self.rvalue is not None: + yield self.rvalue + + attr_names = ("op",) + + +class Alignas(Node): + __slots__ = ("alignment", "coord", "__weakref__") + + def __init__(self, alignment, coord=None): + self.alignment = alignment + self.coord = coord + + def children(self): + nodelist = [] + if self.alignment is not None: + nodelist.append(("alignment", self.alignment)) + return tuple(nodelist) + + def __iter__(self): + if self.alignment is not None: + yield self.alignment + + attr_names = () + + +class BinaryOp(Node): + __slots__ = ("op", "left", "right", "coord", "__weakref__") + + def __init__(self, op, left, right, coord=None): + self.op = op + self.left = left + self.right = right + self.coord = coord + + def children(self): + nodelist = [] + if self.left is not None: + nodelist.append(("left", self.left)) + if self.right is not None: + nodelist.append(("right", self.right)) + return tuple(nodelist) + + def __iter__(self): + if self.left is not None: + yield self.left + if self.right is not None: + yield self.right + + attr_names = ("op",) + + +class Break(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class Case(Node): + __slots__ = ("expr", "stmts", "coord", "__weakref__") + + def __init__(self, expr, stmts, coord=None): + self.expr = expr + self.stmts = stmts + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + for i, child in enumerate(self.stmts or []): + nodelist.append((f"stmts[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + for child in self.stmts or []: + yield child + + attr_names = () + + +class Cast(Node): + __slots__ = ("to_type", "expr", "coord", "__weakref__") + + def __init__(self, to_type, expr, coord=None): + self.to_type = to_type + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.to_type is not None: + nodelist.append(("to_type", self.to_type)) + if self.expr is not None: + nodelist.append(("expr", self.expr)) + return tuple(nodelist) + + def __iter__(self): + if self.to_type is not None: + yield self.to_type + if self.expr is not None: + yield self.expr + + attr_names = () + + +class Compound(Node): + __slots__ = ("block_items", "coord", "__weakref__") + + def __init__(self, block_items, coord=None): + self.block_items = block_items + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.block_items or []): + nodelist.append((f"block_items[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.block_items or []: + yield child + + attr_names = () + + +class CompoundLiteral(Node): + __slots__ = ("type", "init", "coord", "__weakref__") + + def __init__(self, type, init, coord=None): + self.type = type + self.init = init + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + if self.init is not None: + nodelist.append(("init", self.init)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + if self.init is not None: + yield self.init + + attr_names = () + + +class Constant(Node): + __slots__ = ("type", "value", "coord", "__weakref__") + + def __init__(self, type, value, coord=None): + self.type = type + self.value = value + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ( + "type", + "value", + ) + + +class Continue(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class Decl(Node): + __slots__ = ( + "name", + "quals", + "align", + "storage", + "funcspec", + "type", + "init", + "bitsize", + "coord", + "__weakref__", + ) + + def __init__( + self, name, quals, align, storage, funcspec, type, init, bitsize, coord=None + ): + self.name = name + self.quals = quals + self.align = align + self.storage = storage + self.funcspec = funcspec + self.type = type + self.init = init + self.bitsize = bitsize + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + if self.init is not None: + nodelist.append(("init", self.init)) + if self.bitsize is not None: + nodelist.append(("bitsize", self.bitsize)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + if self.init is not None: + yield self.init + if self.bitsize is not None: + yield self.bitsize + + attr_names = ( + "name", + "quals", + "align", + "storage", + "funcspec", + ) + + +class DeclList(Node): + __slots__ = ("decls", "coord", "__weakref__") + + def __init__(self, decls, coord=None): + self.decls = decls + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.decls or []): + nodelist.append((f"decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.decls or []: + yield child + + attr_names = () + + +class Default(Node): + __slots__ = ("stmts", "coord", "__weakref__") + + def __init__(self, stmts, coord=None): + self.stmts = stmts + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.stmts or []): + nodelist.append((f"stmts[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.stmts or []: + yield child + + attr_names = () + + +class DoWhile(Node): + __slots__ = ("cond", "stmt", "coord", "__weakref__") + + def __init__(self, cond, stmt, coord=None): + self.cond = cond + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class EllipsisParam(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class EmptyStatement(Node): + __slots__ = ("coord", "__weakref__") + + def __init__(self, coord=None): + self.coord = coord + + def children(self): + return () + + def __iter__(self): + return + yield + + attr_names = () + + +class Enum(Node): + __slots__ = ("name", "values", "coord", "__weakref__") + + def __init__(self, name, values, coord=None): + self.name = name + self.values = values + self.coord = coord + + def children(self): + nodelist = [] + if self.values is not None: + nodelist.append(("values", self.values)) + return tuple(nodelist) + + def __iter__(self): + if self.values is not None: + yield self.values + + attr_names = ("name",) + + +class Enumerator(Node): + __slots__ = ("name", "value", "coord", "__weakref__") + + def __init__(self, name, value, coord=None): + self.name = name + self.value = value + self.coord = coord + + def children(self): + nodelist = [] + if self.value is not None: + nodelist.append(("value", self.value)) + return tuple(nodelist) + + def __iter__(self): + if self.value is not None: + yield self.value + + attr_names = ("name",) + + +class EnumeratorList(Node): + __slots__ = ("enumerators", "coord", "__weakref__") + + def __init__(self, enumerators, coord=None): + self.enumerators = enumerators + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.enumerators or []): + nodelist.append((f"enumerators[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.enumerators or []: + yield child + + attr_names = () + + +class ExprList(Node): + __slots__ = ("exprs", "coord", "__weakref__") + + def __init__(self, exprs, coord=None): + self.exprs = exprs + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.exprs or []): + nodelist.append((f"exprs[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.exprs or []: + yield child + + attr_names = () + + +class FileAST(Node): + __slots__ = ("ext", "coord", "__weakref__") + + def __init__(self, ext, coord=None): + self.ext = ext + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.ext or []): + nodelist.append((f"ext[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.ext or []: + yield child + + attr_names = () + + +class For(Node): + __slots__ = ("init", "cond", "next", "stmt", "coord", "__weakref__") + + def __init__(self, init, cond, next, stmt, coord=None): + self.init = init + self.cond = cond + self.next = next + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.init is not None: + nodelist.append(("init", self.init)) + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.next is not None: + nodelist.append(("next", self.next)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.init is not None: + yield self.init + if self.cond is not None: + yield self.cond + if self.next is not None: + yield self.next + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class FuncCall(Node): + __slots__ = ("name", "args", "coord", "__weakref__") + + def __init__(self, name, args, coord=None): + self.name = name + self.args = args + self.coord = coord + + def children(self): + nodelist = [] + if self.name is not None: + nodelist.append(("name", self.name)) + if self.args is not None: + nodelist.append(("args", self.args)) + return tuple(nodelist) + + def __iter__(self): + if self.name is not None: + yield self.name + if self.args is not None: + yield self.args + + attr_names = () + + +class FuncDecl(Node): + __slots__ = ("args", "type", "coord", "__weakref__") + + def __init__(self, args, type, coord=None): + self.args = args + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.args is not None: + nodelist.append(("args", self.args)) + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.args is not None: + yield self.args + if self.type is not None: + yield self.type + + attr_names = () + + +class FuncDef(Node): + __slots__ = ("decl", "param_decls", "body", "coord", "__weakref__") + + def __init__(self, decl, param_decls, body, coord=None): + self.decl = decl + self.param_decls = param_decls + self.body = body + self.coord = coord + + def children(self): + nodelist = [] + if self.decl is not None: + nodelist.append(("decl", self.decl)) + if self.body is not None: + nodelist.append(("body", self.body)) + for i, child in enumerate(self.param_decls or []): + nodelist.append((f"param_decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + if self.decl is not None: + yield self.decl + if self.body is not None: + yield self.body + for child in self.param_decls or []: + yield child + + attr_names = () + + +class Goto(Node): + __slots__ = ("name", "coord", "__weakref__") + + def __init__(self, name, coord=None): + self.name = name + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("name",) + + +class ID(Node): + __slots__ = ("name", "coord", "__weakref__") + + def __init__(self, name, coord=None): + self.name = name + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("name",) + + +class IdentifierType(Node): + __slots__ = ("names", "coord", "__weakref__") + + def __init__(self, names, coord=None): + self.names = names + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("names",) + + +class If(Node): + __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__") + + def __init__(self, cond, iftrue, iffalse, coord=None): + self.cond = cond + self.iftrue = iftrue + self.iffalse = iffalse + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.iftrue is not None: + nodelist.append(("iftrue", self.iftrue)) + if self.iffalse is not None: + nodelist.append(("iffalse", self.iffalse)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.iftrue is not None: + yield self.iftrue + if self.iffalse is not None: + yield self.iffalse + + attr_names = () + + +class InitList(Node): + __slots__ = ("exprs", "coord", "__weakref__") + + def __init__(self, exprs, coord=None): + self.exprs = exprs + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.exprs or []): + nodelist.append((f"exprs[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.exprs or []: + yield child + + attr_names = () + + +class Label(Node): + __slots__ = ("name", "stmt", "coord", "__weakref__") + + def __init__(self, name, stmt, coord=None): + self.name = name + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.stmt is not None: + yield self.stmt + + attr_names = ("name",) + + +class NamedInitializer(Node): + __slots__ = ("name", "expr", "coord", "__weakref__") + + def __init__(self, name, expr, coord=None): + self.name = name + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + for i, child in enumerate(self.name or []): + nodelist.append((f"name[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + for child in self.name or []: + yield child + + attr_names = () + + +class ParamList(Node): + __slots__ = ("params", "coord", "__weakref__") + + def __init__(self, params, coord=None): + self.params = params + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.params or []): + nodelist.append((f"params[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.params or []: + yield child + + attr_names = () + + +class PtrDecl(Node): + __slots__ = ("quals", "type", "coord", "__weakref__") + + def __init__(self, quals, type, coord=None): + self.quals = quals + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ("quals",) + + +class Return(Node): + __slots__ = ("expr", "coord", "__weakref__") + + def __init__(self, expr, coord=None): + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + + attr_names = () + + +class StaticAssert(Node): + __slots__ = ("cond", "message", "coord", "__weakref__") + + def __init__(self, cond, message, coord=None): + self.cond = cond + self.message = message + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.message is not None: + nodelist.append(("message", self.message)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.message is not None: + yield self.message + + attr_names = () + + +class Struct(Node): + __slots__ = ("name", "decls", "coord", "__weakref__") + + def __init__(self, name, decls, coord=None): + self.name = name + self.decls = decls + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.decls or []): + nodelist.append((f"decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.decls or []: + yield child + + attr_names = ("name",) + + +class StructRef(Node): + __slots__ = ("name", "type", "field", "coord", "__weakref__") + + def __init__(self, name, type, field, coord=None): + self.name = name + self.type = type + self.field = field + self.coord = coord + + def children(self): + nodelist = [] + if self.name is not None: + nodelist.append(("name", self.name)) + if self.field is not None: + nodelist.append(("field", self.field)) + return tuple(nodelist) + + def __iter__(self): + if self.name is not None: + yield self.name + if self.field is not None: + yield self.field + + attr_names = ("type",) + + +class Switch(Node): + __slots__ = ("cond", "stmt", "coord", "__weakref__") + + def __init__(self, cond, stmt, coord=None): + self.cond = cond + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class TernaryOp(Node): + __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__") + + def __init__(self, cond, iftrue, iffalse, coord=None): + self.cond = cond + self.iftrue = iftrue + self.iffalse = iffalse + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.iftrue is not None: + nodelist.append(("iftrue", self.iftrue)) + if self.iffalse is not None: + nodelist.append(("iffalse", self.iffalse)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.iftrue is not None: + yield self.iftrue + if self.iffalse is not None: + yield self.iffalse + + attr_names = () + + +class TypeDecl(Node): + __slots__ = ("declname", "quals", "align", "type", "coord", "__weakref__") + + def __init__(self, declname, quals, align, type, coord=None): + self.declname = declname + self.quals = quals + self.align = align + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ( + "declname", + "quals", + "align", + ) + + +class Typedef(Node): + __slots__ = ("name", "quals", "storage", "type", "coord", "__weakref__") + + def __init__(self, name, quals, storage, type, coord=None): + self.name = name + self.quals = quals + self.storage = storage + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ( + "name", + "quals", + "storage", + ) + + +class Typename(Node): + __slots__ = ("name", "quals", "align", "type", "coord", "__weakref__") + + def __init__(self, name, quals, align, type, coord=None): + self.name = name + self.quals = quals + self.align = align + self.type = type + self.coord = coord + + def children(self): + nodelist = [] + if self.type is not None: + nodelist.append(("type", self.type)) + return tuple(nodelist) + + def __iter__(self): + if self.type is not None: + yield self.type + + attr_names = ( + "name", + "quals", + "align", + ) + + +class UnaryOp(Node): + __slots__ = ("op", "expr", "coord", "__weakref__") + + def __init__(self, op, expr, coord=None): + self.op = op + self.expr = expr + self.coord = coord + + def children(self): + nodelist = [] + if self.expr is not None: + nodelist.append(("expr", self.expr)) + return tuple(nodelist) + + def __iter__(self): + if self.expr is not None: + yield self.expr + + attr_names = ("op",) + + +class Union(Node): + __slots__ = ("name", "decls", "coord", "__weakref__") + + def __init__(self, name, decls, coord=None): + self.name = name + self.decls = decls + self.coord = coord + + def children(self): + nodelist = [] + for i, child in enumerate(self.decls or []): + nodelist.append((f"decls[{i}]", child)) + return tuple(nodelist) + + def __iter__(self): + for child in self.decls or []: + yield child + + attr_names = ("name",) + + +class While(Node): + __slots__ = ("cond", "stmt", "coord", "__weakref__") + + def __init__(self, cond, stmt, coord=None): + self.cond = cond + self.stmt = stmt + self.coord = coord + + def children(self): + nodelist = [] + if self.cond is not None: + nodelist.append(("cond", self.cond)) + if self.stmt is not None: + nodelist.append(("stmt", self.stmt)) + return tuple(nodelist) + + def __iter__(self): + if self.cond is not None: + yield self.cond + if self.stmt is not None: + yield self.stmt + + attr_names = () + + +class Pragma(Node): + __slots__ = ("string", "coord", "__weakref__") + + def __init__(self, string, coord=None): + self.string = string + self.coord = coord + + def children(self): + nodelist = [] + return tuple(nodelist) + + def __iter__(self): + return + yield + + attr_names = ("string",) diff --git a/lib/python3.11/site-packages/pycparser/c_generator.py b/lib/python3.11/site-packages/pycparser/c_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..424e00e06bec67f6285e51947a3896a81592ae49 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/c_generator.py @@ -0,0 +1,573 @@ +# ------------------------------------------------------------------------------ +# pycparser: c_generator.py +# +# C code generator from pycparser AST nodes. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ +from typing import Callable, List, Optional + +from . import c_ast + + +class CGenerator: + """Uses the same visitor pattern as c_ast.NodeVisitor, but modified to + return a value from each visit method, using string accumulation in + generic_visit. + """ + + indent_level: int + reduce_parentheses: bool + + def __init__(self, reduce_parentheses: bool = False) -> None: + """Constructs C-code generator + + reduce_parentheses: + if True, eliminates needless parentheses on binary operators + """ + # Statements start with indentation of self.indent_level spaces, using + # the _make_indent method. + self.indent_level = 0 + self.reduce_parentheses = reduce_parentheses + + def _make_indent(self) -> str: + return " " * self.indent_level + + def visit(self, node: c_ast.Node) -> str: + method = "visit_" + node.__class__.__name__ + return getattr(self, method, self.generic_visit)(node) + + def generic_visit(self, node: Optional[c_ast.Node]) -> str: + if node is None: + return "" + else: + return "".join(self.visit(c) for c_name, c in node.children()) + + def visit_Constant(self, n: c_ast.Constant) -> str: + return n.value + + def visit_ID(self, n: c_ast.ID) -> str: + return n.name + + def visit_Pragma(self, n: c_ast.Pragma) -> str: + ret = "#pragma" + if n.string: + ret += " " + n.string + return ret + + def visit_ArrayRef(self, n: c_ast.ArrayRef) -> str: + arrref = self._parenthesize_unless_simple(n.name) + return arrref + "[" + self.visit(n.subscript) + "]" + + def visit_StructRef(self, n: c_ast.StructRef) -> str: + sref = self._parenthesize_unless_simple(n.name) + return sref + n.type + self.visit(n.field) + + def visit_FuncCall(self, n: c_ast.FuncCall) -> str: + fref = self._parenthesize_unless_simple(n.name) + args = self.visit(n.args) if n.args is not None else "" + return fref + "(" + args + ")" + + def visit_UnaryOp(self, n: c_ast.UnaryOp) -> str: + match n.op: + case "sizeof": + # Always parenthesize the argument of sizeof since it can be + # a name. + return f"sizeof({self.visit(n.expr)})" + case "p++": + operand = self._parenthesize_unless_simple(n.expr) + return f"{operand}++" + case "p--": + operand = self._parenthesize_unless_simple(n.expr) + return f"{operand}--" + case _: + operand = self._parenthesize_unless_simple(n.expr) + return f"{n.op}{operand}" + + # Precedence map of binary operators: + precedence_map = { + # Should be in sync with c_parser.CParser.precedence + # Higher numbers are stronger binding + "||": 0, # weakest binding + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, + "!=": 5, + ">": 6, + ">=": 6, + "<": 6, + "<=": 6, + ">>": 7, + "<<": 7, + "+": 8, + "-": 8, + "*": 9, + "/": 9, + "%": 9, # strongest binding + } + + def visit_BinaryOp(self, n: c_ast.BinaryOp) -> str: + # Note: all binary operators are left-to-right associative + # + # If `n.left.op` has a stronger or equally binding precedence in + # comparison to `n.op`, no parenthesis are needed for the left: + # e.g., `(a*b) + c` is equivalent to `a*b + c`, as well as + # `(a+b) - c` is equivalent to `a+b - c` (same precedence). + # If the left operator is weaker binding than the current, then + # parentheses are necessary: + # e.g., `(a+b) * c` is NOT equivalent to `a+b * c`. + lval_str = self._parenthesize_if( + n.left, + lambda d: not ( + self._is_simple_node(d) + or self.reduce_parentheses + and isinstance(d, c_ast.BinaryOp) + and self.precedence_map[d.op] >= self.precedence_map[n.op] + ), + ) + # If `n.right.op` has a stronger -but not equal- binding precedence, + # parenthesis can be omitted on the right: + # e.g., `a + (b*c)` is equivalent to `a + b*c`. + # If the right operator is weaker or equally binding, then parentheses + # are necessary: + # e.g., `a * (b+c)` is NOT equivalent to `a * b+c` and + # `a - (b+c)` is NOT equivalent to `a - b+c` (same precedence). + rval_str = self._parenthesize_if( + n.right, + lambda d: not ( + self._is_simple_node(d) + or self.reduce_parentheses + and isinstance(d, c_ast.BinaryOp) + and self.precedence_map[d.op] > self.precedence_map[n.op] + ), + ) + return f"{lval_str} {n.op} {rval_str}" + + def visit_Assignment(self, n: c_ast.Assignment) -> str: + rval_str = self._parenthesize_if( + n.rvalue, lambda n: isinstance(n, c_ast.Assignment) + ) + return f"{self.visit(n.lvalue)} {n.op} {rval_str}" + + def visit_IdentifierType(self, n: c_ast.IdentifierType) -> str: + return " ".join(n.names) + + def _visit_expr(self, n: c_ast.Node) -> str: + match n: + case c_ast.InitList(): + return "{" + self.visit(n) + "}" + case c_ast.ExprList() | c_ast.Compound(): + return "(" + self.visit(n) + ")" + case _: + return self.visit(n) + + def visit_Decl(self, n: c_ast.Decl, no_type: bool = False) -> str: + # no_type is used when a Decl is part of a DeclList, where the type is + # explicitly only for the first declaration in a list. + # + s = n.name if no_type else self._generate_decl(n) + if n.bitsize: + s += " : " + self.visit(n.bitsize) + if n.init: + s += " = " + self._visit_expr(n.init) + return s + + def visit_DeclList(self, n: c_ast.DeclList) -> str: + s = self.visit(n.decls[0]) + if len(n.decls) > 1: + s += ", " + ", ".join( + self.visit_Decl(decl, no_type=True) for decl in n.decls[1:] + ) + return s + + def visit_Typedef(self, n: c_ast.Typedef) -> str: + s = "" + if n.storage: + s += " ".join(n.storage) + " " + s += self._generate_type(n.type) + return s + + def visit_Cast(self, n: c_ast.Cast) -> str: + s = "(" + self._generate_type(n.to_type, emit_declname=False) + ")" + return s + " " + self._parenthesize_unless_simple(n.expr) + + def visit_ExprList(self, n: c_ast.ExprList) -> str: + visited_subexprs = [] + for expr in n.exprs: + visited_subexprs.append(self._visit_expr(expr)) + return ", ".join(visited_subexprs) + + def visit_InitList(self, n: c_ast.InitList) -> str: + visited_subexprs = [] + for expr in n.exprs: + visited_subexprs.append(self._visit_expr(expr)) + return ", ".join(visited_subexprs) + + def visit_Enum(self, n: c_ast.Enum) -> str: + return self._generate_struct_union_enum(n, name="enum") + + def visit_Alignas(self, n: c_ast.Alignas) -> str: + return "_Alignas({})".format(self.visit(n.alignment)) + + def visit_Enumerator(self, n: c_ast.Enumerator) -> str: + if not n.value: + return "{indent}{name},\n".format( + indent=self._make_indent(), + name=n.name, + ) + else: + return "{indent}{name} = {value},\n".format( + indent=self._make_indent(), + name=n.name, + value=self.visit(n.value), + ) + + def visit_FuncDef(self, n: c_ast.FuncDef) -> str: + decl = self.visit(n.decl) + self.indent_level = 0 + body = self.visit(n.body) + if n.param_decls: + knrdecls = ";\n".join(self.visit(p) for p in n.param_decls) + return decl + "\n" + knrdecls + ";\n" + body + "\n" + else: + return decl + "\n" + body + "\n" + + def visit_FileAST(self, n: c_ast.FileAST) -> str: + s = "" + for ext in n.ext: + match ext: + case c_ast.FuncDef(): + s += self.visit(ext) + case c_ast.Pragma(): + s += self.visit(ext) + "\n" + case _: + s += self.visit(ext) + ";\n" + return s + + def visit_Compound(self, n: c_ast.Compound) -> str: + s = self._make_indent() + "{\n" + self.indent_level += 2 + if n.block_items: + s += "".join(self._generate_stmt(stmt) for stmt in n.block_items) + self.indent_level -= 2 + s += self._make_indent() + "}\n" + return s + + def visit_CompoundLiteral(self, n: c_ast.CompoundLiteral) -> str: + return "(" + self.visit(n.type) + "){" + self.visit(n.init) + "}" + + def visit_EmptyStatement(self, n: c_ast.EmptyStatement) -> str: + return ";" + + def visit_ParamList(self, n: c_ast.ParamList) -> str: + return ", ".join(self.visit(param) for param in n.params) + + def visit_Return(self, n: c_ast.Return) -> str: + s = "return" + if n.expr: + s += " " + self.visit(n.expr) + return s + ";" + + def visit_Break(self, n: c_ast.Break) -> str: + return "break;" + + def visit_Continue(self, n: c_ast.Continue) -> str: + return "continue;" + + def visit_TernaryOp(self, n: c_ast.TernaryOp) -> str: + s = "(" + self._visit_expr(n.cond) + ") ? " + s += "(" + self._visit_expr(n.iftrue) + ") : " + s += "(" + self._visit_expr(n.iffalse) + ")" + return s + + def visit_If(self, n: c_ast.If) -> str: + s = "if (" + if n.cond: + s += self.visit(n.cond) + s += ")\n" + s += self._generate_stmt(n.iftrue, add_indent=True) + if n.iffalse: + s += self._make_indent() + "else\n" + s += self._generate_stmt(n.iffalse, add_indent=True) + return s + + def visit_For(self, n: c_ast.For) -> str: + s = "for (" + if n.init: + s += self.visit(n.init) + s += ";" + if n.cond: + s += " " + self.visit(n.cond) + s += ";" + if n.next: + s += " " + self.visit(n.next) + s += ")\n" + s += self._generate_stmt(n.stmt, add_indent=True) + return s + + def visit_While(self, n: c_ast.While) -> str: + s = "while (" + if n.cond: + s += self.visit(n.cond) + s += ")\n" + s += self._generate_stmt(n.stmt, add_indent=True) + return s + + def visit_DoWhile(self, n: c_ast.DoWhile) -> str: + s = "do\n" + s += self._generate_stmt(n.stmt, add_indent=True) + s += self._make_indent() + "while (" + if n.cond: + s += self.visit(n.cond) + s += ");" + return s + + def visit_StaticAssert(self, n: c_ast.StaticAssert) -> str: + s = "_Static_assert(" + s += self.visit(n.cond) + if n.message: + s += "," + s += self.visit(n.message) + s += ")" + return s + + def visit_Switch(self, n: c_ast.Switch) -> str: + s = "switch (" + self.visit(n.cond) + ")\n" + s += self._generate_stmt(n.stmt, add_indent=True) + return s + + def visit_Case(self, n: c_ast.Case) -> str: + s = "case " + self.visit(n.expr) + ":\n" + for stmt in n.stmts: + s += self._generate_stmt(stmt, add_indent=True) + return s + + def visit_Default(self, n: c_ast.Default) -> str: + s = "default:\n" + for stmt in n.stmts: + s += self._generate_stmt(stmt, add_indent=True) + return s + + def visit_Label(self, n: c_ast.Label) -> str: + return n.name + ":\n" + self._generate_stmt(n.stmt) + + def visit_Goto(self, n: c_ast.Goto) -> str: + return "goto " + n.name + ";" + + def visit_EllipsisParam(self, n: c_ast.EllipsisParam) -> str: + return "..." + + def visit_Struct(self, n: c_ast.Struct) -> str: + return self._generate_struct_union_enum(n, "struct") + + def visit_Typename(self, n: c_ast.Typename) -> str: + return self._generate_type(n.type) + + def visit_Union(self, n: c_ast.Union) -> str: + return self._generate_struct_union_enum(n, "union") + + def visit_NamedInitializer(self, n: c_ast.NamedInitializer) -> str: + s = "" + for name in n.name: + if isinstance(name, c_ast.ID): + s += "." + name.name + else: + s += "[" + self.visit(name) + "]" + s += " = " + self._visit_expr(n.expr) + return s + + def visit_FuncDecl(self, n: c_ast.FuncDecl) -> str: + return self._generate_type(n) + + def visit_ArrayDecl(self, n: c_ast.ArrayDecl) -> str: + return self._generate_type(n, emit_declname=False) + + def visit_TypeDecl(self, n: c_ast.TypeDecl) -> str: + return self._generate_type(n, emit_declname=False) + + def visit_PtrDecl(self, n: c_ast.PtrDecl) -> str: + return self._generate_type(n, emit_declname=False) + + def _generate_struct_union_enum( + self, n: c_ast.Struct | c_ast.Union | c_ast.Enum, name: str + ) -> str: + """Generates code for structs, unions, and enums. name should be + 'struct', 'union', or 'enum'. + """ + if name in ("struct", "union"): + assert isinstance(n, (c_ast.Struct, c_ast.Union)) + members = n.decls + body_function = self._generate_struct_union_body + else: + assert name == "enum" + assert isinstance(n, c_ast.Enum) + members = None if n.values is None else n.values.enumerators + body_function = self._generate_enum_body + s = name + " " + (n.name or "") + if members is not None: + # None means no members + # Empty sequence means an empty list of members + s += "\n" + s += self._make_indent() + self.indent_level += 2 + s += "{\n" + s += body_function(members) + self.indent_level -= 2 + s += self._make_indent() + "}" + return s + + def _generate_struct_union_body(self, members: List[c_ast.Node]) -> str: + return "".join(self._generate_stmt(decl) for decl in members) + + def _generate_enum_body(self, members: List[c_ast.Enumerator]) -> str: + # `[:-2] + '\n'` removes the final `,` from the enumerator list + return "".join(self.visit(value) for value in members)[:-2] + "\n" + + def _generate_stmt(self, n: c_ast.Node, add_indent: bool = False) -> str: + """Generation from a statement node. This method exists as a wrapper + for individual visit_* methods to handle different treatment of + some statements in this context. + """ + if add_indent: + self.indent_level += 2 + indent = self._make_indent() + if add_indent: + self.indent_level -= 2 + + match n: + case ( + c_ast.Decl() + | c_ast.Assignment() + | c_ast.Cast() + | c_ast.UnaryOp() + | c_ast.BinaryOp() + | c_ast.TernaryOp() + | c_ast.FuncCall() + | c_ast.ArrayRef() + | c_ast.StructRef() + | c_ast.Constant() + | c_ast.ID() + | c_ast.Typedef() + | c_ast.ExprList() + ): + # These can also appear in an expression context so no semicolon + # is added to them automatically + # + return indent + self.visit(n) + ";\n" + case c_ast.Compound(): + # No extra indentation required before the opening brace of a + # compound - because it consists of multiple lines it has to + # compute its own indentation. + # + return self.visit(n) + case c_ast.If(): + return indent + self.visit(n) + case _: + return indent + self.visit(n) + "\n" + + def _generate_decl(self, n: c_ast.Decl) -> str: + """Generation from a Decl node.""" + s = "" + if n.funcspec: + s = " ".join(n.funcspec) + " " + if n.storage: + s += " ".join(n.storage) + " " + if n.align: + s += self.visit(n.align[0]) + " " + s += self._generate_type(n.type) + return s + + def _generate_type( + self, + n: c_ast.Node, + modifiers: List[c_ast.Node] = [], + emit_declname: bool = True, + ) -> str: + """Recursive generation from a type node. n is the type node. + modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers + encountered on the way down to a TypeDecl, to allow proper + generation from it. + """ + # ~ print(n, modifiers) + match n: + case c_ast.TypeDecl(): + s = "" + if n.quals: + s += " ".join(n.quals) + " " + s += self.visit(n.type) + + nstr = n.declname if n.declname and emit_declname else "" + # Resolve modifiers. + # Wrap in parens to distinguish pointer to array and pointer to + # function syntax. + # + for i, modifier in enumerate(modifiers): + match modifier: + case c_ast.ArrayDecl(): + if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl): + nstr = "(" + nstr + ")" + nstr += "[" + if modifier.dim_quals: + nstr += " ".join(modifier.dim_quals) + " " + if modifier.dim is not None: + nstr += self.visit(modifier.dim) + nstr += "]" + case c_ast.FuncDecl(): + if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl): + nstr = "(" + nstr + ")" + args = ( + self.visit(modifier.args) + if modifier.args is not None + else "" + ) + nstr += "(" + args + ")" + case c_ast.PtrDecl(): + if modifier.quals: + quals = " ".join(modifier.quals) + suffix = f" {nstr}" if nstr else "" + nstr = f"* {quals}{suffix}" + else: + nstr = "*" + nstr + if nstr: + s += " " + nstr + return s + case c_ast.Decl(): + return self._generate_decl(n.type) + case c_ast.Typename(): + return self._generate_type(n.type, emit_declname=emit_declname) + case c_ast.IdentifierType(): + return " ".join(n.names) + " " + case c_ast.ArrayDecl() | c_ast.PtrDecl() | c_ast.FuncDecl(): + return self._generate_type( + n.type, modifiers + [n], emit_declname=emit_declname + ) + case _: + return self.visit(n) + + def _parenthesize_if( + self, n: c_ast.Node, condition: Callable[[c_ast.Node], bool] + ) -> str: + """Visits 'n' and returns its string representation, parenthesized + if the condition function applied to the node returns True. + """ + s = self._visit_expr(n) + if condition(n): + return "(" + s + ")" + else: + return s + + def _parenthesize_unless_simple(self, n: c_ast.Node) -> str: + """Common use case for _parenthesize_if""" + return self._parenthesize_if(n, lambda d: not self._is_simple_node(d)) + + def _is_simple_node(self, n: c_ast.Node) -> bool: + """Returns True for nodes that are "simple" - i.e. nodes that always + have higher precedence than operators. + """ + return isinstance( + n, + (c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall), + ) diff --git a/lib/python3.11/site-packages/pycparser/c_lexer.py b/lib/python3.11/site-packages/pycparser/c_lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..ef59d695448751017f34fb033196a0217f48e5f0 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/c_lexer.py @@ -0,0 +1,706 @@ +# ------------------------------------------------------------------------------ +# pycparser: c_lexer.py +# +# CLexer class: lexer for the C language +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ +import re +from dataclasses import dataclass +from enum import Enum +from typing import Callable, Dict, List, Optional, Tuple + + +@dataclass(slots=True) +class _Token: + type: str + value: str + lineno: int + column: int + + +class CLexer: + """A standalone lexer for C. + + Parameters for construction: + error_func: + Called with (msg, line, column) on lexing errors. + on_lbrace_func: + Called when an LBRACE token is produced (used for scope tracking). + on_rbrace_func: + Called when an RBRACE token is produced (used for scope tracking). + type_lookup_func: + Called with an identifier name; expected to return True if it is + a typedef name and should be tokenized as TYPEID. + + Call input(text) to initialize lexing, and then keep calling token() to + get the next token, until it returns None (at end of input). + """ + + def __init__( + self, + error_func: Callable[[str, int, int], None], + on_lbrace_func: Callable[[], None], + on_rbrace_func: Callable[[], None], + type_lookup_func: Callable[[str], bool], + ) -> None: + self.error_func = error_func + self.on_lbrace_func = on_lbrace_func + self.on_rbrace_func = on_rbrace_func + self.type_lookup_func = type_lookup_func + self._init_state() + + def input(self, text: str, filename: str = "") -> None: + """Initialize the lexer to the given input text. + + filename is an optional name identifying the file from which the input + comes. The lexer can modify it if #line directives are encountered. + """ + self._init_state() + self._lexdata = text + self._filename = filename + + def _init_state(self) -> None: + self._lexdata = "" + self._filename = "" + self._pos = 0 + self._line_start = 0 + self._pending_tok: Optional[_Token] = None + self._lineno = 1 + + @property + def filename(self) -> str: + return self._filename + + def token(self) -> Optional[_Token]: + # Lexing strategy overview: + # + # - We maintain a current position (self._pos), line number, and the + # byte offset of the current line start. The lexer is a simple loop + # that skips whitespace/newlines and emits one token per call. + # - A small amount of logic is handled manually before regex matching: + # + # * Preprocessor-style directives: if we see '#', we check whether + # it's a #line or #pragma directive and consume it inline. #line + # updates lineno/filename and produces no tokens. #pragma can yield + # both PPPRAGMA and PPPRAGMASTR, but token() returns a single token, + # so we stash the PPPRAGMASTR as _pending_tok to return on the next + # token() call. Otherwise we return PPHASH. + # * Newlines update lineno/line-start tracking so tokens can record + # accurate columns. + # + # - The bulk of tokens are recognized in _match_token: + # + # * _regex_rules: regex patterns for identifiers, literals, and other + # complex tokens (including error-producing patterns). The lexer + # uses a combined _regex_master to scan options at the same time. + # * _fixed_tokens: exact string matches for operators and punctuation, + # resolved by longest match. + # + # - Error patterns call the error callback and advance minimally, which + # keeps lexing resilient while reporting useful diagnostics. + text = self._lexdata + n = len(text) + + if self._pending_tok is not None: + tok = self._pending_tok + self._pending_tok = None + return tok + + while self._pos < n: + match text[self._pos]: + case " " | "\t": + self._pos += 1 + case "\n": + self._lineno += 1 + self._pos += 1 + self._line_start = self._pos + case "#": + if _line_pattern.match(text, self._pos + 1): + self._pos += 1 + self._handle_ppline() + continue + if _pragma_pattern.match(text, self._pos + 1): + self._pos += 1 + toks = self._handle_pppragma() + if len(toks) > 1: + self._pending_tok = toks[1] + if len(toks) > 0: + return toks[0] + continue + tok = self._make_token("PPHASH", "#", self._pos) + self._pos += 1 + return tok + case _: + if tok := self._match_token(): + return tok + else: + continue + + def _match_token(self) -> Optional[_Token]: + """Match one token at the current position. + + Returns a Token on success, or None if no token could be matched and + an error was reported. This method always advances _pos by the matched + length, or by 1 on error/no-match. + """ + text = self._lexdata + pos = self._pos + # We pick the longest match between: + # - the master regex (identifiers, literals, error patterns, etc.) + # - fixed operator/punctuator literals from the bucket for text[pos] + # + # The longest match is required to ensure we properly lex something + # like ".123" (a floating-point constant) as a single entity (with + # FLOAT_CONST), rather than a PERIOD followed by a number. + # + # The fixed-literal buckets are already length-sorted, so within that + # bucket we can take the first match. However, we still compare its + # length to the regex match because the regex may have matched a longer + # token that should take precedence. + best = None + + if m := _regex_master.match(text, pos): + tok_type = m.lastgroup + # All master-regex alternatives are named; lastgroup shouldn't be None. + assert tok_type is not None + value = m.group(tok_type) + length = len(value) + action, msg = _regex_actions[tok_type] + best = (length, tok_type, value, action, msg) + + if bucket := _fixed_tokens_by_first.get(text[pos]): + for entry in bucket: + if text.startswith(entry.literal, pos): + length = len(entry.literal) + if best is None or length > best[0]: + best = ( + length, + entry.tok_type, + entry.literal, + _RegexAction.TOKEN, + None, + ) + break + + if best is None: + msg = f"Illegal character {repr(text[pos])}" + self._error(msg, pos) + self._pos += 1 + return None + + length, tok_type, value, action, msg = best + if action == _RegexAction.ERROR: + if tok_type == "BAD_CHAR_CONST": + msg = f"Invalid char constant {value}" + # All other ERROR rules provide a message. + assert msg is not None + self._error(msg, pos) + self._pos += max(1, length) + return None + + if action == _RegexAction.ID: + tok_type = _keyword_map.get(value, "ID") + if tok_type == "ID" and self.type_lookup_func(value): + tok_type = "TYPEID" + + tok = self._make_token(tok_type, value, pos) + self._pos += length + + if tok.type == "LBRACE": + self.on_lbrace_func() + elif tok.type == "RBRACE": + self.on_rbrace_func() + + return tok + + def _make_token(self, tok_type: str, value: str, pos: int) -> _Token: + """Create a Token at an absolute input position. + + Expects tok_type/value and the absolute byte offset pos in the current + input. Does not advance lexer state; callers manage _pos themselves. + Returns a Token with lineno/column computed from current line tracking. + """ + column = pos - self._line_start + 1 + tok = _Token(tok_type, value, self._lineno, column) + return tok + + def _error(self, msg: str, pos: int) -> None: + column = pos - self._line_start + 1 + self.error_func(msg, self._lineno, column) + + def _handle_ppline(self) -> None: + # Since #line directives aren't supposed to return tokens but should + # only affect the lexer's state (update line/filename for coords), this + # method does a bit of parsing on its own. It doesn't return anything, + # but its side effect is to update self._pos past the directive, and + # potentially update self._lineno and self._filename, based on the + # directive's contents. + # + # Accepted #line forms from preprocessors: + # - "#line 66 \"kwas\\df.h\"" + # - "# 9" + # - "#line 10 \"include/me.h\" 1 2 3" (extra numeric flags) + # - "# 1 \"file.h\" 3" + # Errors we must report: + # - "#line \"file.h\"" (filename before line number) + # - "#line df" (garbage instead of number/string) + # + # We scan the directive line once (after an optional 'line' keyword), + # validating the order: NUMBER, optional STRING, then any NUMBERs. + # The NUMBERs tail is only accepted if a filename STRING was present. + text = self._lexdata + n = len(text) + line_end = text.find("\n", self._pos) + if line_end == -1: + line_end = n + line = text[self._pos : line_end] + pos = 0 + line_len = len(line) + + def skip_ws() -> None: + nonlocal pos + while pos < line_len and line[pos] in " \t": + pos += 1 + + skip_ws() + if line.startswith("line", pos): + pos += 4 + + def success(pp_line: Optional[str], pp_filename: Optional[str]) -> None: + if pp_line is None: + self._error("line number missing in #line", self._pos + line_len) + else: + self._lineno = int(pp_line) + if pp_filename is not None: + self._filename = pp_filename + self._pos = line_end + 1 + self._line_start = self._pos + + def fail(msg: str, offset: int) -> None: + self._error(msg, self._pos + offset) + self._pos = line_end + 1 + self._line_start = self._pos + + skip_ws() + if pos >= line_len: + success(None, None) + return + if line[pos] == '"': + fail("filename before line number in #line", pos) + return + + m = re.match(_decimal_constant, line[pos:]) + if not m: + fail("invalid #line directive", pos) + return + + pp_line = m.group(0) + pos += len(pp_line) + skip_ws() + if pos >= line_len: + success(pp_line, None) + return + + if line[pos] != '"': + fail("invalid #line directive", pos) + return + + m = re.match(_string_literal, line[pos:]) + if not m: + fail("invalid #line directive", pos) + return + + pp_filename = m.group(0).lstrip('"').rstrip('"') + pos += len(m.group(0)) + + # Consume arbitrary sequence of numeric flags after the directive + while True: + skip_ws() + if pos >= line_len: + break + m = re.match(_decimal_constant, line[pos:]) + if not m: + fail("invalid #line directive", pos) + return + pos += len(m.group(0)) + + success(pp_line, pp_filename) + + def _handle_pppragma(self) -> List[_Token]: + # Parse a full #pragma line; returns a list of tokens with 1 or 2 + # tokens - PPPRAGMA and an optional PPPRAGMASTR. If an empty list is + # returned, it means an error occurred, or we're at the end of input. + # + # Examples: + # - "#pragma" -> PPPRAGMA only + # - "#pragma once" -> PPPRAGMA, PPPRAGMASTR("once") + # - "# pragma omp parallel private(th_id)" -> PPPRAGMA, PPPRAGMASTR("omp parallel private(th_id)") + # - "#\tpragma {pack: 2, smack: 3}" -> PPPRAGMA, PPPRAGMASTR("{pack: 2, smack: 3}") + text = self._lexdata + n = len(text) + pos = self._pos + + while pos < n and text[pos] in " \t": + pos += 1 + if pos >= n: + self._pos = pos + return [] + + if not text.startswith("pragma", pos): + self._error("invalid #pragma directive", pos) + self._pos = pos + 1 + return [] + + pragma_pos = pos + pos += len("pragma") + toks = [self._make_token("PPPRAGMA", "pragma", pragma_pos)] + + while pos < n and text[pos] in " \t": + pos += 1 + + start = pos + while pos < n and text[pos] != "\n": + pos += 1 + if pos > start: + toks.append(self._make_token("PPPRAGMASTR", text[start:pos], start)) + if pos < n and text[pos] == "\n": + self._lineno += 1 + pos += 1 + self._line_start = pos + self._pos = pos + return toks + + +## +## Reserved keywords +## +_keywords: Tuple[str, ...] = ( + "AUTO", + "BREAK", + "CASE", + "CHAR", + "CONST", + "CONTINUE", + "DEFAULT", + "DO", + "DOUBLE", + "ELSE", + "ENUM", + "EXTERN", + "FLOAT", + "FOR", + "GOTO", + "IF", + "INLINE", + "INT", + "LONG", + "REGISTER", + "OFFSETOF", + "RESTRICT", + "RETURN", + "SHORT", + "SIGNED", + "SIZEOF", + "STATIC", + "STRUCT", + "SWITCH", + "TYPEDEF", + "UNION", + "UNSIGNED", + "VOID", + "VOLATILE", + "WHILE", + "__INT128", + "_BOOL", + "_COMPLEX", + "_NORETURN", + "_THREAD_LOCAL", + "_STATIC_ASSERT", + "_ATOMIC", + "_ALIGNOF", + "_ALIGNAS", + "_PRAGMA", +) + +_keyword_map: Dict[str, str] = {} + +for keyword in _keywords: + # Keywords from new C standard are mixed-case, like _Bool, _Alignas, etc. + if keyword.startswith("_") and len(keyword) > 1 and keyword[1].isalpha(): + _keyword_map[keyword[:2].upper() + keyword[2:].lower()] = keyword + else: + _keyword_map[keyword.lower()] = keyword + +## +## Regexes for use in tokens +## + +# valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers) +_identifier = r"[a-zA-Z_$][0-9a-zA-Z_$]*" + +_hex_prefix = "0[xX]" +_hex_digits = "[0-9a-fA-F]+" +_bin_prefix = "0[bB]" +_bin_digits = "[01]+" + +# integer constants (K&R2: A.2.5.1) +_integer_suffix_opt = ( + r"(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?" +) +_decimal_constant = ( + "(0" + _integer_suffix_opt + ")|([1-9][0-9]*" + _integer_suffix_opt + ")" +) +_octal_constant = "0[0-7]*" + _integer_suffix_opt +_hex_constant = _hex_prefix + _hex_digits + _integer_suffix_opt +_bin_constant = _bin_prefix + _bin_digits + _integer_suffix_opt + +_bad_octal_constant = "0[0-7]*[89]" + +# comments are not supported +_unsupported_c_style_comment = r"\/\*" +_unsupported_cxx_style_comment = r"\/\/" + +# character constants (K&R2: A.2.5.2) +# Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line +# directives with Windows paths as filenames (..\..\dir\file) +# For the same reason, decimal_escape allows all digit sequences. We want to +# parse all correct code, even if it means to sometimes parse incorrect +# code. +# +# The original regexes were taken verbatim from the C syntax definition, +# and were later modified to avoid worst-case exponential running time. +# +# simple_escape = r"""([a-zA-Z._~!=&\^\-\\?'"])""" +# decimal_escape = r"""(\d+)""" +# hex_escape = r"""(x[0-9a-fA-F]+)""" +# bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-7])""" +# +# The following modifications were made to avoid the ambiguity that allowed +# backtracking: (https://github.com/eliben/pycparser/issues/61) +# +# - \x was removed from simple_escape, unless it was not followed by a hex +# digit, to avoid ambiguity with hex_escape. +# - hex_escape allows one or more hex characters, but requires that the next +# character(if any) is not hex +# - decimal_escape allows one or more decimal characters, but requires that the +# next character(if any) is not a decimal +# - bad_escape does not allow any decimals (8-9), to avoid conflicting with the +# permissive decimal_escape. +# +# Without this change, python's `re` module would recursively try parsing each +# ambiguous escape sequence in multiple ways. e.g. `\123` could be parsed as +# `\1`+`23`, `\12`+`3`, and `\123`. + +_simple_escape = r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))""" +_decimal_escape = r"""(\d+)(?!\d)""" +_hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])""" +_bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])""" + +_escape_sequence = ( + r"""(\\(""" + _simple_escape + "|" + _decimal_escape + "|" + _hex_escape + "))" +) + +# This complicated regex with lookahead might be slow for strings, so because +# all of the valid escapes (including \x) allowed +# 0 or more non-escaped characters after the first character, +# simple_escape+decimal_escape+hex_escape got simplified to + +_escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])""" + +_cconst_char = r"""([^'\\\n]|""" + _escape_sequence + ")" +_char_const = "'" + _cconst_char + "'" +_wchar_const = "L" + _char_const +_u8char_const = "u8" + _char_const +_u16char_const = "u" + _char_const +_u32char_const = "U" + _char_const +_multicharacter_constant = "'" + _cconst_char + "{2,4}'" +_unmatched_quote = "('" + _cconst_char + "*\\n)|('" + _cconst_char + "*$)" +_bad_char_const = ( + r"""('""" + _cconst_char + """[^'\n]+')|('')|('""" + _bad_escape + r"""[^'\n]*')""" +) + +# string literals (K&R2: A.2.6) +_string_char = r"""([^"\\\n]|""" + _escape_sequence_start_in_string + ")" +_string_literal = '"' + _string_char + '*"' +_wstring_literal = "L" + _string_literal +_u8string_literal = "u8" + _string_literal +_u16string_literal = "u" + _string_literal +_u32string_literal = "U" + _string_literal +_bad_string_literal = '"' + _string_char + "*" + _bad_escape + _string_char + '*"' + +# floating constants (K&R2: A.2.5.3) +_exponent_part = r"""([eE][-+]?[0-9]+)""" +_fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)""" +_floating_constant = ( + "((((" + + _fractional_constant + + ")" + + _exponent_part + + "?)|([0-9]+" + + _exponent_part + + "))[FfLl]?)" +) +_binary_exponent_part = r"""([pP][+-]?[0-9]+)""" +_hex_fractional_constant = ( + "(((" + _hex_digits + r""")?\.""" + _hex_digits + ")|(" + _hex_digits + r"""\.))""" +) +_hex_floating_constant = ( + "(" + + _hex_prefix + + "(" + + _hex_digits + + "|" + + _hex_fractional_constant + + ")" + + _binary_exponent_part + + "[FfLl]?)" +) + + +class _RegexAction(Enum): + TOKEN = 0 + ID = 1 + ERROR = 2 + + +@dataclass(frozen=True) +class _RegexRule: + # tok_type: name of the token emitted for a match + # regex_pattern: the raw regex (no anchors) to match at the current position + # action: TOKEN for normal tokens, ID for identifiers, ERROR to report + # error_message: message used for ERROR entries + tok_type: str + regex_pattern: str + action: _RegexAction + error_message: Optional[str] + + +_regex_rules: List[_RegexRule] = [ + _RegexRule( + "UNSUPPORTED_C_STYLE_COMMENT", + _unsupported_c_style_comment, + _RegexAction.ERROR, + "Comments are not supported, see https://github.com/eliben/pycparser#3using.", + ), + _RegexRule( + "UNSUPPORTED_CXX_STYLE_COMMENT", + _unsupported_cxx_style_comment, + _RegexAction.ERROR, + "Comments are not supported, see https://github.com/eliben/pycparser#3using.", + ), + _RegexRule( + "BAD_STRING_LITERAL", + _bad_string_literal, + _RegexAction.ERROR, + "String contains invalid escape code", + ), + _RegexRule("WSTRING_LITERAL", _wstring_literal, _RegexAction.TOKEN, None), + _RegexRule("U8STRING_LITERAL", _u8string_literal, _RegexAction.TOKEN, None), + _RegexRule("U16STRING_LITERAL", _u16string_literal, _RegexAction.TOKEN, None), + _RegexRule("U32STRING_LITERAL", _u32string_literal, _RegexAction.TOKEN, None), + _RegexRule("STRING_LITERAL", _string_literal, _RegexAction.TOKEN, None), + _RegexRule("HEX_FLOAT_CONST", _hex_floating_constant, _RegexAction.TOKEN, None), + _RegexRule("FLOAT_CONST", _floating_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_HEX", _hex_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_BIN", _bin_constant, _RegexAction.TOKEN, None), + _RegexRule( + "BAD_CONST_OCT", + _bad_octal_constant, + _RegexAction.ERROR, + "Invalid octal constant", + ), + _RegexRule("INT_CONST_OCT", _octal_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_DEC", _decimal_constant, _RegexAction.TOKEN, None), + _RegexRule("INT_CONST_CHAR", _multicharacter_constant, _RegexAction.TOKEN, None), + _RegexRule("CHAR_CONST", _char_const, _RegexAction.TOKEN, None), + _RegexRule("WCHAR_CONST", _wchar_const, _RegexAction.TOKEN, None), + _RegexRule("U8CHAR_CONST", _u8char_const, _RegexAction.TOKEN, None), + _RegexRule("U16CHAR_CONST", _u16char_const, _RegexAction.TOKEN, None), + _RegexRule("U32CHAR_CONST", _u32char_const, _RegexAction.TOKEN, None), + _RegexRule("UNMATCHED_QUOTE", _unmatched_quote, _RegexAction.ERROR, "Unmatched '"), + _RegexRule("BAD_CHAR_CONST", _bad_char_const, _RegexAction.ERROR, None), + _RegexRule("ID", _identifier, _RegexAction.ID, None), +] + +_regex_actions: Dict[str, Tuple[_RegexAction, Optional[str]]] = {} +_regex_pattern_parts: List[str] = [] +for _rule in _regex_rules: + _regex_actions[_rule.tok_type] = (_rule.action, _rule.error_message) + _regex_pattern_parts.append(f"(?P<{_rule.tok_type}>{_rule.regex_pattern})") +# The master regex is a single alternation of all token patterns, each wrapped +# in a named group. We match once at the current position and then use +# `lastgroup` to recover which token kind fired; this avoids iterating over all +# regexes on every character while keeping the same token-level semantics. +_regex_master: re.Pattern[str] = re.compile("|".join(_regex_pattern_parts)) + + +@dataclass(frozen=True) +class _FixedToken: + tok_type: str + literal: str + + +_fixed_tokens: List[_FixedToken] = [ + _FixedToken("ELLIPSIS", "..."), + _FixedToken("LSHIFTEQUAL", "<<="), + _FixedToken("RSHIFTEQUAL", ">>="), + _FixedToken("PLUSPLUS", "++"), + _FixedToken("MINUSMINUS", "--"), + _FixedToken("ARROW", "->"), + _FixedToken("LAND", "&&"), + _FixedToken("LOR", "||"), + _FixedToken("LSHIFT", "<<"), + _FixedToken("RSHIFT", ">>"), + _FixedToken("LE", "<="), + _FixedToken("GE", ">="), + _FixedToken("EQ", "=="), + _FixedToken("NE", "!="), + _FixedToken("TIMESEQUAL", "*="), + _FixedToken("DIVEQUAL", "/="), + _FixedToken("MODEQUAL", "%="), + _FixedToken("PLUSEQUAL", "+="), + _FixedToken("MINUSEQUAL", "-="), + _FixedToken("ANDEQUAL", "&="), + _FixedToken("OREQUAL", "|="), + _FixedToken("XOREQUAL", "^="), + _FixedToken("EQUALS", "="), + _FixedToken("PLUS", "+"), + _FixedToken("MINUS", "-"), + _FixedToken("TIMES", "*"), + _FixedToken("DIVIDE", "/"), + _FixedToken("MOD", "%"), + _FixedToken("OR", "|"), + _FixedToken("AND", "&"), + _FixedToken("NOT", "~"), + _FixedToken("XOR", "^"), + _FixedToken("LNOT", "!"), + _FixedToken("LT", "<"), + _FixedToken("GT", ">"), + _FixedToken("CONDOP", "?"), + _FixedToken("LPAREN", "("), + _FixedToken("RPAREN", ")"), + _FixedToken("LBRACKET", "["), + _FixedToken("RBRACKET", "]"), + _FixedToken("LBRACE", "{"), + _FixedToken("RBRACE", "}"), + _FixedToken("COMMA", ","), + _FixedToken("PERIOD", "."), + _FixedToken("SEMI", ";"), + _FixedToken("COLON", ":"), +] + +# To avoid scanning all fixed tokens on every character, we bucket them by the +# first character. When matching at position i, we only look at the bucket for +# text[i], and we pre-sort that bucket by token length so the first match is +# also the longest. This preserves longest-match semantics (e.g. '>>=' before +# '>>' before '>') while reducing the number of comparisons. +_fixed_tokens_by_first: Dict[str, List[_FixedToken]] = {} +for _entry in _fixed_tokens: + _fixed_tokens_by_first.setdefault(_entry.literal[0], []).append(_entry) +for _bucket in _fixed_tokens_by_first.values(): + _bucket.sort(key=lambda item: len(item.literal), reverse=True) + +_line_pattern: re.Pattern[str] = re.compile(r"([ \t]*line\W)|([ \t]*\d+)") +_pragma_pattern: re.Pattern[str] = re.compile(r"[ \t]*pragma\W") diff --git a/lib/python3.11/site-packages/pycparser/c_parser.py b/lib/python3.11/site-packages/pycparser/c_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f980672cf5eeccea5dc2e60b264d17dd1fbcd058 --- /dev/null +++ b/lib/python3.11/site-packages/pycparser/c_parser.py @@ -0,0 +1,2376 @@ +# ------------------------------------------------------------------------------ +# pycparser: c_parser.py +# +# Recursive-descent parser for the C language. +# +# Eli Bendersky [https://eli.thegreenplace.net/] +# License: BSD +# ------------------------------------------------------------------------------ +from dataclasses import dataclass +from typing import ( + Any, + Dict, + List, + Literal, + NoReturn, + Optional, + Tuple, + TypedDict, + cast, +) + +from . import c_ast +from .c_lexer import CLexer, _Token +from .ast_transforms import fix_switch_cases, fix_atomic_specifiers + + +@dataclass +class Coord: + """Coordinates of a syntactic element. Consists of: + - File name + - Line number + - Column number + """ + + file: str + line: int + column: Optional[int] = None + + def __str__(self) -> str: + text = f"{self.file}:{self.line}" + if self.column: + text += f":{self.column}" + return text + + +class ParseError(Exception): + pass + + +class CParser: + """Recursive-descent C parser. + + Usage: + parser = CParser() + ast = parser.parse(text, filename) + + The `lexer` parameter lets you inject a lexer class (defaults to CLexer). + The parameters after `lexer` are accepted for backward compatibility with + the old PLY-based parser and are otherwise unused. + """ + + def __init__( + self, + lex_optimize: bool = True, + lexer: type[CLexer] = CLexer, + lextab: str = "pycparser.lextab", + yacc_optimize: bool = True, + yacctab: str = "pycparser.yacctab", + yacc_debug: bool = False, + taboutputdir: str = "", + ) -> None: + self.clex: CLexer = lexer( + error_func=self._lex_error_func, + on_lbrace_func=self._lex_on_lbrace_func, + on_rbrace_func=self._lex_on_rbrace_func, + type_lookup_func=self._lex_type_lookup_func, + ) + + # Stack of scopes for keeping track of symbols. _scope_stack[-1] is + # the current (topmost) scope. Each scope is a dictionary that + # specifies whether a name is a type. If _scope_stack[n][name] is + # True, 'name' is currently a type in the scope. If it's False, + # 'name' is used in the scope but not as a type (for instance, if we + # saw: int name; + # If 'name' is not a key in _scope_stack[n] then 'name' was not defined + # in this scope at all. + self._scope_stack: List[Dict[str, bool]] = [dict()] + self._tokens: _TokenStream = _TokenStream(self.clex) + + def parse( + self, text: str, filename: str = "", debug: bool = False + ) -> c_ast.FileAST: + """Parses C code and returns an AST. + + text: + A string containing the C source code + + filename: + Name of the file being parsed (for meaningful + error messages) + + debug: + Deprecated debug flag (unused); for backwards compatibility. + """ + self._scope_stack = [dict()] + self.clex.input(text, filename) + self._tokens = _TokenStream(self.clex) + + ast = self._parse_translation_unit_or_empty() + tok = self._peek() + if tok is not None: + self._parse_error(f"before: {tok.value}", self._tok_coord(tok)) + return ast + + # ------------------------------------------------------------------ + # Scope and declaration helpers + # ------------------------------------------------------------------ + def _coord(self, lineno: int, column: Optional[int] = None) -> Coord: + return Coord(file=self.clex.filename, line=lineno, column=column) + + def _parse_error(self, msg: str, coord: Coord | str | None) -> NoReturn: + raise ParseError(f"{coord}: {msg}") + + def _push_scope(self) -> None: + self._scope_stack.append(dict()) + + def _pop_scope(self) -> None: + assert len(self._scope_stack) > 1 + self._scope_stack.pop() + + def _add_typedef_name(self, name: str, coord: Optional[Coord]) -> None: + """Add a new typedef name (ie a TYPEID) to the current scope""" + if not self._scope_stack[-1].get(name, True): + self._parse_error( + f"Typedef {name!r} previously declared as non-typedef in this scope", + coord, + ) + self._scope_stack[-1][name] = True + + def _add_identifier(self, name: str, coord: Optional[Coord]) -> None: + """Add a new object, function, or enum member name (ie an ID) to the + current scope + """ + if self._scope_stack[-1].get(name, False): + self._parse_error( + f"Non-typedef {name!r} previously declared as typedef in this scope", + coord, + ) + self._scope_stack[-1][name] = False + + def _is_type_in_scope(self, name: str) -> bool: + """Is *name* a typedef-name in the current scope?""" + for scope in reversed(self._scope_stack): + # If name is an identifier in this scope it shadows typedefs in + # higher scopes. + in_scope = scope.get(name) + if in_scope is not None: + return in_scope + return False + + def _lex_error_func(self, msg: str, line: int, column: int) -> None: + self._parse_error(msg, self._coord(line, column)) + + def _lex_on_lbrace_func(self) -> None: + self._push_scope() + + def _lex_on_rbrace_func(self) -> None: + self._pop_scope() + + def _lex_type_lookup_func(self, name: str) -> bool: + """Looks up types that were previously defined with + typedef. + Passed to the lexer for recognizing identifiers that + are types. + """ + return self._is_type_in_scope(name) + + # To understand what's going on here, read sections A.8.5 and + # A.8.6 of K&R2 very carefully. + # + # A C type consists of a basic type declaration, with a list + # of modifiers. For example: + # + # int *c[5]; + # + # The basic declaration here is 'int c', and the pointer and + # the array are the modifiers. + # + # Basic declarations are represented by TypeDecl (from module c_ast) and the + # modifiers are FuncDecl, PtrDecl and ArrayDecl. + # + # The standard states that whenever a new modifier is parsed, it should be + # added to the end of the list of modifiers. For example: + # + # K&R2 A.8.6.2: Array Declarators + # + # In a declaration T D where D has the form + # D1 [constant-expression-opt] + # and the type of the identifier in the declaration T D1 is + # "type-modifier T", the type of the + # identifier of D is "type-modifier array of T" + # + # This is what this method does. The declarator it receives + # can be a list of declarators ending with TypeDecl. It + # tacks the modifier to the end of this list, just before + # the TypeDecl. + # + # Additionally, the modifier may be a list itself. This is + # useful for pointers, that can come as a chain from the rule + # p_pointer. In this case, the whole modifier list is spliced + # into the new location. + def _type_modify_decl(self, decl: Any, modifier: Any) -> c_ast.Node: + """Tacks a type modifier on a declarator, and returns + the modified declarator. + + Note: the declarator and modifier may be modified + """ + modifier_head = modifier + modifier_tail = modifier + + # The modifier may be a nested list. Reach its tail. + while modifier_tail.type: + modifier_tail = modifier_tail.type + + # If the decl is a basic type, just tack the modifier onto it. + if isinstance(decl, c_ast.TypeDecl): + modifier_tail.type = decl + return modifier + else: + # Otherwise, the decl is a list of modifiers. Reach + # its tail and splice the modifier onto the tail, + # pointing to the underlying basic type. + decl_tail = decl + while not isinstance(decl_tail.type, c_ast.TypeDecl): + decl_tail = decl_tail.type + + modifier_tail.type = decl_tail.type + decl_tail.type = modifier_head + return decl + + # Due to the order in which declarators are constructed, + # they have to be fixed in order to look like a normal AST. + # + # When a declaration arrives from syntax construction, it has + # these problems: + # * The innermost TypeDecl has no type (because the basic + # type is only known at the uppermost declaration level) + # * The declaration has no variable name, since that is saved + # in the innermost TypeDecl + # * The typename of the declaration is a list of type + # specifiers, and not a node. Here, basic identifier types + # should be separated from more complex types like enums + # and structs. + # + # This method fixes these problems. + def _fix_decl_name_type( + self, + decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename, + typename: List[Any], + ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename: + """Fixes a declaration. Modifies decl.""" + # Reach the underlying basic type + typ = decl + while not isinstance(typ, c_ast.TypeDecl): + typ = typ.type + + decl.name = typ.declname + typ.quals = decl.quals[:] + + # The typename is a list of types. If any type in this + # list isn't an IdentifierType, it must be the only + # type in the list (it's illegal to declare "int enum ..") + # If all the types are basic, they're collected in the + # IdentifierType holder. + for tn in typename: + if not isinstance(tn, c_ast.IdentifierType): + if len(typename) > 1: + self._parse_error("Invalid multiple types specified", tn.coord) + else: + typ.type = tn + return decl + + if not typename: + # Functions default to returning int + if not isinstance(decl.type, c_ast.FuncDecl): + self._parse_error("Missing type in declaration", decl.coord) + typ.type = c_ast.IdentifierType(["int"], coord=decl.coord) + else: + # At this point, we know that typename is a list of IdentifierType + # nodes. Concatenate all the names into a single list. + typ.type = c_ast.IdentifierType( + [name for id in typename for name in id.names], coord=typename[0].coord + ) + return decl + + def _add_declaration_specifier( + self, + declspec: Optional["_DeclSpec"], + newspec: Any, + kind: "_DeclSpecKind", + append: bool = False, + ) -> "_DeclSpec": + """See _DeclSpec for the specifier dictionary layout.""" + if declspec is None: + spec: _DeclSpec = dict( + qual=[], storage=[], type=[], function=[], alignment=[] + ) + else: + spec = declspec + + if append: + spec[kind].append(newspec) + else: + spec[kind].insert(0, newspec) + + return spec + + def _build_declarations( + self, + spec: "_DeclSpec", + decls: List["_DeclInfo"], + typedef_namespace: bool = False, + ) -> List[c_ast.Node]: + """Builds a list of declarations all sharing the given specifiers. + If typedef_namespace is true, each declared name is added + to the "typedef namespace", which also includes objects, + functions, and enum constants. + """ + is_typedef = "typedef" in spec["storage"] + declarations = [] + + # Bit-fields are allowed to be unnamed. + if decls[0].get("bitsize") is None: + # When redeclaring typedef names as identifiers in inner scopes, a + # problem can occur where the identifier gets grouped into + # spec['type'], leaving decl as None. This can only occur for the + # first declarator. + if decls[0]["decl"] is None: + if ( + len(spec["type"]) < 2 + or len(spec["type"][-1].names) != 1 + or not self._is_type_in_scope(spec["type"][-1].names[0]) + ): + coord = "?" + for t in spec["type"]: + if hasattr(t, "coord"): + coord = t.coord + break + self._parse_error("Invalid declaration", coord) + + # Make this look as if it came from "direct_declarator:ID" + decls[0]["decl"] = c_ast.TypeDecl( + declname=spec["type"][-1].names[0], + type=None, + quals=None, + align=spec["alignment"], + coord=spec["type"][-1].coord, + ) + # Remove the "new" type's name from the end of spec['type'] + del spec["type"][-1] + # A similar problem can occur where the declaration ends up + # looking like an abstract declarator. Give it a name if this is + # the case. + elif not isinstance( + decls[0]["decl"], + (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType), + ): + decls_0_tail = cast(Any, decls[0]["decl"]) + while not isinstance(decls_0_tail, c_ast.TypeDecl): + decls_0_tail = decls_0_tail.type + if decls_0_tail.declname is None: + decls_0_tail.declname = spec["type"][-1].names[0] + del spec["type"][-1] + + for decl in decls: + assert decl["decl"] is not None + if is_typedef: + declaration = c_ast.Typedef( + name=None, + quals=spec["qual"], + storage=spec["storage"], + type=decl["decl"], + coord=decl["decl"].coord, + ) + else: + declaration = c_ast.Decl( + name=None, + quals=spec["qual"], + align=spec["alignment"], + storage=spec["storage"], + funcspec=spec["function"], + type=decl["decl"], + init=decl.get("init"), + bitsize=decl.get("bitsize"), + coord=decl["decl"].coord, + ) + + if isinstance( + declaration.type, + (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType), + ): + fixed_decl = declaration + else: + fixed_decl = self._fix_decl_name_type(declaration, spec["type"]) + + # Add the type name defined by typedef to a + # symbol table (for usage in the lexer) + if typedef_namespace: + if is_typedef: + self._add_typedef_name(fixed_decl.name, fixed_decl.coord) + else: + self._add_identifier(fixed_decl.name, fixed_decl.coord) + + fixed_decl = fix_atomic_specifiers( + cast(c_ast.Decl | c_ast.Typedef, fixed_decl) + ) + declarations.append(fixed_decl) + + return declarations + + def _build_function_definition( + self, + spec: "_DeclSpec", + decl: c_ast.Node, + param_decls: Optional[List[c_ast.Node]], + body: c_ast.Node, + ) -> c_ast.Node: + """Builds a function definition.""" + if "typedef" in spec["storage"]: + self._parse_error("Invalid typedef", decl.coord) + + declaration = self._build_declarations( + spec=spec, + decls=[dict(decl=decl, init=None, bitsize=None)], + typedef_namespace=True, + )[0] + + return c_ast.FuncDef( + decl=declaration, param_decls=param_decls, body=body, coord=decl.coord + ) + + def _select_struct_union_class(self, token: str) -> type: + """Given a token (either STRUCT or UNION), selects the + appropriate AST class. + """ + if token == "struct": + return c_ast.Struct + else: + return c_ast.Union + + # ------------------------------------------------------------------ + # Token helpers + # ------------------------------------------------------------------ + def _peek(self, k: int = 1) -> Optional[_Token]: + """Return the k-th next token without consuming it (1-based).""" + return self._tokens.peek(k) + + def _peek_type(self, k: int = 1) -> Optional[str]: + """Return the type of the k-th next token, or None if absent (1-based).""" + tok = self._peek(k) + return tok.type if tok is not None else None + + def _advance(self) -> _Token: + tok = self._tokens.next() + if tok is None: + self._parse_error("At end of input", self.clex.filename) + else: + return tok + + def _accept(self, token_type: str) -> Optional[_Token]: + """Conditionally consume next token, only if it's of token_type. + + If it is of the expected type, consume and return it. + Otherwise, leaves the token intact and returns None. + """ + tok = self._peek() + if tok is not None and tok.type == token_type: + return self._advance() + return None + + def _expect(self, token_type: str) -> _Token: + tok = self._advance() + if tok.type != token_type: + self._parse_error(f"before: {tok.value}", self._tok_coord(tok)) + return tok + + def _mark(self) -> int: + return self._tokens.mark() + + def _reset(self, mark: int) -> None: + self._tokens.reset(mark) + + def _tok_coord(self, tok: _Token) -> Coord: + return self._coord(tok.lineno, tok.column) + + def _starts_declaration(self, tok: Optional[_Token] = None) -> bool: + tok = tok or self._peek() + if tok is None: + return False + return tok.type in _DECL_START + + def _starts_expression(self, tok: Optional[_Token] = None) -> bool: + tok = tok or self._peek() + if tok is None: + return False + return tok.type in _STARTS_EXPRESSION + + def _starts_statement(self) -> bool: + tok_type = self._peek_type() + if tok_type is None: + return False + if tok_type in _STARTS_STATEMENT: + return True + return self._starts_expression() + + def _starts_declarator(self, id_only: bool = False) -> bool: + tok_type = self._peek_type() + if tok_type is None: + return False + if tok_type in {"TIMES", "LPAREN"}: + return True + if id_only: + return tok_type == "ID" + return tok_type in {"ID", "TYPEID"} + + def _peek_declarator_name_info(self) -> Tuple[Optional[str], bool]: + mark = self._mark() + tok_type, saw_paren = self._scan_declarator_name_info() + self._reset(mark) + return tok_type, saw_paren + + def _parse_any_declarator( + self, allow_abstract: bool = False, typeid_paren_as_abstract: bool = False + ) -> Tuple[Optional[c_ast.Node], bool]: + # C declarators are ambiguous without lookahead. For example: + # int foo(int (aa)); -> aa is a name (ID) + # typedef char TT; + # int bar(int (TT)); -> TT is a type (TYPEID) in parens + name_type, saw_paren = self._peek_declarator_name_info() + if name_type is None or ( + typeid_paren_as_abstract and name_type == "TYPEID" and saw_paren + ): + if not allow_abstract: + tok = self._peek() + coord = self._tok_coord(tok) if tok is not None else self.clex.filename + self._parse_error("Invalid declarator", coord) + decl = self._parse_abstract_declarator_opt() + return decl, False + + if name_type == "TYPEID": + if typeid_paren_as_abstract: + decl = self._parse_typeid_noparen_declarator() + else: + decl = self._parse_typeid_declarator() + else: + decl = self._parse_id_declarator() + return decl, True + + def _scan_declarator_name_info(self) -> Tuple[Optional[str], bool]: + saw_paren = False + while self._accept("TIMES"): + while self._peek_type() in _TYPE_QUALIFIER: + self._advance() + + tok = self._peek() + if tok is None: + return None, saw_paren + if tok.type in {"ID", "TYPEID"}: + self._advance() + return tok.type, saw_paren + if tok.type == "LPAREN": + saw_paren = True + self._advance() + tok_type, nested_paren = self._scan_declarator_name_info() + if nested_paren: + saw_paren = True + depth = 1 + while True: + tok = self._peek() + if tok is None: + return None, saw_paren + if tok.type == "LPAREN": + depth += 1 + elif tok.type == "RPAREN": + depth -= 1 + self._advance() + if depth == 0: + break + continue + self._advance() + return tok_type, saw_paren + return None, saw_paren + + def _starts_direct_abstract_declarator(self) -> bool: + return self._peek_type() in {"LPAREN", "LBRACKET"} + + def _is_assignment_op(self) -> bool: + tok = self._peek() + return tok is not None and tok.type in _ASSIGNMENT_OPS + + def _try_parse_paren_type_name( + self, + ) -> Optional[Tuple[c_ast.Typename, int, _Token]]: + """Parse and return a parenthesized type name if present. + + Returns (typ, mark, lparen_tok) when the next tokens look like + '(' type_name ')', where typ is the parsed type name, mark is the + token-stream position before parsing, and lparen_tok is the LPAREN + token. Returns None if no parenthesized type name is present. + """ + mark = self._mark() + lparen_tok = self._accept("LPAREN") + if lparen_tok is None: + return None + if not self._starts_declaration(): + self._reset(mark) + return None + typ = self._parse_type_name() + if self._accept("RPAREN") is None: + self._reset(mark) + return None + return typ, mark, lparen_tok + + # ------------------------------------------------------------------ + # Top-level + # ------------------------------------------------------------------ + # BNF: translation_unit_or_empty : translation_unit | empty + def _parse_translation_unit_or_empty(self) -> c_ast.FileAST: + if self._peek() is None: + return c_ast.FileAST([]) + return c_ast.FileAST(self._parse_translation_unit()) + + # BNF: translation_unit : external_declaration+ + def _parse_translation_unit(self) -> List[c_ast.Node]: + ext = [] + while self._peek() is not None: + ext.extend(self._parse_external_declaration()) + return ext + + # BNF: external_declaration : function_definition + # | declaration + # | pp_directive + # | pppragma_directive + # | static_assert + # | ';' + def _parse_external_declaration(self) -> List[c_ast.Node]: + tok = self._peek() + if tok is None: + return [] + if tok.type == "PPHASH": + self._parse_pp_directive() + return [] + if tok.type in {"PPPRAGMA", "_PRAGMA"}: + return [self._parse_pppragma_directive()] + if self._accept("SEMI"): + return [] + if tok.type == "_STATIC_ASSERT": + return self._parse_static_assert() + + if not self._starts_declaration(tok): + # Special handling for old-style function definitions that have an + # implicit return type, e.g. + # + # foo() { + # return 5; + # } + # + # These get an implicit 'int' return type. + decl = self._parse_id_declarator() + param_decls = None + if self._peek_type() != "LBRACE": + self._parse_error("Invalid function definition", decl.coord) + spec: _DeclSpec = dict( + qual=[], + alignment=[], + storage=[], + type=[c_ast.IdentifierType(["int"], coord=decl.coord)], + function=[], + ) + func = self._build_function_definition( + spec=spec, + decl=decl, + param_decls=param_decls, + body=self._parse_compound_statement(), + ) + return [func] + + # From here on, parsing a standard declatation/definition. + spec, saw_type, spec_coord = self._parse_declaration_specifiers( + allow_no_type=True + ) + + name_type, _ = self._peek_declarator_name_info() + if name_type != "ID": + decls = self._parse_decl_body_with_spec(spec, saw_type) + self._expect("SEMI") + return decls + + decl = self._parse_id_declarator() + + if self._peek_type() == "LBRACE" or self._starts_declaration(): + param_decls = None + if self._starts_declaration(): + param_decls = self._parse_declaration_list() + if self._peek_type() != "LBRACE": + self._parse_error("Invalid function definition", decl.coord) + if not spec["type"]: + spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)] + func = self._build_function_definition( + spec=spec, + decl=decl, + param_decls=param_decls, + body=self._parse_compound_statement(), + ) + return [func] + + decl_dict: "_DeclInfo" = dict(decl=decl, init=None, bitsize=None) + if self._accept("EQUALS"): + decl_dict["init"] = self._parse_initializer() + decls = self._parse_init_declarator_list(first=decl_dict) + decls = self._build_declarations(spec=spec, decls=decls, typedef_namespace=True) + self._expect("SEMI") + return decls + + # ------------------------------------------------------------------ + # Declarations + # + # Declarations always come as lists (because they can be several in one + # line). When returning parsed declarations, a list is always returned - + # even if it contains a single element. + # ------------------------------------------------------------------ + def _parse_declaration(self) -> List[c_ast.Node]: + decls = self._parse_decl_body() + self._expect("SEMI") + return decls + + # BNF: decl_body : declaration_specifiers decl_body_with_spec + def _parse_decl_body(self) -> List[c_ast.Node]: + spec, saw_type, _ = self._parse_declaration_specifiers(allow_no_type=True) + return self._parse_decl_body_with_spec(spec, saw_type) + + # BNF: decl_body_with_spec : init_declarator_list + # | struct_or_union_or_enum_only + def _parse_decl_body_with_spec( + self, spec: "_DeclSpec", saw_type: bool + ) -> List[c_ast.Node]: + decls = None + if saw_type: + if self._starts_declarator(): + decls = self._parse_init_declarator_list() + else: + if self._starts_declarator(id_only=True): + decls = self._parse_init_declarator_list(id_only=True) + + if decls is None: + ty = spec["type"] + s_u_or_e = (c_ast.Struct, c_ast.Union, c_ast.Enum) + if len(ty) == 1 and isinstance(ty[0], s_u_or_e): + decls = [ + c_ast.Decl( + name=None, + quals=spec["qual"], + align=spec["alignment"], + storage=spec["storage"], + funcspec=spec["function"], + type=ty[0], + init=None, + bitsize=None, + coord=ty[0].coord, + ) + ] + else: + decls = self._build_declarations( + spec=spec, + decls=[dict(decl=None, init=None, bitsize=None)], + typedef_namespace=True, + ) + else: + decls = self._build_declarations( + spec=spec, decls=decls, typedef_namespace=True + ) + + return decls + + # BNF: declaration_list : declaration+ + def _parse_declaration_list(self) -> List[c_ast.Node]: + decls = [] + while self._starts_declaration(): + decls.extend(self._parse_declaration()) + return decls + + # BNF: declaration_specifiers : (storage_class_specifier + # | type_specifier + # | type_qualifier + # | function_specifier + # | alignment_specifier)+ + def _parse_declaration_specifiers( + self, allow_no_type: bool = False + ) -> Tuple["_DeclSpec", bool, Optional[Coord]]: + """Parse declaration-specifier sequence. + + allow_no_type: + If True, allow a missing type specifier without error. + + Returns: + (spec, saw_type, first_coord) where spec is a dict with + qual/storage/type/function/alignment entries, saw_type is True + if a type specifier was consumed, and first_coord is the coord + of the first specifier token (used for diagnostics). + """ + spec = None + saw_type = False + first_coord = None + + while True: + tok = self._peek() + if tok is None: + break + + if tok.type == "_ALIGNAS": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_alignment_specifier(), "alignment", append=True + ) + continue + + if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_atomic_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type in _TYPE_QUALIFIER: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "qual", append=True + ) + continue + + if tok.type in _STORAGE_CLASS: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "storage", append=True + ) + continue + + if tok.type in _FUNCTION_SPEC: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "function", append=True + ) + continue + + if tok.type in _TYPE_SPEC_SIMPLE: + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type == "TYPEID": + if saw_type: + break + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type in {"STRUCT", "UNION"}: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_struct_or_union_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type == "ENUM": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_enum_specifier(), "type", append=True + ) + saw_type = True + continue + + break + + if spec is None: + self._parse_error("Invalid declaration", self.clex.filename) + + if not saw_type and not allow_no_type: + self._parse_error("Missing type in declaration", first_coord) + + return spec, saw_type, first_coord + + # BNF: specifier_qualifier_list : (type_specifier + # | type_qualifier + # | alignment_specifier)+ + def _parse_specifier_qualifier_list(self) -> "_DeclSpec": + spec = None + saw_type = False + saw_alignment = False + first_coord = None + + while True: + tok = self._peek() + if tok is None: + break + + if tok.type == "_ALIGNAS": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_alignment_specifier(), "alignment", append=True + ) + saw_alignment = True + continue + + if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_atomic_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type in _TYPE_QUALIFIER: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._advance().value, "qual", append=True + ) + continue + + if tok.type in _TYPE_SPEC_SIMPLE: + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type == "TYPEID": + if saw_type: + break + if first_coord is None: + first_coord = self._tok_coord(tok) + tok = self._advance() + spec = self._add_declaration_specifier( + spec, + c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)), + "type", + append=True, + ) + saw_type = True + continue + + if tok.type in {"STRUCT", "UNION"}: + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_struct_or_union_specifier(), "type", append=True + ) + saw_type = True + continue + + if tok.type == "ENUM": + if first_coord is None: + first_coord = self._tok_coord(tok) + spec = self._add_declaration_specifier( + spec, self._parse_enum_specifier(), "type", append=True + ) + saw_type = True + continue + + break + + if spec is None: + self._parse_error("Invalid specifier list", self.clex.filename) + + if not saw_type and not saw_alignment: + self._parse_error("Missing type in declaration", first_coord) + + if spec.get("storage") is None: + spec["storage"] = [] + if spec.get("function") is None: + spec["function"] = [] + + return spec + + # BNF: type_qualifier_list : type_qualifier+ + def _parse_type_qualifier_list(self) -> List[str]: + quals = [] + while self._peek_type() in _TYPE_QUALIFIER: + quals.append(self._advance().value) + return quals + + # BNF: alignment_specifier : _ALIGNAS '(' type_name | constant_expression ')' + def _parse_alignment_specifier(self) -> c_ast.Node: + tok = self._expect("_ALIGNAS") + self._expect("LPAREN") + + if self._starts_declaration(): + typ = self._parse_type_name() + self._expect("RPAREN") + return c_ast.Alignas(typ, self._tok_coord(tok)) + + expr = self._parse_constant_expression() + self._expect("RPAREN") + return c_ast.Alignas(expr, self._tok_coord(tok)) + + # BNF: atomic_specifier : _ATOMIC '(' type_name ')' + def _parse_atomic_specifier(self) -> c_ast.Node: + self._expect("_ATOMIC") + self._expect("LPAREN") + typ = self._parse_type_name() + self._expect("RPAREN") + typ.quals.append("_Atomic") + return typ + + # BNF: init_declarator_list : init_declarator (',' init_declarator)* + def _parse_init_declarator_list( + self, first: Optional["_DeclInfo"] = None, id_only: bool = False + ) -> List["_DeclInfo"]: + decls = ( + [first] + if first is not None + else [self._parse_init_declarator(id_only=id_only)] + ) + + while self._accept("COMMA"): + decls.append(self._parse_init_declarator(id_only=id_only)) + return decls + + # BNF: init_declarator : declarator ('=' initializer)? + def _parse_init_declarator(self, id_only: bool = False) -> "_DeclInfo": + decl = self._parse_id_declarator() if id_only else self._parse_declarator() + init = None + if self._accept("EQUALS"): + init = self._parse_initializer() + return dict(decl=decl, init=init, bitsize=None) + + # ------------------------------------------------------------------ + # Structs/unions/enums + # ------------------------------------------------------------------ + # BNF: struct_or_union_specifier : struct_or_union ID? '{' struct_declaration_list? '}' + # | struct_or_union ID + def _parse_struct_or_union_specifier(self) -> c_ast.Node: + tok = self._advance() + klass = self._select_struct_union_class(tok.value) + + if self._peek_type() in {"ID", "TYPEID"}: + name_tok = self._advance() + if self._peek_type() == "LBRACE": + self._advance() + if self._accept("RBRACE"): + return klass( + name=name_tok.value, decls=[], coord=self._tok_coord(name_tok) + ) + decls = self._parse_struct_declaration_list() + self._expect("RBRACE") + return klass( + name=name_tok.value, decls=decls, coord=self._tok_coord(name_tok) + ) + + return klass( + name=name_tok.value, decls=None, coord=self._tok_coord(name_tok) + ) + + if self._peek_type() == "LBRACE": + brace_tok = self._advance() + if self._accept("RBRACE"): + return klass(name=None, decls=[], coord=self._tok_coord(brace_tok)) + decls = self._parse_struct_declaration_list() + self._expect("RBRACE") + return klass(name=None, decls=decls, coord=self._tok_coord(brace_tok)) + + self._parse_error("Invalid struct/union declaration", self._tok_coord(tok)) + + # BNF: struct_declaration_list : struct_declaration+ + def _parse_struct_declaration_list(self) -> List[c_ast.Node]: + decls = [] + while self._peek_type() not in {None, "RBRACE"}: + items = self._parse_struct_declaration() + if items is None: + continue + decls.extend(items) + return decls + + # BNF: struct_declaration : specifier_qualifier_list struct_declarator_list? ';' + # | static_assert + # | pppragma_directive + def _parse_struct_declaration(self) -> Optional[List[c_ast.Node]]: + if self._peek_type() == "SEMI": + self._advance() + return None + if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: + return [self._parse_pppragma_directive()] + + spec = self._parse_specifier_qualifier_list() + assert "typedef" not in spec.get("storage", []) + + decls = None + if self._starts_declarator() or self._peek_type() == "COLON": + decls = self._parse_struct_declarator_list() + if decls is not None: + self._expect("SEMI") + return self._build_declarations(spec=spec, decls=decls) + + if len(spec["type"]) == 1: + node = spec["type"][0] + if isinstance(node, c_ast.Node): + decl_type = node + else: + decl_type = c_ast.IdentifierType(node) + self._expect("SEMI") + return self._build_declarations( + spec=spec, decls=[dict(decl=decl_type, init=None, bitsize=None)] + ) + + self._expect("SEMI") + return self._build_declarations( + spec=spec, decls=[dict(decl=None, init=None, bitsize=None)] + ) + + # BNF: struct_declarator_list : struct_declarator (',' struct_declarator)* + def _parse_struct_declarator_list(self) -> List["_DeclInfo"]: + decls = [self._parse_struct_declarator()] + while self._accept("COMMA"): + decls.append(self._parse_struct_declarator()) + return decls + + # BNF: struct_declarator : declarator? ':' constant_expression + # | declarator (':' constant_expression)? + def _parse_struct_declarator(self) -> "_DeclInfo": + if self._accept("COLON"): + bitsize = self._parse_constant_expression() + return { + "decl": c_ast.TypeDecl(None, None, None, None), + "init": None, + "bitsize": bitsize, + } + + decl = self._parse_declarator() + if self._accept("COLON"): + bitsize = self._parse_constant_expression() + return {"decl": decl, "init": None, "bitsize": bitsize} + + return {"decl": decl, "init": None, "bitsize": None} + + # BNF: enum_specifier : ENUM ID? '{' enumerator_list? '}' + # | ENUM ID + def _parse_enum_specifier(self) -> c_ast.Node: + tok = self._expect("ENUM") + if self._peek_type() in {"ID", "TYPEID"}: + name_tok = self._advance() + if self._peek_type() == "LBRACE": + self._advance() + enums = self._parse_enumerator_list() + self._expect("RBRACE") + return c_ast.Enum(name_tok.value, enums, self._tok_coord(tok)) + return c_ast.Enum(name_tok.value, None, self._tok_coord(tok)) + + self._expect("LBRACE") + enums = self._parse_enumerator_list() + self._expect("RBRACE") + return c_ast.Enum(None, enums, self._tok_coord(tok)) + + # BNF: enumerator_list : enumerator (',' enumerator)* ','? + def _parse_enumerator_list(self) -> c_ast.Node: + enum = self._parse_enumerator() + enum_list = c_ast.EnumeratorList([enum], enum.coord) + while self._accept("COMMA"): + if self._peek_type() == "RBRACE": + break + enum = self._parse_enumerator() + enum_list.enumerators.append(enum) + return enum_list + + # BNF: enumerator : ID ('=' constant_expression)? + def _parse_enumerator(self) -> c_ast.Node: + name_tok = self._expect("ID") + if self._accept("EQUALS"): + value = self._parse_constant_expression() + else: + value = None + enum = c_ast.Enumerator(name_tok.value, value, self._tok_coord(name_tok)) + self._add_identifier(enum.name, enum.coord) + return enum + + # ------------------------------------------------------------------ + # Declarators + # ------------------------------------------------------------------ + # BNF: declarator : pointer? direct_declarator + def _parse_declarator(self) -> c_ast.Node: + decl, _ = self._parse_any_declarator( + allow_abstract=False, typeid_paren_as_abstract=False + ) + assert decl is not None + return decl + + # BNF: id_declarator : declarator with ID name + def _parse_id_declarator(self) -> c_ast.Node: + return self._parse_declarator_kind(kind="id", allow_paren=True) + + # BNF: typeid_declarator : declarator with TYPEID name + def _parse_typeid_declarator(self) -> c_ast.Node: + return self._parse_declarator_kind(kind="typeid", allow_paren=True) + + # BNF: typeid_noparen_declarator : declarator without parenthesized name + def _parse_typeid_noparen_declarator(self) -> c_ast.Node: + return self._parse_declarator_kind(kind="typeid", allow_paren=False) + + # BNF: declarator_kind : pointer? direct_declarator(kind) + def _parse_declarator_kind(self, kind: str, allow_paren: bool) -> c_ast.Node: + ptr = None + if self._peek_type() == "TIMES": + ptr = self._parse_pointer() + direct = self._parse_direct_declarator(kind, allow_paren=allow_paren) + if ptr is not None: + return self._type_modify_decl(direct, ptr) + return direct + + # BNF: direct_declarator : ID | TYPEID | '(' declarator ')' + # | direct_declarator '[' ... ']' + # | direct_declarator '(' ... ')' + def _parse_direct_declarator( + self, kind: str, allow_paren: bool = True + ) -> c_ast.Node: + if allow_paren and self._accept("LPAREN"): + decl = self._parse_declarator_kind(kind, allow_paren=True) + self._expect("RPAREN") + else: + if kind == "id": + name_tok = self._expect("ID") + else: + name_tok = self._expect("TYPEID") + decl = c_ast.TypeDecl( + declname=name_tok.value, + type=None, + quals=None, + align=None, + coord=self._tok_coord(name_tok), + ) + + return self._parse_decl_suffixes(decl) + + def _parse_decl_suffixes(self, decl: c_ast.Node) -> c_ast.Node: + """Parse a chain of array/function suffixes and attach them to decl.""" + while True: + if self._peek_type() == "LBRACKET": + decl = self._type_modify_decl(decl, self._parse_array_decl(decl)) + continue + if self._peek_type() == "LPAREN": + func = self._parse_function_decl(decl) + decl = self._type_modify_decl(decl, func) + continue + break + return decl + + # BNF: array_decl : '[' array_specifiers? assignment_expression? ']' + def _parse_array_decl(self, base_decl: c_ast.Node) -> c_ast.Node: + return self._parse_array_decl_common(base_type=None, coord=base_decl.coord) + + def _parse_array_decl_common( + self, base_type: Optional[c_ast.Node], coord: Optional[Coord] = None + ) -> c_ast.Node: + """Parse an array declarator suffix and return an ArrayDecl node. + + base_type: + Base declarator node to attach (None for direct-declarator parsing, + TypeDecl for abstract declarators). + + coord: + Coordinate to use for the ArrayDecl. If None, uses the '[' token. + """ + lbrack_tok = self._expect("LBRACKET") + if coord is None: + coord = self._tok_coord(lbrack_tok) + + def make_array_decl(dim, dim_quals): + return c_ast.ArrayDecl( + type=base_type, dim=dim, dim_quals=dim_quals, coord=coord + ) + + if self._accept("STATIC"): + dim_quals = ["static"] + (self._parse_type_qualifier_list() or []) + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, dim_quals) + + if self._peek_type() in _TYPE_QUALIFIER: + dim_quals = self._parse_type_qualifier_list() or [] + if self._accept("STATIC"): + dim_quals = dim_quals + ["static"] + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, dim_quals) + times_tok = self._accept("TIMES") + if times_tok: + self._expect("RBRACKET") + dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok)) + return make_array_decl(dim, dim_quals) + dim = None + if self._starts_expression(): + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, dim_quals) + + times_tok = self._accept("TIMES") + if times_tok: + self._expect("RBRACKET") + dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok)) + return make_array_decl(dim, []) + + dim = None + if self._starts_expression(): + dim = self._parse_assignment_expression() + self._expect("RBRACKET") + return make_array_decl(dim, []) + + # BNF: function_decl : '(' parameter_type_list_opt | identifier_list_opt ')' + def _parse_function_decl(self, base_decl: c_ast.Node) -> c_ast.Node: + self._expect("LPAREN") + if self._accept("RPAREN"): + args = None + else: + args = ( + self._parse_parameter_type_list() + if self._starts_declaration() + else self._parse_identifier_list_opt() + ) + self._expect("RPAREN") + + func = c_ast.FuncDecl(args=args, type=None, coord=base_decl.coord) + + if self._peek_type() == "LBRACE": + if func.args is not None: + for param in func.args.params: + if isinstance(param, c_ast.EllipsisParam): + break + name = getattr(param, "name", None) + if name: + self._add_identifier(name, param.coord) + + return func + + # BNF: pointer : '*' type_qualifier_list? pointer? + def _parse_pointer(self) -> Optional[c_ast.Node]: + stars = [] + times_tok = self._accept("TIMES") + while times_tok: + quals = self._parse_type_qualifier_list() or [] + stars.append((quals, self._tok_coord(times_tok))) + times_tok = self._accept("TIMES") + + if not stars: + return None + + ptr = None + for quals, coord in stars: + ptr = c_ast.PtrDecl(quals=quals, type=ptr, coord=coord) + return ptr + + # BNF: parameter_type_list : parameter_list (',' ELLIPSIS)? + def _parse_parameter_type_list(self) -> c_ast.ParamList: + params = self._parse_parameter_list() + if self._peek_type() == "COMMA" and self._peek_type(2) == "ELLIPSIS": + self._advance() + ell_tok = self._advance() + params.params.append(c_ast.EllipsisParam(self._tok_coord(ell_tok))) + return params + + # BNF: parameter_list : parameter_declaration (',' parameter_declaration)* + def _parse_parameter_list(self) -> c_ast.ParamList: + first = self._parse_parameter_declaration() + params = c_ast.ParamList([first], first.coord) + while self._peek_type() == "COMMA" and self._peek_type(2) != "ELLIPSIS": + self._advance() + params.params.append(self._parse_parameter_declaration()) + return params + + # BNF: parameter_declaration : declaration_specifiers declarator? + # | declaration_specifiers abstract_declarator_opt + def _parse_parameter_declaration(self) -> c_ast.Node: + spec, _, spec_coord = self._parse_declaration_specifiers(allow_no_type=True) + + if not spec["type"]: + spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)] + + if self._starts_declarator(): + decl, is_named = self._parse_any_declarator( + allow_abstract=True, typeid_paren_as_abstract=True + ) + if is_named: + return self._build_declarations( + spec=spec, decls=[dict(decl=decl, init=None, bitsize=None)] + )[0] + return self._build_parameter_declaration(spec, decl, spec_coord) + + decl = self._parse_abstract_declarator_opt() + return self._build_parameter_declaration(spec, decl, spec_coord) + + def _build_parameter_declaration( + self, spec: "_DeclSpec", decl: Optional[c_ast.Node], spec_coord: Optional[Coord] + ) -> c_ast.Node: + if ( + len(spec["type"]) > 1 + and len(spec["type"][-1].names) == 1 + and self._is_type_in_scope(spec["type"][-1].names[0]) + ): + return self._build_declarations( + spec=spec, decls=[dict(decl=decl, init=None, bitsize=None)] + )[0] + + decl = c_ast.Typename( + name="", + quals=spec["qual"], + align=None, + type=decl or c_ast.TypeDecl(None, None, None, None), + coord=spec_coord, + ) + return self._fix_decl_name_type(decl, spec["type"]) + + # BNF: identifier_list_opt : identifier_list | empty + def _parse_identifier_list_opt(self) -> Optional[c_ast.Node]: + if self._peek_type() == "RPAREN": + return None + return self._parse_identifier_list() + + # BNF: identifier_list : identifier (',' identifier)* + def _parse_identifier_list(self) -> c_ast.Node: + first = self._parse_identifier() + params = c_ast.ParamList([first], first.coord) + while self._accept("COMMA"): + params.params.append(self._parse_identifier()) + return params + + # ------------------------------------------------------------------ + # Abstract declarators + # ------------------------------------------------------------------ + # BNF: type_name : specifier_qualifier_list abstract_declarator_opt + def _parse_type_name(self) -> c_ast.Typename: + spec = self._parse_specifier_qualifier_list() + decl = self._parse_abstract_declarator_opt() + + coord = None + if decl is not None: + coord = decl.coord + elif spec["type"]: + coord = spec["type"][0].coord + + typename = c_ast.Typename( + name="", + quals=spec["qual"][:], + align=None, + type=decl or c_ast.TypeDecl(None, None, None, None), + coord=coord, + ) + return cast(c_ast.Typename, self._fix_decl_name_type(typename, spec["type"])) + + # BNF: abstract_declarator_opt : pointer? direct_abstract_declarator? + def _parse_abstract_declarator_opt(self) -> Optional[c_ast.Node]: + if self._peek_type() == "TIMES": + ptr = self._parse_pointer() + if self._starts_direct_abstract_declarator(): + decl = self._parse_direct_abstract_declarator() + else: + decl = c_ast.TypeDecl(None, None, None, None) + assert ptr is not None + return self._type_modify_decl(decl, ptr) + + if self._starts_direct_abstract_declarator(): + return self._parse_direct_abstract_declarator() + + return None + + # BNF: direct_abstract_declarator : '(' parameter_type_list_opt ')' + # | '(' abstract_declarator ')' + # | '[' ... ']' + def _parse_direct_abstract_declarator(self) -> c_ast.Node: + lparen_tok = self._accept("LPAREN") + if lparen_tok: + if self._starts_declaration() or self._peek_type() == "RPAREN": + params = self._parse_parameter_type_list_opt() + self._expect("RPAREN") + decl = c_ast.FuncDecl( + args=params, + type=c_ast.TypeDecl(None, None, None, None), + coord=self._tok_coord(lparen_tok), + ) + else: + decl = self._parse_abstract_declarator_opt() + self._expect("RPAREN") + assert decl is not None + elif self._peek_type() == "LBRACKET": + decl = self._parse_abstract_array_base() + else: + self._parse_error("Invalid abstract declarator", self.clex.filename) + + return self._parse_decl_suffixes(decl) + + # BNF: parameter_type_list_opt : parameter_type_list | empty + def _parse_parameter_type_list_opt(self) -> Optional[c_ast.ParamList]: + if self._peek_type() == "RPAREN": + return None + return self._parse_parameter_type_list() + + # BNF: abstract_array_base : '[' array_specifiers? assignment_expression? ']' + def _parse_abstract_array_base(self) -> c_ast.Node: + return self._parse_array_decl_common( + base_type=c_ast.TypeDecl(None, None, None, None), coord=None + ) + + # ------------------------------------------------------------------ + # Statements + # ------------------------------------------------------------------ + # BNF: statement : labeled_statement | compound_statement + # | selection_statement | iteration_statement + # | jump_statement | expression_statement + # | static_assert | pppragma_directive + def _parse_statement(self) -> c_ast.Node | List[c_ast.Node]: + tok_type = self._peek_type() + match tok_type: + case "CASE" | "DEFAULT": + return self._parse_labeled_statement() + case "ID" if self._peek_type(2) == "COLON": + return self._parse_labeled_statement() + case "LBRACE": + return self._parse_compound_statement() + case "IF" | "SWITCH": + return self._parse_selection_statement() + case "WHILE" | "DO" | "FOR": + return self._parse_iteration_statement() + case "GOTO" | "BREAK" | "CONTINUE" | "RETURN": + return self._parse_jump_statement() + case "PPPRAGMA" | "_PRAGMA": + return self._parse_pppragma_directive() + case "_STATIC_ASSERT": + return self._parse_static_assert() + case _: + return self._parse_expression_statement() + + # BNF: pragmacomp_or_statement : pppragma_directive* statement + def _parse_pragmacomp_or_statement(self) -> c_ast.Node | List[c_ast.Node]: + if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: + pragmas = self._parse_pppragma_directive_list() + stmt = self._parse_statement() + return c_ast.Compound(block_items=pragmas + [stmt], coord=pragmas[0].coord) + return self._parse_statement() + + # BNF: block_item : declaration | statement + def _parse_block_item(self) -> c_ast.Node | List[c_ast.Node]: + if self._starts_declaration(): + return self._parse_declaration() + return self._parse_statement() + + # BNF: block_item_list : block_item+ + def _parse_block_item_list(self) -> List[c_ast.Node]: + items = [] + while self._peek_type() not in {"RBRACE", None}: + item = self._parse_block_item() + if isinstance(item, list): + if item == [None]: + continue + items.extend(item) + else: + items.append(item) + return items + + # BNF: compound_statement : '{' block_item_list? '}' + def _parse_compound_statement(self) -> c_ast.Node: + lbrace_tok = self._expect("LBRACE") + if self._accept("RBRACE"): + return c_ast.Compound(block_items=None, coord=self._tok_coord(lbrace_tok)) + block_items = self._parse_block_item_list() + self._expect("RBRACE") + return c_ast.Compound( + block_items=block_items, coord=self._tok_coord(lbrace_tok) + ) + + # BNF: labeled_statement : ID ':' statement + # | CASE constant_expression ':' statement + # | DEFAULT ':' statement + def _parse_labeled_statement(self) -> c_ast.Node: + tok_type = self._peek_type() + match tok_type: + case "ID": + name_tok = self._advance() + self._expect("COLON") + if self._starts_statement(): + stmt = self._parse_pragmacomp_or_statement() + else: + stmt = c_ast.EmptyStatement(self._tok_coord(name_tok)) + return c_ast.Label(name_tok.value, stmt, self._tok_coord(name_tok)) + case "CASE": + case_tok = self._advance() + expr = self._parse_constant_expression() + self._expect("COLON") + if self._starts_statement(): + stmt = self._parse_pragmacomp_or_statement() + else: + stmt = c_ast.EmptyStatement(self._tok_coord(case_tok)) + return c_ast.Case(expr, [stmt], self._tok_coord(case_tok)) + case "DEFAULT": + def_tok = self._advance() + self._expect("COLON") + if self._starts_statement(): + stmt = self._parse_pragmacomp_or_statement() + else: + stmt = c_ast.EmptyStatement(self._tok_coord(def_tok)) + return c_ast.Default([stmt], self._tok_coord(def_tok)) + case _: + self._parse_error("Invalid labeled statement", self.clex.filename) + + # BNF: selection_statement : IF '(' expression ')' statement (ELSE statement)? + # | SWITCH '(' expression ')' statement + def _parse_selection_statement(self) -> c_ast.Node: + tok = self._advance() + match tok.type: + case "IF": + self._expect("LPAREN") + cond = self._parse_expression() + self._expect("RPAREN") + then_stmt = self._parse_pragmacomp_or_statement() + if self._accept("ELSE"): + else_stmt = self._parse_pragmacomp_or_statement() + return c_ast.If(cond, then_stmt, else_stmt, self._tok_coord(tok)) + return c_ast.If(cond, then_stmt, None, self._tok_coord(tok)) + case "SWITCH": + self._expect("LPAREN") + expr = self._parse_expression() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return fix_switch_cases(c_ast.Switch(expr, stmt, self._tok_coord(tok))) + case _: + self._parse_error("Invalid selection statement", self._tok_coord(tok)) + + # BNF: iteration_statement : WHILE '(' expression ')' statement + # | DO statement WHILE '(' expression ')' ';' + # | FOR '(' (declaration | expression_opt) ';' + # expression_opt ';' expression_opt ')' statement + def _parse_iteration_statement(self) -> c_ast.Node: + tok = self._advance() + match tok.type: + case "WHILE": + self._expect("LPAREN") + cond = self._parse_expression() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return c_ast.While(cond, stmt, self._tok_coord(tok)) + case "DO": + stmt = self._parse_pragmacomp_or_statement() + self._expect("WHILE") + self._expect("LPAREN") + cond = self._parse_expression() + self._expect("RPAREN") + self._expect("SEMI") + return c_ast.DoWhile(cond, stmt, self._tok_coord(tok)) + case "FOR": + self._expect("LPAREN") + if self._starts_declaration(): + decls = self._parse_declaration() + init = c_ast.DeclList(decls, self._tok_coord(tok)) + cond = self._parse_expression_opt() + self._expect("SEMI") + next_expr = self._parse_expression_opt() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok)) + + init = self._parse_expression_opt() + self._expect("SEMI") + cond = self._parse_expression_opt() + self._expect("SEMI") + next_expr = self._parse_expression_opt() + self._expect("RPAREN") + stmt = self._parse_pragmacomp_or_statement() + return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok)) + case _: + self._parse_error("Invalid iteration statement", self._tok_coord(tok)) + + # BNF: jump_statement : GOTO ID ';' | BREAK ';' | CONTINUE ';' + # | RETURN expression? ';' + def _parse_jump_statement(self) -> c_ast.Node: + tok = self._advance() + match tok.type: + case "GOTO": + name_tok = self._expect("ID") + self._expect("SEMI") + return c_ast.Goto(name_tok.value, self._tok_coord(tok)) + case "BREAK": + self._expect("SEMI") + return c_ast.Break(self._tok_coord(tok)) + case "CONTINUE": + self._expect("SEMI") + return c_ast.Continue(self._tok_coord(tok)) + case "RETURN": + if self._accept("SEMI"): + return c_ast.Return(None, self._tok_coord(tok)) + expr = self._parse_expression() + self._expect("SEMI") + return c_ast.Return(expr, self._tok_coord(tok)) + case _: + self._parse_error("Invalid jump statement", self._tok_coord(tok)) + + # BNF: expression_statement : expression_opt ';' + def _parse_expression_statement(self) -> c_ast.Node: + expr = self._parse_expression_opt() + semi_tok = self._expect("SEMI") + if expr is None: + return c_ast.EmptyStatement(self._tok_coord(semi_tok)) + return expr + + # ------------------------------------------------------------------ + # Expressions + # ------------------------------------------------------------------ + # BNF: expression_opt : expression | empty + def _parse_expression_opt(self) -> Optional[c_ast.Node]: + if self._starts_expression(): + return self._parse_expression() + return None + + # BNF: expression : assignment_expression (',' assignment_expression)* + def _parse_expression(self) -> c_ast.Node: + expr = self._parse_assignment_expression() + if not self._accept("COMMA"): + return expr + exprs = [expr, self._parse_assignment_expression()] + while self._accept("COMMA"): + exprs.append(self._parse_assignment_expression()) + return c_ast.ExprList(exprs, expr.coord) + + # BNF: assignment_expression : conditional_expression + # | unary_expression assignment_op assignment_expression + def _parse_assignment_expression(self) -> c_ast.Node: + if self._peek_type() == "LPAREN" and self._peek_type(2) == "LBRACE": + self._advance() + comp = self._parse_compound_statement() + self._expect("RPAREN") + return comp + + expr = self._parse_conditional_expression() + if self._is_assignment_op(): + op = self._advance().value + rhs = self._parse_assignment_expression() + return c_ast.Assignment(op, expr, rhs, expr.coord) + return expr + + # BNF: conditional_expression : binary_expression + # | binary_expression '?' expression ':' conditional_expression + def _parse_conditional_expression(self) -> c_ast.Node: + expr = self._parse_binary_expression() + if self._accept("CONDOP"): + iftrue = self._parse_expression() + self._expect("COLON") + iffalse = self._parse_conditional_expression() + return c_ast.TernaryOp(expr, iftrue, iffalse, expr.coord) + return expr + + # BNF: binary_expression : cast_expression (binary_op cast_expression)* + def _parse_binary_expression( + self, min_prec: int = 0, lhs: Optional[c_ast.Node] = None + ) -> c_ast.Node: + if lhs is None: + lhs = self._parse_cast_expression() + + while True: + tok = self._peek() + if tok is None or tok.type not in _BINARY_PRECEDENCE: + break + prec = _BINARY_PRECEDENCE[tok.type] + if prec < min_prec: + break + + op = tok.value + self._advance() + rhs = self._parse_cast_expression() + + while True: + next_tok = self._peek() + if next_tok is None or next_tok.type not in _BINARY_PRECEDENCE: + break + next_prec = _BINARY_PRECEDENCE[next_tok.type] + if next_prec > prec: + rhs = self._parse_binary_expression(next_prec, rhs) + else: + break + + lhs = c_ast.BinaryOp(op, lhs, rhs, lhs.coord) + + return lhs + + # BNF: cast_expression : '(' type_name ')' cast_expression + # | unary_expression + def _parse_cast_expression(self) -> c_ast.Node: + result = self._try_parse_paren_type_name() + if result is not None: + typ, mark, lparen_tok = result + if self._peek_type() == "LBRACE": + # (type){...} is a compound literal, not a cast. Examples: + # (int){1} -> compound literal, handled in postfix + # (int) x -> cast, handled below + self._reset(mark) + else: + expr = self._parse_cast_expression() + return c_ast.Cast(typ, expr, self._tok_coord(lparen_tok)) + return self._parse_unary_expression() + + # BNF: unary_expression : postfix_expression + # | '++' unary_expression + # | '--' unary_expression + # | unary_op cast_expression + # | 'sizeof' unary_expression + # | 'sizeof' '(' type_name ')' + # | '_Alignof' '(' type_name ')' + def _parse_unary_expression(self) -> c_ast.Node: + tok_type = self._peek_type() + if tok_type in {"PLUSPLUS", "MINUSMINUS"}: + tok = self._advance() + expr = self._parse_unary_expression() + return c_ast.UnaryOp(tok.value, expr, expr.coord) + + if tok_type in {"AND", "TIMES", "PLUS", "MINUS", "NOT", "LNOT"}: + tok = self._advance() + expr = self._parse_cast_expression() + return c_ast.UnaryOp(tok.value, expr, expr.coord) + + if tok_type == "SIZEOF": + tok = self._advance() + result = self._try_parse_paren_type_name() + if result is not None: + typ, _, _ = result + return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok)) + expr = self._parse_unary_expression() + return c_ast.UnaryOp(tok.value, expr, self._tok_coord(tok)) + + if tok_type == "_ALIGNOF": + tok = self._advance() + self._expect("LPAREN") + typ = self._parse_type_name() + self._expect("RPAREN") + return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok)) + + return self._parse_postfix_expression() + + # BNF: postfix_expression : primary_expression postfix_suffix* + # | '(' type_name ')' '{' initializer_list ','? '}' + def _parse_postfix_expression(self) -> c_ast.Node: + result = self._try_parse_paren_type_name() + if result is not None: + typ, mark, _ = result + # Disambiguate between casts and compound literals: + # (int) x -> cast + # (int) {1} -> compound literal + if self._accept("LBRACE"): + init = self._parse_initializer_list() + self._accept("COMMA") + self._expect("RBRACE") + return c_ast.CompoundLiteral(typ, init) + else: + self._reset(mark) + + expr = self._parse_primary_expression() + while True: + if self._accept("LBRACKET"): + sub = self._parse_expression() + self._expect("RBRACKET") + expr = c_ast.ArrayRef(expr, sub, expr.coord) + continue + if self._accept("LPAREN"): + if self._peek_type() == "RPAREN": + self._advance() + args = None + else: + args = self._parse_argument_expression_list() + self._expect("RPAREN") + expr = c_ast.FuncCall(expr, args, expr.coord) + continue + if self._peek_type() in {"PERIOD", "ARROW"}: + op_tok = self._advance() + name_tok = self._advance() + if name_tok.type not in {"ID", "TYPEID"}: + self._parse_error( + "Invalid struct reference", self._tok_coord(name_tok) + ) + field = c_ast.ID(name_tok.value, self._tok_coord(name_tok)) + expr = c_ast.StructRef(expr, op_tok.value, field, expr.coord) + continue + if self._peek_type() in {"PLUSPLUS", "MINUSMINUS"}: + tok = self._advance() + expr = c_ast.UnaryOp("p" + tok.value, expr, expr.coord) + continue + break + return expr + + # BNF: primary_expression : ID | constant | string_literal + # | '(' expression ')' | offsetof + def _parse_primary_expression(self) -> c_ast.Node: + tok_type = self._peek_type() + if tok_type == "ID": + return self._parse_identifier() + if ( + tok_type in _INT_CONST + or tok_type in _FLOAT_CONST + or tok_type in _CHAR_CONST + ): + return self._parse_constant() + if tok_type in _STRING_LITERAL: + return self._parse_unified_string_literal() + if tok_type in _WSTR_LITERAL: + return self._parse_unified_wstring_literal() + if tok_type == "LPAREN": + self._advance() + expr = self._parse_expression() + self._expect("RPAREN") + return expr + if tok_type == "OFFSETOF": + off_tok = self._advance() + self._expect("LPAREN") + typ = self._parse_type_name() + self._expect("COMMA") + designator = self._parse_offsetof_member_designator() + self._expect("RPAREN") + coord = self._tok_coord(off_tok) + return c_ast.FuncCall( + c_ast.ID(off_tok.value, coord), + c_ast.ExprList([typ, designator], coord), + coord, + ) + + self._parse_error("Invalid expression", self.clex.filename) + + # BNF: offsetof_member_designator : identifier_or_typeid + # ('.' identifier_or_typeid | '[' expression ']')* + def _parse_offsetof_member_designator(self) -> c_ast.Node: + node = self._parse_identifier_or_typeid() + while True: + if self._accept("PERIOD"): + field = self._parse_identifier_or_typeid() + node = c_ast.StructRef(node, ".", field, node.coord) + continue + if self._accept("LBRACKET"): + expr = self._parse_expression() + self._expect("RBRACKET") + node = c_ast.ArrayRef(node, expr, node.coord) + continue + break + return node + + # BNF: argument_expression_list : assignment_expression (',' assignment_expression)* + def _parse_argument_expression_list(self) -> c_ast.Node: + expr = self._parse_assignment_expression() + exprs = [expr] + while self._accept("COMMA"): + exprs.append(self._parse_assignment_expression()) + return c_ast.ExprList(exprs, expr.coord) + + # BNF: constant_expression : conditional_expression + def _parse_constant_expression(self) -> c_ast.Node: + return self._parse_conditional_expression() + + # ------------------------------------------------------------------ + # Terminals + # ------------------------------------------------------------------ + # BNF: identifier : ID + def _parse_identifier(self) -> c_ast.Node: + tok = self._expect("ID") + return c_ast.ID(tok.value, self._tok_coord(tok)) + + # BNF: identifier_or_typeid : ID | TYPEID + def _parse_identifier_or_typeid(self) -> c_ast.Node: + tok = self._advance() + if tok.type not in {"ID", "TYPEID"}: + self._parse_error("Expected identifier", self._tok_coord(tok)) + return c_ast.ID(tok.value, self._tok_coord(tok)) + + # BNF: constant : INT_CONST | FLOAT_CONST | CHAR_CONST + def _parse_constant(self) -> c_ast.Node: + tok = self._advance() + if tok.type in _INT_CONST: + u_count = 0 + l_count = 0 + for ch in tok.value[-3:]: + if ch in ("l", "L"): + l_count += 1 + elif ch in ("u", "U"): + u_count += 1 + if u_count > 1: + raise ValueError("Constant cannot have more than one u/U suffix.") + if l_count > 2: + raise ValueError("Constant cannot have more than two l/L suffix.") + prefix = "unsigned " * u_count + "long " * l_count + return c_ast.Constant(prefix + "int", tok.value, self._tok_coord(tok)) + + if tok.type in _FLOAT_CONST: + if tok.value[-1] in ("f", "F"): + t = "float" + elif tok.value[-1] in ("l", "L"): + t = "long double" + else: + t = "double" + return c_ast.Constant(t, tok.value, self._tok_coord(tok)) + + if tok.type in _CHAR_CONST: + return c_ast.Constant("char", tok.value, self._tok_coord(tok)) + + self._parse_error("Invalid constant", self._tok_coord(tok)) + + # BNF: unified_string_literal : STRING_LITERAL+ + def _parse_unified_string_literal(self) -> c_ast.Node: + tok = self._expect("STRING_LITERAL") + node = c_ast.Constant("string", tok.value, self._tok_coord(tok)) + while self._peek_type() == "STRING_LITERAL": + tok2 = self._advance() + node.value = node.value[:-1] + tok2.value[1:] + return node + + # BNF: unified_wstring_literal : WSTRING_LITERAL+ + def _parse_unified_wstring_literal(self) -> c_ast.Node: + tok = self._advance() + if tok.type not in _WSTR_LITERAL: + self._parse_error("Invalid string literal", self._tok_coord(tok)) + node = c_ast.Constant("string", tok.value, self._tok_coord(tok)) + while self._peek_type() in _WSTR_LITERAL: + tok2 = self._advance() + node.value = node.value.rstrip()[:-1] + tok2.value[2:] + return node + + # ------------------------------------------------------------------ + # Initializers + # ------------------------------------------------------------------ + # BNF: initializer : assignment_expression + # | '{' initializer_list ','? '}' + # | '{' '}' + def _parse_initializer(self) -> c_ast.Node: + lbrace_tok = self._accept("LBRACE") + if lbrace_tok: + if self._accept("RBRACE"): + return c_ast.InitList([], self._tok_coord(lbrace_tok)) + init_list = self._parse_initializer_list() + self._accept("COMMA") + self._expect("RBRACE") + return init_list + + return self._parse_assignment_expression() + + # BNF: initializer_list : initializer_item (',' initializer_item)* ','? + def _parse_initializer_list(self) -> c_ast.Node: + items = [self._parse_initializer_item()] + while self._accept("COMMA"): + if self._peek_type() == "RBRACE": + break + items.append(self._parse_initializer_item()) + return c_ast.InitList(items, items[0].coord) + + # BNF: initializer_item : designation? initializer + def _parse_initializer_item(self) -> c_ast.Node: + designation = None + if self._peek_type() in {"LBRACKET", "PERIOD"}: + designation = self._parse_designation() + init = self._parse_initializer() + if designation is not None: + return c_ast.NamedInitializer(designation, init) + return init + + # BNF: designation : designator_list '=' + def _parse_designation(self) -> List[c_ast.Node]: + designators = self._parse_designator_list() + self._expect("EQUALS") + return designators + + # BNF: designator_list : designator+ + def _parse_designator_list(self) -> List[c_ast.Node]: + designators = [] + while self._peek_type() in {"LBRACKET", "PERIOD"}: + designators.append(self._parse_designator()) + return designators + + # BNF: designator : '[' constant_expression ']' + # | '.' identifier_or_typeid + def _parse_designator(self) -> c_ast.Node: + if self._accept("LBRACKET"): + expr = self._parse_constant_expression() + self._expect("RBRACKET") + return expr + if self._accept("PERIOD"): + return self._parse_identifier_or_typeid() + self._parse_error("Invalid designator", self.clex.filename) + + # ------------------------------------------------------------------ + # Preprocessor-like directives + # ------------------------------------------------------------------ + # BNF: pp_directive : '#' ... (unsupported) + def _parse_pp_directive(self) -> NoReturn: + tok = self._expect("PPHASH") + self._parse_error("Directives not supported yet", self._tok_coord(tok)) + + # BNF: pppragma_directive : PPPRAGMA PPPRAGMASTR? + # | _PRAGMA '(' string_literal ')' + def _parse_pppragma_directive(self) -> c_ast.Node: + if self._peek_type() == "PPPRAGMA": + tok = self._advance() + if self._peek_type() == "PPPRAGMASTR": + str_tok = self._advance() + return c_ast.Pragma(str_tok.value, self._tok_coord(str_tok)) + return c_ast.Pragma("", self._tok_coord(tok)) + + if self._peek_type() == "_PRAGMA": + tok = self._advance() + lparen = self._expect("LPAREN") + literal = self._parse_unified_string_literal() + self._expect("RPAREN") + return c_ast.Pragma(literal, self._tok_coord(lparen)) + + self._parse_error("Invalid pragma", self.clex.filename) + + # BNF: pppragma_directive_list : pppragma_directive+ + def _parse_pppragma_directive_list(self) -> List[c_ast.Node]: + pragmas = [] + while self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: + pragmas.append(self._parse_pppragma_directive()) + return pragmas + + # BNF: static_assert : _STATIC_ASSERT '(' constant_expression (',' string_literal)? ')' + def _parse_static_assert(self) -> List[c_ast.Node]: + tok = self._expect("_STATIC_ASSERT") + self._expect("LPAREN") + cond = self._parse_constant_expression() + msg = None + if self._accept("COMMA"): + msg = self._parse_unified_string_literal() + self._expect("RPAREN") + return [c_ast.StaticAssert(cond, msg, self._tok_coord(tok))] + + +_ASSIGNMENT_OPS = { + "EQUALS", + "XOREQUAL", + "TIMESEQUAL", + "DIVEQUAL", + "MODEQUAL", + "PLUSEQUAL", + "MINUSEQUAL", + "LSHIFTEQUAL", + "RSHIFTEQUAL", + "ANDEQUAL", + "OREQUAL", +} + +# Precedence of operators (lower number = weather binding) +# If this changes, c_generator.CGenerator.precedence_map needs to change as +# well +_BINARY_PRECEDENCE = { + "LOR": 0, + "LAND": 1, + "OR": 2, + "XOR": 3, + "AND": 4, + "EQ": 5, + "NE": 5, + "GT": 6, + "GE": 6, + "LT": 6, + "LE": 6, + "RSHIFT": 7, + "LSHIFT": 7, + "PLUS": 8, + "MINUS": 8, + "TIMES": 9, + "DIVIDE": 9, + "MOD": 9, +} + +_STORAGE_CLASS = {"AUTO", "REGISTER", "STATIC", "EXTERN", "TYPEDEF", "_THREAD_LOCAL"} + +_FUNCTION_SPEC = {"INLINE", "_NORETURN"} + +_TYPE_QUALIFIER = {"CONST", "RESTRICT", "VOLATILE", "_ATOMIC"} + +_TYPE_SPEC_SIMPLE = { + "VOID", + "_BOOL", + "CHAR", + "SHORT", + "INT", + "LONG", + "FLOAT", + "DOUBLE", + "_COMPLEX", + "SIGNED", + "UNSIGNED", + "__INT128", +} + +_DECL_START = ( + _STORAGE_CLASS + | _FUNCTION_SPEC + | _TYPE_QUALIFIER + | _TYPE_SPEC_SIMPLE + | {"TYPEID", "STRUCT", "UNION", "ENUM", "_ALIGNAS", "_ATOMIC"} +) + +_EXPR_START = { + "ID", + "LPAREN", + "PLUSPLUS", + "MINUSMINUS", + "PLUS", + "MINUS", + "TIMES", + "AND", + "NOT", + "LNOT", + "SIZEOF", + "_ALIGNOF", + "OFFSETOF", +} + +_INT_CONST = { + "INT_CONST_DEC", + "INT_CONST_OCT", + "INT_CONST_HEX", + "INT_CONST_BIN", + "INT_CONST_CHAR", +} + +_FLOAT_CONST = {"FLOAT_CONST", "HEX_FLOAT_CONST"} + +_CHAR_CONST = { + "CHAR_CONST", + "WCHAR_CONST", + "U8CHAR_CONST", + "U16CHAR_CONST", + "U32CHAR_CONST", +} + +_STRING_LITERAL = {"STRING_LITERAL"} + +_WSTR_LITERAL = { + "WSTRING_LITERAL", + "U8STRING_LITERAL", + "U16STRING_LITERAL", + "U32STRING_LITERAL", +} + +_STARTS_EXPRESSION = ( + _EXPR_START + | _INT_CONST + | _FLOAT_CONST + | _CHAR_CONST + | _STRING_LITERAL + | _WSTR_LITERAL +) + +_STARTS_STATEMENT = { + "LBRACE", + "IF", + "SWITCH", + "WHILE", + "DO", + "FOR", + "GOTO", + "BREAK", + "CONTINUE", + "RETURN", + "CASE", + "DEFAULT", + "PPPRAGMA", + "_PRAGMA", + "_STATIC_ASSERT", + "SEMI", +} + + +class _TokenStream: + """Wraps a lexer to provide convenient, buffered access to the underlying + token stream. The lexer is expected to be initialized with the input + string already. + """ + + def __init__(self, lexer: CLexer) -> None: + self._lexer = lexer + self._buffer: List[Optional[_Token]] = [] + self._index = 0 + + def peek(self, k: int = 1) -> Optional[_Token]: + """Peek at the k-th next token in the stream, without consuming it. + + Examples: + k=1 returns the immediate next token. + k=2 returns the token after that. + """ + if k <= 0: + return None + self._fill(k) + return self._buffer[self._index + k - 1] + + def next(self) -> Optional[_Token]: + """Consume a single token and return it.""" + self._fill(1) + tok = self._buffer[self._index] + self._index += 1 + return tok + + # The 'mark' and 'reset' methods are useful for speculative parsing with + # backtracking; when the parser needs to examine a sequence of tokens + # and potentially decide to try a different path on the same sequence, it + # can call 'mark' to obtain the current token position, and if the first + # path fails restore the position with `reset(pos)`. + def mark(self) -> int: + return self._index + + def reset(self, mark: int) -> None: + self._index = mark + + def _fill(self, n: int) -> None: + while len(self._buffer) < self._index + n: + tok = self._lexer.token() + self._buffer.append(tok) + if tok is None: + break + + +# Declaration specifiers are represented by a dictionary with entries: +# - qual: a list of type qualifiers +# - storage: a list of storage class specifiers +# - type: a list of type specifiers +# - function: a list of function specifiers +# - alignment: a list of alignment specifiers +class _DeclSpec(TypedDict): + qual: List[Any] + storage: List[Any] + type: List[Any] + function: List[Any] + alignment: List[Any] + + +_DeclSpecKind = Literal["qual", "storage", "type", "function", "alignment"] + + +class _DeclInfo(TypedDict): + # Declarator payloads used by declaration/initializer parsing: + # - decl: the declarator node (may be None for abstract/implicit cases) + # - init: optional initializer expression + # - bitsize: optional bit-field width expression (for struct declarators) + decl: Optional[c_ast.Node] + init: Optional[c_ast.Node] + bitsize: Optional[c_ast.Node] diff --git a/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/INSTALLER b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/METADATA b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..29068a781ba9da41573d1d09224c4016e21d4b93 --- /dev/null +++ b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/METADATA @@ -0,0 +1,173 @@ +Metadata-Version: 2.4 +Name: pydantic_core +Version: 2.46.4 +Classifier: Development Status :: 3 - Alpha +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: Implementation :: GraalPy +Classifier: Programming Language :: Rust +Classifier: Framework :: Pydantic +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS +Classifier: Typing :: Typed +Requires-Dist: typing-extensions>=4.14.1 +License-File: LICENSE +Summary: Core functionality for Pydantic validation and serialization +Home-Page: https://github.com/pydantic/pydantic +Author-email: Samuel Colvin , Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, David Montague , David Hewitt , Sydney Runkle , Victorien Plot +License-Expression: MIT +Requires-Python: >=3.9 +Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM +Project-URL: Funding, https://github.com/sponsors/samuelcolvin +Project-URL: Homepage, https://github.com/pydantic +Project-URL: Source, https://github.com/pydantic/pydantic/tree/main/pydantic-core + +# pydantic-core + +[![CI](https://github.com/pydantic/pydantic-core/workflows/ci/badge.svg?event=push)](https://github.com/pydantic/pydantic-core/actions?query=event%3Apush+branch%3Amain+workflow%3Aci) +[![Coverage](https://codecov.io/gh/pydantic/pydantic-core/branch/main/graph/badge.svg)](https://codecov.io/gh/pydantic/pydantic-core) +[![pypi](https://img.shields.io/pypi/v/pydantic-core.svg)](https://pypi.python.org/pypi/pydantic-core) +[![versions](https://img.shields.io/pypi/pyversions/pydantic-core.svg)](https://github.com/pydantic/pydantic-core) +[![license](https://img.shields.io/github/license/pydantic/pydantic-core.svg)](https://github.com/pydantic/pydantic-core/blob/main/LICENSE) + +This package provides the core functionality for [pydantic](https://docs.pydantic.dev) validation and serialization. + +Pydantic-core is currently around 17x faster than pydantic V1. +See [`tests/benchmarks/`](./tests/benchmarks/) for details. + +## Example of direct usage + +*NOTE: You should not need to use pydantic-core directly; instead, use pydantic, which in turn uses pydantic-core.* + +```py +from pydantic_core import SchemaValidator, ValidationError + + +v = SchemaValidator( + { + 'type': 'typed-dict', + 'fields': { + 'name': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'str', + }, + }, + 'age': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'int', + 'ge': 18, + }, + }, + 'is_developer': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'default', + 'schema': {'type': 'bool'}, + 'default': True, + }, + }, + }, + } +) + +r1 = v.validate_python({'name': 'Samuel', 'age': 35}) +assert r1 == {'name': 'Samuel', 'age': 35, 'is_developer': True} + +# pydantic-core can also validate JSON directly +r2 = v.validate_json('{"name": "Samuel", "age": 35}') +assert r1 == r2 + +try: + v.validate_python({'name': 'Samuel', 'age': 11}) +except ValidationError as e: + print(e) + """ + 1 validation error for model + age + Input should be greater than or equal to 18 + [type=greater_than_equal, context={ge: 18}, input_value=11, input_type=int] + """ +``` + +## Getting Started + +### Prerequisites + +You'll need: + +1. **[Rust](https://rustup.rs/)** - Rust stable (or nightly for coverage) +2. **[uv](https://docs.astral.sh/uv/getting-started/installation/)** - Fast Python package manager (will install Python 3.9+ automatically) +3. **[git](https://git-scm.com/)** - For version control +4. **[make](https://www.gnu.org/software/make/)** - For running development commands (or use `nmake` on Windows) + +### Quick Start + +```bash +# Clone the repository (or from your fork) +git clone git@github.com:pydantic/pydantic-core.git +cd pydantic-core + +# Install all dependencies using uv, setup pre-commit hooks, and build the development version +make install +``` + +Verify your installation by running: + +```bash +make +``` + +This runs a full development cycle: formatting, building, linting, and testing + +### Development Commands + +Run `make help` to see all available commands, or use these common ones: + +```bash +make build-dev # to build the package during development +make build-prod # to perform an optimised build for benchmarking +make test # to run the tests +make testcov # to run the tests and generate a coverage report +make lint # to run the linter +make format # to format python and rust code +make all # to run to run build-dev + format + lint + test +``` + +### Useful Resources + +* [`python/pydantic_core/_pydantic_core.pyi`](./python/pydantic_core/_pydantic_core.pyi) - Python API types +* [`python/pydantic_core/core_schema.py`](./python/pydantic_core/core_schema.py) - Core schema definitions +* [`tests/`](./tests) - Comprehensive usage examples + +## Profiling + +It's possible to profile the code using the [`flamegraph` utility from `flamegraph-rs`](https://github.com/flamegraph-rs/flamegraph). (Tested on Linux.) You can install this with `cargo install flamegraph`. + +Run `make build-profiling` to install a release build with debugging symbols included (needed for profiling). + +Once that is built, you can profile pytest benchmarks with (e.g.): + +```bash +flamegraph -- pytest tests/benchmarks/test_micro_benchmarks.py -k test_list_of_ints_core_py --benchmark-enable +``` + +The `flamegraph` command will produce an interactive SVG at `flamegraph.svg`. + +## Releasing + +TBC (needs to be integrated into `pydantic` repository release process). + diff --git a/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/WHEEL b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ed35e5a15c1a9fc28265b0fffe9fc5d50aab9c42 --- /dev/null +++ b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: maturin (1.13.1) +Root-Is-Purelib: false +Tag: cp311-cp311-manylinux_2_17_x86_64 +Tag: cp311-cp311-manylinux2014_x86_64 diff --git a/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/licenses/LICENSE b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0716871caabdbbb3e77a0371d49936cef1923ea1 --- /dev/null +++ b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Samuel Colvin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/sboms/pydantic-core.cyclonedx.json b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/sboms/pydantic-core.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..78274e5eeea28031a2199d3d805c56fd4cebc0fc --- /dev/null +++ b/lib/python3.11/site-packages/pydantic_core-2.46.4.dist-info/sboms/pydantic-core.cyclonedx.json @@ -0,0 +1,3961 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:d4a6d8ed-560b-42df-8150-4f2b49f7c4bd", + "metadata": { + "timestamp": "2026-05-06T08:31:02.714477427Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.9" + } + ], + "component": { + "type": "library", + "bom-ref": "path+file:///home/runner/work/pydantic/pydantic/pydantic-core#2.46.4", + "name": "pydantic-core", + "version": "2.46.4", + "scope": "required", + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/pydantic-core@2.46.4?download_url=file://.", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pydantic/pydantic" + }, + { + "type": "vcs", + "url": "https://github.com/pydantic/pydantic.git" + } + ], + "components": [ + { + "type": "library", + "bom-ref": "path+file:///home/runner/work/pydantic/pydantic/pydantic-core#2.46.4 bin-target-0", + "name": "_pydantic_core", + "version": "2.46.4", + "purl": "pkg:cargo/pydantic-core@2.46.4?download_url=file://.#src/lib.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:all_targets", + "value": "true" + } + ] + }, + "components": [ + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "author": "Tom Kaitchuck ", + "name": "ahash", + "version": "0.8.12", + "description": "A non-cryptographic hash function using AES-NI for high performance", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ahash@0.8.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ahash" + }, + { + "type": "vcs", + "url": "https://github.com/tkaitchuck/ahash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.3", + "author": "Andrew Gallant ", + "name": "aho-corasick", + "version": "1.1.3", + "description": "Fast multiple substring searching.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/aho-corasick@1.1.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/BurntSushi/aho-corasick" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/aho-corasick" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21", + "author": "Zakarum ", + "name": "allocator-api2", + "version": "0.2.21", + "description": "Mirror of Rust's allocator API", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/allocator-api2@0.2.21", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/allocator-api2" + }, + { + "type": "website", + "url": "https://github.com/zakarumych/allocator-api2" + }, + { + "type": "vcs", + "url": "https://github.com/zakarumych/allocator-api2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.3.0", + "author": "Josh Stone ", + "name": "autocfg", + "version": "1.3.0", + "description": "Automatic cfg for Rust compiler features", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/autocfg@1.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/autocfg/" + }, + { + "type": "vcs", + "url": "https://github.com/cuviper/autocfg" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "author": "Marshall Pierce ", + "name": "base64", + "version": "0.22.1", + "description": "encodes and decodes base64 as bytes or utf8", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/base64@0.22.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base64" + }, + { + "type": "vcs", + "url": "https://github.com/marshallpierce/rust-base64" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.9.1", + "author": "The Rust Project Developers", + "name": "bitflags", + "version": "2.9.1", + "description": "A macro to generate structures which behave like bitflags. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bitflags@2.9.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bitflags" + }, + { + "type": "website", + "url": "https://github.com/bitflags/bitflags" + }, + { + "type": "vcs", + "url": "https://github.com/bitflags/bitflags" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitvec@1.0.1", + "name": "bitvec", + "version": "1.0.1", + "description": "Addresses memory by bits, for packed collections and bitfields", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/bitvec@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bitvec/latest/bitvec" + }, + { + "type": "website", + "url": "https://bitvecto-rs.github.io/bitvec" + }, + { + "type": "vcs", + "url": "https://github.com/bitvecto-rs/bitvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bumpalo@3.19.0", + "author": "Nick Fitzgerald ", + "name": "bumpalo", + "version": "3.19.0", + "description": "A fast bump allocation arena for Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bumpalo@3.19.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bumpalo" + }, + { + "type": "vcs", + "url": "https://github.com/fitzgen/bumpalo" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.0.101", + "author": "Alex Crichton ", + "name": "cc", + "version": "1.0.101", + "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ac367972e516d45567c7eafc73d24e1c193dcf200a8d94e9db7b3d38b349572d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cc@1.0.101", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cc" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cc-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "author": "Alex Crichton ", + "name": "cfg-if", + "version": "1.0.0", + "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cfg-if@1.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cfg-if" + }, + { + "type": "website", + "url": "https://github.com/alexcrichton/cfg-if" + }, + { + "type": "vcs", + "url": "https://github.com/alexcrichton/cfg-if" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "author": "Jane Lusby ", + "name": "displaydoc", + "version": "0.2.5", + "description": "A derive macro for implementing the display Trait via a doc comment and string interpolation ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/displaydoc@0.2.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/displaydoc" + }, + { + "type": "website", + "url": "https://github.com/yaahc/displaydoc" + }, + { + "type": "vcs", + "url": "https://github.com/yaahc/displaydoc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#enum_dispatch@0.3.13", + "author": "Anton Lazarev ", + "name": "enum_dispatch", + "version": "0.3.13", + "description": "Near drop-in replacement for dynamic-dispatched method calls with up to 10x the speed", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/enum_dispatch@0.3.13", + "externalReferences": [ + { + "type": "vcs", + "url": "https://gitlab.com/antonok/enum_dispatch" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "name": "equivalent", + "version": "1.0.2", + "description": "Traits for key comparison in maps.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/equivalent@1.0.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/indexmap-rs/equivalent" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0", + "author": "Orson Peters ", + "name": "foldhash", + "version": "0.2.0", + "description": "A fast, non-cryptographic, minimally DoS-resistant hashing algorithm.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + } + ], + "licenses": [ + { + "expression": "Zlib" + } + ], + "purl": "pkg:cargo/foldhash@0.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/orlp/foldhash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "author": "The rust-url developers", + "name": "form_urlencoded", + "version": "1.2.2", + "description": "Parser and serializer for the application/x-www-form-urlencoded syntax, as used by HTML forms.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/form_urlencoded@1.2.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/servo/rust-url" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#funty@2.0.0", + "author": "myrrlyn ", + "name": "funty", + "version": "2.0.0", + "description": "Trait generalization over the primitive types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/funty@2.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/funty" + }, + { + "type": "vcs", + "url": "https://github.com/myrrlyn/funty" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.3", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.3.3", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.3.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1", + "author": "Amanieu d'Antras ", + "name": "hashbrown", + "version": "0.16.1", + "description": "A Rust port of Google's SwissTable hash map", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashbrown@0.16.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/hashbrown" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "name": "heck", + "version": "0.5.0", + "description": "heck is a case conversion library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/heck@0.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/withoutboats/heck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "author": "KokaKiwi ", + "name": "hex", + "version": "0.4.3", + "description": "Encoding and decoding data into/from hexadecimal representation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hex@0.4.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hex/" + }, + { + "type": "vcs", + "url": "https://github.com/KokaKiwi/rust-hex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_collections@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_collections", + "version": "1.5.0", + "description": "Collection of API for use in ICU libraries.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_collections@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locid@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_locid", + "version": "1.5.0", + "description": "API for managing Unicode Language and Locale Identifiers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_locid@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locid_transform@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_locid_transform", + "version": "1.5.0", + "description": "API for Unicode Language and Locale Identifiers canonicalization", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_locid_transform@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locid_transform_data@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_locid_transform_data", + "version": "1.5.0", + "description": "Data for the icu_locid_transform crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_locid_transform_data@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_normalizer", + "version": "1.5.0", + "description": "API for normalizing text into Unicode Normalization Forms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_normalizer@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer_data@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_normalizer_data", + "version": "1.5.0", + "description": "Data for the icu_normalizer crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_normalizer_data@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties@1.5.1", + "author": "The ICU4X Project Developers", + "name": "icu_properties", + "version": "1.5.1", + "description": "Definitions for Unicode properties", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_properties@1.5.1", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties_data@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_properties_data", + "version": "1.5.0", + "description": "Data for the icu_properties crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_properties_data@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_provider@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_provider", + "version": "1.5.0", + "description": "Trait and struct definitions for the ICU data provider", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_provider@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_provider_macros@1.5.0", + "author": "The ICU4X Project Developers", + "name": "icu_provider_macros", + "version": "1.5.0", + "description": "Proc macros for ICU data providers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_provider_macros@1.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "author": "The rust-url developers", + "name": "idna", + "version": "1.1.0", + "description": "IDNA (Internationalizing Domain Names in Applications) and Punycode.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/idna@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/servo/rust-url/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#idna_adapter@1.2.0", + "author": "The rust-url developers", + "name": "idna_adapter", + "version": "1.2.0", + "description": "Back end adapter for idna", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/idna_adapter@1.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/idna_adapter/latest/idna_adapter/" + }, + { + "type": "website", + "url": "https://docs.rs/crate/idna_adapter/latest" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/idna_adapter" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.11", + "author": "David Tolnay ", + "name": "itoa", + "version": "1.0.11", + "description": "Fast integer primitive to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itoa@1.0.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itoa" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/itoa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#jiter@0.14.0", + "author": "Samuel Colvin ", + "name": "jiter", + "version": "0.14.0", + "description": "Fast Iterable JSON parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b6f3b5d3f84b36f4ad09fd1da896d23d9852a1aa86556578dd0289f43dce311d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/jiter@0.14.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pydantic/jiter/" + }, + { + "type": "vcs", + "url": "https://github.com/pydantic/jiter/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#js-sys@0.3.77", + "author": "The wasm-bindgen Developers", + "name": "js-sys", + "version": "0.3.77", + "description": "Bindings for all JS global objects and functions in all JS environments like Node.js and browsers, built on `#[wasm_bindgen]` using the `wasm-bindgen` crate. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/js-sys@0.3.77", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/js-sys" + }, + { + "type": "website", + "url": "https://rustwasm.github.io/wasm-bindgen/" + }, + { + "type": "vcs", + "url": "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/js-sys" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.5", + "author": "Alex Huszagh ", + "name": "lexical-parse-float", + "version": "1.0.5", + "description": "Efficient parsing of floats from strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "de6f9cb01fb0b08060209a057c048fcbab8717b4c1ecd2eac66ebfe39a65b0f2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-parse-float@1.0.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.5", + "author": "Alex Huszagh ", + "name": "lexical-parse-integer", + "version": "1.0.5", + "description": "Efficient parsing of integers from strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "72207aae22fc0a121ba7b6d479e42cbfea549af1479c3f3a4f12c70dd66df12e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-parse-integer@1.0.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.6", + "author": "Alex Huszagh ", + "name": "lexical-util", + "version": "1.0.6", + "description": "Shared utilities for lexical creates.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5a82e24bf537fd24c177ffbbdc6ebcc8d54732c35b50a3f28cc3f4e4c949a0b3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-util@1.0.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185", + "author": "The Rust Project Developers", + "name": "libc", + "version": "0.2.185", + "description": "Raw FFI bindings to platform libraries like libc.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/libc@0.2.185", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/libc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#litemap@0.7.3", + "author": "The ICU4X Project Developers", + "name": "litemap", + "version": "0.7.3", + "description": "A key-value Map implementation based on a flat, sorted Vec.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/litemap@0.7.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/litemap" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#log@0.4.27", + "author": "The Rust Project Developers", + "name": "log", + "version": "0.4.27", + "description": "A lightweight logging facade for Rust ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/log@0.4.27", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/log" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/log" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lru@0.16.3", + "author": "Jerome Froelich ", + "name": "lru", + "version": "0.16.3", + "description": "A LRU cache implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a1dc47f592c06f33f8e3aea9591776ec7c9f9e4124778ff8a3c3b87159f7e593" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/lru@0.16.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/lru/" + }, + { + "type": "website", + "url": "https://github.com/jeromefroe/lru-rs" + }, + { + "type": "vcs", + "url": "https://github.com/jeromefroe/lru-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.7.4", + "author": "Andrew Gallant , bluss", + "name": "memchr", + "version": "2.7.4", + "description": "Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for 1, 2 or 3 byte search and single substring search. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/memchr@2.7.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/memchr/" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/memchr" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/memchr" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "author": "The Rust Project Developers", + "name": "num-bigint", + "version": "0.4.6", + "description": "Big integer implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-bigint@0.4.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-bigint" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-bigint" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-bigint" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "author": "The Rust Project Developers", + "name": "num-integer", + "version": "0.1.46", + "description": "Integer traits and functions", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-integer@0.1.46", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-integer" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-integer" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-integer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "author": "The Rust Project Developers", + "name": "num-traits", + "version": "0.2.19", + "description": "Numeric traits for generic mathematics", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-traits@0.2.19", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-traits" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-traits" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "author": "Aleksey Kladov ", + "name": "once_cell", + "version": "1.21.3", + "description": "Single assignment cells and lazy values.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell@1.21.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/once_cell" + }, + { + "type": "vcs", + "url": "https://github.com/matklad/once_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "author": "The rust-url developers", + "name": "percent-encoding", + "version": "2.3.2", + "description": "Percent encoding and decoding", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/percent-encoding@2.3.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/servo/rust-url/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.6.0", + "name": "portable-atomic", + "version": "1.6.0", + "description": "Portable atomic types including support for 128-bit atomics, atomic float, etc. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/portable-atomic@1.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/portable-atomic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "author": "David Tolnay , Alex Crichton ", + "name": "proc-macro2", + "version": "1.0.86", + "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2@1.0.86", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/proc-macro2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-build-config", + "version": "0.28.3", + "description": "Build configuration for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-build-config@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-ffi", + "version": "0.28.3", + "description": "Python-API bindings for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-ffi@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "other", + "url": "python" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros-backend", + "version": "0.28.3", + "description": "Code generation for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros-backend@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros", + "version": "0.28.3", + "description": "Proc macros for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3", + "version": "0.28.3", + "description": "Bindings to Python interpreter", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3@0.28.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pyo3/" + }, + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#python3-dll-a@0.2.14", + "author": "Sergey Kvachonok , messense , Adam Reichold ", + "name": "python3-dll-a", + "version": "0.2.14", + "description": "Standalone python3(y)(t).dll import library generator", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d381ef313ae70b4da5f95f8a4de773c6aa5cd28f73adec4b4a31df70b66780d8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/python3-dll-a@0.2.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/PyO3/python3-dll-a" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "author": "David Tolnay ", + "name": "quote", + "version": "1.0.44", + "description": "Quasi-quoting macro quote!(...)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quote@1.0.44", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quote/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/quote" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#r-efi@5.2.0", + "name": "r-efi", + "version": "5.2.0", + "description": "UEFI Reference Specification Protocol Constants and Definitions", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0 OR LGPL-2.1-or-later" + } + ], + "purl": "pkg:cargo/r-efi@5.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/r-efi/r-efi/wiki" + }, + { + "type": "vcs", + "url": "https://github.com/r-efi/r-efi" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#radium@0.7.0", + "author": "Nika Layzell , myrrlyn ", + "name": "radium", + "version": "0.7.0", + "description": "Portable interfaces for maybe-atomic types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/radium@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/radium" + }, + { + "type": "website", + "url": "https://github.com/bitvecto-rs/radium" + }, + { + "type": "vcs", + "url": "https://github.com/bitvecto-rs/radium" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.13", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-automata", + "version": "0.4.13", + "description": "Automata construction and matching using regular expressions.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-automata@0.4.13", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-automata" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex/tree/master/regex-automata" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.5", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-syntax", + "version": "0.8.5", + "description": "A regular expression parser.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-syntax@0.8.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-syntax" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex/tree/master/regex-syntax" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex", + "version": "1.12.3", + "description": "An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear time matching on all inputs. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex@1.12.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.17", + "author": "David Tolnay ", + "name": "rustversion", + "version": "1.0.17", + "description": "Conditional compilation according to rustc compiler version", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rustversion@1.0.17", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rustversion" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/rustversion" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde", + "version": "1.0.228", + "description": "A generic serialization/deserialization framework", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_core", + "version": "1.0.228", + "description": "Serde traits only, with no support for derive -- use the `serde` crate instead", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_core@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_core" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_derive", + "version": "1.0.228", + "description": "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_derive@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://serde.rs/derive.html" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_json", + "version": "1.0.149", + "description": "A JSON serialization file format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_json@1.0.149", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_json" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/json" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "author": "The Servo Project Developers", + "name": "smallvec", + "version": "1.15.1", + "description": "'Small vector' optimization: store up to a small number of items on the stack", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/smallvec@1.15.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/smallvec/" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-smallvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#speedate@0.17.0", + "author": "Samuel Colvin ", + "name": "speedate", + "version": "0.17.0", + "description": "Fast and simple datetime, date, time and duration parsing", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "aba069c070b5e213f2a094deb7e5ed50ecb092be36102a4f4042e8d2056d060e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/speedate@0.17.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pydantic/speedate/" + }, + { + "type": "vcs", + "url": "https://github.com/pydantic/speedate/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.0", + "author": "Robert Grosse ", + "name": "stable_deref_trait", + "version": "1.2.0", + "description": "An unsafe marker trait for types like Box and Rc that dereference to a stable address even when moved, and hence can be used with libraries such as owning_ref and rental. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/stable_deref_trait@1.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/stable_deref_trait/1.2.0/stable_deref_trait" + }, + { + "type": "vcs", + "url": "https://github.com/storyyeller/stable_deref_trait" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0", + "author": "Nikolai Vazquez", + "name": "static_assertions", + "version": "1.1.0", + "description": "Compile-time assertions to ensure that invariants are met.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/static_assertions@1.1.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/static_assertions/" + }, + { + "type": "website", + "url": "https://github.com/nvzqz/static-assertions-rs" + }, + { + "type": "vcs", + "url": "https://github.com/nvzqz/static-assertions-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "author": "Peter Glotfelty ", + "name": "strum", + "version": "0.27.2", + "description": "Helpful macros for working with enums and strings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strum@0.27.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strum" + }, + { + "type": "website", + "url": "https://github.com/Peternator7/strum" + }, + { + "type": "vcs", + "url": "https://github.com/Peternator7/strum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "author": "Peter Glotfelty ", + "name": "strum_macros", + "version": "0.27.2", + "description": "Helpful macros for working with enums and strings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strum_macros@0.27.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strum" + }, + { + "type": "website", + "url": "https://github.com/Peternator7/strum" + }, + { + "type": "vcs", + "url": "https://github.com/Peternator7/strum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82", + "author": "David Tolnay ", + "name": "syn", + "version": "2.0.82", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "83540f837a8afc019423a8edb95b52a8effe46957ee402287f4292fae35be021" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@2.0.82", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.1", + "author": "Nika Layzell ", + "name": "synstructure", + "version": "0.13.1", + "description": "Helper methods and macros for custom derives", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/synstructure@0.13.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/synstructure" + }, + { + "type": "vcs", + "url": "https://github.com/mystor/synstructure" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1", + "author": "Elliott Linder , myrrlyn ", + "name": "tap", + "version": "1.0.1", + "description": "Generic extensions for tapping values in Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tap@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tap" + }, + { + "type": "website", + "url": "https://github.com/myrrlyn/tap" + }, + { + "type": "vcs", + "url": "https://github.com/myrrlyn/tap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.4", + "author": "Dan Gohman ", + "name": "target-lexicon", + "version": "0.13.4", + "description": "LLVM target triple types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b1dd07eb858a2067e2f3c7155d54e929265c264e6f37efe3ee7a8d1b5a1dd0ba" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception" + } + ], + "purl": "pkg:cargo/target-lexicon@0.13.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/target-lexicon/" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/target-lexicon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.7.6", + "author": "The ICU4X Project Developers", + "name": "tinystr", + "version": "0.7.6", + "description": "A small ASCII-only bounded length string representation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/tinystr@0.7.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12", + "author": "David Tolnay ", + "name": "unicode-ident", + "version": "1.0.12", + "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + } + ], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0) AND Unicode-DFS-2016" + } + ], + "purl": "pkg:cargo/unicode-ident@1.0.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-ident" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unicode-ident" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "author": "The rust-url developers", + "name": "url", + "version": "2.5.8", + "description": "URL library for Rust, based on the WHATWG URL Standard", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/url@2.5.8", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/url" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-url" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utf16_iter@1.0.5", + "author": "Henri Sivonen ", + "name": "utf16_iter", + "version": "1.0.5", + "description": "Iterator by char over potentially-invalid UTF-16 in &[u16]", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/utf16_iter@1.0.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/utf16_iter/" + }, + { + "type": "website", + "url": "https://docs.rs/utf16_iter/" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/utf16_iter" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4", + "author": "Henri Sivonen ", + "name": "utf8_iter", + "version": "1.0.4", + "description": "Iterator by char over potentially-invalid UTF-8 in &[u8]", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/utf8_iter@1.0.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/utf8_iter/" + }, + { + "type": "website", + "url": "https://docs.rs/utf8_iter/" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/utf8_iter" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#uuid@1.23.0", + "author": "Ashley Mannix, Dylan DPC, Hunar Roop Kahlon", + "name": "uuid", + "version": "1.23.0", + "description": "A library to generate and parse UUIDs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/uuid@1.23.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/uuid" + }, + { + "type": "website", + "url": "https://github.com/uuid-rs/uuid" + }, + { + "type": "vcs", + "url": "https://github.com/uuid-rs/uuid" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "author": "Sergio Benitez ", + "name": "version_check", + "version": "0.9.5", + "description": "Tiny crate to check the version of the installed/running rustc.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/version_check@0.9.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/version_check/" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/version_check" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wasi@0.14.2+wasi-0.2.4", + "author": "The Cranelift Project Developers", + "name": "wasi", + "version": "0.14.2+wasi-0.2.4", + "description": "WASI API bindings for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/wasi@0.14.2+wasi-0.2.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wasi" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/wasi-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-backend@0.2.100", + "author": "The wasm-bindgen Developers", + "name": "wasm-bindgen-backend", + "version": "0.2.100", + "description": "Backend code generation of the wasm-bindgen tool ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/wasm-bindgen-backend@0.2.100", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wasm-bindgen-backend" + }, + { + "type": "website", + "url": "https://rustwasm.github.io/wasm-bindgen/" + }, + { + "type": "vcs", + "url": "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/backend" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-macro-support@0.2.100", + "author": "The wasm-bindgen Developers", + "name": "wasm-bindgen-macro-support", + "version": "0.2.100", + "description": "The part of the implementation of the `#[wasm_bindgen]` attribute that is not in the shared backend crate ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/wasm-bindgen-macro-support@0.2.100", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wasm-bindgen" + }, + { + "type": "website", + "url": "https://rustwasm.github.io/wasm-bindgen/" + }, + { + "type": "vcs", + "url": "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/macro-support" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-macro@0.2.100", + "author": "The wasm-bindgen Developers", + "name": "wasm-bindgen-macro", + "version": "0.2.100", + "description": "Definition of the `#[wasm_bindgen]` attribute, an internal dependency ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/wasm-bindgen-macro@0.2.100", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wasm-bindgen" + }, + { + "type": "website", + "url": "https://rustwasm.github.io/wasm-bindgen/" + }, + { + "type": "vcs", + "url": "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/macro" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-shared@0.2.100", + "author": "The wasm-bindgen Developers", + "name": "wasm-bindgen-shared", + "version": "0.2.100", + "description": "Shared support between wasm-bindgen and wasm-bindgen cli, an internal dependency. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/wasm-bindgen-shared@0.2.100", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wasm-bindgen-shared" + }, + { + "type": "website", + "url": "https://rustwasm.github.io/wasm-bindgen/" + }, + { + "type": "other", + "url": "wasm_bindgen" + }, + { + "type": "vcs", + "url": "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/shared" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen@0.2.100", + "author": "The wasm-bindgen Developers", + "name": "wasm-bindgen", + "version": "0.2.100", + "description": "Easy support for interacting between JS and Rust. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/wasm-bindgen@0.2.100", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wasm-bindgen" + }, + { + "type": "website", + "url": "https://rustwasm.github.io/" + }, + { + "type": "vcs", + "url": "https://github.com/rustwasm/wasm-bindgen" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wit-bindgen-rt@0.39.0", + "name": "wit-bindgen-rt", + "version": "0.39.0", + "description": "Runtime support for the `wit-bindgen` crate ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/wit-bindgen-rt@0.39.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/bytecodealliance/wit-bindgen" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/wit-bindgen" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#write16@1.0.0", + "name": "write16", + "version": "1.0.0", + "description": "A UTF-16 analog of the Write trait", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/write16@1.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/write16/" + }, + { + "type": "website", + "url": "https://docs.rs/write16/" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/write16" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#writeable@0.5.5", + "author": "The ICU4X Project Developers", + "name": "writeable", + "version": "0.5.5", + "description": "A more efficient alternative to fmt::Display", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/writeable@0.5.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wyz@0.5.1", + "author": "myrrlyn ", + "name": "wyz", + "version": "0.5.1", + "description": "myrrlyn’s utility collection", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/wyz@0.5.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wyz" + }, + { + "type": "website", + "url": "https://myrrlyn.net/crates/wyz" + }, + { + "type": "vcs", + "url": "https://github.com/myrrlyn/wyz" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#yoke-derive@0.7.4", + "author": "Manish Goregaokar ", + "name": "yoke-derive", + "version": "0.7.4", + "description": "Custom derive for the yoke crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/yoke-derive@0.7.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#yoke@0.7.4", + "author": "Manish Goregaokar ", + "name": "yoke", + "version": "0.7.4", + "description": "Abstraction allowing borrowed data to be carried along with the backing data it borrows from", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/yoke@0.7.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy-derive@0.8.25", + "author": "Joshua Liebow-Feeser , Jack Wrenn ", + "name": "zerocopy-derive", + "version": "0.8.25", + "description": "Custom derive for traits from the zerocopy crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zerocopy-derive@0.8.25", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/google/zerocopy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.25", + "author": "Joshua Liebow-Feeser , Jack Wrenn ", + "name": "zerocopy", + "version": "0.8.25", + "description": "Zerocopy makes zero-cost memory manipulation effortless. We write \"unsafe\" so you don't have to.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zerocopy@0.8.25", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/google/zerocopy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom-derive@0.1.4", + "author": "Manish Goregaokar ", + "name": "zerofrom-derive", + "version": "0.1.4", + "description": "Custom derive for the zerofrom crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerofrom-derive@0.1.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.4", + "author": "Manish Goregaokar ", + "name": "zerofrom", + "version": "0.1.4", + "description": "ZeroFrom trait for constructing", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerofrom@0.1.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec-derive@0.10.3", + "author": "Manish Goregaokar ", + "name": "zerovec-derive", + "version": "0.10.3", + "description": "Custom derive for the zerovec crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerovec-derive@0.10.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4", + "author": "The ICU4X Project Developers", + "name": "zerovec", + "version": "0.10.4", + "description": "Zero-copy vector backed by a byte array", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerovec@0.10.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.6", + "author": "David Tolnay ", + "name": "zmij", + "version": "1.0.6", + "description": "A double-to-string conversion algorithm based on Schubfach and yy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "aac060176f7020d62c3bcc1cdbcec619d54f48b07ad1963a3f80ce7a0c17755f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zmij@1.0.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/zmij" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/zmij" + } + ] + } + ], + "dependencies": [ + { + "ref": "path+file:///home/runner/work/pydantic/pydantic/pydantic-core#2.46.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#enum_dispatch@0.3.13", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#jiter@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#lru@0.16.3", + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#speedate@0.17.0", + "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.23.0", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.25" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.7.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.9.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitvec@1.0.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#funty@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#radium@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#wyz@0.5.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bumpalo@3.19.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.0.101" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#enum_dispatch@0.3.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#funty@2.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185", + "registry+https://github.com/rust-lang/crates.io-index#r-efi@5.2.0", + "registry+https://github.com/rust-lang/crates.io-index#wasi@0.14.2+wasi-0.2.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21", + "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_collections@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.7.4", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locid@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#litemap@0.7.3", + "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.7.6", + "registry+https://github.com/rust-lang/crates.io-index#writeable@0.5.5", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locid_transform@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#icu_locid@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_locid_transform_data@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_provider@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.7.6", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locid_transform_data@1.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#icu_collections@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer_data@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_properties@1.5.1", + "registry+https://github.com/rust-lang/crates.io-index#icu_provider@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#utf16_iter@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#write16@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer_data@1.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties@1.5.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#icu_collections@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_locid_transform@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_properties_data@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_provider@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.7.6", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties_data@1.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_provider@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#icu_locid@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_provider_macros@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.7.6", + "registry+https://github.com/rust-lang/crates.io-index#writeable@0.5.5", + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.7.4", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_provider_macros@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#idna_adapter@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#idna_adapter@1.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#icu_properties@1.5.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.11" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#jiter@0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#bitvec@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#js-sys@0.3.77", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen@0.2.100" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#litemap@0.7.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#log@0.4.27" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lru@0.16.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.7.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.6.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#python3-dll-a@0.2.14", + "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185", + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.6.0", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#python3-dll-a@0.2.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.0.101" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#r-efi@5.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#radium@0.7.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.3", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.7.4", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.3", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.7.4", + "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.17" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.11", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.7.4", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#speedate@0.17.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.7.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utf16_iter@1.0.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#uuid@1.23.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#js-sys@0.3.77", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen@0.2.100" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wasi@0.14.2+wasi-0.2.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#wit-bindgen-rt@0.39.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-backend@0.2.100", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bumpalo@3.19.0", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.27", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-shared@0.2.100" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-macro-support@0.2.100", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-backend@0.2.100", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-shared@0.2.100" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-macro@0.2.100", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-macro-support@0.2.100" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-shared@0.2.100", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen@0.2.100", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.3", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.17", + "registry+https://github.com/rust-lang/crates.io-index#wasm-bindgen-macro@0.2.100" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wit-bindgen-rt@0.39.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.9.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#write16@1.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#writeable@0.5.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wyz@0.5.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#yoke-derive@0.7.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82", + "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#yoke@0.7.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#yoke-derive@0.7.4", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy-derive@0.8.25", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.25", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerocopy-derive@0.8.25" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom-derive@0.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82", + "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerofrom-derive@0.1.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec-derive@0.10.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.86", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.44", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.82" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.10.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.7.4", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#zerovec-derive@0.10.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.6" + } + ] +} \ No newline at end of file diff --git a/lib/python3.11/site-packages/pygments/__init__.py b/lib/python3.11/site-packages/pygments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5ba538b05cab44263485e2ba88ef466f230259 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/__init__.py @@ -0,0 +1,82 @@ +""" + Pygments + ~~~~~~~~ + + Pygments is a syntax highlighting package written in Python. + + It is a generic syntax highlighter for general use in all kinds of software + such as forum systems, wikis or other applications that need to prettify + source code. Highlights are: + + * a wide range of common languages and markup formats is supported + * special attention is paid to details, increasing quality by a fair amount + * support for new languages and formats are added easily + * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image + formats that PIL supports, and ANSI sequences + * it is usable as a command-line tool and as a library + * ... and it highlights even Brainfuck! + + The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``. + + .. _Pygments master branch: + https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" +from io import StringIO, BytesIO + +__version__ = '2.20.0' +__docformat__ = 'restructuredtext' + +__all__ = ['lex', 'format', 'highlight'] + + +def lex(code, lexer): + """ + Lex `code` with the `lexer` (must be a `Lexer` instance) + and return an iterable of tokens. Currently, this only calls + `lexer.get_tokens()`. + """ + try: + return lexer.get_tokens(code) + except TypeError: + # Heuristic to catch a common mistake. + from pygments.lexer import RegexLexer + if isinstance(lexer, type) and issubclass(lexer, RegexLexer): + raise TypeError('lex() argument must be a lexer instance, ' + 'not a class') + raise + + +def format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin + """ + Format ``tokens`` (an iterable of tokens) with the formatter ``formatter`` + (a `Formatter` instance). + + If ``outfile`` is given and a valid file object (an object with a + ``write`` method), the result will be written to it, otherwise it + is returned as a string. + """ + try: + if not outfile: + realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO() + formatter.format(tokens, realoutfile) + return realoutfile.getvalue() + else: + formatter.format(tokens, outfile) + except TypeError: + # Heuristic to catch a common mistake. + from pygments.formatter import Formatter + if isinstance(formatter, type) and issubclass(formatter, Formatter): + raise TypeError('format() argument must be a formatter instance, ' + 'not a class') + raise + + +def highlight(code, lexer, formatter, outfile=None): + """ + This is the most high-level highlighting function. It combines `lex` and + `format` in one function. + """ + return format(lex(code, lexer), formatter, outfile) diff --git a/lib/python3.11/site-packages/pygments/__main__.py b/lib/python3.11/site-packages/pygments/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..818bfc3ae6ac4b79e029f714c56101ab2b1076ea --- /dev/null +++ b/lib/python3.11/site-packages/pygments/__main__.py @@ -0,0 +1,17 @@ +""" + pygments.__main__ + ~~~~~~~~~~~~~~~~~ + + Main entry point for ``python -m pygments``. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import sys +import pygments.cmdline + +try: + sys.exit(pygments.cmdline.main(sys.argv)) +except KeyboardInterrupt: + sys.exit(1) diff --git a/lib/python3.11/site-packages/pygments/cmdline.py b/lib/python3.11/site-packages/pygments/cmdline.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4a1fb43926b7f7bdd7ef5028dbe19a9137515a --- /dev/null +++ b/lib/python3.11/site-packages/pygments/cmdline.py @@ -0,0 +1,668 @@ +""" + pygments.cmdline + ~~~~~~~~~~~~~~~~ + + Command line interface. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import os +import sys +import shutil +import argparse +from textwrap import dedent + +from pygments import __version__, highlight +from pygments.util import ClassNotFound, OptionError, docstring_headline, \ + guess_decode, guess_decode_from_terminal, terminal_encoding, \ + UnclosingTextIOWrapper +from pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \ + load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filename +from pygments.lexers.special import TextLexer +from pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter +from pygments.formatters import get_all_formatters, get_formatter_by_name, \ + load_formatter_from_file, get_formatter_for_filename, find_formatter_class +from pygments.formatters.terminal import TerminalFormatter +from pygments.formatters.terminal256 import Terminal256Formatter, TerminalTrueColorFormatter +from pygments.filters import get_all_filters, find_filter_class +from pygments.styles import get_all_styles, get_style_by_name + + +def _parse_options(o_strs): + opts = {} + if not o_strs: + return opts + for o_str in o_strs: + if not o_str.strip(): + continue + o_args = o_str.split(',') + for o_arg in o_args: + o_arg = o_arg.strip() + try: + o_key, o_val = o_arg.split('=', 1) + o_key = o_key.strip() + o_val = o_val.strip() + except ValueError: + opts[o_arg] = True + else: + opts[o_key] = o_val + return opts + + +def _parse_filters(f_strs): + filters = [] + if not f_strs: + return filters + for f_str in f_strs: + if ':' in f_str: + fname, fopts = f_str.split(':', 1) + filters.append((fname, _parse_options([fopts]))) + else: + filters.append((f_str, {})) + return filters + + +def _print_help(what, name): + try: + if what == 'lexer': + cls = get_lexer_by_name(name) + print(f"Help on the {cls.name} lexer:") + print(dedent(cls.__doc__)) + elif what == 'formatter': + cls = find_formatter_class(name) + print(f"Help on the {cls.name} formatter:") + print(dedent(cls.__doc__)) + elif what == 'filter': + cls = find_filter_class(name) + print(f"Help on the {name} filter:") + print(dedent(cls.__doc__)) + return 0 + except (AttributeError, ValueError): + print(f"{what} not found!", file=sys.stderr) + return 1 + + +def _print_list(what): + if what == 'lexer': + print() + print("Lexers:") + print("~~~~~~~") + + info = [] + for fullname, names, exts, _ in get_all_lexers(): + tup = (', '.join(names)+':', fullname, + exts and '(filenames ' + ', '.join(exts) + ')' or '') + info.append(tup) + info.sort() + for i in info: + print(('* {}\n {} {}').format(*i)) + + elif what == 'formatter': + print() + print("Formatters:") + print("~~~~~~~~~~~") + + info = [] + for cls in get_all_formatters(): + doc = docstring_headline(cls) + tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and + '(filenames ' + ', '.join(cls.filenames) + ')' or '') + info.append(tup) + info.sort() + for i in info: + print(('* {}\n {} {}').format(*i)) + + elif what == 'filter': + print() + print("Filters:") + print("~~~~~~~~") + + for name in get_all_filters(): + cls = find_filter_class(name) + print("* " + name + ':') + print(f" {docstring_headline(cls)}") + + elif what == 'style': + print() + print("Styles:") + print("~~~~~~~") + + for name in get_all_styles(): + cls = get_style_by_name(name) + print("* " + name + ':') + print(f" {docstring_headline(cls)}") + + +def _print_list_as_json(requested_items): + import json + result = {} + if 'lexer' in requested_items: + info = {} + for fullname, names, filenames, mimetypes in get_all_lexers(): + info[fullname] = { + 'aliases': names, + 'filenames': filenames, + 'mimetypes': mimetypes + } + result['lexers'] = info + + if 'formatter' in requested_items: + info = {} + for cls in get_all_formatters(): + doc = docstring_headline(cls) + info[cls.name] = { + 'aliases': cls.aliases, + 'filenames': cls.filenames, + 'doc': doc + } + result['formatters'] = info + + if 'filter' in requested_items: + info = {} + for name in get_all_filters(): + cls = find_filter_class(name) + info[name] = { + 'doc': docstring_headline(cls) + } + result['filters'] = info + + if 'style' in requested_items: + info = {} + for name in get_all_styles(): + cls = get_style_by_name(name) + info[name] = { + 'doc': docstring_headline(cls) + } + result['styles'] = info + + json.dump(result, sys.stdout) + +def main_inner(parser, argns): + if argns.help: + parser.print_help() + return 0 + + if argns.V: + print(f'Pygments version {__version__}, (c) 2006-present by Georg Brandl, Matthäus ' + 'Chajdas and contributors.') + return 0 + + def is_only_option(opt): + return not any(v for (k, v) in vars(argns).items() if k != opt) + + # handle ``pygmentize -L`` + if argns.L is not None: + arg_set = set() + for k, v in vars(argns).items(): + if v: + arg_set.add(k) + + arg_set.discard('L') + arg_set.discard('json') + + if arg_set: + parser.print_help(sys.stderr) + return 2 + + # print version + if not argns.json: + main(['', '-V']) + allowed_types = {'lexer', 'formatter', 'filter', 'style'} + largs = [arg.rstrip('s') for arg in argns.L] + if any(arg not in allowed_types for arg in largs): + parser.print_help(sys.stderr) + return 0 + if not largs: + largs = allowed_types + if not argns.json: + for arg in largs: + _print_list(arg) + else: + _print_list_as_json(largs) + return 0 + + # handle ``pygmentize -H`` + if argns.H: + if not is_only_option('H'): + parser.print_help(sys.stderr) + return 2 + what, name = argns.H + if what not in ('lexer', 'formatter', 'filter'): + parser.print_help(sys.stderr) + return 2 + return _print_help(what, name) + + # parse -O options + parsed_opts = _parse_options(argns.O or []) + + # parse -P options + for p_opt in argns.P or []: + try: + name, value = p_opt.split('=', 1) + except ValueError: + parsed_opts[p_opt] = True + else: + parsed_opts[name] = value + + # encodings + inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding')) + outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding')) + + # handle ``pygmentize -N`` + if argns.N: + lexer = find_lexer_class_for_filename(argns.N) + if lexer is None: + lexer = TextLexer + + print(lexer.aliases[0]) + return 0 + + # handle ``pygmentize -C`` + if argns.C: + inp = sys.stdin.buffer.read() + try: + lexer = guess_lexer(inp, inencoding=inencoding) + except ClassNotFound: + lexer = TextLexer + + print(lexer.aliases[0]) + return 0 + + # handle ``pygmentize -S`` + S_opt = argns.S + a_opt = argns.a + if S_opt is not None: + f_opt = argns.f + if not f_opt: + parser.print_help(sys.stderr) + return 2 + if argns.l or argns.INPUTFILE: + parser.print_help(sys.stderr) + return 2 + + try: + parsed_opts['style'] = S_opt + fmter = get_formatter_by_name(f_opt, **parsed_opts) + except ClassNotFound as err: + print(err, file=sys.stderr) + return 1 + + print(fmter.get_style_defs(a_opt or '')) + return 0 + + # if no -S is given, -a is not allowed + if argns.a is not None: + parser.print_help(sys.stderr) + return 2 + + # parse -F options + F_opts = _parse_filters(argns.F or []) + + # -x: allow custom (eXternal) lexers and formatters + allow_custom_lexer_formatter = bool(argns.x) + + # select lexer + lexer = None + + # given by name? + lexername = argns.l + if lexername: + # custom lexer, located relative to user's cwd + if allow_custom_lexer_formatter and '.py' in lexername: + try: + filename = None + name = None + if ':' in lexername: + filename, name = lexername.rsplit(':', 1) + + if '.py' in name: + # This can happen on Windows: If the lexername is + # C:\lexer.py -- return to normal load path in that case + name = None + + if filename and name: + lexer = load_lexer_from_file(filename, name, + **parsed_opts) + else: + lexer = load_lexer_from_file(lexername, **parsed_opts) + except ClassNotFound as err: + print('Error:', err, file=sys.stderr) + return 1 + else: + try: + lexer = get_lexer_by_name(lexername, **parsed_opts) + except (OptionError, ClassNotFound) as err: + print('Error:', err, file=sys.stderr) + return 1 + + # read input code + code = None + + if argns.INPUTFILE: + if argns.s: + print('Error: -s option not usable when input file specified', + file=sys.stderr) + return 2 + + infn = argns.INPUTFILE + try: + with open(infn, 'rb') as infp: + code = infp.read() + except Exception as err: + print('Error: cannot read infile:', err, file=sys.stderr) + return 1 + if not inencoding: + code, inencoding = guess_decode(code) + + # do we have to guess the lexer? + if not lexer: + try: + lexer = get_lexer_for_filename(infn, code, **parsed_opts) + except ClassNotFound as err: + if argns.g: + try: + lexer = guess_lexer(code, **parsed_opts) + except ClassNotFound: + lexer = TextLexer(**parsed_opts) + else: + print('Error:', err, file=sys.stderr) + return 1 + except OptionError as err: + print('Error:', err, file=sys.stderr) + return 1 + + elif not argns.s: # treat stdin as full file (-s support is later) + # read code from terminal, always in binary mode since we want to + # decode ourselves and be tolerant with it + code = sys.stdin.buffer.read() # use .buffer to get a binary stream + if not inencoding: + code, inencoding = guess_decode_from_terminal(code, sys.stdin) + # else the lexer will do the decoding + if not lexer: + try: + lexer = guess_lexer(code, **parsed_opts) + except ClassNotFound: + lexer = TextLexer(**parsed_opts) + + else: # -s option needs a lexer with -l + if not lexer: + print('Error: when using -s a lexer has to be selected with -l', + file=sys.stderr) + return 2 + + # process filters + for fname, fopts in F_opts: + try: + lexer.add_filter(fname, **fopts) + except ClassNotFound as err: + print('Error:', err, file=sys.stderr) + return 1 + + # select formatter + outfn = argns.o + fmter = argns.f + if fmter: + # custom formatter, located relative to user's cwd + if allow_custom_lexer_formatter and '.py' in fmter: + try: + filename = None + name = None + if ':' in fmter: + # Same logic as above for custom lexer + filename, name = fmter.rsplit(':', 1) + + if '.py' in name: + name = None + + if filename and name: + fmter = load_formatter_from_file(filename, name, + **parsed_opts) + else: + fmter = load_formatter_from_file(fmter, **parsed_opts) + except ClassNotFound as err: + print('Error:', err, file=sys.stderr) + return 1 + else: + try: + fmter = get_formatter_by_name(fmter, **parsed_opts) + except (OptionError, ClassNotFound) as err: + print('Error:', err, file=sys.stderr) + return 1 + + if outfn: + if not fmter: + try: + fmter = get_formatter_for_filename(outfn, **parsed_opts) + except (OptionError, ClassNotFound) as err: + print('Error:', err, file=sys.stderr) + return 1 + try: + outfile = open(outfn, 'wb') + except Exception as err: + print('Error: cannot open outfile:', err, file=sys.stderr) + return 1 + else: + if not fmter: + if os.environ.get('COLORTERM','') in ('truecolor', '24bit'): + fmter = TerminalTrueColorFormatter(**parsed_opts) + elif '256' in os.environ.get('TERM', ''): + fmter = Terminal256Formatter(**parsed_opts) + else: + fmter = TerminalFormatter(**parsed_opts) + outfile = sys.stdout.buffer + + # determine output encoding if not explicitly selected + if not outencoding: + if outfn: + # output file? use lexer encoding for now (can still be None) + fmter.encoding = inencoding + else: + # else use terminal encoding + fmter.encoding = terminal_encoding(sys.stdout) + + # provide coloring under Windows, if possible + if not outfn and sys.platform in ('win32', 'cygwin') and \ + fmter.name in ('Terminal', 'Terminal256'): # pragma: no cover + # unfortunately colorama doesn't support binary streams on Py3 + outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding) + fmter.encoding = None + try: + import colorama.initialise + except ImportError: + pass + else: + outfile = colorama.initialise.wrap_stream( + outfile, convert=None, strip=None, autoreset=False, wrap=True) + + # When using the LaTeX formatter and the option `escapeinside` is + # specified, we need a special lexer which collects escaped text + # before running the chosen language lexer. + escapeinside = parsed_opts.get('escapeinside', '') + if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter): + left = escapeinside[0] + right = escapeinside[1] + lexer = LatexEmbeddedLexer(left, right, lexer) + + # ... and do it! + if not argns.s: + # process whole input as per normal... + try: + highlight(code, lexer, fmter, outfile) + finally: + if outfn: + outfile.close() + return 0 + else: + # line by line processing of stdin (eg: for 'tail -f')... + try: + while 1: + line = sys.stdin.buffer.readline() + if not line: + break + if not inencoding: + line = guess_decode_from_terminal(line, sys.stdin)[0] + highlight(line, lexer, fmter, outfile) + if hasattr(outfile, 'flush'): + outfile.flush() + return 0 + except KeyboardInterrupt: # pragma: no cover + return 0 + finally: + if outfn: + outfile.close() + + +class HelpFormatter(argparse.HelpFormatter): + def __init__(self, prog, indent_increment=2, max_help_position=16, width=None): + if width is None: + try: + width = shutil.get_terminal_size().columns - 2 + except Exception: + pass + argparse.HelpFormatter.__init__(self, prog, indent_increment, + max_help_position, width) + + +def main(args=sys.argv): + """ + Main command line entry point. + """ + desc = "Highlight an input file and write the result to an output file." + parser = argparse.ArgumentParser(description=desc, add_help=False, + formatter_class=HelpFormatter) + + operation = parser.add_argument_group('Main operation') + lexersel = operation.add_mutually_exclusive_group() + lexersel.add_argument( + '-l', metavar='LEXER', + help='Specify the lexer to use. (Query names with -L.) If not ' + 'given and -g is not present, the lexer is guessed from the filename.') + lexersel.add_argument( + '-g', action='store_true', + help='Guess the lexer from the file contents, or pass through ' + 'as plain text if nothing can be guessed.') + operation.add_argument( + '-F', metavar='FILTER[:options]', action='append', + help='Add a filter to the token stream. (Query names with -L.) ' + 'Filter options are given after a colon if necessary.') + operation.add_argument( + '-f', metavar='FORMATTER', + help='Specify the formatter to use. (Query names with -L.) ' + 'If not given, the formatter is guessed from the output filename, ' + 'and defaults to the terminal formatter if the output is to the ' + 'terminal or an unknown file extension.') + operation.add_argument( + '-O', metavar='OPTION=value[,OPTION=value,...]', action='append', + help='Give options to the lexer and formatter as a comma-separated ' + 'list of key-value pairs. ' + 'Example: `-O bg=light,python=cool`.') + operation.add_argument( + '-P', metavar='OPTION=value', action='append', + help='Give a single option to the lexer and formatter - with this ' + 'you can pass options whose value contains commas and equal signs. ' + 'Example: `-P "heading=Pygments, the Python highlighter"`.') + operation.add_argument( + '-o', metavar='OUTPUTFILE', + help='Where to write the output. Defaults to standard output.') + + operation.add_argument( + 'INPUTFILE', nargs='?', + help='Where to read the input. Defaults to standard input.') + + flags = parser.add_argument_group('Operation flags') + flags.add_argument( + '-v', action='store_true', + help='Print a detailed traceback on unhandled exceptions, which ' + 'is useful for debugging and bug reports.') + flags.add_argument( + '-s', action='store_true', + help='Process lines one at a time until EOF, rather than waiting to ' + 'process the entire file. This only works for stdin, only for lexers ' + 'with no line-spanning constructs, and is intended for streaming ' + 'input such as you get from `tail -f`. ' + 'Example usage: `tail -f sql.log | pygmentize -s -l sql`.') + flags.add_argument( + '-x', action='store_true', + help='Allow custom lexers and formatters to be loaded from a .py file ' + 'relative to the current working directory. For example, ' + '`-l ./customlexer.py -x`. By default, this option expects a file ' + 'with a class named CustomLexer or CustomFormatter; you can also ' + 'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). ' + 'Users should be very careful not to use this option with untrusted ' + 'files, because it will import and run them.') + flags.add_argument('--json', help='Output as JSON. This can ' + 'be only used in conjunction with -L.', + default=False, + action='store_true') + + special_modes_group = parser.add_argument_group( + 'Special modes - do not do any highlighting') + special_modes = special_modes_group.add_mutually_exclusive_group() + special_modes.add_argument( + '-S', metavar='STYLE -f formatter', + help='Print style definitions for STYLE for a formatter ' + 'given with -f. The argument given by -a is formatter ' + 'dependent.') + special_modes.add_argument( + '-L', nargs='*', metavar='WHAT', + help='List lexers, formatters, styles or filters -- ' + 'give additional arguments for the thing(s) you want to list ' + '(e.g. "styles"), or omit them to list everything.') + special_modes.add_argument( + '-N', metavar='FILENAME', + help='Guess and print out a lexer name based solely on the given ' + 'filename. Does not take input or highlight anything. If no specific ' + 'lexer can be determined, "text" is printed.') + special_modes.add_argument( + '-C', action='store_true', + help='Like -N, but print out a lexer name based solely on ' + 'a given content from standard input.') + special_modes.add_argument( + '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'), + help='Print detailed help for the object of type , ' + 'where is one of "lexer", "formatter" or "filter".') + special_modes.add_argument( + '-V', action='store_true', + help='Print the package version.') + special_modes.add_argument( + '-h', '--help', action='store_true', + help='Print this help.') + special_modes_group.add_argument( + '-a', metavar='ARG', + help='Formatter-specific additional argument for the -S (print ' + 'style sheet) mode.') + + argns = parser.parse_args(args[1:]) + + try: + return main_inner(parser, argns) + except BrokenPipeError: + # someone closed our stdout, e.g. by quitting a pager. + return 0 + except Exception: + if argns.v: + print(file=sys.stderr) + print('*' * 65, file=sys.stderr) + print('An unhandled exception occurred while highlighting.', + file=sys.stderr) + print('Please report the whole traceback to the issue tracker at', + file=sys.stderr) + print('.', + file=sys.stderr) + print('*' * 65, file=sys.stderr) + print(file=sys.stderr) + raise + import traceback + info = traceback.format_exception(*sys.exc_info()) + msg = info[-1].strip() + if len(info) >= 3: + # extract relevant file and position info + msg += '\n (f{})'.format(info[-2].split('\n')[0].strip()[1:]) + print(file=sys.stderr) + print('*** Error while highlighting:', file=sys.stderr) + print(msg, file=sys.stderr) + print('*** If this is a bug you want to report, please rerun with -v.', + file=sys.stderr) + return 1 diff --git a/lib/python3.11/site-packages/pygments/console.py b/lib/python3.11/site-packages/pygments/console.py new file mode 100644 index 0000000000000000000000000000000000000000..d9009168cadbe25ba0bb1fc5427a5db0f1582830 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/console.py @@ -0,0 +1,70 @@ +""" + pygments.console + ~~~~~~~~~~~~~~~~ + + Format colored console output. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +esc = "\x1b[" + +codes = {} +codes[""] = "" +codes["reset"] = esc + "39;49;00m" + +codes["bold"] = esc + "01m" +codes["faint"] = esc + "02m" +codes["standout"] = esc + "03m" +codes["underline"] = esc + "04m" +codes["blink"] = esc + "05m" +codes["overline"] = esc + "06m" + +dark_colors = ["black", "red", "green", "yellow", "blue", + "magenta", "cyan", "gray"] +light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue", + "brightmagenta", "brightcyan", "white"] + +x = 30 +for dark, light in zip(dark_colors, light_colors): + codes[dark] = esc + "%im" % x + codes[light] = esc + "%im" % (60 + x) + x += 1 + +del dark, light, x + +codes["white"] = codes["bold"] + + +def reset_color(): + return codes["reset"] + + +def colorize(color_key, text): + return codes[color_key] + text + codes["reset"] + + +def ansiformat(attr, text): + """ + Format ``text`` with a color and/or some attributes:: + + color normal color + *color* bold color + _color_ underlined color + +color+ blinking color + """ + result = [] + if attr[:1] == attr[-1:] == '+': + result.append(codes['blink']) + attr = attr[1:-1] + if attr[:1] == attr[-1:] == '*': + result.append(codes['bold']) + attr = attr[1:-1] + if attr[:1] == attr[-1:] == '_': + result.append(codes['underline']) + attr = attr[1:-1] + result.append(codes[attr]) + result.append(text) + result.append(codes['reset']) + return ''.join(result) diff --git a/lib/python3.11/site-packages/pygments/filter.py b/lib/python3.11/site-packages/pygments/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..6c926c26cfcf0ca7579f05affcab46c389595b71 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/filter.py @@ -0,0 +1,70 @@ +""" + pygments.filter + ~~~~~~~~~~~~~~~ + + Module that implements the default filter. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + + +def apply_filters(stream, filters, lexer=None): + """ + Use this method to apply an iterable of filters to + a stream. If lexer is given it's forwarded to the + filter, otherwise the filter receives `None`. + """ + def _apply(filter_, stream): + yield from filter_.filter(lexer, stream) + for filter_ in filters: + stream = _apply(filter_, stream) + return stream + + +def simplefilter(f): + """ + Decorator that converts a function into a filter:: + + @simplefilter + def lowercase(self, lexer, stream, options): + for ttype, value in stream: + yield ttype, value.lower() + """ + return type(f.__name__, (FunctionFilter,), { + '__module__': getattr(f, '__module__'), + '__doc__': f.__doc__, + 'function': f, + }) + + +class Filter: + """ + Default filter. Subclass this class or use the `simplefilter` + decorator to create own filters. + """ + + def __init__(self, **options): + self.options = options + + def filter(self, lexer, stream): + raise NotImplementedError() + + +class FunctionFilter(Filter): + """ + Abstract class used by `simplefilter` to create simple + function filters on the fly. The `simplefilter` decorator + automatically creates subclasses of this class for + functions passed to it. + """ + function = None + + def __init__(self, **options): + if not hasattr(self, 'function'): + raise TypeError(f'{self.__class__.__name__!r} used without bound function') + Filter.__init__(self, **options) + + def filter(self, lexer, stream): + # pylint: disable=not-callable + yield from self.function(lexer, stream, self.options) diff --git a/lib/python3.11/site-packages/pygments/filters/__init__.py b/lib/python3.11/site-packages/pygments/filters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ba6adb5b75ac3bf8e9e94868575e6ce770e6c1 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/filters/__init__.py @@ -0,0 +1,942 @@ +""" + pygments.filters + ~~~~~~~~~~~~~~~~ + + Module containing filter lookup functions and default + filters. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \ + string_to_tokentype +from pygments.filter import Filter +from pygments.util import get_list_opt, get_int_opt, get_bool_opt, \ + get_choice_opt, ClassNotFound, OptionError +from pygments.plugin import find_plugin_filters + + +def find_filter_class(filtername): + """Lookup a filter by name. Return None if not found.""" + if filtername in FILTERS: + return FILTERS[filtername] + for name, cls in find_plugin_filters(): + if name == filtername: + return cls + return None + + +def get_filter_by_name(filtername, **options): + """Return an instantiated filter. + + Options are passed to the filter initializer if wanted. + Raise a ClassNotFound if not found. + """ + cls = find_filter_class(filtername) + if cls: + return cls(**options) + else: + raise ClassNotFound(f'filter {filtername!r} not found') + + +def get_all_filters(): + """Return a generator of all filter names.""" + yield from FILTERS + for name, _ in find_plugin_filters(): + yield name + + +def _replace_special(ttype, value, regex, specialttype, + replacefunc=lambda x: x): + last = 0 + for match in regex.finditer(value): + start, end = match.start(), match.end() + if start != last: + yield ttype, value[last:start] + yield specialttype, replacefunc(value[start:end]) + last = end + if last != len(value): + yield ttype, value[last:] + + +class CodeTagFilter(Filter): + """Highlight special code tags in comments and docstrings. + + Options accepted: + + `codetags` : list of strings + A list of strings that are flagged as code tags. The default is to + highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``. + + .. versionchanged:: 2.13 + Now recognizes ``FIXME`` by default. + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + tags = get_list_opt(options, 'codetags', + ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE']) + self.tag_re = re.compile(r'\b({})\b'.format('|'.join([ + re.escape(tag) for tag in tags if tag + ]))) + + def filter(self, lexer, stream): + regex = self.tag_re + for ttype, value in stream: + if ttype in String.Doc or \ + ttype in Comment and \ + ttype not in Comment.Preproc: + yield from _replace_special(ttype, value, regex, Comment.Special) + else: + yield ttype, value + + +class SymbolFilter(Filter): + """Convert mathematical symbols into Unicode characters. + + Examples are ``\\`` in Isabelle or + ``\\longrightarrow`` in LaTeX. + + This is mostly useful for HTML or console output when you want to + approximate the source rendering you'd see in an IDE. + + Options accepted: + + `lang` : string + The symbol language. Must be one of ``'isabelle'`` or + ``'latex'``. The default is ``'isabelle'``. + """ + + latex_symbols = { + '\\alpha' : '\U000003b1', + '\\beta' : '\U000003b2', + '\\gamma' : '\U000003b3', + '\\delta' : '\U000003b4', + '\\varepsilon' : '\U000003b5', + '\\zeta' : '\U000003b6', + '\\eta' : '\U000003b7', + '\\vartheta' : '\U000003b8', + '\\iota' : '\U000003b9', + '\\kappa' : '\U000003ba', + '\\lambda' : '\U000003bb', + '\\mu' : '\U000003bc', + '\\nu' : '\U000003bd', + '\\xi' : '\U000003be', + '\\pi' : '\U000003c0', + '\\varrho' : '\U000003c1', + '\\sigma' : '\U000003c3', + '\\tau' : '\U000003c4', + '\\upsilon' : '\U000003c5', + '\\varphi' : '\U000003c6', + '\\chi' : '\U000003c7', + '\\psi' : '\U000003c8', + '\\omega' : '\U000003c9', + '\\Gamma' : '\U00000393', + '\\Delta' : '\U00000394', + '\\Theta' : '\U00000398', + '\\Lambda' : '\U0000039b', + '\\Xi' : '\U0000039e', + '\\Pi' : '\U000003a0', + '\\Sigma' : '\U000003a3', + '\\Upsilon' : '\U000003a5', + '\\Phi' : '\U000003a6', + '\\Psi' : '\U000003a8', + '\\Omega' : '\U000003a9', + '\\leftarrow' : '\U00002190', + '\\longleftarrow' : '\U000027f5', + '\\rightarrow' : '\U00002192', + '\\longrightarrow' : '\U000027f6', + '\\Leftarrow' : '\U000021d0', + '\\Longleftarrow' : '\U000027f8', + '\\Rightarrow' : '\U000021d2', + '\\Longrightarrow' : '\U000027f9', + '\\leftrightarrow' : '\U00002194', + '\\longleftrightarrow' : '\U000027f7', + '\\Leftrightarrow' : '\U000021d4', + '\\Longleftrightarrow' : '\U000027fa', + '\\mapsto' : '\U000021a6', + '\\longmapsto' : '\U000027fc', + '\\relbar' : '\U00002500', + '\\Relbar' : '\U00002550', + '\\hookleftarrow' : '\U000021a9', + '\\hookrightarrow' : '\U000021aa', + '\\leftharpoondown' : '\U000021bd', + '\\rightharpoondown' : '\U000021c1', + '\\leftharpoonup' : '\U000021bc', + '\\rightharpoonup' : '\U000021c0', + '\\rightleftharpoons' : '\U000021cc', + '\\leadsto' : '\U0000219d', + '\\downharpoonleft' : '\U000021c3', + '\\downharpoonright' : '\U000021c2', + '\\upharpoonleft' : '\U000021bf', + '\\upharpoonright' : '\U000021be', + '\\restriction' : '\U000021be', + '\\uparrow' : '\U00002191', + '\\Uparrow' : '\U000021d1', + '\\downarrow' : '\U00002193', + '\\Downarrow' : '\U000021d3', + '\\updownarrow' : '\U00002195', + '\\Updownarrow' : '\U000021d5', + '\\langle' : '\U000027e8', + '\\rangle' : '\U000027e9', + '\\lceil' : '\U00002308', + '\\rceil' : '\U00002309', + '\\lfloor' : '\U0000230a', + '\\rfloor' : '\U0000230b', + '\\flqq' : '\U000000ab', + '\\frqq' : '\U000000bb', + '\\bot' : '\U000022a5', + '\\top' : '\U000022a4', + '\\wedge' : '\U00002227', + '\\bigwedge' : '\U000022c0', + '\\vee' : '\U00002228', + '\\bigvee' : '\U000022c1', + '\\forall' : '\U00002200', + '\\exists' : '\U00002203', + '\\nexists' : '\U00002204', + '\\neg' : '\U000000ac', + '\\Box' : '\U000025a1', + '\\Diamond' : '\U000025c7', + '\\vdash' : '\U000022a2', + '\\models' : '\U000022a8', + '\\dashv' : '\U000022a3', + '\\surd' : '\U0000221a', + '\\le' : '\U00002264', + '\\ge' : '\U00002265', + '\\ll' : '\U0000226a', + '\\gg' : '\U0000226b', + '\\lesssim' : '\U00002272', + '\\gtrsim' : '\U00002273', + '\\lessapprox' : '\U00002a85', + '\\gtrapprox' : '\U00002a86', + '\\in' : '\U00002208', + '\\notin' : '\U00002209', + '\\subset' : '\U00002282', + '\\supset' : '\U00002283', + '\\subseteq' : '\U00002286', + '\\supseteq' : '\U00002287', + '\\sqsubset' : '\U0000228f', + '\\sqsupset' : '\U00002290', + '\\sqsubseteq' : '\U00002291', + '\\sqsupseteq' : '\U00002292', + '\\cap' : '\U00002229', + '\\bigcap' : '\U000022c2', + '\\cup' : '\U0000222a', + '\\bigcup' : '\U000022c3', + '\\sqcup' : '\U00002294', + '\\bigsqcup' : '\U00002a06', + '\\sqcap' : '\U00002293', + '\\Bigsqcap' : '\U00002a05', + '\\setminus' : '\U00002216', + '\\propto' : '\U0000221d', + '\\uplus' : '\U0000228e', + '\\bigplus' : '\U00002a04', + '\\sim' : '\U0000223c', + '\\doteq' : '\U00002250', + '\\simeq' : '\U00002243', + '\\approx' : '\U00002248', + '\\asymp' : '\U0000224d', + '\\cong' : '\U00002245', + '\\equiv' : '\U00002261', + '\\Join' : '\U000022c8', + '\\bowtie' : '\U00002a1d', + '\\prec' : '\U0000227a', + '\\succ' : '\U0000227b', + '\\preceq' : '\U0000227c', + '\\succeq' : '\U0000227d', + '\\parallel' : '\U00002225', + '\\mid' : '\U000000a6', + '\\pm' : '\U000000b1', + '\\mp' : '\U00002213', + '\\times' : '\U000000d7', + '\\div' : '\U000000f7', + '\\cdot' : '\U000022c5', + '\\star' : '\U000022c6', + '\\circ' : '\U00002218', + '\\dagger' : '\U00002020', + '\\ddagger' : '\U00002021', + '\\lhd' : '\U000022b2', + '\\rhd' : '\U000022b3', + '\\unlhd' : '\U000022b4', + '\\unrhd' : '\U000022b5', + '\\triangleleft' : '\U000025c3', + '\\triangleright' : '\U000025b9', + '\\triangle' : '\U000025b3', + '\\triangleq' : '\U0000225c', + '\\oplus' : '\U00002295', + '\\bigoplus' : '\U00002a01', + '\\otimes' : '\U00002297', + '\\bigotimes' : '\U00002a02', + '\\odot' : '\U00002299', + '\\bigodot' : '\U00002a00', + '\\ominus' : '\U00002296', + '\\oslash' : '\U00002298', + '\\dots' : '\U00002026', + '\\cdots' : '\U000022ef', + '\\sum' : '\U00002211', + '\\prod' : '\U0000220f', + '\\coprod' : '\U00002210', + '\\infty' : '\U0000221e', + '\\int' : '\U0000222b', + '\\oint' : '\U0000222e', + '\\clubsuit' : '\U00002663', + '\\diamondsuit' : '\U00002662', + '\\heartsuit' : '\U00002661', + '\\spadesuit' : '\U00002660', + '\\aleph' : '\U00002135', + '\\emptyset' : '\U00002205', + '\\nabla' : '\U00002207', + '\\partial' : '\U00002202', + '\\flat' : '\U0000266d', + '\\natural' : '\U0000266e', + '\\sharp' : '\U0000266f', + '\\angle' : '\U00002220', + '\\copyright' : '\U000000a9', + '\\textregistered' : '\U000000ae', + '\\textonequarter' : '\U000000bc', + '\\textonehalf' : '\U000000bd', + '\\textthreequarters' : '\U000000be', + '\\textordfeminine' : '\U000000aa', + '\\textordmasculine' : '\U000000ba', + '\\euro' : '\U000020ac', + '\\pounds' : '\U000000a3', + '\\yen' : '\U000000a5', + '\\textcent' : '\U000000a2', + '\\textcurrency' : '\U000000a4', + '\\textdegree' : '\U000000b0', + } + + isabelle_symbols = { + '\\' : '\U0001d7ec', + '\\' : '\U0001d7ed', + '\\' : '\U0001d7ee', + '\\' : '\U0001d7ef', + '\\' : '\U0001d7f0', + '\\' : '\U0001d7f1', + '\\' : '\U0001d7f2', + '\\' : '\U0001d7f3', + '\\' : '\U0001d7f4', + '\\' : '\U0001d7f5', + '\\' : '\U0001d49c', + '\\' : '\U0000212c', + '\\' : '\U0001d49e', + '\\' : '\U0001d49f', + '\\' : '\U00002130', + '\\' : '\U00002131', + '\\' : '\U0001d4a2', + '\\' : '\U0000210b', + '\\' : '\U00002110', + '\\' : '\U0001d4a5', + '\\' : '\U0001d4a6', + '\\' : '\U00002112', + '\\' : '\U00002133', + '\\' : '\U0001d4a9', + '\\' : '\U0001d4aa', + '\\

' : '\U0001d5c9', + '\\' : '\U0001d5ca', + '\\' : '\U0001d5cb', + '\\' : '\U0001d5cc', + '\\' : '\U0001d5cd', + '\\' : '\U0001d5ce', + '\\' : '\U0001d5cf', + '\\' : '\U0001d5d0', + '\\' : '\U0001d5d1', + '\\' : '\U0001d5d2', + '\\' : '\U0001d5d3', + '\\' : '\U0001d504', + '\\' : '\U0001d505', + '\\' : '\U0000212d', + '\\

' : '\U0001d507', + '\\' : '\U0001d508', + '\\' : '\U0001d509', + '\\' : '\U0001d50a', + '\\' : '\U0000210c', + '\\' : '\U00002111', + '\\' : '\U0001d50d', + '\\' : '\U0001d50e', + '\\' : '\U0001d50f', + '\\' : '\U0001d510', + '\\' : '\U0001d511', + '\\' : '\U0001d512', + '\\' : '\U0001d513', + '\\' : '\U0001d514', + '\\' : '\U0000211c', + '\\' : '\U0001d516', + '\\' : '\U0001d517', + '\\' : '\U0001d518', + '\\' : '\U0001d519', + '\\' : '\U0001d51a', + '\\' : '\U0001d51b', + '\\' : '\U0001d51c', + '\\' : '\U00002128', + '\\' : '\U0001d51e', + '\\' : '\U0001d51f', + '\\' : '\U0001d520', + '\\
' : '\U0001d521', + '\\' : '\U0001d522', + '\\' : '\U0001d523', + '\\' : '\U0001d524', + '\\' : '\U0001d525', + '\\' : '\U0001d526', + '\\' : '\U0001d527', + '\\' : '\U0001d528', + '\\' : '\U0001d529', + '\\' : '\U0001d52a', + '\\' : '\U0001d52b', + '\\' : '\U0001d52c', + '\\' : '\U0001d52d', + '\\' : '\U0001d52e', + '\\' : '\U0001d52f', + '\\' : '\U0001d530', + '\\' : '\U0001d531', + '\\' : '\U0001d532', + '\\' : '\U0001d533', + '\\' : '\U0001d534', + '\\' : '\U0001d535', + '\\' : '\U0001d536', + '\\' : '\U0001d537', + '\\' : '\U000003b1', + '\\' : '\U000003b2', + '\\' : '\U000003b3', + '\\' : '\U000003b4', + '\\' : '\U000003b5', + '\\' : '\U000003b6', + '\\' : '\U000003b7', + '\\' : '\U000003b8', + '\\' : '\U000003b9', + '\\' : '\U000003ba', + '\\' : '\U000003bb', + '\\' : '\U000003bc', + '\\' : '\U000003bd', + '\\' : '\U000003be', + '\\' : '\U000003c0', + '\\' : '\U000003c1', + '\\' : '\U000003c3', + '\\' : '\U000003c4', + '\\' : '\U000003c5', + '\\' : '\U000003c6', + '\\' : '\U000003c7', + '\\' : '\U000003c8', + '\\' : '\U000003c9', + '\\' : '\U00000393', + '\\' : '\U00000394', + '\\' : '\U00000398', + '\\' : '\U0000039b', + '\\' : '\U0000039e', + '\\' : '\U000003a0', + '\\' : '\U000003a3', + '\\' : '\U000003a5', + '\\' : '\U000003a6', + '\\' : '\U000003a8', + '\\' : '\U000003a9', + '\\' : '\U0001d539', + '\\' : '\U00002102', + '\\' : '\U00002115', + '\\' : '\U0000211a', + '\\' : '\U0000211d', + '\\' : '\U00002124', + '\\' : '\U00002190', + '\\' : '\U000027f5', + '\\' : '\U00002192', + '\\' : '\U000027f6', + '\\' : '\U000021d0', + '\\' : '\U000027f8', + '\\' : '\U000021d2', + '\\' : '\U000027f9', + '\\' : '\U00002194', + '\\' : '\U000027f7', + '\\' : '\U000021d4', + '\\' : '\U000027fa', + '\\' : '\U000021a6', + '\\' : '\U000027fc', + '\\' : '\U00002500', + '\\' : '\U00002550', + '\\' : '\U000021a9', + '\\' : '\U000021aa', + '\\' : '\U000021bd', + '\\' : '\U000021c1', + '\\' : '\U000021bc', + '\\' : '\U000021c0', + '\\' : '\U000021cc', + '\\' : '\U0000219d', + '\\' : '\U000021c3', + '\\' : '\U000021c2', + '\\' : '\U000021bf', + '\\' : '\U000021be', + '\\' : '\U000021be', + '\\' : '\U00002237', + '\\' : '\U00002191', + '\\' : '\U000021d1', + '\\' : '\U00002193', + '\\' : '\U000021d3', + '\\' : '\U00002195', + '\\' : '\U000021d5', + '\\' : '\U000027e8', + '\\' : '\U000027e9', + '\\' : '\U00002308', + '\\' : '\U00002309', + '\\' : '\U0000230a', + '\\' : '\U0000230b', + '\\' : '\U00002987', + '\\' : '\U00002988', + '\\' : '\U000027e6', + '\\' : '\U000027e7', + '\\' : '\U00002983', + '\\' : '\U00002984', + '\\' : '\U000000ab', + '\\' : '\U000000bb', + '\\' : '\U000022a5', + '\\' : '\U000022a4', + '\\' : '\U00002227', + '\\' : '\U000022c0', + '\\' : '\U00002228', + '\\' : '\U000022c1', + '\\' : '\U00002200', + '\\' : '\U00002203', + '\\' : '\U00002204', + '\\' : '\U000000ac', + '\\' : '\U000025a1', + '\\' : '\U000025c7', + '\\' : '\U000022a2', + '\\' : '\U000022a8', + '\\' : '\U000022a9', + '\\' : '\U000022ab', + '\\' : '\U000022a3', + '\\' : '\U0000221a', + '\\' : '\U00002264', + '\\' : '\U00002265', + '\\' : '\U0000226a', + '\\' : '\U0000226b', + '\\' : '\U00002272', + '\\' : '\U00002273', + '\\' : '\U00002a85', + '\\' : '\U00002a86', + '\\' : '\U00002208', + '\\' : '\U00002209', + '\\' : '\U00002282', + '\\' : '\U00002283', + '\\' : '\U00002286', + '\\' : '\U00002287', + '\\' : '\U0000228f', + '\\' : '\U00002290', + '\\' : '\U00002291', + '\\' : '\U00002292', + '\\' : '\U00002229', + '\\' : '\U000022c2', + '\\' : '\U0000222a', + '\\' : '\U000022c3', + '\\' : '\U00002294', + '\\' : '\U00002a06', + '\\' : '\U00002293', + '\\' : '\U00002a05', + '\\' : '\U00002216', + '\\' : '\U0000221d', + '\\' : '\U0000228e', + '\\' : '\U00002a04', + '\\' : '\U00002260', + '\\' : '\U0000223c', + '\\' : '\U00002250', + '\\' : '\U00002243', + '\\' : '\U00002248', + '\\' : '\U0000224d', + '\\' : '\U00002245', + '\\' : '\U00002323', + '\\' : '\U00002261', + '\\' : '\U00002322', + '\\' : '\U000022c8', + '\\' : '\U00002a1d', + '\\' : '\U0000227a', + '\\' : '\U0000227b', + '\\' : '\U0000227c', + '\\' : '\U0000227d', + '\\' : '\U00002225', + '\\' : '\U000000a6', + '\\' : '\U000000b1', + '\\' : '\U00002213', + '\\' : '\U000000d7', + '\\
' : '\U000000f7', + '\\' : '\U000022c5', + '\\' : '\U000022c6', + '\\' : '\U00002219', + '\\' : '\U00002218', + '\\' : '\U00002020', + '\\' : '\U00002021', + '\\' : '\U000022b2', + '\\' : '\U000022b3', + '\\' : '\U000022b4', + '\\' : '\U000022b5', + '\\' : '\U000025c3', + '\\' : '\U000025b9', + '\\' : '\U000025b3', + '\\' : '\U0000225c', + '\\' : '\U00002295', + '\\' : '\U00002a01', + '\\' : '\U00002297', + '\\' : '\U00002a02', + '\\' : '\U00002299', + '\\' : '\U00002a00', + '\\' : '\U00002296', + '\\' : '\U00002298', + '\\' : '\U00002026', + '\\' : '\U000022ef', + '\\' : '\U00002211', + '\\' : '\U0000220f', + '\\' : '\U00002210', + '\\' : '\U0000221e', + '\\' : '\U0000222b', + '\\' : '\U0000222e', + '\\' : '\U00002663', + '\\' : '\U00002662', + '\\' : '\U00002661', + '\\' : '\U00002660', + '\\' : '\U00002135', + '\\' : '\U00002205', + '\\' : '\U00002207', + '\\' : '\U00002202', + '\\' : '\U0000266d', + '\\' : '\U0000266e', + '\\' : '\U0000266f', + '\\' : '\U00002220', + '\\' : '\U000000a9', + '\\' : '\U000000ae', + '\\' : '\U000000ad', + '\\' : '\U000000af', + '\\' : '\U000000bc', + '\\' : '\U000000bd', + '\\' : '\U000000be', + '\\' : '\U000000aa', + '\\' : '\U000000ba', + '\\
' : '\U000000a7', + '\\' : '\U000000b6', + '\\' : '\U000000a1', + '\\' : '\U000000bf', + '\\' : '\U000020ac', + '\\' : '\U000000a3', + '\\' : '\U000000a5', + '\\' : '\U000000a2', + '\\' : '\U000000a4', + '\\' : '\U000000b0', + '\\' : '\U00002a3f', + '\\' : '\U00002127', + '\\' : '\U000025ca', + '\\' : '\U00002118', + '\\' : '\U00002240', + '\\' : '\U000022c4', + '\\' : '\U000000b4', + '\\' : '\U00000131', + '\\' : '\U000000a8', + '\\' : '\U000000b8', + '\\' : '\U000002dd', + '\\' : '\U000003f5', + '\\' : '\U000023ce', + '\\' : '\U00002039', + '\\' : '\U0000203a', + '\\' : '\U00002302', + '\\<^sub>' : '\U000021e9', + '\\<^sup>' : '\U000021e7', + '\\<^bold>' : '\U00002759', + '\\<^bsub>' : '\U000021d8', + '\\<^esub>' : '\U000021d9', + '\\<^bsup>' : '\U000021d7', + '\\<^esup>' : '\U000021d6', + } + + lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols} + + def __init__(self, **options): + Filter.__init__(self, **options) + lang = get_choice_opt(options, 'lang', + ['isabelle', 'latex'], 'isabelle') + self.symbols = self.lang_map[lang] + + def filter(self, lexer, stream): + for ttype, value in stream: + if value in self.symbols: + yield ttype, self.symbols[value] + else: + yield ttype, value + + +class KeywordCaseFilter(Filter): + """Convert keywords to lowercase or uppercase or capitalize them. + + This means first letter uppercase, rest lowercase. + + This can be useful e.g. if you highlight Pascal code and want to adapt the + code to your styleguide. + + Options accepted: + + `case` : string + The casing to convert keywords to. Must be one of ``'lower'``, + ``'upper'`` or ``'capitalize'``. The default is ``'lower'``. + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + case = get_choice_opt(options, 'case', + ['lower', 'upper', 'capitalize'], 'lower') + self.convert = getattr(str, case) + + def filter(self, lexer, stream): + for ttype, value in stream: + if ttype in Keyword: + yield ttype, self.convert(value) + else: + yield ttype, value + + +class NameHighlightFilter(Filter): + """Highlight a normal Name (and Name.*) token with a different token type. + + Example:: + + filter = NameHighlightFilter( + names=['foo', 'bar', 'baz'], + tokentype=Name.Function, + ) + + This would highlight the names "foo", "bar" and "baz" + as functions. `Name.Function` is the default token type. + + Options accepted: + + `names` : list of strings + A list of names that should be given the different token type. + There is no default. + `tokentype` : TokenType or string + A token type or a string containing a token type name that is + used for highlighting the strings in `names`. The default is + `Name.Function`. + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + self.names = set(get_list_opt(options, 'names', [])) + tokentype = options.get('tokentype') + if tokentype: + self.tokentype = string_to_tokentype(tokentype) + else: + self.tokentype = Name.Function + + def filter(self, lexer, stream): + for ttype, value in stream: + if ttype in Name and value in self.names: + yield self.tokentype, value + else: + yield ttype, value + + +class ErrorToken(Exception): + pass + + +class RaiseOnErrorTokenFilter(Filter): + """Raise an exception when the lexer generates an error token. + + Options accepted: + + `excclass` : Exception class + The exception class to raise. + The default is `pygments.filters.ErrorToken`. + + .. versionadded:: 0.8 + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + self.exception = options.get('excclass', ErrorToken) + try: + # issubclass() will raise TypeError if first argument is not a class + if not issubclass(self.exception, Exception): + raise TypeError + except TypeError: + raise OptionError('excclass option is not an exception class') + + def filter(self, lexer, stream): + for ttype, value in stream: + if ttype is Error: + raise self.exception(value) + yield ttype, value + + +class VisibleWhitespaceFilter(Filter): + """Convert tabs, newlines and/or spaces to visible characters. + + Options accepted: + + `spaces` : string or bool + If this is a one-character string, spaces will be replaces by this string. + If it is another true value, spaces will be replaced by ``·`` (unicode + MIDDLE DOT). If it is a false value, spaces will not be replaced. The + default is ``False``. + `tabs` : string or bool + The same as for `spaces`, but the default replacement character is ``»`` + (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value + is ``False``. Note: this will not work if the `tabsize` option for the + lexer is nonzero, as tabs will already have been expanded then. + `tabsize` : int + If tabs are to be replaced by this filter (see the `tabs` option), this + is the total number of characters that a tab should be expanded to. + The default is ``8``. + `newlines` : string or bool + The same as for `spaces`, but the default replacement character is ``¶`` + (unicode PILCROW SIGN). The default value is ``False``. + `wstokentype` : bool + If true, give whitespace the special `Whitespace` token type. This allows + styling the visible whitespace differently (e.g. greyed out), but it can + disrupt background colors. The default is ``True``. + + .. versionadded:: 0.8 + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + for name, default in [('spaces', '·'), + ('tabs', '»'), + ('newlines', '¶')]: + opt = options.get(name, False) + if isinstance(opt, str) and len(opt) == 1: + setattr(self, name, opt) + else: + setattr(self, name, (opt and default or '')) + tabsize = get_int_opt(options, 'tabsize', 8) + if self.tabs: + self.tabs += ' ' * (tabsize - 1) + if self.newlines: + self.newlines += '\n' + self.wstt = get_bool_opt(options, 'wstokentype', True) + + def filter(self, lexer, stream): + if self.wstt: + spaces = self.spaces or ' ' + tabs = self.tabs or '\t' + newlines = self.newlines or '\n' + regex = re.compile(r'\s') + + def replacefunc(wschar): + if wschar == ' ': + return spaces + elif wschar == '\t': + return tabs + elif wschar == '\n': + return newlines + return wschar + + for ttype, value in stream: + yield from _replace_special(ttype, value, regex, Whitespace, + replacefunc) + else: + spaces, tabs, newlines = self.spaces, self.tabs, self.newlines + # simpler processing + for ttype, value in stream: + if spaces: + value = value.replace(' ', spaces) + if tabs: + value = value.replace('\t', tabs) + if newlines: + value = value.replace('\n', newlines) + yield ttype, value + + +class GobbleFilter(Filter): + """Gobble source code lines (eats initial characters). + + This filter drops the first ``n`` characters off every line of code. This + may be useful when the source code fed to the lexer is indented by a fixed + amount of space that isn't desired in the output. + + Options accepted: + + `n` : int + The number of characters to gobble. + + .. versionadded:: 1.2 + """ + def __init__(self, **options): + Filter.__init__(self, **options) + self.n = get_int_opt(options, 'n', 0) + + def gobble(self, value, left): + if left < len(value): + return value[left:], 0 + else: + return '', left - len(value) + + def filter(self, lexer, stream): + n = self.n + left = n # How many characters left to gobble. + for ttype, value in stream: + # Remove ``left`` tokens from first line, ``n`` from all others. + parts = value.split('\n') + (parts[0], left) = self.gobble(parts[0], left) + for i in range(1, len(parts)): + (parts[i], left) = self.gobble(parts[i], n) + value = '\n'.join(parts) + + if value != '': + yield ttype, value + + +class TokenMergeFilter(Filter): + """Merge consecutive tokens with the same token type in the output stream. + + .. versionadded:: 1.2 + """ + def __init__(self, **options): + Filter.__init__(self, **options) + + def filter(self, lexer, stream): + current_type = None + current_value = None + for ttype, value in stream: + if ttype is current_type: + current_value += value + else: + if current_type is not None: + yield current_type, current_value + current_type = ttype + current_value = value + if current_type is not None: + yield current_type, current_value + + +FILTERS = { + 'codetagify': CodeTagFilter, + 'keywordcase': KeywordCaseFilter, + 'highlight': NameHighlightFilter, + 'raiseonerror': RaiseOnErrorTokenFilter, + 'whitespace': VisibleWhitespaceFilter, + 'gobble': GobbleFilter, + 'tokenmerge': TokenMergeFilter, + 'symbols': SymbolFilter, +} diff --git a/lib/python3.11/site-packages/pygments/filters/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/pygments/filters/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3897e3b50f52068fb65ade1bbe0537f2b9654303 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/filters/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatter.py b/lib/python3.11/site-packages/pygments/formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa603d551c99fab81f2aa29037c3b8b89d0fcd5 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/formatter.py @@ -0,0 +1,129 @@ +""" + pygments.formatter + ~~~~~~~~~~~~~~~~~~ + + Base formatter class. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import codecs + +from pygments.util import get_bool_opt +from pygments.styles import get_style_by_name + +__all__ = ['Formatter'] + + +def _lookup_style(style): + if isinstance(style, str): + return get_style_by_name(style) + return style + + +class Formatter: + """ + Converts a token stream to text. + + Formatters should have attributes to help selecting them. These + are similar to the corresponding :class:`~pygments.lexer.Lexer` + attributes. + + .. autoattribute:: name + :no-value: + + .. autoattribute:: aliases + :no-value: + + .. autoattribute:: filenames + :no-value: + + You can pass options as keyword arguments to the constructor. + All formatters accept these basic options: + + ``style`` + The style to use, can be a string or a Style subclass + (default: "default"). Not used by e.g. the + TerminalFormatter. + ``full`` + Tells the formatter to output a "full" document, i.e. + a complete self-contained document. This doesn't have + any effect for some formatters (default: false). + ``title`` + If ``full`` is true, the title that should be used to + caption the document (default: ''). + ``encoding`` + If given, must be an encoding name. This will be used to + convert the Unicode token strings to byte strings in the + output. If it is "" or None, Unicode strings will be written + to the output file, which most file-like objects do not + support (default: None). + ``outencoding`` + Overrides ``encoding`` if given. + + """ + + #: Full name for the formatter, in human-readable form. + name = None + + #: A list of short, unique identifiers that can be used to lookup + #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`. + aliases = [] + + #: A list of fnmatch patterns that match filenames for which this + #: formatter can produce output. The patterns in this list should be unique + #: among all formatters. + filenames = [] + + #: If True, this formatter outputs Unicode strings when no encoding + #: option is given. + unicodeoutput = True + + def __init__(self, **options): + """ + As with lexers, this constructor takes arbitrary optional arguments, + and if you override it, you should first process your own options, then + call the base class implementation. + """ + self.style = _lookup_style(options.get('style', 'default')) + self.full = get_bool_opt(options, 'full', False) + self.title = options.get('title', '') + self.encoding = options.get('encoding', None) or None + if self.encoding in ('guess', 'chardet'): + # can happen for e.g. pygmentize -O encoding=guess + self.encoding = 'utf-8' + self.encoding = options.get('outencoding') or self.encoding + self.options = options + + def get_style_defs(self, arg=''): + """ + This method must return statements or declarations suitable to define + the current style for subsequent highlighted text (e.g. CSS classes + in the `HTMLFormatter`). + + The optional argument `arg` can be used to modify the generation and + is formatter dependent (it is standardized because it can be given on + the command line). + + This method is called by the ``-S`` :doc:`command-line option `, + the `arg` is then given by the ``-a`` option. + """ + return '' + + def format(self, tokensource, outfile): + """ + This method must format the tokens from the `tokensource` iterable and + write the formatted version to the file object `outfile`. + + Formatter options can control how exactly the tokens are converted. + """ + if self.encoding: + # wrap the outfile in a StreamWriter + outfile = codecs.lookup(self.encoding)[3](outfile) + return self.format_unencoded(tokensource, outfile) + + # Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to + # Formatter. This helps when using third-party type stubs from typeshed. + def __class_getitem__(cls, name): + return cls diff --git a/lib/python3.11/site-packages/pygments/formatters/__init__.py b/lib/python3.11/site-packages/pygments/formatters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..829496dc97e147d159e106ddc12a49e8e416faf1 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/formatters/__init__.py @@ -0,0 +1,157 @@ +""" + pygments.formatters + ~~~~~~~~~~~~~~~~~~~ + + Pygments formatters. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re +import sys +import types +import fnmatch +from os.path import basename + +from pygments.formatters._mapping import FORMATTERS +from pygments.plugin import find_plugin_formatters +from pygments.util import ClassNotFound + +__all__ = ['get_formatter_by_name', 'get_formatter_for_filename', + 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS) + +_formatter_cache = {} # classes by name +_pattern_cache = {} + + +def _fn_matches(fn, glob): + """Return whether the supplied file name fn matches pattern filename.""" + if glob not in _pattern_cache: + pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob)) + return pattern.match(fn) + return _pattern_cache[glob].match(fn) + + +def _load_formatters(module_name): + """Load a formatter (and all others in the module too).""" + mod = __import__(module_name, None, None, ['__all__']) + for formatter_name in mod.__all__: + cls = getattr(mod, formatter_name) + _formatter_cache[cls.name] = cls + + +def get_all_formatters(): + """Return a generator for all formatter classes.""" + # NB: this returns formatter classes, not info like get_all_lexers(). + for info in FORMATTERS.values(): + if info[1] not in _formatter_cache: + _load_formatters(info[0]) + yield _formatter_cache[info[1]] + for _, formatter in find_plugin_formatters(): + yield formatter + + +def find_formatter_class(alias): + """Lookup a formatter by alias. + + Returns None if not found. + """ + for module_name, name, aliases, _, _ in FORMATTERS.values(): + if alias in aliases: + if name not in _formatter_cache: + _load_formatters(module_name) + return _formatter_cache[name] + for _, cls in find_plugin_formatters(): + if alias in cls.aliases: + return cls + + +def get_formatter_by_name(_alias, **options): + """ + Return an instance of a :class:`.Formatter` subclass that has `alias` in its + aliases list. The formatter is given the `options` at its instantiation. + + Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that + alias is found. + """ + cls = find_formatter_class(_alias) + if cls is None: + raise ClassNotFound(f"no formatter found for name {_alias!r}") + return cls(**options) + + +def load_formatter_from_file(filename, formattername="CustomFormatter", **options): + """ + Return a `Formatter` subclass instance loaded from the provided file, relative + to the current directory. + + The file is expected to contain a Formatter class named ``formattername`` + (by default, CustomFormatter). Users should be very careful with the input, because + this method is equivalent to running ``eval()`` on the input file. The formatter is + given the `options` at its instantiation. + + :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading + the formatter. + + .. versionadded:: 2.2 + """ + try: + # This empty dict will contain the namespace for the exec'd file + custom_namespace = {} + with open(filename, 'rb') as f: + exec(f.read(), custom_namespace) + # Retrieve the class `formattername` from that namespace + if formattername not in custom_namespace: + raise ClassNotFound(f'no valid {formattername} class found in {filename}') + formatter_class = custom_namespace[formattername] + # And finally instantiate it with the options + return formatter_class(**options) + except OSError as err: + raise ClassNotFound(f'cannot read {filename}: {err}') + except ClassNotFound: + raise + except Exception as err: + raise ClassNotFound(f'error when loading custom formatter: {err}') + + +def get_formatter_for_filename(fn, **options): + """ + Return a :class:`.Formatter` subclass instance that has a filename pattern + matching `fn`. The formatter is given the `options` at its instantiation. + + Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename + is found. + """ + fn = basename(fn) + for modname, name, _, filenames, _ in FORMATTERS.values(): + for filename in filenames: + if _fn_matches(fn, filename): + if name not in _formatter_cache: + _load_formatters(modname) + return _formatter_cache[name](**options) + for _name, cls in find_plugin_formatters(): + for filename in cls.filenames: + if _fn_matches(fn, filename): + return cls(**options) + raise ClassNotFound(f"no formatter found for file name {fn!r}") + + +class _automodule(types.ModuleType): + """Automatically import formatters.""" + + def __getattr__(self, name): + info = FORMATTERS.get(name) + if info: + _load_formatters(info[0]) + cls = _formatter_cache[info[1]] + setattr(self, name, cls) + return cls + raise AttributeError(name) + + +oldmod = sys.modules[__name__] +newmod = _automodule(__name__) +newmod.__dict__.update(oldmod.__dict__) +sys.modules[__name__] = newmod +del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6edc6d5e2f5c4e8bf6f2fd9d8b5056fe73456d5b Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/__init__.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/_mapping.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/_mapping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa5c3bb98f909c5f457c716aa7389e0aa6f7c454 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/_mapping.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/bbcode.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/bbcode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f54fe048fe9cdb232fa9fb059996cbb3b1b2e652 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/bbcode.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/groff.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/groff.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..040588b64f768d4c48fcbec77ebfe84fe079b20c Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/groff.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/html.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/html.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fe6eb276e0048a11a31fc74a75a6c4e4a9e25f3 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/html.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/img.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/img.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbd4a32508b65d942aad5a8fe13258e3949a9a34 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/img.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/irc.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/irc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eca12be58da9cdcdffa5ab91385b75cee0deb03d Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/irc.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/latex.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/latex.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73f961ee4f89c8252d02949f85b9cc4be8a5dcc7 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/latex.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/other.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/other.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9500c15f5ca2d93838f0f32825e95de6e420e16 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/other.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/pangomarkup.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/pangomarkup.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a73de095f54cfab009bb50f56ec94206f4e490a Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/pangomarkup.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/rtf.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/rtf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6cc8e3eb242acc10cd1375b558ad6c18d4bd030 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/rtf.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/svg.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/svg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..742346a078f3d88c053f24638224af76da3b4d6b Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/svg.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/terminal.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/terminal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4319c86f73bc894626256ad4b920653ee195eef6 Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/terminal.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/__pycache__/terminal256.cpython-311.pyc b/lib/python3.11/site-packages/pygments/formatters/__pycache__/terminal256.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4cefb08b9f53bf59c978ba0eac0a66324243fcb Binary files /dev/null and b/lib/python3.11/site-packages/pygments/formatters/__pycache__/terminal256.cpython-311.pyc differ diff --git a/lib/python3.11/site-packages/pygments/formatters/_mapping.py b/lib/python3.11/site-packages/pygments/formatters/_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..72ca84040b626183e3328679db600c13472021be --- /dev/null +++ b/lib/python3.11/site-packages/pygments/formatters/_mapping.py @@ -0,0 +1,23 @@ +# Automatically generated by scripts/gen_mapfiles.py. +# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead. + +FORMATTERS = { + 'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'), + 'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), + 'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), + 'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'), + 'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ```` tags. By default, the content is enclosed in a ``
`` tag, itself wrapped in a ``
`` tag (but see the `nowrap` option). The ``
``'s CSS class can be set by the `cssclass` option."), + 'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'), + 'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), + 'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), + 'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'), + 'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'), + 'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'), + 'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'), + 'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'), + 'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a ```` element with explicit ``x`` and ``y`` coordinates containing ```` elements with the individual token styles.'), + 'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'), + 'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'), + 'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'), + 'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'), +} diff --git a/lib/python3.11/site-packages/pygments/formatters/bbcode.py b/lib/python3.11/site-packages/pygments/formatters/bbcode.py new file mode 100644 index 0000000000000000000000000000000000000000..90d8d806f202e9dff22e33c431f3e35cefdd6642 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/formatters/bbcode.py @@ -0,0 +1,108 @@ +""" + pygments.formatters.bbcode + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + BBcode formatter. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + + +from pygments.formatter import Formatter +from pygments.util import get_bool_opt + +__all__ = ['BBCodeFormatter'] + + +class BBCodeFormatter(Formatter): + """ + Format tokens with BBcodes. These formatting codes are used by many + bulletin boards, so you can highlight your sourcecode with pygments before + posting it there. + + This formatter has no support for background colors and borders, as there + are no common BBcode tags for that. + + Some board systems (e.g. phpBB) don't support colors in their [code] tag, + so you can't use the highlighting together with that tag. + Text in a [code] tag usually is shown with a monospace font (which this + formatter can do with the ``monofont`` option) and no spaces (which you + need for indentation) are removed. + + Additional options accepted: + + `style` + The style to use, can be a string or a Style subclass (default: + ``'default'``). + + `codetag` + If set to true, put the output into ``[code]`` tags (default: + ``false``) + + `monofont` + If set to true, add a tag to show the code with a monospace font + (default: ``false``). + """ + name = 'BBCode' + aliases = ['bbcode', 'bb'] + filenames = [] + + def __init__(self, **options): + Formatter.__init__(self, **options) + self._code = get_bool_opt(options, 'codetag', False) + self._mono = get_bool_opt(options, 'monofont', False) + + self.styles = {} + self._make_styles() + + def _make_styles(self): + for ttype, ndef in self.style: + start = end = '' + if ndef['color']: + start += '[color=#{}]'.format(ndef['color']) + end = '[/color]' + end + if ndef['bold']: + start += '[b]' + end = '[/b]' + end + if ndef['italic']: + start += '[i]' + end = '[/i]' + end + if ndef['underline']: + start += '[u]' + end = '[/u]' + end + # there are no common BBcodes for background-color and border + + self.styles[ttype] = start, end + + def format_unencoded(self, tokensource, outfile): + if self._code: + outfile.write('[code]') + if self._mono: + outfile.write('[font=monospace]') + + lastval = '' + lasttype = None + + for ttype, value in tokensource: + while ttype not in self.styles: + ttype = ttype.parent + if ttype == lasttype: + lastval += value + else: + if lastval: + start, end = self.styles[lasttype] + outfile.write(''.join((start, lastval, end))) + lastval = value + lasttype = ttype + + if lastval: + start, end = self.styles[lasttype] + outfile.write(''.join((start, lastval, end))) + + if self._mono: + outfile.write('[/font]') + if self._code: + outfile.write('[/code]') + if self._code or self._mono: + outfile.write('\n') diff --git a/lib/python3.11/site-packages/pygments/formatters/groff.py b/lib/python3.11/site-packages/pygments/formatters/groff.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d3146b45b0103dbad53aa2822757b8102d1c42 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/formatters/groff.py @@ -0,0 +1,170 @@ +""" + pygments.formatters.groff + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Formatter for groff output. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import math +from pygments.formatter import Formatter +from pygments.util import get_bool_opt, get_int_opt + +__all__ = ['GroffFormatter'] + + +class GroffFormatter(Formatter): + """ + Format tokens with groff escapes to change their color and font style. + + .. versionadded:: 2.11 + + Additional options accepted: + + `style` + The style to use, can be a string or a Style subclass (default: + ``'default'``). + + `monospaced` + If set to true, monospace font will be used (default: ``true``). + + `linenos` + If set to true, print the line numbers (default: ``false``). + + `wrap` + Wrap lines to the specified number of characters. Disabled if set to 0 + (default: ``0``). + """ + + name = 'groff' + aliases = ['groff','troff','roff'] + filenames = [] + + def __init__(self, **options): + Formatter.__init__(self, **options) + + self.monospaced = get_bool_opt(options, 'monospaced', True) + self.linenos = get_bool_opt(options, 'linenos', False) + self._lineno = 0 + self.wrap = get_int_opt(options, 'wrap', 0) + self._linelen = 0 + + self.styles = {} + self._make_styles() + + + def _make_styles(self): + regular = '\\f[CR]' if self.monospaced else '\\f[R]' + bold = '\\f[CB]' if self.monospaced else '\\f[B]' + italic = '\\f[CI]' if self.monospaced else '\\f[I]' + + for ttype, ndef in self.style: + start = end = '' + if ndef['color']: + start += '\\m[{}]'.format(ndef['color']) + end = '\\m[]' + end + if ndef['bold']: + start += bold + end = regular + end + if ndef['italic']: + start += italic + end = regular + end + if ndef['bgcolor']: + start += '\\M[{}]'.format(ndef['bgcolor']) + end = '\\M[]' + end + + self.styles[ttype] = start, end + + + def _define_colors(self, outfile): + colors = set() + for _, ndef in self.style: + if ndef['color'] is not None: + colors.add(ndef['color']) + + for color in sorted(colors): + outfile.write('.defcolor ' + color + ' rgb #' + color + '\n') + + + def _write_lineno(self, outfile): + self._lineno += 1 + outfile.write("%s% 4d " % (self._lineno != 1 and '\n' or '', self._lineno)) + + + def _wrap_line(self, line): + length = len(line.rstrip('\n')) + space = ' ' if self.linenos else '' + newline = '' + + if length > self.wrap: + for i in range(0, math.floor(length / self.wrap)): + chunk = line[i*self.wrap:i*self.wrap+self.wrap] + newline += (chunk + '\n' + space) + remainder = length % self.wrap + if remainder > 0: + newline += line[-remainder-1:] + self._linelen = remainder + elif self._linelen + length > self.wrap: + newline = ('\n' + space) + line + self._linelen = length + else: + newline = line + self._linelen += length + + return newline + + + def _escape_chars(self, text): + text = text.replace('\\', '\\[u005C]'). \ + replace('.', '\\[char46]'). \ + replace('\'', '\\[u0027]'). \ + replace('`', '\\[u0060]'). \ + replace('~', '\\[u007E]') + copy = text + + for char in copy: + if len(char) != len(char.encode()): + uni = char.encode('unicode_escape') \ + .decode()[1:] \ + .replace('x', 'u00') \ + .upper() + text = text.replace(char, '\\[u' + uni[1:] + ']') + + return text + + + def format_unencoded(self, tokensource, outfile): + self._define_colors(outfile) + + outfile.write('.nf\n\\f[CR]\n') + + if self.linenos: + self._write_lineno(outfile) + + for ttype, value in tokensource: + while ttype not in self.styles: + ttype = ttype.parent + start, end = self.styles[ttype] + + for line in value.splitlines(True): + if self.wrap > 0: + line = self._wrap_line(line) + + if start and end: + text = self._escape_chars(line.rstrip('\n')) + if text != '': + outfile.write(''.join((start, text, end))) + else: + outfile.write(self._escape_chars(line.rstrip('\n'))) + + if line.endswith('\n'): + if self.linenos: + self._write_lineno(outfile) + self._linelen = 0 + else: + outfile.write('\n') + self._linelen = 0 + + outfile.write('\n.fi') diff --git a/lib/python3.11/site-packages/pygments/formatters/html.py b/lib/python3.11/site-packages/pygments/formatters/html.py new file mode 100644 index 0000000000000000000000000000000000000000..17e67414520e016127fba1541207f23c19a0d187 --- /dev/null +++ b/lib/python3.11/site-packages/pygments/formatters/html.py @@ -0,0 +1,997 @@ +""" + pygments.formatters.html + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Formatter for HTML output. + + :copyright: Copyright 2006-present by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import functools +import os +import sys +import os.path +from io import StringIO + +from pygments.formatter import Formatter +from pygments.token import Token, Text, STANDARD_TYPES +from pygments.util import get_bool_opt, get_int_opt, get_list_opt + +import html + +try: + import ctags +except ImportError: + ctags = None + +__all__ = ['HtmlFormatter'] + + +_escape_html_table = { + ord('&'): '&', + ord('<'): '<', + ord('>'): '>', + ord('"'): '"', + ord("'"): ''', +} + + +def escape_html(text, table=_escape_html_table): + """Escape &, <, > as well as single and double quotes for HTML.""" + return text.translate(table) + + +def webify(color): + if color.startswith('calc') or color.startswith('var'): + return color + else: + # Check if the color can be shortened from 6 to 3 characters + color = color.upper() + if (len(color) == 6 and + ( color[0] == color[1] + and color[2] == color[3] + and color[4] == color[5])): + return f'#{color[0]}{color[2]}{color[4]}' + else: + return f'#{color}' + + +def _get_ttype_class(ttype): + fname = STANDARD_TYPES.get(ttype) + if fname: + return fname + aname = '' + while fname is None: + aname = '-' + ttype[-1] + aname + ttype = ttype.parent + fname = STANDARD_TYPES.get(ttype) + return fname + aname + + +CSSFILE_TEMPLATE = '''\ +/* +generated by Pygments +Copyright 2006-present by the Pygments team. +Licensed under the BSD license, see LICENSE for details. +*/ +%(styledefs)s +''' + +DOC_HEADER = '''\ + + + + + %(title)s + + + + +

%(title)s

+ +''' + +DOC_HEADER_EXTERNALCSS = '''\ + + + + + %(title)s + + + + +

%(title)s

+ +''' + +DOC_FOOTER = '''\ + + +''' + + +class HtmlFormatter(Formatter): + r""" + Format tokens as HTML 4 ```` tags. By default, the content is enclosed + in a ``
`` tag, itself wrapped in a ``
`` tag (but see the `nowrap` option). + The ``
``'s CSS class can be set by the `cssclass` option. + + If the `linenos` option is set to ``"table"``, the ``
`` is
+    additionally wrapped inside a ```` which has one row and two
+    cells: one containing the line numbers and one containing the code.
+    Example:
+
+    .. sourcecode:: html
+
+        
+
+ + +
+
1
+            2
+
+
def foo(bar):
+              pass
+            
+
+ + (whitespace added to improve clarity). + + A list of lines can be specified using the `hl_lines` option to make these + lines highlighted (as of Pygments 0.11). + + With the `full` option, a complete HTML 4 document is output, including + the style definitions inside a ``$)', _handle_cssblock), + + include('keywords'), + include('inline'), + ], + 'keywords': [ + (words(( + '\\define', '\\end', 'caption', 'created', 'modified', 'tags', + 'title', 'type'), prefix=r'^', suffix=r'\b'), + Keyword), + ], + 'inline': [ + # escape + (r'\\.', Text), + # created or modified date + (r'\d{17}', Number.Integer), + # italics + (r'(\s)(//[^/]+//)((?=\W|\n))', + bygroups(Text, Generic.Emph, Text)), + # superscript + (r'(\s)(\^\^[^\^]+\^\^)', bygroups(Text, Generic.Emph)), + # subscript + (r'(\s)(,,[^,]+,,)', bygroups(Text, Generic.Emph)), + # underscore + (r'(\s)(__[^_]+__)', bygroups(Text, Generic.Strong)), + # bold + (r"(\s)(''[^']+'')((?=\W|\n))", + bygroups(Text, Generic.Strong, Text)), + # strikethrough + (r'(\s)(~~[^~]+~~)((?=\W|\n))', + bygroups(Text, Generic.Deleted, Text)), + # TiddlyWiki variables + (r'<<[^>]+>>', Name.Tag), + (r'\$\$[^$]+\$\$', Name.Tag), + (r'\$\([^)]+\)\$', Name.Tag), + # TiddlyWiki style or class + (r'^@@.*$', Name.Tag), + # HTML tags + (r']+>', Name.Tag), + # inline code + (r'`[^`]+`', String.Backtick), + # HTML escaped symbols + (r'&\S*?;', String.Regex), + # Wiki links + (r'(\[{2})([^]\|]+)(\]{2})', bygroups(Text, Name.Tag, Text)), + # External links + (r'(\[{2})([^]\|]+)(\|)([^]\|]+)(\]{2})', + bygroups(Text, Name.Tag, Text, Name.Attribute, Text)), + # Transclusion + (r'(\{{2})([^}]+)(\}{2})', bygroups(Text, Name.Tag, Text)), + # URLs + (r'(\b.?.?tps?://[^\s"]+)', bygroups(Name.Attribute)), + + # general text, must come last! + (r'[\w]+', Text), + (r'.', Text) + ], + } + + def __init__(self, **options): + self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True) + RegexLexer.__init__(self, **options) + + +class WikitextLexer(RegexLexer): + """ + For MediaWiki Wikitext. + + Parsing Wikitext is tricky, and results vary between different MediaWiki + installations, so we only highlight common syntaxes (built-in or from + popular extensions), and also assume templates produce no unbalanced + syntaxes. + """ + name = 'Wikitext' + url = 'https://www.mediawiki.org/wiki/Wikitext' + aliases = ['wikitext', 'mediawiki'] + filenames = [] + mimetypes = ['text/x-wiki'] + version_added = '2.15' + flags = re.MULTILINE + + def nowiki_tag_rules(tag_name): + return [ + (rf'(?i)()', bygroups(Punctuation, + Name.Tag, Whitespace, Punctuation), '#pop'), + include('entity'), + include('text'), + ] + + def plaintext_tag_rules(tag_name): + return [ + (rf'(?si)(.*?)()', bygroups(Text, + Punctuation, Name.Tag, Whitespace, Punctuation), '#pop'), + ] + + def delegate_tag_rules(tag_name, lexer, **lexer_kwargs): + return [ + (rf'(?i)()', bygroups(Punctuation, + Name.Tag, Whitespace, Punctuation), '#pop'), + (rf'(?si).+?(?=)', using(lexer, **lexer_kwargs)), + ] + + def text_rules(token): + return [ + (r'\w+', token), + (r'[^\S\n]+', token), + (r'(?s).', token), + ] + + def handle_syntaxhighlight(self, match, ctx): + from pygments.lexers import get_lexer_by_name + + attr_content = match.group() + start = 0 + index = 0 + while True: + index = attr_content.find('>', start) + # Exclude comment end (-->) + if attr_content[index-2:index] != '--': + break + start = index + 1 + + if index == -1: + # No tag end + yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr']) + return + attr = attr_content[:index] + yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr']) + yield match.start(3) + index, Punctuation, '>' + + lexer = None + content = attr_content[index+1:] + lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr) + + if len(lang_match) >= 1: + # Pick the last match in case of multiple matches + lang = lang_match[-1][1] + try: + lexer = get_lexer_by_name(lang) + except ClassNotFound: + pass + + if lexer is None: + yield match.start() + index + 1, Text, content + else: + yield from lexer.get_tokens_unprocessed(content) + + def handle_score(self, match, ctx): + attr_content = match.group() + start = 0 + index = 0 + while True: + index = attr_content.find('>', start) + # Exclude comment end (-->) + if attr_content[index-2:index] != '--': + break + start = index + 1 + + if index == -1: + # No tag end + yield from self.get_tokens_unprocessed(attr_content, stack=['root', 'attr']) + return + attr = attr_content[:index] + content = attr_content[index+1:] + yield from self.get_tokens_unprocessed(attr, stack=['root', 'attr']) + yield match.start(3) + index, Punctuation, '>' + + lang_match = re.findall(r'\blang=("|\'|)(\w+)(\1)', attr) + # Pick the last match in case of multiple matches + lang = lang_match[-1][1] if len(lang_match) >= 1 else 'lilypond' + + if lang == 'lilypond': # Case sensitive + yield from LilyPondLexer().get_tokens_unprocessed(content) + else: # ABC + # FIXME: Use ABC lexer in the future + yield match.start() + index + 1, Text, content + + # a-z removed to prevent linter from complaining, REMEMBER to use (?i) + title_char = r' %!"$&\'()*,\-./0-9:;=?@A-Z\\\^_`~+\u0080-\uFFFF' + nbsp_char = r'(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000])' + link_address = r'(?:[0-9.]+|\[[0-9a-f:.]+\]|[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD])' + link_char_class = r'[^\x00-\x20"<>\[\]\x7F\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFFFD]' + double_slashes_i = { + '__FORCETOC__', '__NOCONTENTCONVERT__', '__NOCC__', '__NOEDITSECTION__', '__NOGALLERY__', + '__NOTITLECONVERT__', '__NOTC__', '__NOTOC__', '__TOC__', + } + double_slashes = { + '__EXPECTUNUSEDCATEGORY__', '__HIDDENCAT__', '__INDEX__', '__NEWSECTIONLINK__', + '__NOINDEX__', '__NONEWSECTIONLINK__', '__STATICREDIRECT__', '__NOGLOBAL__', + '__DISAMBIG__', '__EXPECTED_UNCONNECTED_PAGE__', + } + protocols = { + 'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://', 'https://', + 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:', 'nntp://', 'redis://', + 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://', 'svn://', 'tel:', 'telnet://', 'urn:', + 'worldwind://', 'xmpp:', '//', + } + non_relative_protocols = protocols - {'//'} + html_tags = { + 'abbr', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', + 'data', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', + 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'link', 'mark', 'meta', 'ol', 'p', 'q', 'rb', 'rp', + 'rt', 'rtc', 'ruby', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', + 'table', 'td', 'th', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr', + } + parser_tags = { + 'graph', 'charinsert', 'rss', 'chem', 'categorytree', 'nowiki', 'inputbox', 'math', + 'hiero', 'score', 'pre', 'ref', 'translate', 'imagemap', 'templatestyles', 'languages', + 'noinclude', 'mapframe', 'section', 'poem', 'syntaxhighlight', 'includeonly', 'tvar', + 'onlyinclude', 'templatedata', 'langconvert', 'timeline', 'dynamicpagelist', 'gallery', + 'maplink', 'ce', 'references', + } + variant_langs = { + # ZhConverter.php + 'zh', 'zh-hans', 'zh-hant', 'zh-cn', 'zh-hk', 'zh-mo', 'zh-my', 'zh-sg', 'zh-tw', + # WuuConverter.php + 'wuu', 'wuu-hans', 'wuu-hant', + # UzConverter.php + 'uz', 'uz-latn', 'uz-cyrl', + # TlyConverter.php + 'tly', 'tly-cyrl', + # TgConverter.php + 'tg', 'tg-latn', + # SrConverter.php + 'sr', 'sr-ec', 'sr-el', + # ShiConverter.php + 'shi', 'shi-tfng', 'shi-latn', + # ShConverter.php + 'sh-latn', 'sh-cyrl', + # KuConverter.php + 'ku', 'ku-arab', 'ku-latn', + # IuConverter.php + 'iu', 'ike-cans', 'ike-latn', + # GanConverter.php + 'gan', 'gan-hans', 'gan-hant', + # EnConverter.php + 'en', 'en-x-piglatin', + # CrhConverter.php + 'crh', 'crh-cyrl', 'crh-latn', + # BanConverter.php + 'ban', 'ban-bali', 'ban-x-dharma', 'ban-x-palmleaf', 'ban-x-pku', + } + magic_vars_i = { + 'ARTICLEPATH', 'INT', 'PAGEID', 'SCRIPTPATH', 'SERVER', 'SERVERNAME', 'STYLEPATH', + } + magic_vars = { + '!', '=', 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'CONTENTLANGUAGE', + 'CONTENTLANG', 'CURRENTDAY', 'CURRENTDAY2', 'CURRENTDAYNAME', 'CURRENTDOW', 'CURRENTHOUR', + 'CURRENTMONTH', 'CURRENTMONTH2', 'CURRENTMONTH1', 'CURRENTMONTHABBREV', 'CURRENTMONTHNAME', + 'CURRENTMONTHNAMEGEN', 'CURRENTTIME', 'CURRENTTIMESTAMP', 'CURRENTVERSION', 'CURRENTWEEK', + 'CURRENTYEAR', 'DIRECTIONMARK', 'DIRMARK', 'FULLPAGENAME', 'FULLPAGENAMEE', 'LOCALDAY', + 'LOCALDAY2', 'LOCALDAYNAME', 'LOCALDOW', 'LOCALHOUR', 'LOCALMONTH', 'LOCALMONTH2', + 'LOCALMONTH1', 'LOCALMONTHABBREV', 'LOCALMONTHNAME', 'LOCALMONTHNAMEGEN', 'LOCALTIME', + 'LOCALTIMESTAMP', 'LOCALWEEK', 'LOCALYEAR', 'NAMESPACE', 'NAMESPACEE', 'NAMESPACENUMBER', + 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS', 'NUMBEROFARTICLES', 'NUMBEROFEDITS', + 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS', 'PAGELANGUAGE', 'PAGENAME', 'PAGENAMEE', + 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH', 'REVISIONMONTH1', + 'REVISIONSIZE', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME', + 'ROOTPAGENAMEE', 'SITENAME', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE', + 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE', + 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE', + } + parser_functions_i = { + 'ANCHORENCODE', 'BIDI', 'CANONICALURL', 'CANONICALURLE', 'FILEPATH', 'FORMATNUM', + 'FULLURL', 'FULLURLE', 'GENDER', 'GRAMMAR', 'INT', r'\#LANGUAGE', 'LC', 'LCFIRST', 'LOCALURL', + 'LOCALURLE', 'NS', 'NSE', 'PADLEFT', 'PADRIGHT', 'PAGEID', 'PLURAL', 'UC', 'UCFIRST', + 'URLENCODE', + } + parser_functions = { + 'BASEPAGENAME', 'BASEPAGENAMEE', 'CASCADINGSOURCES', 'DEFAULTSORT', 'DEFAULTSORTKEY', + 'DEFAULTCATEGORYSORT', 'FULLPAGENAME', 'FULLPAGENAMEE', 'NAMESPACE', 'NAMESPACEE', + 'NAMESPACENUMBER', 'NUMBERINGROUP', 'NUMINGROUP', 'NUMBEROFACTIVEUSERS', 'NUMBEROFADMINS', + 'NUMBEROFARTICLES', 'NUMBEROFEDITS', 'NUMBEROFFILES', 'NUMBEROFPAGES', 'NUMBEROFUSERS', + 'PAGENAME', 'PAGENAMEE', 'PAGESINCATEGORY', 'PAGESINCAT', 'PAGESIZE', 'PROTECTIONEXPIRY', + 'PROTECTIONLEVEL', 'REVISIONDAY', 'REVISIONDAY2', 'REVISIONID', 'REVISIONMONTH', + 'REVISIONMONTH1', 'REVISIONTIMESTAMP', 'REVISIONUSER', 'REVISIONYEAR', 'ROOTPAGENAME', + 'ROOTPAGENAMEE', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME', 'SUBJECTPAGENAMEE', + 'ARTICLEPAGENAMEE', 'SUBJECTSPACE', 'ARTICLESPACE', 'SUBJECTSPACEE', 'ARTICLESPACEE', + 'SUBPAGENAME', 'SUBPAGENAMEE', 'TALKPAGENAME', 'TALKPAGENAMEE', 'TALKSPACE', 'TALKSPACEE', + 'INT', 'DISPLAYTITLE', 'PAGESINNAMESPACE', 'PAGESINNS', + } + + tokens = { + 'root': [ + # Redirects + (r"""(?xi) + (\A\s*?)(\#REDIRECT:?) # may contain a colon + (\s+)(\[\[) (?=[^\]\n]* \]\]$) + """, + bygroups(Whitespace, Keyword, Whitespace, Punctuation), 'redirect-inner'), + # Subheadings + (r'^(={2,6})(.+?)(\1)(\s*$\n)', + bygroups(Generic.Subheading, Generic.Subheading, Generic.Subheading, Whitespace)), + # Headings + (r'^(=.+?=)(\s*$\n)', + bygroups(Generic.Heading, Whitespace)), + # Double-slashed magic words + (words(double_slashes_i, prefix=r'(?i)'), Name.Function.Magic), + (words(double_slashes), Name.Function.Magic), + # Raw URLs + (r'(?i)\b(?:{}){}{}*'.format('|'.join(protocols), + link_address, link_char_class), Name.Label), + # Magic links + (rf'\b(?:RFC|PMID){nbsp_char}+[0-9]+\b', + Name.Function.Magic), + (r"""(?x) + \bISBN {nbsp_char} + (?: 97[89] {nbsp_dash}? )? + (?: [0-9] {nbsp_dash}? ){{9}} # escape format() + [0-9Xx]\b + """.format(nbsp_char=nbsp_char, nbsp_dash=f'(?:-|{nbsp_char})'), Name.Function.Magic), + include('list'), + include('inline'), + include('text'), + ], + 'redirect-inner': [ + (r'(\]\])(\s*?\n)', bygroups(Punctuation, Whitespace), '#pop'), + (r'(\#)([^#]*?)', bygroups(Punctuation, Name.Label)), + (rf'(?i)[{title_char}]+', Name.Tag), + ], + 'list': [ + # Description lists + (r'^;', Keyword, 'dt'), + # Ordered lists, unordered lists and indents + (r'^[#:*]+', Keyword), + # Horizontal rules + (r'^-{4,}', Keyword), + ], + 'inline': [ + # Signatures + (r'~{3,5}', Keyword), + # Entities + include('entity'), + # Bold & italic + (r"('')(''')(?!')", bygroups(Generic.Emph, + Generic.EmphStrong), 'inline-italic-bold'), + (r"'''(?!')", Generic.Strong, 'inline-bold'), + (r"''(?!')", Generic.Emph, 'inline-italic'), + # Comments & parameters & templates + include('replaceable'), + # Media links + ( + r"""(?xi) + (\[\[) + (File|Image) (:) + ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | )*) + (?: (\#) ([{}]*?) )? + """.format(title_char, f'{title_char}#'), + bygroups(Punctuation, Name.Namespace, Punctuation, + using(this, state=['wikilink-name']), Punctuation, Name.Label), + 'medialink-inner' + ), + # Wikilinks + ( + r"""(?xi) + (\[\[)(?!{}) # Should not contain URLs + (?: ([{}]*) (:))? + ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | )*?) + (?: (\#) ([{}]*?) )? + (\]\]) + """.format('|'.join(protocols), title_char.replace('/', ''), + title_char, f'{title_char}#'), + bygroups(Punctuation, Name.Namespace, Punctuation, + using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation) + ), + ( + r"""(?xi) + (\[\[)(?!{}) + (?: ([{}]*) (:))? + ((?: [{}] | \{{{{2,3}}[^{{}}]*?\}}{{2,3}} | )*?) + (?: (\#) ([{}]*?) )? + (\|) + """.format('|'.join(protocols), title_char.replace('/', ''), + title_char, f'{title_char}#'), + bygroups(Punctuation, Name.Namespace, Punctuation, + using(this, state=['wikilink-name']), Punctuation, Name.Label, Punctuation), + 'wikilink-inner' + ), + # External links + ( + r"""(?xi) + (\[) + ((?:{}) {} {}*) + (\s*) + """.format('|'.join(protocols), link_address, link_char_class), + bygroups(Punctuation, Name.Label, Whitespace), + 'extlink-inner' + ), + # Tables + (r'^(:*)(\s*?)(\{\|)([^\n]*)$', bygroups(Keyword, + Whitespace, Punctuation, using(this, state=['root', 'attr'])), 'table'), + # HTML tags + (r'(?i)(<)({})\b'.format('|'.join(html_tags)), + bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'), + (r'(?i)()'.format('|'.join(html_tags)), + bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)), + # + (r'(?i)(<)(nowiki)\b', bygroups(Punctuation, + Name.Tag), ('tag-nowiki', 'tag-inner')), + #
+            (r'(?i)(<)(pre)\b', bygroups(Punctuation,
+             Name.Tag), ('tag-pre', 'tag-inner')),
+            # 
+            (r'(?i)(<)(categorytree)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-categorytree', 'tag-inner')),
+            # 
+            (r'(?i)(<)(hiero)\b', bygroups(Punctuation,
+             Name.Tag), ('tag-hiero', 'tag-inner')),
+            # 
+            (r'(?i)(<)(math)\b', bygroups(Punctuation,
+             Name.Tag), ('tag-math', 'tag-inner')),
+            # 
+            (r'(?i)(<)(chem)\b', bygroups(Punctuation,
+             Name.Tag), ('tag-chem', 'tag-inner')),
+            # 
+            (r'(?i)(<)(ce)\b', bygroups(Punctuation,
+             Name.Tag), ('tag-ce', 'tag-inner')),
+            # 
+            (r'(?i)(<)(charinsert)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-charinsert', 'tag-inner')),
+            # 
+            (r'(?i)(<)(templatedata)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-templatedata', 'tag-inner')),
+            # 
+            (r'(?i)(<)(gallery)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-gallery', 'tag-inner')),
+            # 
+            (r'(?i)(<)(gallery)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-graph', 'tag-inner')),
+            # 
+            (r'(?i)(<)(dynamicpagelist)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-dynamicpagelist', 'tag-inner')),
+            # 
+            (r'(?i)(<)(inputbox)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-inputbox', 'tag-inner')),
+            # 
+            (r'(?i)(<)(rss)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-rss', 'tag-inner')),
+            # 
+            (r'(?i)(<)(imagemap)\b', bygroups(
+                Punctuation, Name.Tag), ('tag-imagemap', 'tag-inner')),
+            # 
+            (r'(?i)()',
+             bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
+            (r'(?si)(<)(syntaxhighlight)\b([^>]*?(?.*?)(?=)',
+             bygroups(Punctuation, Name.Tag, handle_syntaxhighlight)),
+            # : Fallback case for self-closing tags
+            (r'(?i)(<)(syntaxhighlight)\b(\s*?)((?:[^>]|-->)*?)(/\s*?(?)*?)(/\s*?(?)*?)(/\s*?(?|\Z)', Comment.Multiline),
+            # Parameters
+            (
+                r"""(?x)
+                (\{{3})
+                    ([^|]*?)
+                    (?=\}{3}|\|)
+                """,
+                bygroups(Punctuation, Name.Variable),
+                'parameter-inner',
+            ),
+            # Magic variables
+            (r'(?i)(\{{\{{)(\s*)({})(\s*)(\}}\}})'.format('|'.join(magic_vars_i)),
+             bygroups(Punctuation, Whitespace, Name.Function, Whitespace, Punctuation)),
+            (r'(\{{\{{)(\s*)({})(\s*)(\}}\}})'.format('|'.join(magic_vars)),
+                bygroups(Punctuation, Whitespace, Name.Function, Whitespace, Punctuation)),
+            # Parser functions & templates
+            (r'\{\{', Punctuation, 'template-begin-space'),
+            #  legacy syntax
+            (r'(?i)(<)(tvar)\b(\|)([^>]*?)(>)', bygroups(Punctuation,
+             Name.Tag, Punctuation, String, Punctuation)),
+            (r'', Punctuation, '#pop'),
+            # 
+            (r'(?i)(<)(tvar)\b', bygroups(Punctuation, Name.Tag), 'tag-inner-ordinary'),
+            (r'(?i)()',
+             bygroups(Punctuation, Name.Tag, Whitespace, Punctuation)),
+        ],
+        'parameter-inner': [
+            (r'\}{3}', Punctuation, '#pop'),
+            (r'\|', Punctuation),
+            include('inline'),
+            include('text'),
+        ],
+        'template-begin-space': [
+            # Templates allow line breaks at the beginning, and due to how MediaWiki handles
+            # comments, an extra state is required to handle things like {{\n\n name}}
+            (r'|\Z)', Comment.Multiline),
+            (r'\s+', Whitespace),
+            # Parser functions
+            (
+                r'(?i)(\#[{}]*?|{})(:)'.format(title_char,
+                                           '|'.join(parser_functions_i)),
+                bygroups(Name.Function, Punctuation), ('#pop', 'template-inner')
+            ),
+            (
+                r'({})(:)'.format('|'.join(parser_functions)),
+                bygroups(Name.Function, Punctuation), ('#pop', 'template-inner')
+            ),
+            # Templates
+            (
+                rf'(?i)([{title_char}]*?)(:)',
+                bygroups(Name.Namespace, Punctuation), ('#pop', 'template-name')
+            ),
+            default(('#pop', 'template-name'),),
+        ],
+        'template-name': [
+            (r'(\s*?)(\|)', bygroups(Text, Punctuation), ('#pop', 'template-inner')),
+            (r'\}\}', Punctuation, '#pop'),
+            (r'\n', Text, '#pop'),
+            include('replaceable'),
+            *text_rules(Name.Tag),
+        ],
+        'template-inner': [
+            (r'\}\}', Punctuation, '#pop'),
+            (r'\|', Punctuation),
+            (
+                r"""(?x)
+                    (?<=\|)
+                    ( (?: (?! \{\{ | \}\} )[^=\|<])*? ) # Exclude templates and tags
+                    (=)
+                """,
+                bygroups(Name.Label, Operator)
+            ),
+            include('inline'),
+            include('text'),
+        ],
+        'table': [
+            # Use [ \t\n\r\0\x0B] instead of \s to follow PHP trim() behavior
+            # Endings
+            (r'^([ \t\n\r\0\x0B]*?)(\|\})',
+             bygroups(Whitespace, Punctuation), '#pop'),
+            # Table rows
+            (r'^([ \t\n\r\0\x0B]*?)(\|-+)(.*)$', bygroups(Whitespace, Punctuation,
+             using(this, state=['root', 'attr']))),
+            # Captions
+            (
+                r"""(?x)
+                ^([ \t\n\r\0\x0B]*?)(\|\+)
+                # Exclude links, template and tags
+                (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|) )?
+                (.*?)$
+                """,
+                bygroups(Whitespace, Punctuation, using(this, state=[
+                         'root', 'attr']), Punctuation, Generic.Heading),
+            ),
+            # Table data
+            (
+                r"""(?x)
+                ( ^(?:[ \t\n\r\0\x0B]*?)\| | \|\| )
+                (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|)(?!\|) )?
+                """,
+                bygroups(Punctuation, using(this, state=[
+                         'root', 'attr']), Punctuation),
+            ),
+            # Table headers
+            (
+                r"""(?x)
+                ( ^(?:[ \t\n\r\0\x0B]*?)!  )
+                (?: ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )(\|)(?!\|) )?
+                """,
+                bygroups(Punctuation, using(this, state=[
+                         'root', 'attr']), Punctuation),
+                'table-header',
+            ),
+            include('list'),
+            include('inline'),
+            include('text'),
+        ],
+        'table-header': [
+            # Requires another state for || handling inside headers
+            (r'\n', Text, '#pop'),
+            (
+                r"""(?x)
+                (!!|\|\|)
+                (?:
+                    ( (?: (?! \[\[ | \{\{ )[^|\n<] )*? )
+                    (\|)(?!\|)
+                )?
+                """,
+                bygroups(Punctuation, using(this, state=[
+                         'root', 'attr']), Punctuation)
+            ),
+            *text_rules(Generic.Subheading),
+        ],
+        'entity': [
+            (r'&\S*?;', Name.Entity),
+        ],
+        'dt': [
+            (r'\n', Text, '#pop'),
+            include('inline'),
+            (r':', Keyword, '#pop'),
+            include('text'),
+        ],
+        'extlink-inner': [
+            (r'\]', Punctuation, '#pop'),
+            include('inline'),
+            include('text'),
+        ],
+        'nowiki-ish': [
+            include('entity'),
+            include('text'),
+        ],
+        'attr': [
+            include('replaceable'),
+            (r'\s+', Whitespace),
+            (r'(=)(\s*)(")', bygroups(Operator, Whitespace, String.Double), 'attr-val-2'),
+            (r"(=)(\s*)(')", bygroups(Operator, Whitespace, String.Single), 'attr-val-1'),
+            (r'(=)(\s*)', bygroups(Operator, Whitespace), 'attr-val-0'),
+            (r'[\w:-]+', Name.Attribute),
+
+        ],
+        'attr-val-0': [
+            (r'\s', Whitespace, '#pop'),
+            include('replaceable'),
+            *text_rules(String),
+        ],
+        'attr-val-1': [
+            (r"'", String.Single, '#pop'),
+            include('replaceable'),
+            *text_rules(String.Single),
+        ],
+        'attr-val-2': [
+            (r'"', String.Double, '#pop'),
+            include('replaceable'),
+            *text_rules(String.Double),
+        ],
+        'tag-inner-ordinary': [
+            (r'/?\s*>', Punctuation, '#pop'),
+            include('tag-attr'),
+        ],
+        'tag-inner': [
+            # Return to root state for self-closing tags
+            (r'/\s*>', Punctuation, '#pop:2'),
+            (r'\s*>', Punctuation, '#pop'),
+            include('tag-attr'),
+        ],
+        # There states below are just like their non-tag variants, the key difference is
+        # they forcibly quit when encountering tag closing markup
+        'tag-attr': [
+            include('replaceable'),
+            (r'\s+', Whitespace),
+            (r'(=)(\s*)(")', bygroups(Operator,
+             Whitespace, String.Double), 'tag-attr-val-2'),
+            (r"(=)(\s*)(')", bygroups(Operator,
+             Whitespace, String.Single), 'tag-attr-val-1'),
+            (r'(=)(\s*)', bygroups(Operator, Whitespace), 'tag-attr-val-0'),
+            (r'[\w:-]+', Name.Attribute),
+
+        ],
+        'tag-attr-val-0': [
+            (r'\s', Whitespace, '#pop'),
+            (r'/?>', Punctuation, '#pop:2'),
+            include('replaceable'),
+            *text_rules(String),
+        ],
+        'tag-attr-val-1': [
+            (r"'", String.Single, '#pop'),
+            (r'/?>', Punctuation, '#pop:2'),
+            include('replaceable'),
+            *text_rules(String.Single),
+        ],
+        'tag-attr-val-2': [
+            (r'"', String.Double, '#pop'),
+            (r'/?>', Punctuation, '#pop:2'),
+            include('replaceable'),
+            *text_rules(String.Double),
+        ],
+        'tag-nowiki': nowiki_tag_rules('nowiki'),
+        'tag-pre': nowiki_tag_rules('pre'),
+        'tag-categorytree': plaintext_tag_rules('categorytree'),
+        'tag-dynamicpagelist': plaintext_tag_rules('dynamicpagelist'),
+        'tag-hiero': plaintext_tag_rules('hiero'),
+        'tag-inputbox': plaintext_tag_rules('inputbox'),
+        'tag-imagemap': plaintext_tag_rules('imagemap'),
+        'tag-charinsert': plaintext_tag_rules('charinsert'),
+        'tag-timeline': plaintext_tag_rules('timeline'),
+        'tag-gallery': plaintext_tag_rules('gallery'),
+        'tag-graph': plaintext_tag_rules('graph'),
+        'tag-rss': plaintext_tag_rules('rss'),
+        'tag-math': delegate_tag_rules('math', TexLexer, state='math'),
+        'tag-chem': delegate_tag_rules('chem', TexLexer, state='math'),
+        'tag-ce': delegate_tag_rules('ce', TexLexer, state='math'),
+        'tag-templatedata': delegate_tag_rules('templatedata', JsonLexer),
+        'text-italic': text_rules(Generic.Emph),
+        'text-bold': text_rules(Generic.Strong),
+        'text-bold-italic': text_rules(Generic.EmphStrong),
+        'text': text_rules(Text),
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/math.py b/lib/python3.11/site-packages/pygments/lexers/math.py
new file mode 100644
index 0000000000000000000000000000000000000000..b38c13e1209ae49df646465b00c5fd3df40bf30a
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/math.py
@@ -0,0 +1,21 @@
+"""
+    pygments.lexers.math
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Just export lexers that were contained in this module.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+# ruff: noqa: F401
+from pygments.lexers.python import NumPyLexer
+from pygments.lexers.matlab import MatlabLexer, MatlabSessionLexer, \
+    OctaveLexer, ScilabLexer
+from pygments.lexers.julia import JuliaLexer, JuliaConsoleLexer
+from pygments.lexers.r import RConsoleLexer, SLexer, RdLexer
+from pygments.lexers.modeling import BugsLexer, JagsLexer, StanLexer
+from pygments.lexers.idl import IDLLexer
+from pygments.lexers.algebra import MuPADLexer
+
+__all__ = []
diff --git a/lib/python3.11/site-packages/pygments/lexers/matlab.py b/lib/python3.11/site-packages/pygments/lexers/matlab.py
new file mode 100644
index 0000000000000000000000000000000000000000..b27f4db63edd75313a76304d7a403f9d62d2b3b2
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/matlab.py
@@ -0,0 +1,3307 @@
+"""
+    pygments.lexers.matlab
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Matlab and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import Lexer, RegexLexer, bygroups, default, words, \
+    do_insertions, include
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Generic, Whitespace
+
+from pygments.lexers import _scilab_builtins
+
+__all__ = ['MatlabLexer', 'MatlabSessionLexer', 'OctaveLexer', 'ScilabLexer']
+
+
+class MatlabLexer(RegexLexer):
+    """
+    For Matlab source code.
+    """
+    name = 'Matlab'
+    aliases = ['matlab']
+    filenames = ['*.m']
+    mimetypes = ['text/matlab']
+    url = 'https://www.mathworks.com/products/matlab.html'
+    version_added = '0.10'
+
+    _operators = r'-|==|~=|<=|>=|<|>|&&|&|~|\|\|?|\.\*|\*|\+|\.\^|\^|\.\\|\./|/|\\'
+
+    tokens = {
+        'expressions': [
+            # operators:
+            (_operators, Operator),
+
+            # numbers (must come before punctuation to handle `.5`; cannot use
+            # `\b` due to e.g. `5. + .5`).  The negative lookahead on operators
+            # avoids including the dot in `1./x` (the dot is part of `./`).
+            (rf'(? and then
+            # (equal | open-parenthesis |  | ).
+            (rf'(?:^|(?<=;))(\s*)(\w+)(\s+)(?!=|\(|{_operators}\s|\s)',
+             bygroups(Whitespace, Name, Whitespace), 'commandargs'),
+
+            include('expressions')
+        ],
+        'blockcomment': [
+            (r'^\s*%\}', Comment.Multiline, '#pop'),
+            (r'^.*\n', Comment.Multiline),
+            (r'.', Comment.Multiline),
+        ],
+        'deffunc': [
+            (r'(\s*)(?:(\S+)(\s*)(=)(\s*))?(.+)(\()(.*)(\))(\s*)',
+             bygroups(Whitespace, Text, Whitespace, Punctuation,
+                      Whitespace, Name.Function, Punctuation, Text,
+                      Punctuation, Whitespace), '#pop'),
+            # function with no args
+            (r'(\s*)([a-zA-Z_]\w*)',
+             bygroups(Whitespace, Name.Function), '#pop'),
+        ],
+        'propattrs': [
+            (r'(\w+)(\s*)(=)(\s*)(\d+)',
+             bygroups(Name.Builtin, Whitespace, Punctuation, Whitespace,
+                      Number)),
+            (r'(\w+)(\s*)(=)(\s*)([a-zA-Z]\w*)',
+             bygroups(Name.Builtin, Whitespace, Punctuation, Whitespace,
+                      Keyword)),
+            (r',', Punctuation),
+            (r'\)', Punctuation, '#pop'),
+            (r'\s+', Whitespace),
+            (r'.', Text),
+        ],
+        'defprops': [
+            (r'%\{\s*\n', Comment.Multiline, 'blockcomment'),
+            (r'%.*$', Comment),
+            (r'(?.
+    """
+    name = 'Matlab session'
+    aliases = ['matlabsession']
+    url = 'https://www.mathworks.com/products/matlab.html'
+    version_added = '0.10'
+    _example = "matlabsession/matlabsession_sample.txt"
+
+    def get_tokens_unprocessed(self, text):
+        mlexer = MatlabLexer(**self.options)
+
+        curcode = ''
+        insertions = []
+        continuation = False
+
+        for match in line_re.finditer(text):
+            line = match.group()
+
+            if line.startswith('>> '):
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, line[:3])]))
+                curcode += line[3:]
+
+            elif line.startswith('>>'):
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, line[:2])]))
+                curcode += line[2:]
+
+            elif line.startswith('???'):
+
+                idx = len(curcode)
+
+                # without is showing error on same line as before...?
+                # line = "\n" + line
+                token = (0, Generic.Traceback, line)
+                insertions.append((idx, [token]))
+            elif continuation and insertions:
+                # line_start is the length of the most recent prompt symbol
+                line_start = len(insertions[-1][-1][-1])
+                # Set leading spaces with the length of the prompt to be a generic prompt
+                # This keeps code aligned when prompts are removed, say with some Javascript
+                if line.startswith(' '*line_start):
+                    insertions.append(
+                        (len(curcode), [(0, Generic.Prompt, line[:line_start])]))
+                    curcode += line[line_start:]
+                else:
+                    curcode += line
+            else:
+                if curcode:
+                    yield from do_insertions(
+                        insertions, mlexer.get_tokens_unprocessed(curcode))
+                    curcode = ''
+                    insertions = []
+
+                yield match.start(), Generic.Output, line
+
+            # Does not allow continuation if a comment is included after the ellipses.
+            # Continues any line that ends with ..., even comments (lines that start with %)
+            if line.strip().endswith('...'):
+                continuation = True
+            else:
+                continuation = False
+
+        if curcode:  # or item:
+            yield from do_insertions(
+                insertions, mlexer.get_tokens_unprocessed(curcode))
+
+
+class OctaveLexer(RegexLexer):
+    """
+    For GNU Octave source code.
+    """
+    name = 'Octave'
+    url = 'https://www.gnu.org/software/octave/index'
+    aliases = ['octave']
+    filenames = ['*.m']
+    mimetypes = ['text/octave']
+    version_added = '1.5'
+
+    # These lists are generated automatically.
+    # Run the following in bash shell:
+    #
+    # First dump all of the Octave manual into a plain text file:
+    #
+    #   $ info octave --subnodes -o octave-manual
+    #
+    # Now grep through it:
+
+    # for i in \
+    #     "Built-in Function" "Command" "Function File" \
+    #     "Loadable Function" "Mapping Function";
+    # do
+    #     perl -e '@name = qw('"$i"');
+    #              print lc($name[0]),"_kw = [\n"';
+    #
+    #     perl -n -e 'print "\"$1\",\n" if /-- '"$i"': .* (\w*) \(/;' \
+    #         octave-manual | sort | uniq ;
+    #     echo "]" ;
+    #     echo;
+    # done
+
+    # taken from Octave Mercurial changeset 8cc154f45e37 (30-jan-2011)
+
+    builtin_kw = (
+        "addlistener", "addpath", "addproperty", "all",
+        "and", "any", "argnames", "argv", "assignin",
+        "atexit", "autoload",
+        "available_graphics_toolkits", "beep_on_error",
+        "bitand", "bitmax", "bitor", "bitshift", "bitxor",
+        "cat", "cell", "cellstr", "char", "class", "clc",
+        "columns", "command_line_path",
+        "completion_append_char", "completion_matches",
+        "complex", "confirm_recursive_rmdir", "cputime",
+        "crash_dumps_octave_core", "ctranspose", "cumprod",
+        "cumsum", "debug_on_error", "debug_on_interrupt",
+        "debug_on_warning", "default_save_options",
+        "dellistener", "diag", "diff", "disp",
+        "doc_cache_file", "do_string_escapes", "double",
+        "drawnow", "e", "echo_executing_commands", "eps",
+        "eq", "errno", "errno_list", "error", "eval",
+        "evalin", "exec", "exist", "exit", "eye", "false",
+        "fclear", "fclose", "fcntl", "fdisp", "feof",
+        "ferror", "feval", "fflush", "fgetl", "fgets",
+        "fieldnames", "file_in_loadpath", "file_in_path",
+        "filemarker", "filesep", "find_dir_in_path",
+        "fixed_point_format", "fnmatch", "fopen", "fork",
+        "formula", "fprintf", "fputs", "fread", "freport",
+        "frewind", "fscanf", "fseek", "fskipl", "ftell",
+        "functions", "fwrite", "ge", "genpath", "get",
+        "getegid", "getenv", "geteuid", "getgid",
+        "getpgrp", "getpid", "getppid", "getuid", "glob",
+        "gt", "gui_mode", "history_control",
+        "history_file", "history_size",
+        "history_timestamp_format_string", "home",
+        "horzcat", "hypot", "ifelse",
+        "ignore_function_time_stamp", "inferiorto",
+        "info_file", "info_program", "inline", "input",
+        "intmax", "intmin", "ipermute",
+        "is_absolute_filename", "isargout", "isbool",
+        "iscell", "iscellstr", "ischar", "iscomplex",
+        "isempty", "isfield", "isfloat", "isglobal",
+        "ishandle", "isieee", "isindex", "isinteger",
+        "islogical", "ismatrix", "ismethod", "isnull",
+        "isnumeric", "isobject", "isreal",
+        "is_rooted_relative_filename", "issorted",
+        "isstruct", "isvarname", "kbhit", "keyboard",
+        "kill", "lasterr", "lasterror", "lastwarn",
+        "ldivide", "le", "length", "link", "linspace",
+        "logical", "lstat", "lt", "make_absolute_filename",
+        "makeinfo_program", "max_recursion_depth", "merge",
+        "methods", "mfilename", "minus", "mislocked",
+        "mkdir", "mkfifo", "mkstemp", "mldivide", "mlock",
+        "mouse_wheel_zoom", "mpower", "mrdivide", "mtimes",
+        "munlock", "nargin", "nargout",
+        "native_float_format", "ndims", "ne", "nfields",
+        "nnz", "norm", "not", "numel", "nzmax",
+        "octave_config_info", "octave_core_file_limit",
+        "octave_core_file_name",
+        "octave_core_file_options", "ones", "or",
+        "output_max_field_width", "output_precision",
+        "page_output_immediately", "page_screen_output",
+        "path", "pathsep", "pause", "pclose", "permute",
+        "pi", "pipe", "plus", "popen", "power",
+        "print_empty_dimensions", "printf",
+        "print_struct_array_contents", "prod",
+        "program_invocation_name", "program_name",
+        "putenv", "puts", "pwd", "quit", "rats", "rdivide",
+        "readdir", "readlink", "read_readline_init_file",
+        "realmax", "realmin", "rehash", "rename",
+        "repelems", "re_read_readline_init_file", "reset",
+        "reshape", "resize", "restoredefaultpath",
+        "rethrow", "rmdir", "rmfield", "rmpath", "rows",
+        "save_header_format_string", "save_precision",
+        "saving_history", "scanf", "set", "setenv",
+        "shell_cmd", "sighup_dumps_octave_core",
+        "sigterm_dumps_octave_core", "silent_functions",
+        "single", "size", "size_equal", "sizemax",
+        "sizeof", "sleep", "source", "sparse_auto_mutate",
+        "split_long_rows", "sprintf", "squeeze", "sscanf",
+        "stat", "stderr", "stdin", "stdout", "strcmp",
+        "strcmpi", "string_fill_char", "strncmp",
+        "strncmpi", "struct", "struct_levels_to_print",
+        "strvcat", "subsasgn", "subsref", "sum", "sumsq",
+        "superiorto", "suppress_verbose_help_message",
+        "symlink", "system", "tic", "tilde_expand",
+        "times", "tmpfile", "tmpnam", "toc", "toupper",
+        "transpose", "true", "typeinfo", "umask", "uminus",
+        "uname", "undo_string_escapes", "unlink", "uplus",
+        "upper", "usage", "usleep", "vec", "vectorize",
+        "vertcat", "waitpid", "warning", "warranty",
+        "whos_line_format", "yes_or_no", "zeros",
+        "inf", "Inf", "nan", "NaN")
+
+    command_kw = ("close", "load", "who", "whos")
+
+    function_kw = (
+        "accumarray", "accumdim", "acosd", "acotd",
+        "acscd", "addtodate", "allchild", "ancestor",
+        "anova", "arch_fit", "arch_rnd", "arch_test",
+        "area", "arma_rnd", "arrayfun", "ascii", "asctime",
+        "asecd", "asind", "assert", "atand",
+        "autoreg_matrix", "autumn", "axes", "axis", "bar",
+        "barh", "bartlett", "bartlett_test", "beep",
+        "betacdf", "betainv", "betapdf", "betarnd",
+        "bicgstab", "bicubic", "binary", "binocdf",
+        "binoinv", "binopdf", "binornd", "bitcmp",
+        "bitget", "bitset", "blackman", "blanks",
+        "blkdiag", "bone", "box", "brighten", "calendar",
+        "cast", "cauchy_cdf", "cauchy_inv", "cauchy_pdf",
+        "cauchy_rnd", "caxis", "celldisp", "center", "cgs",
+        "chisquare_test_homogeneity",
+        "chisquare_test_independence", "circshift", "cla",
+        "clabel", "clf", "clock", "cloglog", "closereq",
+        "colon", "colorbar", "colormap", "colperm",
+        "comet", "common_size", "commutation_matrix",
+        "compan", "compare_versions", "compass",
+        "computer", "cond", "condest", "contour",
+        "contourc", "contourf", "contrast", "conv",
+        "convhull", "cool", "copper", "copyfile", "cor",
+        "corrcoef", "cor_test", "cosd", "cotd", "cov",
+        "cplxpair", "cross", "cscd", "cstrcat", "csvread",
+        "csvwrite", "ctime", "cumtrapz", "curl", "cut",
+        "cylinder", "date", "datenum", "datestr",
+        "datetick", "datevec", "dblquad", "deal",
+        "deblank", "deconv", "delaunay", "delaunayn",
+        "delete", "demo", "detrend", "diffpara", "diffuse",
+        "dir", "discrete_cdf", "discrete_inv",
+        "discrete_pdf", "discrete_rnd", "display",
+        "divergence", "dlmwrite", "dos", "dsearch",
+        "dsearchn", "duplication_matrix", "durbinlevinson",
+        "ellipsoid", "empirical_cdf", "empirical_inv",
+        "empirical_pdf", "empirical_rnd", "eomday",
+        "errorbar", "etime", "etreeplot", "example",
+        "expcdf", "expinv", "expm", "exppdf", "exprnd",
+        "ezcontour", "ezcontourf", "ezmesh", "ezmeshc",
+        "ezplot", "ezpolar", "ezsurf", "ezsurfc", "factor",
+        "factorial", "fail", "fcdf", "feather", "fftconv",
+        "fftfilt", "fftshift", "figure", "fileattrib",
+        "fileparts", "fill", "findall", "findobj",
+        "findstr", "finv", "flag", "flipdim", "fliplr",
+        "flipud", "fpdf", "fplot", "fractdiff", "freqz",
+        "freqz_plot", "frnd", "fsolve",
+        "f_test_regression", "ftp", "fullfile", "fzero",
+        "gamcdf", "gaminv", "gampdf", "gamrnd", "gca",
+        "gcbf", "gcbo", "gcf", "genvarname", "geocdf",
+        "geoinv", "geopdf", "geornd", "getfield", "ginput",
+        "glpk", "gls", "gplot", "gradient",
+        "graphics_toolkit", "gray", "grid", "griddata",
+        "griddatan", "gtext", "gunzip", "gzip", "hadamard",
+        "hamming", "hankel", "hanning", "hggroup",
+        "hidden", "hilb", "hist", "histc", "hold", "hot",
+        "hotelling_test", "housh", "hsv", "hurst",
+        "hygecdf", "hygeinv", "hygepdf", "hygernd",
+        "idivide", "ifftshift", "image", "imagesc",
+        "imfinfo", "imread", "imshow", "imwrite", "index",
+        "info", "inpolygon", "inputname", "interpft",
+        "interpn", "intersect", "invhilb", "iqr", "isa",
+        "isdefinite", "isdir", "is_duplicate_entry",
+        "isequal", "isequalwithequalnans", "isfigure",
+        "ishermitian", "ishghandle", "is_leap_year",
+        "isletter", "ismac", "ismember", "ispc", "isprime",
+        "isprop", "isscalar", "issquare", "isstrprop",
+        "issymmetric", "isunix", "is_valid_file_id",
+        "isvector", "jet", "kendall",
+        "kolmogorov_smirnov_cdf",
+        "kolmogorov_smirnov_test", "kruskal_wallis_test",
+        "krylov", "kurtosis", "laplace_cdf", "laplace_inv",
+        "laplace_pdf", "laplace_rnd", "legend", "legendre",
+        "license", "line", "linkprop", "list_primes",
+        "loadaudio", "loadobj", "logistic_cdf",
+        "logistic_inv", "logistic_pdf", "logistic_rnd",
+        "logit", "loglog", "loglogerr", "logm", "logncdf",
+        "logninv", "lognpdf", "lognrnd", "logspace",
+        "lookfor", "ls_command", "lsqnonneg", "magic",
+        "mahalanobis", "manova", "matlabroot",
+        "mcnemar_test", "mean", "meansq", "median", "menu",
+        "mesh", "meshc", "meshgrid", "meshz", "mexext",
+        "mget", "mkpp", "mode", "moment", "movefile",
+        "mpoles", "mput", "namelengthmax", "nargchk",
+        "nargoutchk", "nbincdf", "nbininv", "nbinpdf",
+        "nbinrnd", "nchoosek", "ndgrid", "newplot", "news",
+        "nonzeros", "normcdf", "normest", "norminv",
+        "normpdf", "normrnd", "now", "nthroot", "null",
+        "ocean", "ols", "onenormest", "optimget",
+        "optimset", "orderfields", "orient", "orth",
+        "pack", "pareto", "parseparams", "pascal", "patch",
+        "pathdef", "pcg", "pchip", "pcolor", "pcr",
+        "peaks", "periodogram", "perl", "perms", "pie",
+        "pink", "planerot", "playaudio", "plot",
+        "plotmatrix", "plotyy", "poisscdf", "poissinv",
+        "poisspdf", "poissrnd", "polar", "poly",
+        "polyaffine", "polyarea", "polyderiv", "polyfit",
+        "polygcd", "polyint", "polyout", "polyreduce",
+        "polyval", "polyvalm", "postpad", "powerset",
+        "ppder", "ppint", "ppjumps", "ppplot", "ppval",
+        "pqpnonneg", "prepad", "primes", "print",
+        "print_usage", "prism", "probit", "qp", "qqplot",
+        "quadcc", "quadgk", "quadl", "quadv", "quiver",
+        "qzhess", "rainbow", "randi", "range", "rank",
+        "ranks", "rat", "reallog", "realpow", "realsqrt",
+        "record", "rectangle_lw", "rectangle_sw",
+        "rectint", "refresh", "refreshdata",
+        "regexptranslate", "repmat", "residue", "ribbon",
+        "rindex", "roots", "rose", "rosser", "rotdim",
+        "rref", "run", "run_count", "rundemos", "run_test",
+        "runtests", "saveas", "saveaudio", "saveobj",
+        "savepath", "scatter", "secd", "semilogx",
+        "semilogxerr", "semilogy", "semilogyerr",
+        "setaudio", "setdiff", "setfield", "setxor",
+        "shading", "shift", "shiftdim", "sign_test",
+        "sinc", "sind", "sinetone", "sinewave", "skewness",
+        "slice", "sombrero", "sortrows", "spaugment",
+        "spconvert", "spdiags", "spearman", "spectral_adf",
+        "spectral_xdf", "specular", "speed", "spencer",
+        "speye", "spfun", "sphere", "spinmap", "spline",
+        "spones", "sprand", "sprandn", "sprandsym",
+        "spring", "spstats", "spy", "sqp", "stairs",
+        "statistics", "std", "stdnormal_cdf",
+        "stdnormal_inv", "stdnormal_pdf", "stdnormal_rnd",
+        "stem", "stft", "strcat", "strchr", "strjust",
+        "strmatch", "strread", "strsplit", "strtok",
+        "strtrim", "strtrunc", "structfun", "studentize",
+        "subplot", "subsindex", "subspace", "substr",
+        "substruct", "summer", "surf", "surface", "surfc",
+        "surfl", "surfnorm", "svds", "swapbytes",
+        "sylvester_matrix", "symvar", "synthesis", "table",
+        "tand", "tar", "tcdf", "tempdir", "tempname",
+        "test", "text", "textread", "textscan", "tinv",
+        "title", "toeplitz", "tpdf", "trace", "trapz",
+        "treelayout", "treeplot", "triangle_lw",
+        "triangle_sw", "tril", "trimesh", "triplequad",
+        "triplot", "trisurf", "triu", "trnd", "tsearchn",
+        "t_test", "t_test_regression", "type", "unidcdf",
+        "unidinv", "unidpdf", "unidrnd", "unifcdf",
+        "unifinv", "unifpdf", "unifrnd", "union", "unique",
+        "unix", "unmkpp", "unpack", "untabify", "untar",
+        "unwrap", "unzip", "u_test", "validatestring",
+        "vander", "var", "var_test", "vech", "ver",
+        "version", "view", "voronoi", "voronoin",
+        "waitforbuttonpress", "wavread", "wavwrite",
+        "wblcdf", "wblinv", "wblpdf", "wblrnd", "weekday",
+        "welch_test", "what", "white", "whitebg",
+        "wienrnd", "wilcoxon_test", "wilkinson", "winter",
+        "xlabel", "xlim", "ylabel", "yulewalker", "zip",
+        "zlabel", "z_test")
+
+    loadable_kw = (
+        "airy", "amd", "balance", "besselh", "besseli",
+        "besselj", "besselk", "bessely", "bitpack",
+        "bsxfun", "builtin", "ccolamd", "cellfun",
+        "cellslices", "chol", "choldelete", "cholinsert",
+        "cholinv", "cholshift", "cholupdate", "colamd",
+        "colloc", "convhulln", "convn", "csymamd",
+        "cummax", "cummin", "daspk", "daspk_options",
+        "dasrt", "dasrt_options", "dassl", "dassl_options",
+        "dbclear", "dbdown", "dbstack", "dbstatus",
+        "dbstop", "dbtype", "dbup", "dbwhere", "det",
+        "dlmread", "dmperm", "dot", "eig", "eigs",
+        "endgrent", "endpwent", "etree", "fft", "fftn",
+        "fftw", "filter", "find", "full", "gcd",
+        "getgrent", "getgrgid", "getgrnam", "getpwent",
+        "getpwnam", "getpwuid", "getrusage", "givens",
+        "gmtime", "gnuplot_binary", "hess", "ifft",
+        "ifftn", "inv", "isdebugmode", "issparse", "kron",
+        "localtime", "lookup", "lsode", "lsode_options",
+        "lu", "luinc", "luupdate", "matrix_type", "max",
+        "min", "mktime", "pinv", "qr", "qrdelete",
+        "qrinsert", "qrshift", "qrupdate", "quad",
+        "quad_options", "qz", "rand", "rande", "randg",
+        "randn", "randp", "randperm", "rcond", "regexp",
+        "regexpi", "regexprep", "schur", "setgrent",
+        "setpwent", "sort", "spalloc", "sparse", "spparms",
+        "sprank", "sqrtm", "strfind", "strftime",
+        "strptime", "strrep", "svd", "svd_driver", "syl",
+        "symamd", "symbfact", "symrcm", "time", "tsearch",
+        "typecast", "urlread", "urlwrite")
+
+    mapping_kw = (
+        "abs", "acos", "acosh", "acot", "acoth", "acsc",
+        "acsch", "angle", "arg", "asec", "asech", "asin",
+        "asinh", "atan", "atanh", "beta", "betainc",
+        "betaln", "bincoeff", "cbrt", "ceil", "conj", "cos",
+        "cosh", "cot", "coth", "csc", "csch", "erf", "erfc",
+        "erfcx", "erfinv", "exp", "finite", "fix", "floor",
+        "fmod", "gamma", "gammainc", "gammaln", "imag",
+        "isalnum", "isalpha", "isascii", "iscntrl",
+        "isdigit", "isfinite", "isgraph", "isinf",
+        "islower", "isna", "isnan", "isprint", "ispunct",
+        "isspace", "isupper", "isxdigit", "lcm", "lgamma",
+        "log", "lower", "mod", "real", "rem", "round",
+        "roundb", "sec", "sech", "sign", "sin", "sinh",
+        "sqrt", "tan", "tanh", "toascii", "tolower", "xor")
+
+    builtin_consts = (
+        "EDITOR", "EXEC_PATH", "I", "IMAGE_PATH", "NA",
+        "OCTAVE_HOME", "OCTAVE_VERSION", "PAGER",
+        "PAGER_FLAGS", "SEEK_CUR", "SEEK_END", "SEEK_SET",
+        "SIG", "S_ISBLK", "S_ISCHR", "S_ISDIR", "S_ISFIFO",
+        "S_ISLNK", "S_ISREG", "S_ISSOCK", "WCONTINUE",
+        "WCOREDUMP", "WEXITSTATUS", "WIFCONTINUED",
+        "WIFEXITED", "WIFSIGNALED", "WIFSTOPPED", "WNOHANG",
+        "WSTOPSIG", "WTERMSIG", "WUNTRACED")
+
+    tokens = {
+        'root': [
+            (r'%\{\s*\n', Comment.Multiline, 'percentblockcomment'),
+            (r'#\{\s*\n', Comment.Multiline, 'hashblockcomment'),
+            (r'[%#].*$', Comment),
+            (r'^\s*function\b', Keyword, 'deffunc'),
+
+            # from 'iskeyword' on hg changeset 8cc154f45e37
+            (words((
+                '__FILE__', '__LINE__', 'break', 'case', 'catch', 'classdef',
+                'continue', 'do', 'else', 'elseif', 'end', 'end_try_catch',
+                'end_unwind_protect', 'endclassdef', 'endevents', 'endfor',
+                'endfunction', 'endif', 'endmethods', 'endproperties', 'endswitch',
+                'endwhile', 'events', 'for', 'function', 'get', 'global', 'if',
+                'methods', 'otherwise', 'persistent', 'properties', 'return',
+                'set', 'static', 'switch', 'try', 'until', 'unwind_protect',
+                'unwind_protect_cleanup', 'while'), suffix=r'\b'),
+             Keyword),
+
+            (words(builtin_kw + command_kw + function_kw + loadable_kw + mapping_kw,
+                   suffix=r'\b'),  Name.Builtin),
+
+            (words(builtin_consts, suffix=r'\b'), Name.Constant),
+
+            # operators in Octave but not Matlab:
+            (r'-=|!=|!|/=|--', Operator),
+            # operators:
+            (r'-|==|~=|<|>|<=|>=|&&|&|~|\|\|?', Operator),
+            # operators in Octave but not Matlab requiring escape for re:
+            (r'\*=|\+=|\^=|\/=|\\=|\*\*|\+\+|\.\*\*', Operator),
+            # operators requiring escape for re:
+            (r'\.\*|\*|\+|\.\^|\^|\.\\|\.\/|\/|\\', Operator),
+
+
+            # punctuation:
+            (r'[\[\](){}:@.,]', Punctuation),
+            (r'=|:|;', Punctuation),
+
+            (r'"[^"]*"', String),
+
+            (r'(\d+\.\d*|\d*\.\d+)([eEf][+-]?[0-9]+)?', Number.Float),
+            (r'\d+[eEf][+-]?[0-9]+', Number.Float),
+            (r'\d+', Number.Integer),
+
+            # quote can be transpose, instead of string:
+            # (not great, but handles common cases...)
+            (r'(?<=[\w)\].])\'+', Operator),
+            (r'(?|<=|>=|&&|&|~|\|\|?', Operator),
+            # operators requiring escape for re:
+            (r'\.\*|\*|\+|\.\^|\^|\.\\|\.\/|\/|\\', Operator),
+
+            # punctuation:
+            (r'[\[\](){}@.,=:;]+', Punctuation),
+
+            (r'"[^"]*"', String),
+
+            # quote can be transpose, instead of string:
+            # (not great, but handles common cases...)
+            (r'(?<=[\w)\].])\'+', Operator),
+            (r'(?', r'<', r'|', r'!', r"'")
+
+    operator_words = ('and', 'or', 'not')
+
+    tokens = {
+        'root': [
+            (r'/\*', Comment.Multiline, 'comment'),
+            (r'"(?:[^"\\]|\\.)*"', String),
+            (r'\(|\)|\[|\]|\{|\}', Punctuation),
+            (r'[,;$]', Punctuation),
+            (words (constants), Name.Constant),
+            (words (keywords), Keyword),
+            (words (operators), Operator),
+            (words (operator_words), Operator.Word),
+            (r'''(?x)
+              ((?:[a-zA-Z_#][\w#]*|`[^`]*`)
+              (?:::[a-zA-Z_#][\w#]*|`[^`]*`)*)(\s*)([(])''',
+             bygroups(Name.Function, Text.Whitespace, Punctuation)),
+            (r'''(?x)
+              (?:[a-zA-Z_#%][\w#%]*|`[^`]*`)
+              (?:::[a-zA-Z_#%][\w#%]*|`[^`]*`)*''', Name.Variable),
+            (r'[-+]?(\d*\.\d+([bdefls][-+]?\d+)?|\d+(\.\d*)?[bdefls][-+]?\d+)', Number.Float),
+            (r'[-+]?\d+', Number.Integer),
+            (r'\s+', Text.Whitespace),
+            (r'.', Text)
+        ],
+        'comment': [
+            (r'[^*/]+', Comment.Multiline),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'[*/]', Comment.Multiline)
+        ]
+    }
+
+    def analyse_text (text):
+        strength = 0.0
+        # Input expression terminator.
+        if re.search (r'\$\s*$', text, re.MULTILINE):
+            strength += 0.05
+        # Function definition operator.
+        if ':=' in text:
+            strength += 0.02
+        return strength
diff --git a/lib/python3.11/site-packages/pygments/lexers/meson.py b/lib/python3.11/site-packages/pygments/lexers/meson.py
new file mode 100644
index 0000000000000000000000000000000000000000..154a2de5a154a139e337d04a62d990b694bb5379
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/meson.py
@@ -0,0 +1,139 @@
+"""
+    pygments.lexers.meson
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Pygments lexer for the Meson build system
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words, include
+from pygments.token import Comment, Name, Number, Punctuation, Operator, \
+    Keyword, String, Whitespace
+
+__all__ = ['MesonLexer']
+
+
+class MesonLexer(RegexLexer):
+    """Meson language lexer.
+
+    The grammar definition use to transcribe the syntax was retrieved from
+    https://mesonbuild.com/Syntax.html#grammar for version 0.58.
+    Some of those definitions are improperly transcribed, so the Meson++
+    implementation was also checked: https://github.com/dcbaker/meson-plus-plus.
+    """
+
+    # TODO String interpolation @VARNAME@ inner matches
+    # TODO keyword_arg: value inner matches
+
+    name = 'Meson'
+    url = 'https://mesonbuild.com/'
+    aliases = ['meson', 'meson.build']
+    filenames = ['meson.build', 'meson.options', 'meson_options.txt']
+    mimetypes = ['text/x-meson']
+    version_added = '2.10'
+
+    tokens = {
+        'root': [
+            (r'#.*?$', Comment),
+            (r"'''.*'''", String.Single),
+            (r'[1-9][0-9]*', Number.Integer),
+            (r'0o[0-7]+', Number.Oct),
+            (r'0x[a-fA-F0-9]+', Number.Hex),
+            include('string'),
+            include('keywords'),
+            include('expr'),
+            (r'[a-zA-Z_][a-zA-Z_0-9]*', Name),
+            (r'\s+', Whitespace),
+        ],
+        'string': [
+            (r"[']{3}([']{0,2}([^\\']|\\(.|\n)))*[']{3}", String),
+            (r"'.*?(?`_.
+    """
+
+    name = "MCFunction"
+    url = "https://minecraft.wiki/w/Commands"
+    aliases = ["mcfunction", "mcf"]
+    filenames = ["*.mcfunction"]
+    mimetypes = ["text/mcfunction"]
+    version_added = '2.12'
+
+    # Used to denotate the start of a block comment, borrowed from Github's mcfunction
+    _block_comment_prefix = "[>!]"
+
+    tokens = {
+        "root": [
+            include("names"),
+            include("comments"),
+            include("literals"),
+            include("whitespace"),
+            include("property"),
+            include("operators"),
+            include("selectors"),
+        ],
+
+        "names": [
+            # The start of a command (either beginning of line OR after the run keyword)
+            #  We don't encode a list of keywords since mods, plugins, or even pre-processors
+            #  may add new commands, so we have a 'close-enough' regex which catches them.
+            (r"^(\s*)([a-z_]+)", bygroups(Whitespace, Name.Builtin)),
+            (r"(?<=run)\s+[a-z_]+", Name.Builtin),
+
+            # UUID
+            (r"\b[0-9a-fA-F]+(?:-[0-9a-fA-F]+){4}\b", Name.Variable),
+            include("resource-name"),
+            # normal command names and scoreboards
+            #  there's no way to know the differences unfortuntely
+            (r"[A-Za-z_][\w.#%$]+", Keyword.Constant),
+            (r"[#%$][\w.#%$]+", Name.Variable.Magic),
+        ],
+
+        "resource-name": [
+            # resource names have to be lowercase
+            (r"#?[a-z_][a-z_.-]*:[a-z0-9_./-]+", Name.Function),
+            # similar to above except optional `:``
+            #  a `/` must be present "somewhere"
+            (r"#?[a-z0-9_\.\-]+\/[a-z0-9_\.\-\/]+", Name.Function),
+        ],
+
+        "whitespace": [
+            (r"\s+", Whitespace),
+        ],
+
+        "comments": [
+            (rf"^\s*(#{_block_comment_prefix})", Comment.Multiline,
+             ("comments.block", "comments.block.emphasized")),
+            (r"#.*$", Comment.Single),
+        ],
+        "comments.block": [
+            (rf"^\s*#{_block_comment_prefix}", Comment.Multiline,
+             "comments.block.emphasized"),
+            (r"^\s*#", Comment.Multiline, "comments.block.normal"),
+            default("#pop"),
+        ],
+        "comments.block.normal": [
+            include("comments.block.special"),
+            (r"\S+", Comment.Multiline),
+            (r"\n", Text, "#pop"),
+            include("whitespace"),
+        ],
+        "comments.block.emphasized": [
+            include("comments.block.special"),
+            (r"\S+", String.Doc),
+            (r"\n", Text, "#pop"),
+            include("whitespace"),
+        ],
+        "comments.block.special": [
+            # Params
+            (r"@\S+", Name.Decorator),
+
+            include("resource-name"),
+
+            # Scoreboard player names
+            (r"[#%$][\w.#%$]+", Name.Variable.Magic),
+        ],
+
+        "operators": [
+            (r"[\-~%^?!+*<>\\/|&=.]", Operator),
+        ],
+
+        "literals": [
+            (r"\.\.", Literal),
+            (r"(true|false)", Keyword.Pseudo),
+
+            # these are like unquoted strings and appear in many places
+            (r"[A-Za-z_]+", Name.Variable.Class),
+
+            (r"[0-7]b", Number.Byte),
+            (r"[+-]?\d*\.?\d+([eE]?[+-]?\d+)?[df]?\b", Number.Float),
+            (r"[+-]?\d+\b", Number.Integer),
+            (r'"', String.Double, "literals.string-double"),
+            (r"'", String.Single, "literals.string-single"),
+        ],
+        "literals.string-double": [
+            (r"\\.", String.Escape),
+            (r'[^\\"\n]+', String.Double),
+            (r'"', String.Double, "#pop"),
+        ],
+        "literals.string-single": [
+            (r"\\.", String.Escape),
+            (r"[^\\'\n]+", String.Single),
+            (r"'", String.Single, "#pop"),
+        ],
+
+        "selectors": [
+            (r"@[a-z]", Name.Variable),
+        ],
+
+
+        ## Generic Property Container
+        # There are several, differing instances where the language accepts
+        #  specific contained keys or contained key, value pairings.
+        #
+        # Property Maps:
+        # - Starts with either `[` or `{`
+        # - Key separated by `:` or `=`
+        # - Deliminated by `,`
+        #
+        # Property Lists:
+        # - Starts with `[`
+        # - Deliminated by `,`
+        #
+        # For simplicity, these patterns match a generic, nestable structure
+        #  which follow a key, value pattern. For normal lists, there's only keys.
+        # This allow some "illegal" structures, but we'll accept those for
+        #  sake of simplicity
+        #
+        # Examples:
+        # - `[facing=up, powered=true]` (blockstate)
+        # - `[name="hello world", nbt={key: 1b}]` (selector + nbt)
+        # - `[{"text": "value"}, "literal"]` (json)
+        ##
+        "property": [
+            # This state gets included in root and also several substates
+            # We do this to shortcut the starting of new properties
+            #  within other properties. Lists can have sublists and compounds
+            #  and values can start a new property (see the `difficult_1.txt`
+            #  snippet).
+            (r"\{", Punctuation, ("property.curly", "property.key")),
+            (r"\[", Punctuation, ("property.square", "property.key")),
+        ],
+        "property.curly": [
+            include("whitespace"),
+            include("property"),
+            (r"\}", Punctuation, "#pop"),
+        ],
+        "property.square": [
+            include("whitespace"),
+            include("property"),
+            (r"\]", Punctuation, "#pop"),
+
+            # lists can have sequences of items
+            (r",", Punctuation),
+        ],
+        "property.key": [
+            include("whitespace"),
+
+            # resource names (for advancements)
+            #  can omit `:` to default `minecraft:`
+            # must check if there is a future equals sign if `:` is in the name
+            (r"#?[a-z_][a-z_\.\-]*\:[a-z0-9_\.\-/]+(?=\s*\=)", Name.Attribute, "property.delimiter"),
+            (r"#?[a-z_][a-z0-9_\.\-/]+", Name.Attribute, "property.delimiter"),
+
+            # unquoted NBT key
+            (r"[A-Za-z_\-\+]+", Name.Attribute, "property.delimiter"),
+
+            # quoted JSON or NBT key
+            (r'"', Name.Attribute, "property.delimiter", "literals.string-double"),
+            (r"'", Name.Attribute, "property.delimiter", "literals.string-single"),
+
+            # index for a list
+            (r"-?\d+", Number.Integer, "property.delimiter"),
+
+            default("#pop"),
+        ],
+        "property.key.string-double": [
+            (r"\\.", String.Escape),
+            (r'[^\\"\n]+', Name.Attribute),
+            (r'"', Name.Attribute, "#pop"),
+        ],
+        "property.key.string-single": [
+            (r"\\.", String.Escape),
+            (r"[^\\'\n]+", Name.Attribute),
+            (r"'", Name.Attribute, "#pop"),
+        ],
+        "property.delimiter": [
+            include("whitespace"),
+
+            (r"[:=]!?", Punctuation, "property.value"),
+            (r",", Punctuation),
+
+            default("#pop"),
+        ],
+        "property.value": [
+            include("whitespace"),
+
+            # unquoted resource names are valid literals here
+            (r"#?[a-z_][a-z_\.\-]*\:[a-z0-9_\.\-/]+", Name.Tag),
+            (r"#?[a-z_][a-z0-9_\.\-/]+", Name.Tag),
+
+            include("literals"),
+            include("property"),
+
+            default("#pop"),
+        ],
+    }
+
+
+class MCSchemaLexer(RegexLexer):
+    """Lexer for Minecraft Add-ons data Schemas, an interface structure standard used in Minecraft
+    """
+
+    name = 'MCSchema'
+    url = 'https://learn.microsoft.com/en-us/minecraft/creator/reference/content/schemasreference/'
+    aliases = ['mcschema']
+    filenames = ['*.mcschema']
+    mimetypes = ['text/mcschema']
+    version_added = '2.14'
+
+    tokens = {
+        'commentsandwhitespace': [
+            (r'\s+', Whitespace),
+            (r'//.*?$', Comment.Single),
+            (r'/\*.*?\*/', Comment.Multiline)
+        ],
+        'slashstartsregex': [
+            include('commentsandwhitespace'),
+            (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
+             r'([gimuysd]+\b|\B)', String.Regex, '#pop'),
+            (r'(?=/)', Text, ('#pop', 'badregex')),
+            default('#pop')
+        ],
+        'badregex': [
+            (r'\n', Whitespace, '#pop')
+        ],
+        'singlestring': [
+            (r'\\.', String.Escape),
+            (r"'", String.Single, '#pop'),
+            (r"[^\\']+", String.Single),
+        ],
+        'doublestring': [
+            (r'\\.', String.Escape),
+            (r'"', String.Double, '#pop'),
+            (r'[^\\"]+', String.Double),
+        ],
+        'root': [
+            (r'^(?=\s|/|', Comment, '#pop'),
+            (r'[^\-]+|-', Comment),
+        ],
+    }
+
+
+class ReasonLexer(RegexLexer):
+    """
+    For the ReasonML language.
+    """
+
+    name = 'ReasonML'
+    url = 'https://reasonml.github.io/'
+    aliases = ['reasonml', 'reason']
+    filenames = ['*.re', '*.rei']
+    mimetypes = ['text/x-reasonml']
+    version_added = '2.6'
+
+    keywords = (
+        'as', 'assert', 'begin', 'class', 'constraint', 'do', 'done', 'downto',
+        'else', 'end', 'exception', 'external', 'false', 'for', 'fun', 'esfun',
+        'function', 'functor', 'if', 'in', 'include', 'inherit', 'initializer', 'lazy',
+        'let', 'switch', 'module', 'pub', 'mutable', 'new', 'nonrec', 'object', 'of',
+        'open', 'pri', 'rec', 'sig', 'struct', 'then', 'to', 'true', 'try',
+        'type', 'val', 'virtual', 'when', 'while', 'with',
+    )
+    keyopts = (
+        '!=', '#', '&', '&&', r'\(', r'\)', r'\*', r'\+', ',', '-',
+        r'-\.', '=>', r'\.', r'\.\.', r'\.\.\.', ':', '::', ':=', ':>', ';', ';;', '<',
+        '<-', '=', '>', '>]', r'>\}', r'\?', r'\?\?', r'\[', r'\[<', r'\[>',
+        r'\[\|', ']', '_', '`', r'\{', r'\{<', r'\|', r'\|\|', r'\|]', r'\}', '~'
+    )
+
+    operators = r'[!$%&*+\./:<=>?@^|~-]'
+    word_operators = ('and', 'asr', 'land', 'lor', 'lsl', 'lsr', 'lxor', 'mod', 'or')
+    prefix_syms = r'[!?~]'
+    infix_syms = r'[=<>@^|&+\*/$%-]'
+    primitives = ('unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array')
+
+    tokens = {
+        'escape-sequence': [
+            (r'\\[\\"\'ntbr]', String.Escape),
+            (r'\\[0-9]{3}', String.Escape),
+            (r'\\x[0-9a-fA-F]{2}', String.Escape),
+        ],
+        'root': [
+            (r'\s+', Text),
+            (r'false|true|\(\)|\[\]', Name.Builtin.Pseudo),
+            (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'),
+            (r'\b([A-Z][\w\']*)', Name.Class),
+            (r'//.*?\n', Comment.Single),
+            (r'\/\*(?!/)', Comment.Multiline, 'comment'),
+            (r'\b({})\b'.format('|'.join(keywords)), Keyword),
+            (r'({})'.format('|'.join(keyopts[::-1])), Operator.Word),
+            (rf'({infix_syms}|{prefix_syms})?{operators}', Operator),
+            (r'\b({})\b'.format('|'.join(word_operators)), Operator.Word),
+            (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type),
+
+            (r"[^\W\d][\w']*", Name),
+
+            (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float),
+            (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
+            (r'0[oO][0-7][0-7_]*', Number.Oct),
+            (r'0[bB][01][01_]*', Number.Bin),
+            (r'\d[\d_]*', Number.Integer),
+
+            (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'",
+             String.Char),
+            (r"'.'", String.Char),
+            (r"'", Keyword),
+
+            (r'"', String.Double, 'string'),
+
+            (r'[~?][a-z][\w\']*:', Name.Variable),
+        ],
+        'comment': [
+            (r'[^/*]+', Comment.Multiline),
+            (r'\/\*', Comment.Multiline, '#push'),
+            (r'\*\/', Comment.Multiline, '#pop'),
+            (r'\*', Comment.Multiline),
+        ],
+        'string': [
+            (r'[^\\"]+', String.Double),
+            include('escape-sequence'),
+            (r'\\\n', String.Double),
+            (r'"', String.Double, '#pop'),
+        ],
+        'dotted': [
+            (r'\s+', Text),
+            (r'\.', Punctuation),
+            (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace),
+            (r'[A-Z][\w\']*', Name.Class, '#pop'),
+            (r'[a-z_][\w\']*', Name, '#pop'),
+            default('#pop'),
+        ],
+    }
+
+
+class FStarLexer(RegexLexer):
+    """
+    For the F* language.
+    """
+
+    name = 'FStar'
+    url = 'https://www.fstar-lang.org/'
+    aliases = ['fstar']
+    filenames = ['*.fst', '*.fsti']
+    mimetypes = ['text/x-fstar']
+    version_added = '2.7'
+
+    keywords = (
+        'abstract', 'attributes', 'noeq', 'unopteq', 'and'
+        'begin', 'by', 'default', 'effect', 'else', 'end', 'ensures',
+        'exception', 'exists', 'false', 'forall', 'fun', 'function', 'if',
+        'in', 'include', 'inline', 'inline_for_extraction', 'irreducible',
+        'logic', 'match', 'module', 'mutable', 'new', 'new_effect', 'noextract',
+        'of', 'open', 'opaque', 'private', 'range_of', 'reifiable',
+        'reify', 'reflectable', 'requires', 'set_range_of', 'sub_effect',
+        'synth', 'then', 'total', 'true', 'try', 'type', 'unfold', 'unfoldable',
+        'val', 'when', 'with', 'not'
+    )
+    decl_keywords = ('let', 'rec')
+    assume_keywords = ('assume', 'admit', 'assert', 'calc')
+    keyopts = (
+        r'~', r'-', r'/\\', r'\\/', r'<:', r'<@', r'\(\|', r'\|\)', r'#', r'u#',
+        r'&', r'\(', r'\)', r'\(\)', r',', r'~>', r'->', r'<-', r'<--', r'<==>',
+        r'==>', r'\.', r'\?', r'\?\.', r'\.\[', r'\.\(', r'\.\(\|', r'\.\[\|',
+        r'\{:pattern', r':', r'::', r':=', r';', r';;', r'=', r'%\[', r'!\{',
+        r'\[', r'\[@', r'\[\|', r'\|>', r'\]', r'\|\]', r'\{', r'\|', r'\}', r'\$'
+    )
+
+    operators = r'[!$%&*+\./:<=>?@^|~-]'
+    prefix_syms = r'[!?~]'
+    infix_syms = r'[=<>@^|&+\*/$%-]'
+    primitives = ('unit', 'int', 'float', 'bool', 'string', 'char', 'list', 'array')
+
+    tokens = {
+        'escape-sequence': [
+            (r'\\[\\"\'ntbr]', String.Escape),
+            (r'\\[0-9]{3}', String.Escape),
+            (r'\\x[0-9a-fA-F]{2}', String.Escape),
+        ],
+        'root': [
+            (r'\s+', Text),
+            (r'false|true|False|True|\(\)|\[\]', Name.Builtin.Pseudo),
+            (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'),
+            (r'\b([A-Z][\w\']*)', Name.Class),
+            (r'\(\*(?![)])', Comment, 'comment'),
+            (r'\/\/.+$', Comment),
+            (r'\b({})\b'.format('|'.join(keywords)), Keyword),
+            (r'\b({})\b'.format('|'.join(assume_keywords)), Name.Exception),
+            (r'\b({})\b'.format('|'.join(decl_keywords)), Keyword.Declaration),
+            (r'({})'.format('|'.join(keyopts[::-1])), Operator),
+            (rf'({infix_syms}|{prefix_syms})?{operators}', Operator),
+            (r'\b({})\b'.format('|'.join(primitives)), Keyword.Type),
+
+            (r"[^\W\d][\w']*", Name),
+
+            (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float),
+            (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
+            (r'0[oO][0-7][0-7_]*', Number.Oct),
+            (r'0[bB][01][01_]*', Number.Bin),
+            (r'\d[\d_]*', Number.Integer),
+
+            (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'",
+             String.Char),
+            (r"'.'", String.Char),
+            (r"'", Keyword),  # a stray quote is another syntax element
+            (r"\`([\w\'.]+)\`", Operator.Word),  # for infix applications
+            (r"\`", Keyword),  # for quoting
+            (r'"', String.Double, 'string'),
+
+            (r'[~?][a-z][\w\']*:', Name.Variable),
+        ],
+        'comment': [
+            (r'[^(*)]+', Comment),
+            (r'\(\*', Comment, '#push'),
+            (r'\*\)', Comment, '#pop'),
+            (r'[(*)]', Comment),
+        ],
+        'string': [
+            (r'[^\\"]+', String.Double),
+            include('escape-sequence'),
+            (r'\\\n', String.Double),
+            (r'"', String.Double, '#pop'),
+        ],
+        'dotted': [
+            (r'\s+', Text),
+            (r'\.', Punctuation),
+            (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace),
+            (r'[A-Z][\w\']*', Name.Class, '#pop'),
+            (r'[a-z_][\w\']*', Name, '#pop'),
+            default('#pop'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/modeling.py b/lib/python3.11/site-packages/pygments/lexers/modeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c22aeb0043a31b6231fb031134b12cafe1024fc
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/modeling.py
@@ -0,0 +1,368 @@
+"""
+    pygments.lexers.modeling
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for modeling languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, bygroups, using, default
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Whitespace
+
+from pygments.lexers.html import HtmlLexer
+from pygments.lexers import _stan_builtins
+
+__all__ = ['ModelicaLexer', 'BugsLexer', 'JagsLexer', 'StanLexer']
+
+
+class ModelicaLexer(RegexLexer):
+    """
+    For Modelica source code.
+    """
+    name = 'Modelica'
+    url = 'http://www.modelica.org/'
+    aliases = ['modelica']
+    filenames = ['*.mo']
+    mimetypes = ['text/x-modelica']
+    version_added = '1.1'
+
+    flags = re.DOTALL | re.MULTILINE
+
+    _name = r"(?:'(?:[^\\']|\\.)+'|[a-zA-Z_]\w*)"
+
+    tokens = {
+        'whitespace': [
+            (r'[\s\ufeff]+', Text),
+            (r'//[^\n]*\n?', Comment.Single),
+            (r'/\*.*?\*/', Comment.Multiline)
+        ],
+        'root': [
+            include('whitespace'),
+            (r'"', String.Double, 'string'),
+            (r'[()\[\]{},;]+', Punctuation),
+            (r'\.?[*^/+-]|\.|<>|[<>:=]=?', Operator),
+            (r'\d+(\.?\d*[eE][-+]?\d+|\.\d*)', Number.Float),
+            (r'\d+', Number.Integer),
+            (r'(abs|acos|actualStream|array|asin|assert|AssertionLevel|atan|'
+             r'atan2|backSample|Boolean|cardinality|cat|ceil|change|Clock|'
+             r'Connections|cos|cosh|cross|delay|diagonal|div|edge|exp|'
+             r'ExternalObject|fill|floor|getInstanceName|hold|homotopy|'
+             r'identity|inStream|integer|Integer|interval|inverse|isPresent|'
+             r'linspace|log|log10|matrix|max|min|mod|ndims|noClock|noEvent|'
+             r'ones|outerProduct|pre|previous|product|Real|reinit|rem|rooted|'
+             r'sample|scalar|semiLinear|shiftSample|sign|sin|sinh|size|skew|'
+             r'smooth|spatialDistribution|sqrt|StateSelect|String|subSample|'
+             r'sum|superSample|symmetric|tan|tanh|terminal|terminate|time|'
+             r'transpose|vector|zeros)\b', Name.Builtin),
+            (r'(algorithm|annotation|break|connect|constant|constrainedby|der|'
+             r'discrete|each|else|elseif|elsewhen|encapsulated|enumeration|'
+             r'equation|exit|expandable|extends|external|firstTick|final|flow|for|if|'
+             r'import|impure|in|initial|inner|input|interval|loop|nondiscrete|outer|'
+             r'output|parameter|partial|protected|public|pure|redeclare|'
+             r'replaceable|return|stream|then|when|while)\b',
+             Keyword.Reserved),
+            (r'(and|not|or)\b', Operator.Word),
+            (r'(block|class|connector|end|function|model|operator|package|'
+             r'record|type)\b', Keyword.Reserved, 'class'),
+            (r'(false|true)\b', Keyword.Constant),
+            (r'within\b', Keyword.Reserved, 'package-prefix'),
+            (_name, Name)
+        ],
+        'class': [
+            include('whitespace'),
+            (r'(function|record)\b', Keyword.Reserved),
+            (r'(if|for|when|while)\b', Keyword.Reserved, '#pop'),
+            (_name, Name.Class, '#pop'),
+            default('#pop')
+        ],
+        'package-prefix': [
+            include('whitespace'),
+            (_name, Name.Namespace, '#pop'),
+            default('#pop')
+        ],
+        'string': [
+            (r'"', String.Double, '#pop'),
+            (r'\\[\'"?\\abfnrtv]', String.Escape),
+            (r'(?i)<\s*html\s*>([^\\"]|\\.)+?(<\s*/\s*html\s*>|(?="))',
+             using(HtmlLexer)),
+            (r'<|\\?[^"\\<]+', String.Double)
+        ]
+    }
+
+
+class BugsLexer(RegexLexer):
+    """
+    Pygments Lexer for OpenBugs and WinBugs
+    models.
+    """
+
+    name = 'BUGS'
+    aliases = ['bugs', 'winbugs', 'openbugs']
+    filenames = ['*.bug']
+    url = 'https://www.mrc-bsu.cam.ac.uk/software/bugs/openbugs'
+    version_added = '1.6'
+
+    _FUNCTIONS = (
+        # Scalar functions
+        'abs', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh',
+        'cloglog', 'cos', 'cosh', 'cumulative', 'cut', 'density', 'deviance',
+        'equals', 'expr', 'gammap', 'ilogit', 'icloglog', 'integral', 'log',
+        'logfact', 'loggam', 'logit', 'max', 'min', 'phi', 'post.p.value',
+        'pow', 'prior.p.value', 'probit', 'replicate.post', 'replicate.prior',
+        'round', 'sin', 'sinh', 'solution', 'sqrt', 'step', 'tan', 'tanh',
+        'trunc',
+        # Vector functions
+        'inprod', 'interp.lin', 'inverse', 'logdet', 'mean', 'eigen.vals',
+        'ode', 'prod', 'p.valueM', 'rank', 'ranked', 'replicate.postM',
+        'sd', 'sort', 'sum',
+        # Special
+        'D', 'I', 'F', 'T', 'C')
+    """ OpenBUGS built-in functions
+
+    From http://www.openbugs.info/Manuals/ModelSpecification.html#ContentsAII
+
+    This also includes
+
+    - T, C, I : Truncation and censoring.
+      ``T`` and ``C`` are in OpenBUGS. ``I`` in WinBUGS.
+    - D : ODE
+    - F : Functional http://www.openbugs.info/Examples/Functionals.html
+
+    """
+
+    _DISTRIBUTIONS = ('dbern', 'dbin', 'dcat', 'dnegbin', 'dpois',
+                      'dhyper', 'dbeta', 'dchisqr', 'ddexp', 'dexp',
+                      'dflat', 'dgamma', 'dgev', 'df', 'dggamma', 'dgpar',
+                      'dloglik', 'dlnorm', 'dlogis', 'dnorm', 'dpar',
+                      'dt', 'dunif', 'dweib', 'dmulti', 'ddirch', 'dmnorm',
+                      'dmt', 'dwish')
+    """ OpenBUGS built-in distributions
+
+    Functions from
+    http://www.openbugs.info/Manuals/ModelSpecification.html#ContentsAI
+    """
+
+    tokens = {
+        'whitespace': [
+            (r"\s+", Text),
+        ],
+        'comments': [
+            # Comments
+            (r'#.*$', Comment.Single),
+        ],
+        'root': [
+            # Comments
+            include('comments'),
+            include('whitespace'),
+            # Block start
+            (r'(model)(\s+)(\{)',
+             bygroups(Keyword.Namespace, Text, Punctuation)),
+            # Reserved Words
+            (r'(for|in)(?![\w.])', Keyword.Reserved),
+            # Built-in Functions
+            (r'({})(?=\s*\()'.format(r'|'.join(_FUNCTIONS + _DISTRIBUTIONS)),
+             Name.Builtin),
+            # Regular variable names
+            (r'[A-Za-z][\w.]*', Name),
+            # Number Literals
+            (r'[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?', Number),
+            # Punctuation
+            (r'\[|\]|\(|\)|:|,|;', Punctuation),
+            # Assignment operators
+            # SLexer makes these tokens Operators.
+            (r'<-|~', Operator),
+            # Infix and prefix operators
+            (r'\+|-|\*|/', Operator),
+            # Block
+            (r'[{}]', Punctuation),
+        ]
+    }
+
+    def analyse_text(text):
+        if re.search(r"^\s*model\s*{", text, re.M):
+            return 0.7
+        else:
+            return 0.0
+
+
+class JagsLexer(RegexLexer):
+    """
+    Pygments Lexer for JAGS.
+    """
+
+    name = 'JAGS'
+    aliases = ['jags']
+    filenames = ['*.jag', '*.bug']
+    url = 'https://mcmc-jags.sourceforge.io'
+    version_added = '1.6'
+
+    # JAGS
+    _FUNCTIONS = (
+        'abs', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh',
+        'cos', 'cosh', 'cloglog',
+        'equals', 'exp', 'icloglog', 'ifelse', 'ilogit', 'log', 'logfact',
+        'loggam', 'logit', 'phi', 'pow', 'probit', 'round', 'sin', 'sinh',
+        'sqrt', 'step', 'tan', 'tanh', 'trunc', 'inprod', 'interp.lin',
+        'logdet', 'max', 'mean', 'min', 'prod', 'sum', 'sd', 'inverse',
+        'rank', 'sort', 't', 'acos', 'acosh', 'asin', 'asinh', 'atan',
+        # Truncation/Censoring (should I include)
+        'T', 'I')
+    # Distributions with density, probability and quartile functions
+    _DISTRIBUTIONS = tuple(f'[dpq]{x}' for x in
+                           ('bern', 'beta', 'dchiqsqr', 'ddexp', 'dexp',
+                            'df', 'gamma', 'gen.gamma', 'logis', 'lnorm',
+                            'negbin', 'nchisqr', 'norm', 'par', 'pois', 'weib'))
+    # Other distributions without density and probability
+    _OTHER_DISTRIBUTIONS = (
+        'dt', 'dunif', 'dbetabin', 'dbern', 'dbin', 'dcat', 'dhyper',
+        'ddirch', 'dmnorm', 'dwish', 'dmt', 'dmulti', 'dbinom', 'dchisq',
+        'dnbinom', 'dweibull', 'ddirich')
+
+    tokens = {
+        'whitespace': [
+            (r"\s+", Text),
+        ],
+        'names': [
+            # Regular variable names
+            (r'[a-zA-Z][\w.]*\b', Name),
+        ],
+        'comments': [
+            # do not use stateful comments
+            (r'(?s)/\*.*?\*/', Comment.Multiline),
+            # Comments
+            (r'#.*$', Comment.Single),
+        ],
+        'root': [
+            # Comments
+            include('comments'),
+            include('whitespace'),
+            # Block start
+            (r'(model|data)(\s+)(\{)',
+             bygroups(Keyword.Namespace, Text, Punctuation)),
+            (r'var(?![\w.])', Keyword.Declaration),
+            # Reserved Words
+            (r'(for|in)(?![\w.])', Keyword.Reserved),
+            # Builtins
+            # Need to use lookahead because . is a valid char
+            (r'({})(?=\s*\()'.format(r'|'.join(_FUNCTIONS
+                                          + _DISTRIBUTIONS
+                                          + _OTHER_DISTRIBUTIONS)),
+             Name.Builtin),
+            # Names
+            include('names'),
+            # Number Literals
+            (r'[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?', Number),
+            (r'\[|\]|\(|\)|:|,|;', Punctuation),
+            # Assignment operators
+            (r'<-|~', Operator),
+            # # JAGS includes many more than OpenBUGS
+            (r'\+|-|\*|\/|\|\|[&]{2}|[<>=]=?|\^|%.*?%', Operator),
+            (r'[{}]', Punctuation),
+        ]
+    }
+
+    def analyse_text(text):
+        if re.search(r'^\s*model\s*\{', text, re.M):
+            if re.search(r'^\s*data\s*\{', text, re.M):
+                return 0.9
+            elif re.search(r'^\s*var', text, re.M):
+                return 0.9
+            else:
+                return 0.3
+        else:
+            return 0
+
+
+class StanLexer(RegexLexer):
+    """Pygments Lexer for Stan models.
+
+    The Stan modeling language is specified in the *Stan Modeling Language
+    User's Guide and Reference Manual, v2.17.0*,
+    `pdf `__.
+    """
+
+    name = 'Stan'
+    aliases = ['stan']
+    filenames = ['*.stan']
+    url = 'https://mc-stan.org'
+    version_added = '1.6'
+
+    tokens = {
+        'whitespace': [
+            (r"\s+", Text),
+        ],
+        'comments': [
+            (r'(?s)/\*.*?\*/', Comment.Multiline),
+            # Comments
+            (r'(//|#).*$', Comment.Single),
+        ],
+        'root': [
+            (r'"[^"]*"', String),
+            # Comments
+            include('comments'),
+            # block start
+            include('whitespace'),
+            # Block start
+            (r'({})(\s*)(\{{)'.format(r'|'.join(('functions', 'data', r'transformed\s+?data',
+                        'parameters', r'transformed\s+parameters',
+                        'model', r'generated\s+quantities'))),
+             bygroups(Keyword.Namespace, Text, Punctuation)),
+            # target keyword
+            (r'target\s*\+=', Keyword),
+            # jacobian += statement
+            (r'jacobian\s*\+=', Keyword),
+            # Reserved Words
+            (r'({})\b'.format(r'|'.join(_stan_builtins.KEYWORDS)), Keyword),
+            # Truncation
+            (r'T(?=\s*\[)', Keyword),
+            # Data types
+            (r'({})\b'.format(r'|'.join(_stan_builtins.TYPES)), Keyword.Type),
+             # < should be punctuation, but elsewhere I can't tell if it is in
+             # a range constraint
+            (r'(<)(\s*)(upper|lower|offset|multiplier)(\s*)(=)',
+             bygroups(Operator, Whitespace, Keyword, Whitespace, Punctuation)),
+            (r'(,)(\s*)(upper)(\s*)(=)',
+             bygroups(Punctuation, Whitespace, Keyword, Whitespace, Punctuation)),
+            # Punctuation
+            (r"[;,\[\]()]", Punctuation),
+            # Builtin
+            (r'({})(?=\s*\()'.format('|'.join(_stan_builtins.FUNCTIONS)), Name.Builtin),
+            (r'(~)(\s*)({})(?=\s*\()'.format('|'.join(_stan_builtins.DISTRIBUTIONS)),
+                bygroups(Operator, Whitespace, Name.Builtin)),
+            # Special names ending in __, like lp__
+            (r'[A-Za-z]\w*__\b', Name.Builtin.Pseudo),
+            (r'({})\b'.format(r'|'.join(_stan_builtins.RESERVED)), Keyword.Reserved),
+            # user-defined functions
+            (r'[A-Za-z]\w*(?=\s*\()]', Name.Function),
+            # Imaginary Literals
+            (r'[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?i', Number.Float),
+            (r'\.[0-9]+([eE][+-]?[0-9]+)?i', Number.Float),
+            (r'[0-9]+i', Number.Float),
+            # Real Literals
+            (r'[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?', Number.Float),
+            (r'\.[0-9]+([eE][+-]?[0-9]+)?', Number.Float),
+            # Integer Literals
+            (r'[0-9]+', Number.Integer),
+            # Regular variable names
+            (r'[A-Za-z]\w*\b', Name),
+            # Assignment operators
+            (r'<-|(?:\+|-|\.?/|\.?\*|=)?=|~', Operator),
+            # Infix, prefix and postfix operators (and = )
+            (r"\+|-|\.?\*|\.?/|\\|'|\.?\^|!=?|<=?|>=?|\|\||&&|%|\?|:|%/%|!", Operator),
+            # Block delimiters
+            (r'[{}]', Punctuation),
+            # Distribution |
+            (r'\|', Punctuation)
+        ]
+    }
+
+    def analyse_text(text):
+        if re.search(r'^\s*parameters\s*\{', text, re.M):
+            return 1.0
+        else:
+            return 0.0
diff --git a/lib/python3.11/site-packages/pygments/lexers/modula2.py b/lib/python3.11/site-packages/pygments/lexers/modula2.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0ebd5c14c33767f8374de499baa938b2c943425
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/modula2.py
@@ -0,0 +1,1579 @@
+"""
+    pygments.lexers.modula2
+    ~~~~~~~~~~~~~~~~~~~~~~~
+
+    Multi-Dialect Lexer for Modula-2.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include
+from pygments.util import get_bool_opt, get_list_opt
+from pygments.token import Text, Comment, Operator, Keyword, Name, \
+    String, Number, Punctuation, Error
+
+__all__ = ['Modula2Lexer']
+
+
+# Multi-Dialect Modula-2 Lexer
+class Modula2Lexer(RegexLexer):
+    """
+    For Modula-2 source code.
+
+    The Modula-2 lexer supports several dialects.  By default, it operates in
+    fallback mode, recognising the *combined* literals, punctuation symbols
+    and operators of all supported dialects, and the *combined* reserved words
+    and builtins of PIM Modula-2, ISO Modula-2 and Modula-2 R10, while not
+    differentiating between library defined identifiers.
+
+    To select a specific dialect, a dialect option may be passed
+    or a dialect tag may be embedded into a source file.
+
+    Dialect Options:
+
+    `m2pim`
+        Select PIM Modula-2 dialect.
+    `m2iso`
+        Select ISO Modula-2 dialect.
+    `m2r10`
+        Select Modula-2 R10 dialect.
+    `objm2`
+        Select Objective Modula-2 dialect.
+
+    The PIM and ISO dialect options may be qualified with a language extension.
+
+    Language Extensions:
+
+    `+aglet`
+        Select Aglet Modula-2 extensions, available with m2iso.
+    `+gm2`
+        Select GNU Modula-2 extensions, available with m2pim.
+    `+p1`
+        Select p1 Modula-2 extensions, available with m2iso.
+    `+xds`
+        Select XDS Modula-2 extensions, available with m2iso.
+
+
+    Passing a Dialect Option via Unix Commandline Interface
+
+    Dialect options may be passed to the lexer using the `dialect` key.
+    Only one such option should be passed. If multiple dialect options are
+    passed, the first valid option is used, any subsequent options are ignored.
+
+    Examples:
+
+    `$ pygmentize -O full,dialect=m2iso -f html -o /path/to/output /path/to/input`
+        Use ISO dialect to render input to HTML output
+    `$ pygmentize -O full,dialect=m2iso+p1 -f rtf -o /path/to/output /path/to/input`
+        Use ISO dialect with p1 extensions to render input to RTF output
+
+
+    Embedding a Dialect Option within a source file
+
+    A dialect option may be embedded in a source file in form of a dialect
+    tag, a specially formatted comment that specifies a dialect option.
+
+    Dialect Tag EBNF::
+
+       dialectTag :
+           OpeningCommentDelim Prefix dialectOption ClosingCommentDelim ;
+
+       dialectOption :
+           'm2pim' | 'm2iso' | 'm2r10' | 'objm2' |
+           'm2iso+aglet' | 'm2pim+gm2' | 'm2iso+p1' | 'm2iso+xds' ;
+
+       Prefix : '!' ;
+
+       OpeningCommentDelim : '(*' ;
+
+       ClosingCommentDelim : '*)' ;
+
+    No whitespace is permitted between the tokens of a dialect tag.
+
+    In the event that a source file contains multiple dialect tags, the first
+    tag that contains a valid dialect option will be used and any subsequent
+    dialect tags will be ignored.  Ideally, a dialect tag should be placed
+    at the beginning of a source file.
+
+    An embedded dialect tag overrides a dialect option set via command line.
+
+    Examples:
+
+    ``(*!m2r10*) DEFINITION MODULE Foobar; ...``
+        Use Modula2 R10 dialect to render this source file.
+    ``(*!m2pim+gm2*) DEFINITION MODULE Bazbam; ...``
+        Use PIM dialect with GNU extensions to render this source file.
+
+
+    Algol Publication Mode:
+
+    In Algol publication mode, source text is rendered for publication of
+    algorithms in scientific papers and academic texts, following the format
+    of the Revised Algol-60 Language Report.  It is activated by passing
+    one of two corresponding styles as an option:
+
+    `algol`
+        render reserved words lowercase underline boldface
+        and builtins lowercase boldface italic
+    `algol_nu`
+        render reserved words lowercase boldface (no underlining)
+        and builtins lowercase boldface italic
+
+    The lexer automatically performs the required lowercase conversion when
+    this mode is activated.
+
+    Example:
+
+    ``$ pygmentize -O full,style=algol -f latex -o /path/to/output /path/to/input``
+        Render input file in Algol publication mode to LaTeX output.
+
+
+    Rendering Mode of First Class ADT Identifiers:
+
+    The rendering of standard library first class ADT identifiers is controlled
+    by option flag "treat_stdlib_adts_as_builtins".
+
+    When this option is turned on, standard library ADT identifiers are rendered
+    as builtins.  When it is turned off, they are rendered as ordinary library
+    identifiers.
+
+    `treat_stdlib_adts_as_builtins` (default: On)
+
+    The option is useful for dialects that support ADTs as first class objects
+    and provide ADTs in the standard library that would otherwise be built-in.
+
+    At present, only Modula-2 R10 supports library ADTs as first class objects
+    and therefore, no ADT identifiers are defined for any other dialects.
+
+    Example:
+
+    ``$ pygmentize -O full,dialect=m2r10,treat_stdlib_adts_as_builtins=Off ...``
+        Render standard library ADTs as ordinary library types.
+
+    .. versionchanged:: 2.1
+       Added multi-dialect support.
+    """
+    name = 'Modula-2'
+    url = 'http://www.modula2.org/'
+    aliases = ['modula2', 'm2']
+    filenames = ['*.def', '*.mod']
+    mimetypes = ['text/x-modula2']
+    version_added = '1.3'
+
+    flags = re.MULTILINE | re.DOTALL
+
+    tokens = {
+        'whitespace': [
+            (r'\n+', Text),  # blank lines
+            (r'\s+', Text),  # whitespace
+        ],
+        'dialecttags': [
+            # PIM Dialect Tag
+            (r'\(\*!m2pim\*\)', Comment.Special),
+            # ISO Dialect Tag
+            (r'\(\*!m2iso\*\)', Comment.Special),
+            # M2R10 Dialect Tag
+            (r'\(\*!m2r10\*\)', Comment.Special),
+            # ObjM2 Dialect Tag
+            (r'\(\*!objm2\*\)', Comment.Special),
+            # Aglet Extensions Dialect Tag
+            (r'\(\*!m2iso\+aglet\*\)', Comment.Special),
+            # GNU Extensions Dialect Tag
+            (r'\(\*!m2pim\+gm2\*\)', Comment.Special),
+            # p1 Extensions Dialect Tag
+            (r'\(\*!m2iso\+p1\*\)', Comment.Special),
+            # XDS Extensions Dialect Tag
+            (r'\(\*!m2iso\+xds\*\)', Comment.Special),
+        ],
+        'identifiers': [
+            (r'([a-zA-Z_$][\w$]*)', Name),
+        ],
+        'prefixed_number_literals': [
+            #
+            # Base-2, whole number
+            (r'0b[01]+(\'[01]+)*', Number.Bin),
+            #
+            # Base-16, whole number
+            (r'0[ux][0-9A-F]+(\'[0-9A-F]+)*', Number.Hex),
+        ],
+        'plain_number_literals': [
+            #
+            # Base-10, real number with exponent
+            (r'[0-9]+(\'[0-9]+)*'  # integral part
+             r'\.[0-9]+(\'[0-9]+)*'  # fractional part
+             r'[eE][+-]?[0-9]+(\'[0-9]+)*',  # exponent
+             Number.Float),
+            #
+            # Base-10, real number without exponent
+            (r'[0-9]+(\'[0-9]+)*'  # integral part
+             r'\.[0-9]+(\'[0-9]+)*',  # fractional part
+             Number.Float),
+            #
+            # Base-10, whole number
+            (r'[0-9]+(\'[0-9]+)*', Number.Integer),
+        ],
+        'suffixed_number_literals': [
+            #
+            # Base-8, whole number
+            (r'[0-7]+B', Number.Oct),
+            #
+            # Base-8, character code
+            (r'[0-7]+C', Number.Oct),
+            #
+            # Base-16, number
+            (r'[0-9A-F]+H', Number.Hex),
+        ],
+        'string_literals': [
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
+        ],
+        'digraph_operators': [
+            # Dot Product Operator
+            (r'\*\.', Operator),
+            # Array Concatenation Operator
+            (r'\+>', Operator),  # M2R10 + ObjM2
+            # Inequality Operator
+            (r'<>', Operator),  # ISO + PIM
+            # Less-Or-Equal, Subset
+            (r'<=', Operator),
+            # Greater-Or-Equal, Superset
+            (r'>=', Operator),
+            # Identity Operator
+            (r'==', Operator),  # M2R10 + ObjM2
+            # Type Conversion Operator
+            (r'::', Operator),  # M2R10 + ObjM2
+            # Assignment Symbol
+            (r':=', Operator),
+            # Postfix Increment Mutator
+            (r'\+\+', Operator),  # M2R10 + ObjM2
+            # Postfix Decrement Mutator
+            (r'--', Operator),  # M2R10 + ObjM2
+        ],
+        'unigraph_operators': [
+            # Arithmetic Operators
+            (r'[+-]', Operator),
+            (r'[*/]', Operator),
+            # ISO 80000-2 compliant Set Difference Operator
+            (r'\\', Operator),  # M2R10 + ObjM2
+            # Relational Operators
+            (r'[=#<>]', Operator),
+            # Dereferencing Operator
+            (r'\^', Operator),
+            # Dereferencing Operator Synonym
+            (r'@', Operator),  # ISO
+            # Logical AND Operator Synonym
+            (r'&', Operator),  # PIM + ISO
+            # Logical NOT Operator Synonym
+            (r'~', Operator),  # PIM + ISO
+            # Smalltalk Message Prefix
+            (r'`', Operator),  # ObjM2
+        ],
+        'digraph_punctuation': [
+            # Range Constructor
+            (r'\.\.', Punctuation),
+            # Opening Chevron Bracket
+            (r'<<', Punctuation),  # M2R10 + ISO
+            # Closing Chevron Bracket
+            (r'>>', Punctuation),  # M2R10 + ISO
+            # Blueprint Punctuation
+            (r'->', Punctuation),  # M2R10 + ISO
+            # Distinguish |# and # in M2 R10
+            (r'\|#', Punctuation),
+            # Distinguish ## and # in M2 R10
+            (r'##', Punctuation),
+            # Distinguish |* and * in M2 R10
+            (r'\|\*', Punctuation),
+        ],
+        'unigraph_punctuation': [
+            # Common Punctuation
+            (r'[()\[\]{},.:;|]', Punctuation),
+            # Case Label Separator Synonym
+            (r'!', Punctuation),  # ISO
+            # Blueprint Punctuation
+            (r'\?', Punctuation),  # M2R10 + ObjM2
+        ],
+        'comments': [
+            # Single Line Comment
+            (r'^//.*?\n', Comment.Single),  # M2R10 + ObjM2
+            # Block Comment
+            (r'\(\*([^$].*?)\*\)', Comment.Multiline),
+            # Template Block Comment
+            (r'/\*(.*?)\*/', Comment.Multiline),  # M2R10 + ObjM2
+        ],
+        'pragmas': [
+            # ISO Style Pragmas
+            (r'<\*.*?\*>', Comment.Preproc),  # ISO, M2R10 + ObjM2
+            # Pascal Style Pragmas
+            (r'\(\*\$.*?\*\)', Comment.Preproc),  # PIM
+        ],
+        'root': [
+            include('whitespace'),
+            include('dialecttags'),
+            include('pragmas'),
+            include('comments'),
+            include('identifiers'),
+            include('suffixed_number_literals'),  # PIM + ISO
+            include('prefixed_number_literals'),  # M2R10 + ObjM2
+            include('plain_number_literals'),
+            include('string_literals'),
+            include('digraph_punctuation'),
+            include('digraph_operators'),
+            include('unigraph_punctuation'),
+            include('unigraph_operators'),
+        ]
+    }
+
+#  C o m m o n   D a t a s e t s
+
+    # Common Reserved Words Dataset
+    common_reserved_words = (
+        # 37 common reserved words
+        'AND', 'ARRAY', 'BEGIN', 'BY', 'CASE', 'CONST', 'DEFINITION', 'DIV',
+        'DO', 'ELSE', 'ELSIF', 'END', 'EXIT', 'FOR', 'FROM', 'IF',
+        'IMPLEMENTATION', 'IMPORT', 'IN', 'LOOP', 'MOD', 'MODULE', 'NOT',
+        'OF', 'OR', 'POINTER', 'PROCEDURE', 'RECORD', 'REPEAT', 'RETURN',
+        'SET', 'THEN', 'TO', 'TYPE', 'UNTIL', 'VAR', 'WHILE',
+    )
+
+    # Common Builtins Dataset
+    common_builtins = (
+        # 16 common builtins
+        'ABS', 'BOOLEAN', 'CARDINAL', 'CHAR', 'CHR', 'FALSE', 'INTEGER',
+        'LONGINT', 'LONGREAL', 'MAX', 'MIN', 'NIL', 'ODD', 'ORD', 'REAL',
+        'TRUE',
+    )
+
+    # Common Pseudo-Module Builtins Dataset
+    common_pseudo_builtins = (
+        # 4 common pseudo builtins
+        'ADDRESS', 'BYTE', 'WORD', 'ADR'
+    )
+
+#  P I M   M o d u l a - 2   D a t a s e t s
+
+    # Lexemes to Mark as Error Tokens for PIM Modula-2
+    pim_lexemes_to_reject = (
+        '!', '`', '@', '$', '%', '?', '\\', '==', '++', '--', '::', '*.',
+        '+>', '->', '<<', '>>', '|#', '##',
+    )
+
+    # PIM Modula-2 Additional Reserved Words Dataset
+    pim_additional_reserved_words = (
+        # 3 additional reserved words
+        'EXPORT', 'QUALIFIED', 'WITH',
+    )
+
+    # PIM Modula-2 Additional Builtins Dataset
+    pim_additional_builtins = (
+        # 16 additional builtins
+        'BITSET', 'CAP', 'DEC', 'DISPOSE', 'EXCL', 'FLOAT', 'HALT', 'HIGH',
+        'INC', 'INCL', 'NEW', 'NIL', 'PROC', 'SIZE', 'TRUNC', 'VAL',
+    )
+
+    # PIM Modula-2 Additional Pseudo-Module Builtins Dataset
+    pim_additional_pseudo_builtins = (
+        # 5 additional pseudo builtins
+        'SYSTEM', 'PROCESS', 'TSIZE', 'NEWPROCESS', 'TRANSFER',
+    )
+
+#  I S O   M o d u l a - 2   D a t a s e t s
+
+    # Lexemes to Mark as Error Tokens for ISO Modula-2
+    iso_lexemes_to_reject = (
+        '`', '$', '%', '?', '\\', '==', '++', '--', '::', '*.', '+>', '->',
+        '<<', '>>', '|#', '##',
+    )
+
+    # ISO Modula-2 Additional Reserved Words Dataset
+    iso_additional_reserved_words = (
+        # 9 additional reserved words (ISO 10514-1)
+        'EXCEPT', 'EXPORT', 'FINALLY', 'FORWARD', 'PACKEDSET', 'QUALIFIED',
+        'REM', 'RETRY', 'WITH',
+        # 10 additional reserved words (ISO 10514-2 & ISO 10514-3)
+        'ABSTRACT', 'AS', 'CLASS', 'GUARD', 'INHERIT', 'OVERRIDE', 'READONLY',
+        'REVEAL', 'TRACED', 'UNSAFEGUARDED',
+    )
+
+    # ISO Modula-2 Additional Builtins Dataset
+    iso_additional_builtins = (
+        # 26 additional builtins (ISO 10514-1)
+        'BITSET', 'CAP', 'CMPLX', 'COMPLEX', 'DEC', 'DISPOSE', 'EXCL', 'FLOAT',
+        'HALT', 'HIGH', 'IM', 'INC', 'INCL', 'INT', 'INTERRUPTIBLE',  'LENGTH',
+        'LFLOAT', 'LONGCOMPLEX', 'NEW', 'PROC', 'PROTECTION', 'RE', 'SIZE',
+        'TRUNC', 'UNINTERRUBTIBLE', 'VAL',
+        # 5 additional builtins (ISO 10514-2 & ISO 10514-3)
+        'CREATE', 'DESTROY', 'EMPTY', 'ISMEMBER', 'SELF',
+    )
+
+    # ISO Modula-2 Additional Pseudo-Module Builtins Dataset
+    iso_additional_pseudo_builtins = (
+        # 14 additional builtins (SYSTEM)
+        'SYSTEM', 'BITSPERLOC', 'LOCSPERBYTE', 'LOCSPERWORD', 'LOC',
+        'ADDADR', 'SUBADR', 'DIFADR', 'MAKEADR', 'ADR',
+        'ROTATE', 'SHIFT', 'CAST', 'TSIZE',
+        # 13 additional builtins (COROUTINES)
+        'COROUTINES', 'ATTACH', 'COROUTINE', 'CURRENT', 'DETACH', 'HANDLER',
+        'INTERRUPTSOURCE', 'IOTRANSFER', 'IsATTACHED', 'LISTEN',
+        'NEWCOROUTINE', 'PROT', 'TRANSFER',
+        # 9 additional builtins (EXCEPTIONS)
+        'EXCEPTIONS', 'AllocateSource', 'CurrentNumber', 'ExceptionNumber',
+        'ExceptionSource', 'GetMessage', 'IsCurrentSource',
+        'IsExceptionalExecution', 'RAISE',
+        # 3 additional builtins (TERMINATION)
+        'TERMINATION', 'IsTerminating', 'HasHalted',
+        # 4 additional builtins (M2EXCEPTION)
+        'M2EXCEPTION', 'M2Exceptions', 'M2Exception', 'IsM2Exception',
+        'indexException', 'rangeException', 'caseSelectException',
+        'invalidLocation', 'functionException', 'wholeValueException',
+        'wholeDivException', 'realValueException', 'realDivException',
+        'complexValueException', 'complexDivException', 'protException',
+        'sysException', 'coException', 'exException',
+    )
+
+#  M o d u l a - 2   R 1 0   D a t a s e t s
+
+    # Lexemes to Mark as Error Tokens for Modula-2 R10
+    m2r10_lexemes_to_reject = (
+        '!', '`', '@', '$', '%', '&', '<>',
+    )
+
+    # Modula-2 R10 reserved words in addition to the common set
+    m2r10_additional_reserved_words = (
+        # 12 additional reserved words
+        'ALIAS', 'ARGLIST', 'BLUEPRINT', 'COPY', 'GENLIB', 'INDETERMINATE',
+        'NEW', 'NONE', 'OPAQUE', 'REFERENTIAL', 'RELEASE', 'RETAIN',
+        # 2 additional reserved words with symbolic assembly option
+        'ASM', 'REG',
+    )
+
+    # Modula-2 R10 builtins in addition to the common set
+    m2r10_additional_builtins = (
+        # 26 additional builtins
+        'CARDINAL', 'COUNT', 'EMPTY', 'EXISTS', 'INSERT', 'LENGTH', 'LONGCARD',
+        'OCTET', 'PTR', 'PRED', 'READ', 'READNEW', 'REMOVE', 'RETRIEVE', 'SORT',
+        'STORE', 'SUBSET', 'SUCC', 'TLIMIT', 'TMAX', 'TMIN', 'TRUE', 'TSIZE',
+        'UNICHAR', 'WRITE', 'WRITEF',
+    )
+
+    # Modula-2 R10 Additional Pseudo-Module Builtins Dataset
+    m2r10_additional_pseudo_builtins = (
+        # 13 additional builtins (TPROPERTIES)
+        'TPROPERTIES', 'PROPERTY', 'LITERAL', 'TPROPERTY', 'TLITERAL',
+        'TBUILTIN', 'TDYN', 'TREFC', 'TNIL', 'TBASE', 'TPRECISION',
+        'TMAXEXP', 'TMINEXP',
+        # 4 additional builtins (CONVERSION)
+        'CONVERSION', 'TSXFSIZE', 'SXF', 'VAL',
+        # 35 additional builtins (UNSAFE)
+        'UNSAFE', 'CAST', 'INTRINSIC', 'AVAIL', 'ADD', 'SUB', 'ADDC', 'SUBC',
+        'FETCHADD', 'FETCHSUB', 'SHL', 'SHR', 'ASHR', 'ROTL', 'ROTR', 'ROTLC',
+        'ROTRC', 'BWNOT', 'BWAND', 'BWOR', 'BWXOR', 'BWNAND', 'BWNOR',
+        'SETBIT', 'TESTBIT', 'LSBIT', 'MSBIT', 'CSBITS', 'BAIL', 'HALT',
+        'TODO', 'FFI', 'ADDR', 'VARGLIST', 'VARGC',
+        # 11 additional builtins (ATOMIC)
+        'ATOMIC', 'INTRINSIC', 'AVAIL', 'SWAP', 'CAS', 'INC', 'DEC', 'BWAND',
+        'BWNAND', 'BWOR', 'BWXOR',
+        # 7 additional builtins (COMPILER)
+        'COMPILER', 'DEBUG', 'MODNAME', 'PROCNAME', 'LINENUM', 'DEFAULT',
+        'HASH',
+        # 5 additional builtins (ASSEMBLER)
+        'ASSEMBLER', 'REGISTER', 'SETREG', 'GETREG', 'CODE',
+    )
+
+#  O b j e c t i v e   M o d u l a - 2   D a t a s e t s
+
+    # Lexemes to Mark as Error Tokens for Objective Modula-2
+    objm2_lexemes_to_reject = (
+        '!', '$', '%', '&', '<>',
+    )
+
+    # Objective Modula-2 Extensions
+    # reserved words in addition to Modula-2 R10
+    objm2_additional_reserved_words = (
+        # 16 additional reserved words
+        'BYCOPY', 'BYREF', 'CLASS', 'CONTINUE', 'CRITICAL', 'INOUT', 'METHOD',
+        'ON', 'OPTIONAL', 'OUT', 'PRIVATE', 'PROTECTED', 'PROTOCOL', 'PUBLIC',
+        'SUPER', 'TRY',
+    )
+
+    # Objective Modula-2 Extensions
+    # builtins in addition to Modula-2 R10
+    objm2_additional_builtins = (
+        # 3 additional builtins
+        'OBJECT', 'NO', 'YES',
+    )
+
+    # Objective Modula-2 Extensions
+    # pseudo-module builtins in addition to Modula-2 R10
+    objm2_additional_pseudo_builtins = (
+        # None
+    )
+
+#  A g l e t   M o d u l a - 2   D a t a s e t s
+
+    # Aglet Extensions
+    # reserved words in addition to ISO Modula-2
+    aglet_additional_reserved_words = (
+        # None
+    )
+
+    # Aglet Extensions
+    # builtins in addition to ISO Modula-2
+    aglet_additional_builtins = (
+        # 9 additional builtins
+        'BITSET8', 'BITSET16', 'BITSET32', 'CARDINAL8', 'CARDINAL16',
+        'CARDINAL32', 'INTEGER8', 'INTEGER16', 'INTEGER32',
+    )
+
+    # Aglet Modula-2 Extensions
+    # pseudo-module builtins in addition to ISO Modula-2
+    aglet_additional_pseudo_builtins = (
+        # None
+    )
+
+#  G N U   M o d u l a - 2   D a t a s e t s
+
+    # GNU Extensions
+    # reserved words in addition to PIM Modula-2
+    gm2_additional_reserved_words = (
+        # 10 additional reserved words
+        'ASM', '__ATTRIBUTE__', '__BUILTIN__', '__COLUMN__', '__DATE__',
+        '__FILE__', '__FUNCTION__', '__LINE__', '__MODULE__', 'VOLATILE',
+    )
+
+    # GNU Extensions
+    # builtins in addition to PIM Modula-2
+    gm2_additional_builtins = (
+        # 21 additional builtins
+        'BITSET8', 'BITSET16', 'BITSET32', 'CARDINAL8', 'CARDINAL16',
+        'CARDINAL32', 'CARDINAL64', 'COMPLEX32', 'COMPLEX64', 'COMPLEX96',
+        'COMPLEX128', 'INTEGER8', 'INTEGER16', 'INTEGER32', 'INTEGER64',
+        'REAL8', 'REAL16', 'REAL32', 'REAL96', 'REAL128', 'THROW',
+    )
+
+    # GNU Extensions
+    # pseudo-module builtins in addition to PIM Modula-2
+    gm2_additional_pseudo_builtins = (
+        # None
+    )
+
+#  p 1   M o d u l a - 2   D a t a s e t s
+
+    # p1 Extensions
+    # reserved words in addition to ISO Modula-2
+    p1_additional_reserved_words = (
+        # None
+    )
+
+    # p1 Extensions
+    # builtins in addition to ISO Modula-2
+    p1_additional_builtins = (
+        # None
+    )
+
+    # p1 Modula-2 Extensions
+    # pseudo-module builtins in addition to ISO Modula-2
+    p1_additional_pseudo_builtins = (
+        # 1 additional builtin
+        'BCD',
+    )
+
+#  X D S   M o d u l a - 2   D a t a s e t s
+
+    # XDS Extensions
+    # reserved words in addition to ISO Modula-2
+    xds_additional_reserved_words = (
+        # 1 additional reserved word
+        'SEQ',
+    )
+
+    # XDS Extensions
+    # builtins in addition to ISO Modula-2
+    xds_additional_builtins = (
+        # 9 additional builtins
+        'ASH', 'ASSERT', 'DIFFADR_TYPE', 'ENTIER', 'INDEX', 'LEN',
+        'LONGCARD', 'SHORTCARD', 'SHORTINT',
+    )
+
+    # XDS Modula-2 Extensions
+    # pseudo-module builtins in addition to ISO Modula-2
+    xds_additional_pseudo_builtins = (
+        # 22 additional builtins (SYSTEM)
+        'PROCESS', 'NEWPROCESS', 'BOOL8', 'BOOL16', 'BOOL32', 'CARD8',
+        'CARD16', 'CARD32', 'INT8', 'INT16', 'INT32', 'REF', 'MOVE',
+        'FILL', 'GET', 'PUT', 'CC', 'int', 'unsigned', 'size_t', 'void'
+        # 3 additional builtins (COMPILER)
+        'COMPILER', 'OPTION', 'EQUATION'
+    )
+
+#  P I M   S t a n d a r d   L i b r a r y   D a t a s e t s
+
+    # PIM Modula-2 Standard Library Modules Dataset
+    pim_stdlib_module_identifiers = (
+        'Terminal', 'FileSystem', 'InOut', 'RealInOut', 'MathLib0', 'Storage',
+    )
+
+    # PIM Modula-2 Standard Library Types Dataset
+    pim_stdlib_type_identifiers = (
+        'Flag', 'FlagSet', 'Response', 'Command', 'Lock', 'Permission',
+        'MediumType', 'File', 'FileProc', 'DirectoryProc', 'FileCommand',
+        'DirectoryCommand',
+    )
+
+    # PIM Modula-2 Standard Library Procedures Dataset
+    pim_stdlib_proc_identifiers = (
+        'Read', 'BusyRead', 'ReadAgain', 'Write', 'WriteString', 'WriteLn',
+        'Create', 'Lookup', 'Close', 'Delete', 'Rename', 'SetRead', 'SetWrite',
+        'SetModify', 'SetOpen', 'Doio', 'SetPos', 'GetPos', 'Length', 'Reset',
+        'Again', 'ReadWord', 'WriteWord', 'ReadChar', 'WriteChar',
+        'CreateMedium', 'DeleteMedium', 'AssignName', 'DeassignName',
+        'ReadMedium', 'LookupMedium', 'OpenInput', 'OpenOutput', 'CloseInput',
+        'CloseOutput', 'ReadString', 'ReadInt', 'ReadCard', 'ReadWrd',
+        'WriteInt', 'WriteCard', 'WriteOct', 'WriteHex', 'WriteWrd',
+        'ReadReal', 'WriteReal', 'WriteFixPt', 'WriteRealOct', 'sqrt', 'exp',
+        'ln', 'sin', 'cos', 'arctan', 'entier', 'ALLOCATE', 'DEALLOCATE',
+    )
+
+    # PIM Modula-2 Standard Library Variables Dataset
+    pim_stdlib_var_identifiers = (
+        'Done', 'termCH', 'in', 'out'
+    )
+
+    # PIM Modula-2 Standard Library Constants Dataset
+    pim_stdlib_const_identifiers = (
+        'EOL',
+    )
+
+#  I S O   S t a n d a r d   L i b r a r y   D a t a s e t s
+
+    # ISO Modula-2 Standard Library Modules Dataset
+    iso_stdlib_module_identifiers = (
+        # TO DO
+    )
+
+    # ISO Modula-2 Standard Library Types Dataset
+    iso_stdlib_type_identifiers = (
+        # TO DO
+    )
+
+    # ISO Modula-2 Standard Library Procedures Dataset
+    iso_stdlib_proc_identifiers = (
+        # TO DO
+    )
+
+    # ISO Modula-2 Standard Library Variables Dataset
+    iso_stdlib_var_identifiers = (
+        # TO DO
+    )
+
+    # ISO Modula-2 Standard Library Constants Dataset
+    iso_stdlib_const_identifiers = (
+        # TO DO
+    )
+
+#  M 2   R 1 0   S t a n d a r d   L i b r a r y   D a t a s e t s
+
+    # Modula-2 R10 Standard Library ADTs Dataset
+    m2r10_stdlib_adt_identifiers = (
+        'BCD', 'LONGBCD', 'BITSET', 'SHORTBITSET', 'LONGBITSET',
+        'LONGLONGBITSET', 'COMPLEX', 'LONGCOMPLEX', 'SHORTCARD', 'LONGLONGCARD',
+        'SHORTINT', 'LONGLONGINT', 'POSINT', 'SHORTPOSINT', 'LONGPOSINT',
+        'LONGLONGPOSINT', 'BITSET8', 'BITSET16', 'BITSET32', 'BITSET64',
+        'BITSET128', 'BS8', 'BS16', 'BS32', 'BS64', 'BS128', 'CARDINAL8',
+        'CARDINAL16', 'CARDINAL32', 'CARDINAL64', 'CARDINAL128', 'CARD8',
+        'CARD16', 'CARD32', 'CARD64', 'CARD128', 'INTEGER8', 'INTEGER16',
+        'INTEGER32', 'INTEGER64', 'INTEGER128', 'INT8', 'INT16', 'INT32',
+        'INT64', 'INT128', 'STRING', 'UNISTRING',
+    )
+
+    # Modula-2 R10 Standard Library Blueprints Dataset
+    m2r10_stdlib_blueprint_identifiers = (
+        'ProtoRoot', 'ProtoComputational', 'ProtoNumeric', 'ProtoScalar',
+        'ProtoNonScalar', 'ProtoCardinal', 'ProtoInteger', 'ProtoReal',
+        'ProtoComplex', 'ProtoVector', 'ProtoTuple', 'ProtoCompArray',
+        'ProtoCollection', 'ProtoStaticArray', 'ProtoStaticSet',
+        'ProtoStaticString', 'ProtoArray', 'ProtoString', 'ProtoSet',
+        'ProtoMultiSet', 'ProtoDictionary', 'ProtoMultiDict', 'ProtoExtension',
+        'ProtoIO', 'ProtoCardMath', 'ProtoIntMath', 'ProtoRealMath',
+    )
+
+    # Modula-2 R10 Standard Library Modules Dataset
+    m2r10_stdlib_module_identifiers = (
+        'ASCII', 'BooleanIO', 'CharIO', 'UnicharIO', 'OctetIO',
+        'CardinalIO', 'LongCardIO', 'IntegerIO', 'LongIntIO', 'RealIO',
+        'LongRealIO', 'BCDIO', 'LongBCDIO', 'CardMath', 'LongCardMath',
+        'IntMath', 'LongIntMath', 'RealMath', 'LongRealMath', 'BCDMath',
+        'LongBCDMath', 'FileIO', 'FileSystem', 'Storage', 'IOSupport',
+    )
+
+    # Modula-2 R10 Standard Library Types Dataset
+    m2r10_stdlib_type_identifiers = (
+        'File', 'Status',
+        # TO BE COMPLETED
+    )
+
+    # Modula-2 R10 Standard Library Procedures Dataset
+    m2r10_stdlib_proc_identifiers = (
+        'ALLOCATE', 'DEALLOCATE', 'SIZE',
+        # TO BE COMPLETED
+    )
+
+    # Modula-2 R10 Standard Library Variables Dataset
+    m2r10_stdlib_var_identifiers = (
+        'stdIn', 'stdOut', 'stdErr',
+    )
+
+    # Modula-2 R10 Standard Library Constants Dataset
+    m2r10_stdlib_const_identifiers = (
+        'pi', 'tau',
+    )
+
+#  D i a l e c t s
+
+    # Dialect modes
+    dialects = (
+        'unknown',
+        'm2pim', 'm2iso', 'm2r10', 'objm2',
+        'm2iso+aglet', 'm2pim+gm2', 'm2iso+p1', 'm2iso+xds',
+    )
+
+#   D a t a b a s e s
+
+    # Lexemes to Mark as Errors Database
+    lexemes_to_reject_db = {
+        # Lexemes to reject for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Lexemes to reject for PIM Modula-2
+        'm2pim': (
+            pim_lexemes_to_reject,
+        ),
+        # Lexemes to reject for ISO Modula-2
+        'm2iso': (
+            iso_lexemes_to_reject,
+        ),
+        # Lexemes to reject for Modula-2 R10
+        'm2r10': (
+            m2r10_lexemes_to_reject,
+        ),
+        # Lexemes to reject for Objective Modula-2
+        'objm2': (
+            objm2_lexemes_to_reject,
+        ),
+        # Lexemes to reject for Aglet Modula-2
+        'm2iso+aglet': (
+            iso_lexemes_to_reject,
+        ),
+        # Lexemes to reject for GNU Modula-2
+        'm2pim+gm2': (
+            pim_lexemes_to_reject,
+        ),
+        # Lexemes to reject for p1 Modula-2
+        'm2iso+p1': (
+            iso_lexemes_to_reject,
+        ),
+        # Lexemes to reject for XDS Modula-2
+        'm2iso+xds': (
+            iso_lexemes_to_reject,
+        ),
+    }
+
+    # Reserved Words Database
+    reserved_words_db = {
+        # Reserved words for unknown dialect
+        'unknown': (
+            common_reserved_words,
+            pim_additional_reserved_words,
+            iso_additional_reserved_words,
+            m2r10_additional_reserved_words,
+        ),
+
+        # Reserved words for PIM Modula-2
+        'm2pim': (
+            common_reserved_words,
+            pim_additional_reserved_words,
+        ),
+
+        # Reserved words for Modula-2 R10
+        'm2iso': (
+            common_reserved_words,
+            iso_additional_reserved_words,
+        ),
+
+        # Reserved words for ISO Modula-2
+        'm2r10': (
+            common_reserved_words,
+            m2r10_additional_reserved_words,
+        ),
+
+        # Reserved words for Objective Modula-2
+        'objm2': (
+            common_reserved_words,
+            m2r10_additional_reserved_words,
+            objm2_additional_reserved_words,
+        ),
+
+        # Reserved words for Aglet Modula-2 Extensions
+        'm2iso+aglet': (
+            common_reserved_words,
+            iso_additional_reserved_words,
+            aglet_additional_reserved_words,
+        ),
+
+        # Reserved words for GNU Modula-2 Extensions
+        'm2pim+gm2': (
+            common_reserved_words,
+            pim_additional_reserved_words,
+            gm2_additional_reserved_words,
+        ),
+
+        # Reserved words for p1 Modula-2 Extensions
+        'm2iso+p1': (
+            common_reserved_words,
+            iso_additional_reserved_words,
+            p1_additional_reserved_words,
+        ),
+
+        # Reserved words for XDS Modula-2 Extensions
+        'm2iso+xds': (
+            common_reserved_words,
+            iso_additional_reserved_words,
+            xds_additional_reserved_words,
+        ),
+    }
+
+    # Builtins Database
+    builtins_db = {
+        # Builtins for unknown dialect
+        'unknown': (
+            common_builtins,
+            pim_additional_builtins,
+            iso_additional_builtins,
+            m2r10_additional_builtins,
+        ),
+
+        # Builtins for PIM Modula-2
+        'm2pim': (
+            common_builtins,
+            pim_additional_builtins,
+        ),
+
+        # Builtins for ISO Modula-2
+        'm2iso': (
+            common_builtins,
+            iso_additional_builtins,
+        ),
+
+        # Builtins for ISO Modula-2
+        'm2r10': (
+            common_builtins,
+            m2r10_additional_builtins,
+        ),
+
+        # Builtins for Objective Modula-2
+        'objm2': (
+            common_builtins,
+            m2r10_additional_builtins,
+            objm2_additional_builtins,
+        ),
+
+        # Builtins for Aglet Modula-2 Extensions
+        'm2iso+aglet': (
+            common_builtins,
+            iso_additional_builtins,
+            aglet_additional_builtins,
+        ),
+
+        # Builtins for GNU Modula-2 Extensions
+        'm2pim+gm2': (
+            common_builtins,
+            pim_additional_builtins,
+            gm2_additional_builtins,
+        ),
+
+        # Builtins for p1 Modula-2 Extensions
+        'm2iso+p1': (
+            common_builtins,
+            iso_additional_builtins,
+            p1_additional_builtins,
+        ),
+
+        # Builtins for XDS Modula-2 Extensions
+        'm2iso+xds': (
+            common_builtins,
+            iso_additional_builtins,
+            xds_additional_builtins,
+        ),
+    }
+
+    # Pseudo-Module Builtins Database
+    pseudo_builtins_db = {
+        # Builtins for unknown dialect
+        'unknown': (
+            common_pseudo_builtins,
+            pim_additional_pseudo_builtins,
+            iso_additional_pseudo_builtins,
+            m2r10_additional_pseudo_builtins,
+        ),
+
+        # Builtins for PIM Modula-2
+        'm2pim': (
+            common_pseudo_builtins,
+            pim_additional_pseudo_builtins,
+        ),
+
+        # Builtins for ISO Modula-2
+        'm2iso': (
+            common_pseudo_builtins,
+            iso_additional_pseudo_builtins,
+        ),
+
+        # Builtins for ISO Modula-2
+        'm2r10': (
+            common_pseudo_builtins,
+            m2r10_additional_pseudo_builtins,
+        ),
+
+        # Builtins for Objective Modula-2
+        'objm2': (
+            common_pseudo_builtins,
+            m2r10_additional_pseudo_builtins,
+            objm2_additional_pseudo_builtins,
+        ),
+
+        # Builtins for Aglet Modula-2 Extensions
+        'm2iso+aglet': (
+            common_pseudo_builtins,
+            iso_additional_pseudo_builtins,
+            aglet_additional_pseudo_builtins,
+        ),
+
+        # Builtins for GNU Modula-2 Extensions
+        'm2pim+gm2': (
+            common_pseudo_builtins,
+            pim_additional_pseudo_builtins,
+            gm2_additional_pseudo_builtins,
+        ),
+
+        # Builtins for p1 Modula-2 Extensions
+        'm2iso+p1': (
+            common_pseudo_builtins,
+            iso_additional_pseudo_builtins,
+            p1_additional_pseudo_builtins,
+        ),
+
+        # Builtins for XDS Modula-2 Extensions
+        'm2iso+xds': (
+            common_pseudo_builtins,
+            iso_additional_pseudo_builtins,
+            xds_additional_pseudo_builtins,
+        ),
+    }
+
+    # Standard Library ADTs Database
+    stdlib_adts_db = {
+        # Empty entry for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Standard Library ADTs for PIM Modula-2
+        'm2pim': (
+            # No first class library types
+        ),
+
+        # Standard Library ADTs for ISO Modula-2
+        'm2iso': (
+            # No first class library types
+        ),
+
+        # Standard Library ADTs for Modula-2 R10
+        'm2r10': (
+            m2r10_stdlib_adt_identifiers,
+        ),
+
+        # Standard Library ADTs for Objective Modula-2
+        'objm2': (
+            m2r10_stdlib_adt_identifiers,
+        ),
+
+        # Standard Library ADTs for Aglet Modula-2
+        'm2iso+aglet': (
+            # No first class library types
+        ),
+
+        # Standard Library ADTs for GNU Modula-2
+        'm2pim+gm2': (
+            # No first class library types
+        ),
+
+        # Standard Library ADTs for p1 Modula-2
+        'm2iso+p1': (
+            # No first class library types
+        ),
+
+        # Standard Library ADTs for XDS Modula-2
+        'm2iso+xds': (
+            # No first class library types
+        ),
+    }
+
+    # Standard Library Modules Database
+    stdlib_modules_db = {
+        # Empty entry for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Standard Library Modules for PIM Modula-2
+        'm2pim': (
+            pim_stdlib_module_identifiers,
+        ),
+
+        # Standard Library Modules for ISO Modula-2
+        'm2iso': (
+            iso_stdlib_module_identifiers,
+        ),
+
+        # Standard Library Modules for Modula-2 R10
+        'm2r10': (
+            m2r10_stdlib_blueprint_identifiers,
+            m2r10_stdlib_module_identifiers,
+            m2r10_stdlib_adt_identifiers,
+        ),
+
+        # Standard Library Modules for Objective Modula-2
+        'objm2': (
+            m2r10_stdlib_blueprint_identifiers,
+            m2r10_stdlib_module_identifiers,
+        ),
+
+        # Standard Library Modules for Aglet Modula-2
+        'm2iso+aglet': (
+            iso_stdlib_module_identifiers,
+        ),
+
+        # Standard Library Modules for GNU Modula-2
+        'm2pim+gm2': (
+            pim_stdlib_module_identifiers,
+        ),
+
+        # Standard Library Modules for p1 Modula-2
+        'm2iso+p1': (
+            iso_stdlib_module_identifiers,
+        ),
+
+        # Standard Library Modules for XDS Modula-2
+        'm2iso+xds': (
+            iso_stdlib_module_identifiers,
+        ),
+    }
+
+    # Standard Library Types Database
+    stdlib_types_db = {
+        # Empty entry for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Standard Library Types for PIM Modula-2
+        'm2pim': (
+            pim_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for ISO Modula-2
+        'm2iso': (
+            iso_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for Modula-2 R10
+        'm2r10': (
+            m2r10_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for Objective Modula-2
+        'objm2': (
+            m2r10_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for Aglet Modula-2
+        'm2iso+aglet': (
+            iso_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for GNU Modula-2
+        'm2pim+gm2': (
+            pim_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for p1 Modula-2
+        'm2iso+p1': (
+            iso_stdlib_type_identifiers,
+        ),
+
+        # Standard Library Types for XDS Modula-2
+        'm2iso+xds': (
+            iso_stdlib_type_identifiers,
+        ),
+    }
+
+    # Standard Library Procedures Database
+    stdlib_procedures_db = {
+        # Empty entry for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Standard Library Procedures for PIM Modula-2
+        'm2pim': (
+            pim_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for ISO Modula-2
+        'm2iso': (
+            iso_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for Modula-2 R10
+        'm2r10': (
+            m2r10_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for Objective Modula-2
+        'objm2': (
+            m2r10_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for Aglet Modula-2
+        'm2iso+aglet': (
+            iso_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for GNU Modula-2
+        'm2pim+gm2': (
+            pim_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for p1 Modula-2
+        'm2iso+p1': (
+            iso_stdlib_proc_identifiers,
+        ),
+
+        # Standard Library Procedures for XDS Modula-2
+        'm2iso+xds': (
+            iso_stdlib_proc_identifiers,
+        ),
+    }
+
+    # Standard Library Variables Database
+    stdlib_variables_db = {
+        # Empty entry for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Standard Library Variables for PIM Modula-2
+        'm2pim': (
+            pim_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for ISO Modula-2
+        'm2iso': (
+            iso_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for Modula-2 R10
+        'm2r10': (
+            m2r10_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for Objective Modula-2
+        'objm2': (
+            m2r10_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for Aglet Modula-2
+        'm2iso+aglet': (
+            iso_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for GNU Modula-2
+        'm2pim+gm2': (
+            pim_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for p1 Modula-2
+        'm2iso+p1': (
+            iso_stdlib_var_identifiers,
+        ),
+
+        # Standard Library Variables for XDS Modula-2
+        'm2iso+xds': (
+            iso_stdlib_var_identifiers,
+        ),
+    }
+
+    # Standard Library Constants Database
+    stdlib_constants_db = {
+        # Empty entry for unknown dialect
+        'unknown': (
+            # LEAVE THIS EMPTY
+        ),
+        # Standard Library Constants for PIM Modula-2
+        'm2pim': (
+            pim_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for ISO Modula-2
+        'm2iso': (
+            iso_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for Modula-2 R10
+        'm2r10': (
+            m2r10_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for Objective Modula-2
+        'objm2': (
+            m2r10_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for Aglet Modula-2
+        'm2iso+aglet': (
+            iso_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for GNU Modula-2
+        'm2pim+gm2': (
+            pim_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for p1 Modula-2
+        'm2iso+p1': (
+            iso_stdlib_const_identifiers,
+        ),
+
+        # Standard Library Constants for XDS Modula-2
+        'm2iso+xds': (
+            iso_stdlib_const_identifiers,
+        ),
+    }
+
+#   M e t h o d s
+
+    # initialise a lexer instance
+    def __init__(self, **options):
+        #
+        # check dialect options
+        #
+        dialects = get_list_opt(options, 'dialect', [])
+        #
+        for dialect_option in dialects:
+            if dialect_option in self.dialects[1:-1]:
+                # valid dialect option found
+                self.set_dialect(dialect_option)
+                break
+        #
+        # Fallback Mode (DEFAULT)
+        else:
+            # no valid dialect option
+            self.set_dialect('unknown')
+        #
+        self.dialect_set_by_tag = False
+        #
+        # check style options
+        #
+        styles = get_list_opt(options, 'style', [])
+        #
+        # use lowercase mode for Algol style
+        if 'algol' in styles or 'algol_nu' in styles:
+            self.algol_publication_mode = True
+        else:
+            self.algol_publication_mode = False
+        #
+        # Check option flags
+        #
+        self.treat_stdlib_adts_as_builtins = get_bool_opt(
+            options, 'treat_stdlib_adts_as_builtins', True)
+        #
+        # call superclass initialiser
+        RegexLexer.__init__(self, **options)
+
+    # Set lexer to a specified dialect
+    def set_dialect(self, dialect_id):
+        #
+        # if __debug__:
+        #    print 'entered set_dialect with arg: ', dialect_id
+        #
+        # check dialect name against known dialects
+        if dialect_id not in self.dialects:
+            dialect = 'unknown'  # default
+        else:
+            dialect = dialect_id
+        #
+        # compose lexemes to reject set
+        lexemes_to_reject_set = set()
+        # add each list of reject lexemes for this dialect
+        for list in self.lexemes_to_reject_db[dialect]:
+            lexemes_to_reject_set.update(set(list))
+        #
+        # compose reserved words set
+        reswords_set = set()
+        # add each list of reserved words for this dialect
+        for list in self.reserved_words_db[dialect]:
+            reswords_set.update(set(list))
+        #
+        # compose builtins set
+        builtins_set = set()
+        # add each list of builtins for this dialect excluding reserved words
+        for list in self.builtins_db[dialect]:
+            builtins_set.update(set(list).difference(reswords_set))
+        #
+        # compose pseudo-builtins set
+        pseudo_builtins_set = set()
+        # add each list of builtins for this dialect excluding reserved words
+        for list in self.pseudo_builtins_db[dialect]:
+            pseudo_builtins_set.update(set(list).difference(reswords_set))
+        #
+        # compose ADTs set
+        adts_set = set()
+        # add each list of ADTs for this dialect excluding reserved words
+        for list in self.stdlib_adts_db[dialect]:
+            adts_set.update(set(list).difference(reswords_set))
+        #
+        # compose modules set
+        modules_set = set()
+        # add each list of builtins for this dialect excluding builtins
+        for list in self.stdlib_modules_db[dialect]:
+            modules_set.update(set(list).difference(builtins_set))
+        #
+        # compose types set
+        types_set = set()
+        # add each list of types for this dialect excluding builtins
+        for list in self.stdlib_types_db[dialect]:
+            types_set.update(set(list).difference(builtins_set))
+        #
+        # compose procedures set
+        procedures_set = set()
+        # add each list of procedures for this dialect excluding builtins
+        for list in self.stdlib_procedures_db[dialect]:
+            procedures_set.update(set(list).difference(builtins_set))
+        #
+        # compose variables set
+        variables_set = set()
+        # add each list of variables for this dialect excluding builtins
+        for list in self.stdlib_variables_db[dialect]:
+            variables_set.update(set(list).difference(builtins_set))
+        #
+        # compose constants set
+        constants_set = set()
+        # add each list of constants for this dialect excluding builtins
+        for list in self.stdlib_constants_db[dialect]:
+            constants_set.update(set(list).difference(builtins_set))
+        #
+        # update lexer state
+        self.dialect = dialect
+        self.lexemes_to_reject = lexemes_to_reject_set
+        self.reserved_words = reswords_set
+        self.builtins = builtins_set
+        self.pseudo_builtins = pseudo_builtins_set
+        self.adts = adts_set
+        self.modules = modules_set
+        self.types = types_set
+        self.procedures = procedures_set
+        self.variables = variables_set
+        self.constants = constants_set
+        #
+        # if __debug__:
+        #    print 'exiting set_dialect'
+        #    print ' self.dialect: ', self.dialect
+        #    print ' self.lexemes_to_reject: ', self.lexemes_to_reject
+        #    print ' self.reserved_words: ', self.reserved_words
+        #    print ' self.builtins: ', self.builtins
+        #    print ' self.pseudo_builtins: ', self.pseudo_builtins
+        #    print ' self.adts: ', self.adts
+        #    print ' self.modules: ', self.modules
+        #    print ' self.types: ', self.types
+        #    print ' self.procedures: ', self.procedures
+        #    print ' self.variables: ', self.variables
+        #    print ' self.types: ', self.types
+        #    print ' self.constants: ', self.constants
+
+    # Extracts a dialect name from a dialect tag comment string  and checks
+    # the extracted name against known dialects.  If a match is found,  the
+    # matching name is returned, otherwise dialect id 'unknown' is returned
+    def get_dialect_from_dialect_tag(self, dialect_tag):
+        #
+        # if __debug__:
+        #    print 'entered get_dialect_from_dialect_tag with arg: ', dialect_tag
+        #
+        # constants
+        left_tag_delim = '(*!'
+        right_tag_delim = '*)'
+        left_tag_delim_len = len(left_tag_delim)
+        right_tag_delim_len = len(right_tag_delim)
+        indicator_start = left_tag_delim_len
+        indicator_end = -(right_tag_delim_len)
+        #
+        # check comment string for dialect indicator
+        if len(dialect_tag) > (left_tag_delim_len + right_tag_delim_len) \
+           and dialect_tag.startswith(left_tag_delim) \
+           and dialect_tag.endswith(right_tag_delim):
+            #
+            # if __debug__:
+            #    print 'dialect tag found'
+            #
+            # extract dialect indicator
+            indicator = dialect_tag[indicator_start:indicator_end]
+            #
+            # if __debug__:
+            #    print 'extracted: ', indicator
+            #
+            # check against known dialects
+            for index in range(1, len(self.dialects)):
+                #
+                # if __debug__:
+                #    print 'dialects[', index, ']: ', self.dialects[index]
+                #
+                if indicator == self.dialects[index]:
+                    #
+                    # if __debug__:
+                    #    print 'matching dialect found'
+                    #
+                    # indicator matches known dialect
+                    return indicator
+            else:
+                # indicator does not match any dialect
+                return 'unknown'  # default
+        else:
+            # invalid indicator string
+            return 'unknown'  # default
+
+    # intercept the token stream, modify token attributes and return them
+    def get_tokens_unprocessed(self, text):
+        for index, token, value in RegexLexer.get_tokens_unprocessed(self, text):
+            #
+            # check for dialect tag if dialect has not been set by tag
+            if not self.dialect_set_by_tag and token == Comment.Special:
+                indicated_dialect = self.get_dialect_from_dialect_tag(value)
+                if indicated_dialect != 'unknown':
+                    # token is a dialect indicator
+                    # reset reserved words and builtins
+                    self.set_dialect(indicated_dialect)
+                    self.dialect_set_by_tag = True
+            #
+            # check for reserved words, predefined and stdlib identifiers
+            if token is Name:
+                if value in self.reserved_words:
+                    token = Keyword.Reserved
+                    if self.algol_publication_mode:
+                        value = value.lower()
+                #
+                elif value in self.builtins:
+                    token = Name.Builtin
+                    if self.algol_publication_mode:
+                        value = value.lower()
+                #
+                elif value in self.pseudo_builtins:
+                    token = Name.Builtin.Pseudo
+                    if self.algol_publication_mode:
+                        value = value.lower()
+                #
+                elif value in self.adts:
+                    if not self.treat_stdlib_adts_as_builtins:
+                        token = Name.Namespace
+                    else:
+                        token = Name.Builtin.Pseudo
+                        if self.algol_publication_mode:
+                            value = value.lower()
+                #
+                elif value in self.modules:
+                    token = Name.Namespace
+                #
+                elif value in self.types:
+                    token = Name.Class
+                #
+                elif value in self.procedures:
+                    token = Name.Function
+                #
+                elif value in self.variables:
+                    token = Name.Variable
+                #
+                elif value in self.constants:
+                    token = Name.Constant
+            #
+            elif token in Number:
+                #
+                # mark prefix number literals as error for PIM and ISO dialects
+                if self.dialect not in ('unknown', 'm2r10', 'objm2'):
+                    if "'" in value or value[0:2] in ('0b', '0x', '0u'):
+                        token = Error
+                #
+                elif self.dialect in ('m2r10', 'objm2'):
+                    # mark base-8 number literals as errors for M2 R10 and ObjM2
+                    if token is Number.Oct:
+                        token = Error
+                    # mark suffix base-16 literals as errors for M2 R10 and ObjM2
+                    elif token is Number.Hex and 'H' in value:
+                        token = Error
+                    # mark real numbers with E as errors for M2 R10 and ObjM2
+                    elif token is Number.Float and 'E' in value:
+                        token = Error
+            #
+            elif token in Comment:
+                #
+                # mark single line comment as error for PIM and ISO dialects
+                if token is Comment.Single:
+                    if self.dialect not in ('unknown', 'm2r10', 'objm2'):
+                        token = Error
+                #
+                if token is Comment.Preproc:
+                    # mark ISO pragma as error for PIM dialects
+                    if value.startswith('<*') and \
+                       self.dialect.startswith('m2pim'):
+                        token = Error
+                    # mark PIM pragma as comment for other dialects
+                    elif value.startswith('(*$') and \
+                            self.dialect != 'unknown' and \
+                            not self.dialect.startswith('m2pim'):
+                        token = Comment.Multiline
+            #
+            else:  # token is neither Name nor Comment
+                #
+                # mark lexemes matching the dialect's error token set as errors
+                if value in self.lexemes_to_reject:
+                    token = Error
+                #
+                # substitute lexemes when in Algol mode
+                if self.algol_publication_mode:
+                    if value == '#':
+                        value = '≠'
+                    elif value == '<=':
+                        value = '≤'
+                    elif value == '>=':
+                        value = '≥'
+                    elif value == '==':
+                        value = '≡'
+                    elif value == '*.':
+                        value = '•'
+
+            # return result
+            yield index, token, value
+
+    def analyse_text(text):
+        """It's Pascal-like, but does not use FUNCTION -- uses PROCEDURE
+        instead."""
+
+        # Check if this looks like Pascal, if not, bail out early
+        if not ('(*' in text and '*)' in text and ':=' in text):
+            return
+
+        result = 0
+        # Procedure is in Modula2
+        if re.search(r'\bPROCEDURE\b', text):
+            result += 0.6
+
+        # FUNCTION is only valid in Pascal, but not in Modula2
+        if re.search(r'\bFUNCTION\b', text):
+            result = 0.0
+
+        return result
diff --git a/lib/python3.11/site-packages/pygments/lexers/mojo.py b/lib/python3.11/site-packages/pygments/lexers/mojo.py
new file mode 100644
index 0000000000000000000000000000000000000000..84aac46694607b0f385fc1aec747c3ffcde7ca74
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/mojo.py
@@ -0,0 +1,707 @@
+"""
+    pygments.lexers.mojo
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Mojo and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import keyword
+
+from pygments import unistring as uni
+from pygments.lexer import (
+    RegexLexer,
+    bygroups,
+    combined,
+    default,
+    include,
+    this,
+    using,
+    words,
+)
+from pygments.token import (
+    Comment,
+    # Error,
+    Keyword,
+    Name,
+    Number,
+    Operator,
+    Punctuation,
+    String,
+    Text,
+    Whitespace,
+)
+from pygments.util import shebang_matches
+
+__all__ = ["MojoLexer"]
+
+
+class MojoLexer(RegexLexer):
+    """
+    For Mojo source code (version 24.2.1).
+    """
+
+    name = "Mojo"
+    url = "https://docs.modular.com/mojo/"
+    aliases = ["mojo", "🔥"]
+    filenames = [
+        "*.mojo",
+        "*.🔥",
+    ]
+    mimetypes = [
+        "text/x-mojo",
+        "application/x-mojo",
+    ]
+    version_added = "2.18"
+
+    uni_name = f"[{uni.xid_start}][{uni.xid_continue}]*"
+
+    def innerstring_rules(ttype):
+        return [
+            # the old style '%s' % (...) string formatting (still valid in Py3)
+            (
+                r"%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?"
+                "[hlL]?[E-GXc-giorsaux%]",
+                String.Interpol,
+            ),
+            # the new style '{}'.format(...) string formatting
+            (
+                r"\{"
+                r"((\w+)((\.\w+)|(\[[^\]]+\]))*)?"  # field name
+                r"(\![sra])?"  # conversion
+                r"(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?"
+                r"\}",
+                String.Interpol,
+            ),
+            # backslashes, quotes and formatting signs must be parsed one at a time
+            (r'[^\\\'"%{\n]+', ttype),
+            (r'[\'"\\]', ttype),
+            # unhandled string formatting sign
+            (r"%|(\{{1,2})", ttype),
+            # newlines are an error (use "nl" state)
+        ]
+
+    def fstring_rules(ttype):
+        return [
+            # Assuming that a '}' is the closing brace after format specifier.
+            # Sadly, this means that we won't detect syntax error. But it's
+            # more important to parse correct syntax correctly, than to
+            # highlight invalid syntax.
+            (r"\}", String.Interpol),
+            (r"\{", String.Interpol, "expr-inside-fstring"),
+            # backslashes, quotes and formatting signs must be parsed one at a time
+            (r'[^\\\'"{}\n]+', ttype),
+            (r'[\'"\\]', ttype),
+            # newlines are an error (use "nl" state)
+        ]
+
+    tokens = {
+        "root": [
+            (r"\s+", Whitespace),
+            (
+                r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")',
+                bygroups(Whitespace, String.Affix, String.Doc),
+            ),
+            (
+                r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')",
+                bygroups(Whitespace, String.Affix, String.Doc),
+            ),
+            (r"\A#!.+$", Comment.Hashbang),
+            (r"#.*$", Comment.Single),
+            (r"\\\n", Whitespace),
+            (r"\\", Whitespace),
+            include("keywords"),
+            include("soft-keywords"),
+            # In the original PR, all the below here used ((?:\s|\\\s)+) to
+            # designate whitespace, but I can't find any example of this being
+            # needed in the example file, so we're replacing it with `\s+`.
+            (
+                r"(alias)(\s+)",
+                bygroups(Keyword, Whitespace),
+                "varname",  # TODO varname the right fit?
+            ),
+            (r"(var)(\s+)", bygroups(Keyword, Whitespace), "varname"),
+            (r"(def)(\s+)", bygroups(Keyword, Whitespace), "funcname"),
+            (r"(fn)(\s+)", bygroups(Keyword, Whitespace), "funcname"),
+            (
+                r"(class)(\s+)",
+                bygroups(Keyword, Whitespace),
+                "classname",
+            ),  # not implemented yet
+            (r"(struct)(\s+)", bygroups(Keyword, Whitespace), "structname"),
+            (r"(trait)(\s+)", bygroups(Keyword, Whitespace), "structname"),
+            (r"(from)(\s+)", bygroups(Keyword.Namespace, Whitespace), "fromimport"),
+            (r"(import)(\s+)", bygroups(Keyword.Namespace, Whitespace), "import"),
+            include("expr"),
+        ],
+        "expr": [
+            # raw f-strings
+            (
+                '(?i)(rf|fr)(""")',
+                bygroups(String.Affix, String.Double),
+                combined("rfstringescape", "tdqf"),
+            ),
+            (
+                "(?i)(rf|fr)(''')",
+                bygroups(String.Affix, String.Single),
+                combined("rfstringescape", "tsqf"),
+            ),
+            (
+                '(?i)(rf|fr)(")',
+                bygroups(String.Affix, String.Double),
+                combined("rfstringescape", "dqf"),
+            ),
+            (
+                "(?i)(rf|fr)(')",
+                bygroups(String.Affix, String.Single),
+                combined("rfstringescape", "sqf"),
+            ),
+            # non-raw f-strings
+            (
+                '([fF])(""")',
+                bygroups(String.Affix, String.Double),
+                combined("fstringescape", "tdqf"),
+            ),
+            (
+                "([fF])(''')",
+                bygroups(String.Affix, String.Single),
+                combined("fstringescape", "tsqf"),
+            ),
+            (
+                '([fF])(")',
+                bygroups(String.Affix, String.Double),
+                combined("fstringescape", "dqf"),
+            ),
+            (
+                "([fF])(')",
+                bygroups(String.Affix, String.Single),
+                combined("fstringescape", "sqf"),
+            ),
+            # raw bytes and strings
+            ('(?i)(rb|br|r)(""")', bygroups(String.Affix, String.Double), "tdqs"),
+            ("(?i)(rb|br|r)(''')", bygroups(String.Affix, String.Single), "tsqs"),
+            ('(?i)(rb|br|r)(")', bygroups(String.Affix, String.Double), "dqs"),
+            ("(?i)(rb|br|r)(')", bygroups(String.Affix, String.Single), "sqs"),
+            # non-raw strings
+            (
+                '([uU]?)(""")',
+                bygroups(String.Affix, String.Double),
+                combined("stringescape", "tdqs"),
+            ),
+            (
+                "([uU]?)(''')",
+                bygroups(String.Affix, String.Single),
+                combined("stringescape", "tsqs"),
+            ),
+            (
+                '([uU]?)(")',
+                bygroups(String.Affix, String.Double),
+                combined("stringescape", "dqs"),
+            ),
+            (
+                "([uU]?)(')",
+                bygroups(String.Affix, String.Single),
+                combined("stringescape", "sqs"),
+            ),
+            # non-raw bytes
+            (
+                '([bB])(""")',
+                bygroups(String.Affix, String.Double),
+                combined("bytesescape", "tdqs"),
+            ),
+            (
+                "([bB])(''')",
+                bygroups(String.Affix, String.Single),
+                combined("bytesescape", "tsqs"),
+            ),
+            (
+                '([bB])(")',
+                bygroups(String.Affix, String.Double),
+                combined("bytesescape", "dqs"),
+            ),
+            (
+                "([bB])(')",
+                bygroups(String.Affix, String.Single),
+                combined("bytesescape", "sqs"),
+            ),
+            (r"[^\S\n]+", Text),
+            include("numbers"),
+            (r"!=|==|<<|>>|:=|[-~+/*%=<>&^|.]", Operator),
+            (r"([]{}:\(\),;[])+", Punctuation),
+            (r"(in|is|and|or|not)\b", Operator.Word),
+            include("expr-keywords"),
+            include("builtins"),
+            include("magicfuncs"),
+            include("magicvars"),
+            include("name"),
+        ],
+        "expr-inside-fstring": [
+            (r"[{([]", Punctuation, "expr-inside-fstring-inner"),
+            # without format specifier
+            (
+                r"(=\s*)?"  # debug (https://bugs.python.org/issue36817)
+                r"(\![sraf])?"  # conversion
+                r"\}",
+                String.Interpol,
+                "#pop",
+            ),
+            # with format specifier
+            # we'll catch the remaining '}' in the outer scope
+            (
+                r"(=\s*)?"  # debug (https://bugs.python.org/issue36817)
+                r"(\![sraf])?"  # conversion
+                r":",
+                String.Interpol,
+                "#pop",
+            ),
+            (r"\s+", Whitespace),  # allow new lines
+            include("expr"),
+        ],
+        "expr-inside-fstring-inner": [
+            (r"[{([]", Punctuation, "expr-inside-fstring-inner"),
+            (r"[])}]", Punctuation, "#pop"),
+            (r"\s+", Whitespace),  # allow new lines
+            include("expr"),
+        ],
+        "expr-keywords": [
+            # Based on https://docs.python.org/3/reference/expressions.html
+            (
+                words(
+                    (
+                        "async for",  # TODO https://docs.modular.com/mojo/roadmap#no-async-for-or-async-with
+                        "async with",  # TODO https://docs.modular.com/mojo/roadmap#no-async-for-or-async-with
+                        "await",
+                        "else",
+                        "for",
+                        "if",
+                        "lambda",
+                        "yield",
+                        "yield from",
+                    ),
+                    suffix=r"\b",
+                ),
+                Keyword,
+            ),
+            (words(("True", "False", "None"), suffix=r"\b"), Keyword.Constant),
+        ],
+        "keywords": [
+            (
+                words(
+                    (
+                        "assert",
+                        "async",
+                        "await",
+                        "borrowed",
+                        "break",
+                        "continue",
+                        "del",
+                        "elif",
+                        "else",
+                        "except",
+                        "finally",
+                        "for",
+                        "global",
+                        "if",
+                        "lambda",
+                        "pass",
+                        "raise",
+                        "nonlocal",
+                        "return",
+                        "try",
+                        "while",
+                        "yield",
+                        "yield from",
+                        "as",
+                        "with",
+                    ),
+                    suffix=r"\b",
+                ),
+                Keyword,
+            ),
+            (words(("True", "False", "None"), suffix=r"\b"), Keyword.Constant),
+        ],
+        "soft-keywords": [
+            # `match`, `case` and `_` soft keywords
+            (
+                r"(^[ \t]*)"  # at beginning of line + possible indentation
+                r"(match|case)\b"  # a possible keyword
+                r"(?![ \t]*(?:"  # not followed by...
+                r"[:,;=^&|@~)\]}]|(?:" +  # characters and keywords that mean this isn't
+                # pattern matching (but None/True/False is ok)
+                r"|".join(k for k in keyword.kwlist if k[0].islower())
+                + r")\b))",
+                bygroups(Whitespace, Keyword),
+                "soft-keywords-inner",
+            ),
+        ],
+        "soft-keywords-inner": [
+            # optional `_` keyword
+            (r"(\s+)([^\n_]*)(_\b)", bygroups(Whitespace, using(this), Keyword)),
+            default("#pop"),
+        ],
+        "builtins": [
+            (
+                words(
+                    (
+                        "__import__",
+                        "abs",
+                        "aiter",
+                        "all",
+                        "any",
+                        "bin",
+                        "bool",
+                        "bytearray",
+                        "breakpoint",
+                        "bytes",
+                        "callable",
+                        "chr",
+                        "classmethod",
+                        "compile",
+                        "complex",
+                        "delattr",
+                        "dict",
+                        "dir",
+                        "divmod",
+                        "enumerate",
+                        "eval",
+                        "filter",
+                        "float",
+                        "format",
+                        "frozenset",
+                        "getattr",
+                        "globals",
+                        "hasattr",
+                        "hash",
+                        "hex",
+                        "id",
+                        "input",
+                        "int",
+                        "isinstance",
+                        "issubclass",
+                        "iter",
+                        "len",
+                        "list",
+                        "locals",
+                        "map",
+                        "max",
+                        "memoryview",
+                        "min",
+                        "next",
+                        "object",
+                        "oct",
+                        "open",
+                        "ord",
+                        "pow",
+                        "print",
+                        "property",
+                        "range",
+                        "repr",
+                        "reversed",
+                        "round",
+                        "set",
+                        "setattr",
+                        "slice",
+                        "sorted",
+                        "staticmethod",
+                        "str",
+                        "sum",
+                        "super",
+                        "tuple",
+                        "type",
+                        "vars",
+                        "zip",
+                        # Mojo builtin types: https://docs.modular.com/mojo/stdlib/builtin/
+                        "AnyType",
+                        "Coroutine",
+                        "DType",
+                        "Error",
+                        "Int",
+                        "List",
+                        "ListLiteral",
+                        "Scalar",
+                        "Int8",
+                        "UInt8",
+                        "Int16",
+                        "UInt16",
+                        "Int32",
+                        "UInt32",
+                        "Int64",
+                        "UInt64",
+                        "BFloat16",
+                        "Float16",
+                        "Float32",
+                        "Float64",
+                        "SIMD",
+                        "String",
+                        "Tensor",
+                        "Tuple",
+                        "Movable",
+                        "Copyable",
+                        "CollectionElement",
+                    ),
+                    prefix=r"(?>',
+    # Binary augmented
+    '+=', '-=', '*=', '/=', '%=', '**=', '&=', '|=', '^=', '<<=', '>>=',
+    # Comparison
+    '==', '!=', '<', '<=', '>', '>=', '<=>',
+    # Patterns and assignment
+    ':=', '?', '=~', '!~', '=>',
+    # Calls and sends
+    '.', '<-', '->',
+]
+_escape_pattern = (
+    r'(?:\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|'
+    r'\\["\'\\bftnr])')
+# _char = _escape_chars + [('.', String.Char)]
+_identifier = r'[_a-zA-Z]\w*'
+
+_constants = [
+    # Void constants
+    'null',
+    # Bool constants
+    'false', 'true',
+    # Double constants
+    'Infinity', 'NaN',
+    # Special objects
+    'M', 'Ref', 'throw', 'traceln',
+]
+
+_guards = [
+    'Any', 'Binding', 'Bool', 'Bytes', 'Char', 'DeepFrozen', 'Double',
+    'Empty', 'Int', 'List', 'Map', 'Near', 'NullOk', 'Same', 'Selfless',
+    'Set', 'Str', 'SubrangeGuard', 'Transparent', 'Void',
+]
+
+_safeScope = [
+    '_accumulateList', '_accumulateMap', '_auditedBy', '_bind',
+    '_booleanFlow', '_comparer', '_equalizer', '_iterForever', '_loop',
+    '_makeBytes', '_makeDouble', '_makeFinalSlot', '_makeInt', '_makeList',
+    '_makeMap', '_makeMessageDesc', '_makeOrderedSpace', '_makeParamDesc',
+    '_makeProtocolDesc', '_makeSourceSpan', '_makeString', '_makeVarSlot',
+    '_makeVerbFacet', '_mapExtract', '_matchSame', '_quasiMatcher',
+    '_slotToBinding', '_splitList', '_suchThat', '_switchFailed',
+    '_validateFor', 'b__quasiParser', 'eval', 'import', 'm__quasiParser',
+    'makeBrandPair', 'makeLazySlot', 'safeScope', 'simple__quasiParser',
+]
+
+
+class MonteLexer(RegexLexer):
+    """
+    Lexer for the Monte programming language.
+    """
+    name = 'Monte'
+    url = 'https://monte.readthedocs.io/'
+    aliases = ['monte']
+    filenames = ['*.mt']
+    version_added = '2.2'
+
+    tokens = {
+        'root': [
+            # Comments
+            (r'#[^\n]*\n', Comment),
+
+            # Docstrings
+            # Apologies for the non-greedy matcher here.
+            (r'/\*\*.*?\*/', String.Doc),
+
+            # `var` declarations
+            (r'\bvar\b', Keyword.Declaration, 'var'),
+
+            # `interface` declarations
+            (r'\binterface\b', Keyword.Declaration, 'interface'),
+
+            # method declarations
+            (words(_methods, prefix='\\b', suffix='\\b'),
+             Keyword, 'method'),
+
+            # All other declarations
+            (words(_declarations, prefix='\\b', suffix='\\b'),
+             Keyword.Declaration),
+
+            # Keywords
+            (words(_keywords, prefix='\\b', suffix='\\b'), Keyword),
+
+            # Literals
+            ('[+-]?0x[_0-9a-fA-F]+', Number.Hex),
+            (r'[+-]?[_0-9]+\.[_0-9]*([eE][+-]?[_0-9]+)?', Number.Float),
+            ('[+-]?[_0-9]+', Number.Integer),
+            ("'", String.Double, 'char'),
+            ('"', String.Double, 'string'),
+
+            # Quasiliterals
+            ('`', String.Backtick, 'ql'),
+
+            # Operators
+            (words(_operators), Operator),
+
+            # Verb operators
+            (_identifier + '=', Operator.Word),
+
+            # Safe scope constants
+            (words(_constants, prefix='\\b', suffix='\\b'),
+             Keyword.Pseudo),
+
+            # Safe scope guards
+            (words(_guards, prefix='\\b', suffix='\\b'), Keyword.Type),
+
+            # All other safe scope names
+            (words(_safeScope, prefix='\\b', suffix='\\b'),
+             Name.Builtin),
+
+            # Identifiers
+            (_identifier, Name),
+
+            # Punctuation
+            (r'\(|\)|\{|\}|\[|\]|:|,', Punctuation),
+
+            # Whitespace
+            (' +', Whitespace),
+
+            # Definite lexer errors
+            ('=', Error),
+        ],
+        'char': [
+            # It is definitely an error to have a char of width == 0.
+            ("'", Error, 'root'),
+            (_escape_pattern, String.Escape, 'charEnd'),
+            ('.', String.Char, 'charEnd'),
+        ],
+        'charEnd': [
+            ("'", String.Char, '#pop:2'),
+            # It is definitely an error to have a char of width > 1.
+            ('.', Error),
+        ],
+        # The state of things coming into an interface.
+        'interface': [
+            (' +', Whitespace),
+            (_identifier, Name.Class, '#pop'),
+            include('root'),
+        ],
+        # The state of things coming into a method.
+        'method': [
+            (' +', Whitespace),
+            (_identifier, Name.Function, '#pop'),
+            include('root'),
+        ],
+        'string': [
+            ('"', String.Double, 'root'),
+            (_escape_pattern, String.Escape),
+            (r'\n', String.Double),
+            ('.', String.Double),
+        ],
+        'ql': [
+            ('`', String.Backtick, 'root'),
+            (r'\$' + _escape_pattern, String.Escape),
+            (r'\$\$', String.Escape),
+            (r'@@', String.Escape),
+            (r'\$\{', String.Interpol, 'qlNest'),
+            (r'@\{', String.Interpol, 'qlNest'),
+            (r'\$' + _identifier, Name),
+            ('@' + _identifier, Name),
+            ('.', String.Backtick),
+        ],
+        'qlNest': [
+            (r'\}', String.Interpol, '#pop'),
+            include('root'),
+        ],
+        # The state of things immediately following `var`.
+        'var': [
+            (' +', Whitespace),
+            (_identifier, Name.Variable, '#pop'),
+            include('root'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/mosel.py b/lib/python3.11/site-packages/pygments/lexers/mosel.py
new file mode 100644
index 0000000000000000000000000000000000000000..912f478773cb575412a937448e709bef101069e3
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/mosel.py
@@ -0,0 +1,447 @@
+"""
+    pygments.lexers.mosel
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the mosel language.
+    http://www.fico.com/en/products/fico-xpress-optimization
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['MoselLexer']
+
+FUNCTIONS = (
+    # core functions
+    '_',
+    'abs',
+    'arctan',
+    'asproc',
+    'assert',
+    'bitflip',
+    'bitneg',
+    'bitset',
+    'bitshift',
+    'bittest',
+    'bitval',
+    'ceil',
+    'cos',
+    'create',
+    'currentdate',
+    'currenttime',
+    'cutelt',
+    'cutfirst',
+    'cuthead',
+    'cutlast',
+    'cuttail',
+    'datablock',
+    'delcell',
+    'exists',
+    'exit',
+    'exp',
+    'exportprob',
+    'fclose',
+    'fflush',
+    'finalize',
+    'findfirst',
+    'findlast',
+    'floor',
+    'fopen',
+    'fselect',
+    'fskipline',
+    'fwrite',
+    'fwrite_',
+    'fwriteln',
+    'fwriteln_',
+    'getact',
+    'getcoeff',
+    'getcoeffs',
+    'getdual',
+    'getelt',
+    'getfid',
+    'getfirst',
+    'getfname',
+    'gethead',
+    'getlast',
+    'getobjval',
+    'getparam',
+    'getrcost',
+    'getreadcnt',
+    'getreverse',
+    'getsize',
+    'getslack',
+    'getsol',
+    'gettail',
+    'gettype',
+    'getvars',
+    'isdynamic',
+    'iseof',
+    'isfinite',
+    'ishidden',
+    'isinf',
+    'isnan',
+    'isodd',
+    'ln',
+    'localsetparam',
+    'log',
+    'makesos1',
+    'makesos2',
+    'maxlist',
+    'memoryuse',
+    'minlist',
+    'newmuid',
+    'publish',
+    'random',
+    'read',
+    'readln',
+    'reset',
+    'restoreparam',
+    'reverse',
+    'round',
+    'setcoeff',
+    'sethidden',
+    'setioerr',
+    'setmatherr',
+    'setname',
+    'setparam',
+    'setrandseed',
+    'setrange',
+    'settype',
+    'sin',
+    'splithead',
+    'splittail',
+    'sqrt',
+    'strfmt',
+    'substr',
+    'timestamp',
+    'unpublish',
+    'versionnum',
+    'versionstr',
+    'write',
+    'write_',
+    'writeln',
+    'writeln_',
+
+    # mosel exam mmxprs | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u
+    'addcut',
+    'addcuts',
+    'addmipsol',
+    'basisstability',
+    'calcsolinfo',
+    'clearmipdir',
+    'clearmodcut',
+    'command',
+    'copysoltoinit',
+    'crossoverlpsol',
+    'defdelayedrows',
+    'defsecurevecs',
+    'delcuts',
+    'dropcuts',
+    'estimatemarginals',
+    'fixglobal',
+    'flushmsgq',
+    'getbstat',
+    'getcnlist',
+    'getcplist',
+    'getdualray',
+    'getiis',
+    'getiissense',
+    'getiistype',
+    'getinfcause',
+    'getinfeas',
+    'getlb',
+    'getlct',
+    'getleft',
+    'getloadedlinctrs',
+    'getloadedmpvars',
+    'getname',
+    'getprimalray',
+    'getprobstat',
+    'getrange',
+    'getright',
+    'getsensrng',
+    'getsize',
+    'getsol',
+    'gettype',
+    'getub',
+    'getvars',
+    'gety',
+    'hasfeature',
+    'implies',
+    'indicator',
+    'initglobal',
+    'ishidden',
+    'isiisvalid',
+    'isintegral',
+    'loadbasis',
+    'loadcuts',
+    'loadlpsol',
+    'loadmipsol',
+    'loadprob',
+    'maximise',
+    'maximize',
+    'minimise',
+    'minimize',
+    'postsolve',
+    'readbasis',
+    'readdirs',
+    'readsol',
+    'refinemipsol',
+    'rejectintsol',
+    'repairinfeas',
+    'repairinfeas_deprec',
+    'resetbasis',
+    'resetiis',
+    'resetsol',
+    'savebasis',
+    'savemipsol',
+    'savesol',
+    'savestate',
+    'selectsol',
+    'setarchconsistency',
+    'setbstat',
+    'setcallback',
+    'setcbcutoff',
+    'setgndata',
+    'sethidden',
+    'setlb',
+    'setmipdir',
+    'setmodcut',
+    'setsol',
+    'setub',
+    'setucbdata',
+    'stopoptimise',
+    'stopoptimize',
+    'storecut',
+    'storecuts',
+    'unloadprob',
+    'uselastbarsol',
+    'writebasis',
+    'writedirs',
+    'writeprob',
+    'writesol',
+    'xor',
+    'xprs_addctr',
+    'xprs_addindic',
+
+    # mosel exam mmsystem | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u
+    'addmonths',
+    'copytext',
+    'cuttext',
+    'deltext',
+    'endswith',
+    'erase',
+    'expandpath',
+    'fcopy',
+    'fdelete',
+    'findfiles',
+    'findtext',
+    'fmove',
+    'formattext',
+    'getasnumber',
+    'getchar',
+    'getcwd',
+    'getdate',
+    'getday',
+    'getdaynum',
+    'getdays',
+    'getdirsep',
+    'getdsoparam',
+    'getendparse',
+    'getenv',
+    'getfsize',
+    'getfstat',
+    'getftime',
+    'gethour',
+    'getminute',
+    'getmonth',
+    'getmsec',
+    'getoserrmsg',
+    'getoserror',
+    'getpathsep',
+    'getqtype',
+    'getsecond',
+    'getsepchar',
+    'getsize',
+    'getstart',
+    'getsucc',
+    'getsysinfo',
+    'getsysstat',
+    'gettime',
+    'gettmpdir',
+    'gettrim',
+    'getweekday',
+    'getyear',
+    'inserttext',
+    'isvalid',
+    'jointext',
+    'makedir',
+    'makepath',
+    'newtar',
+    'newzip',
+    'nextfield',
+    'openpipe',
+    'parseextn',
+    'parseint',
+    'parsereal',
+    'parsetext',
+    'pastetext',
+    'pathmatch',
+    'pathsplit',
+    'qsort',
+    'quote',
+    'readtextline',
+    'regmatch',
+    'regreplace',
+    'removedir',
+    'removefiles',
+    'setchar',
+    'setdate',
+    'setday',
+    'setdsoparam',
+    'setendparse',
+    'setenv',
+    'sethour',
+    'setminute',
+    'setmonth',
+    'setmsec',
+    'setoserror',
+    'setqtype',
+    'setsecond',
+    'setsepchar',
+    'setstart',
+    'setsucc',
+    'settime',
+    'settrim',
+    'setyear',
+    'sleep',
+    'splittext',
+    'startswith',
+    'system',
+    'tarlist',
+    'textfmt',
+    'tolower',
+    'toupper',
+    'trim',
+    'untar',
+    'unzip',
+    'ziplist',
+
+    # mosel exam mmjobs | sed -n -e "s/ [pf][a-z]* \([a-zA-Z0-9_]*\).*/'\1',/p" | sort -u
+    'canceltimer',
+    'clearaliases',
+    'compile',
+    'connect',
+    'detach',
+    'disconnect',
+    'dropnextevent',
+    'findxsrvs',
+    'getaliases',
+    'getannidents',
+    'getannotations',
+    'getbanner',
+    'getclass',
+    'getdsoprop',
+    'getdsopropnum',
+    'getexitcode',
+    'getfromgid',
+    'getfromid',
+    'getfromuid',
+    'getgid',
+    'gethostalias',
+    'getid',
+    'getmodprop',
+    'getmodpropnum',
+    'getnextevent',
+    'getnode',
+    'getrmtid',
+    'getstatus',
+    'getsysinfo',
+    'gettimer',
+    'getuid',
+    'getvalue',
+    'isqueueempty',
+    'load',
+    'nullevent',
+    'peeknextevent',
+    'resetmodpar',
+    'run',
+    'send',
+    'setcontrol',
+    'setdefstream',
+    'setgid',
+    'sethostalias',
+    'setmodpar',
+    'settimer',
+    'setuid',
+    'setworkdir',
+    'stop',
+    'unload',
+    'wait',
+    'waitexpired',
+    'waitfor',
+    'waitforend',
+)
+
+
+class MoselLexer(RegexLexer):
+    """
+    For the Mosel optimization language.
+    """
+    name = 'Mosel'
+    aliases = ['mosel']
+    filenames = ['*.mos']
+    url = 'https://www.fico.com/fico-xpress-optimization/docs/latest/mosel/mosel_lang/dhtml/moselreflang.html'
+    version_added = '2.6'
+
+    tokens = {
+        'root': [
+            (r'\n', Text),
+            (r'\s+', Text.Whitespace),
+            (r'!.*?\n', Comment.Single),
+            (r'\(!(.|\n)*?!\)', Comment.Multiline),
+            (words((
+                'and', 'as', 'break', 'case', 'count', 'declarations', 'do',
+                'dynamic', 'elif', 'else', 'end-', 'end', 'evaluation', 'false',
+                'forall', 'forward', 'from', 'function', 'hashmap', 'if',
+                'imports', 'include', 'initialisations', 'initializations', 'inter',
+                'max', 'min', 'model', 'namespace', 'next', 'not', 'nsgroup',
+                'nssearch', 'of', 'options', 'or', 'package', 'parameters',
+                'procedure', 'public', 'prod', 'record', 'repeat', 'requirements',
+                'return', 'sum', 'then', 'to', 'true', 'union', 'until', 'uses',
+                'version', 'while', 'with'), prefix=r'\b', suffix=r'\b'),
+             Keyword.Builtin),
+            (words((
+                'range', 'array', 'set', 'list', 'mpvar', 'mpproblem', 'linctr',
+                'nlctr', 'integer', 'string', 'real', 'boolean', 'text', 'time',
+                'date', 'datetime', 'returned', 'Model', 'Mosel', 'counter',
+                'xmldoc', 'is_sos1', 'is_sos2', 'is_integer', 'is_binary',
+                'is_continuous', 'is_free', 'is_semcont', 'is_semint',
+                'is_partint'), prefix=r'\b', suffix=r'\b'),
+             Keyword.Type),
+            (r'(\+|\-|\*|/|=|<=|>=|\||\^|<|>|<>|\.\.|\.|:=|::|:|in|mod|div)',
+             Operator),
+            (r'[()\[\]{},;]+', Punctuation),
+            (words(FUNCTIONS,  prefix=r'\b', suffix=r'\b'), Name.Function),
+            (r'(\d+\.(?!\.)\d*|\.(?!.)\d+)([eE][+-]?\d+)?', Number.Float),
+            (r'\d+([eE][+-]?\d+)?', Number.Integer),
+            (r'[+-]?Infinity', Number.Integer),
+            (r'0[xX][0-9a-fA-F]+', Number),
+            (r'"', String.Double, 'double_quote'),
+            (r'\'', String.Single, 'single_quote'),
+            (r'(\w+|(\.(?!\.)))', Text),
+        ],
+        'single_quote': [
+            (r'\'', String.Single, '#pop'),
+            (r'[^\']+', String.Single),
+        ],
+        'double_quote': [
+            (r'(\\"|\\[0-7]{1,3}\D|\\[abfnrtv]|\\\\)', String.Escape),
+            (r'\"', String.Double, '#pop'),
+            (r'[^"\\]+', String.Double),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/ncl.py b/lib/python3.11/site-packages/pygments/lexers/ncl.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2729efba6e23c1d9d3ca86c8971649f2e964c17
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/ncl.py
@@ -0,0 +1,894 @@
+"""
+    pygments.lexers.ncl
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for NCAR Command Language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['NCLLexer']
+
+
+class NCLLexer(RegexLexer):
+    """
+    Lexer for NCL code.
+    """
+    name = 'NCL'
+    aliases = ['ncl']
+    filenames = ['*.ncl']
+    mimetypes = ['text/ncl']
+    url = 'https://www.ncl.ucar.edu'
+    version_added = '2.2'
+
+    flags = re.MULTILINE
+
+    tokens = {
+        'root': [
+            (r';.*\n', Comment),
+            include('strings'),
+            include('core'),
+            (r'[a-zA-Z_]\w*', Name),
+            include('nums'),
+            (r'[\s]+', Text),
+        ],
+        'core': [
+            # Statements
+            (words((
+                'begin', 'break', 'continue', 'create', 'defaultapp', 'do',
+                'else', 'end', 'external', 'exit', 'True', 'False', 'file', 'function',
+                'getvalues', 'graphic', 'group', 'if', 'list', 'load', 'local',
+                'new', '_Missing', 'Missing', 'noparent', 'procedure',
+                'quit', 'QUIT', 'Quit', 'record', 'return', 'setvalues', 'stop',
+                'then', 'while'), prefix=r'\b', suffix=r'\s*\b'),
+             Keyword),
+
+            # Data Types
+            (words((
+                'ubyte', 'uint', 'uint64', 'ulong', 'string', 'byte',
+                'character', 'double', 'float', 'integer', 'int64', 'logical',
+                'long', 'short', 'ushort', 'enumeric', 'numeric', 'snumeric'),
+                prefix=r'\b', suffix=r'\s*\b'),
+             Keyword.Type),
+
+            # Operators
+            (r'[\%^*+\-/<>]', Operator),
+
+            # punctuation:
+            (r'[\[\]():@$!&|.,\\{}]', Punctuation),
+            (r'[=:]', Punctuation),
+
+            # Intrinsics
+            (words((
+                'abs', 'acos', 'addfile', 'addfiles', 'all', 'angmom_atm', 'any',
+                'area_conserve_remap', 'area_hi2lores', 'area_poly_sphere',
+                'asciiread', 'asciiwrite', 'asin', 'atan', 'atan2', 'attsetvalues',
+                'avg', 'betainc', 'bin_avg', 'bin_sum', 'bw_bandpass_filter',
+                'cancor', 'cbinread', 'cbinwrite', 'cd_calendar', 'cd_inv_calendar',
+                'cdfbin_p', 'cdfbin_pr', 'cdfbin_s', 'cdfbin_xn', 'cdfchi_p',
+                'cdfchi_x', 'cdfgam_p', 'cdfgam_x', 'cdfnor_p', 'cdfnor_x',
+                'cdft_p', 'cdft_t', 'ceil', 'center_finite_diff',
+                'center_finite_diff_n', 'cfftb', 'cfftf', 'cfftf_frq_reorder',
+                'charactertodouble', 'charactertofloat', 'charactertointeger',
+                'charactertolong', 'charactertoshort', 'charactertostring',
+                'chartodouble', 'chartofloat', 'chartoint', 'chartointeger',
+                'chartolong', 'chartoshort', 'chartostring', 'chiinv', 'clear',
+                'color_index_to_rgba', 'conform', 'conform_dims', 'cos', 'cosh',
+                'count_unique_values', 'covcorm', 'covcorm_xy', 'craybinnumrec',
+                'craybinrecread', 'create_graphic', 'csa1', 'csa1d', 'csa1s',
+                'csa1x', 'csa1xd', 'csa1xs', 'csa2', 'csa2d', 'csa2l', 'csa2ld',
+                'csa2ls', 'csa2lx', 'csa2lxd', 'csa2lxs', 'csa2s', 'csa2x',
+                'csa2xd', 'csa2xs', 'csa3', 'csa3d', 'csa3l', 'csa3ld', 'csa3ls',
+                'csa3lx', 'csa3lxd', 'csa3lxs', 'csa3s', 'csa3x', 'csa3xd',
+                'csa3xs', 'csc2s', 'csgetp', 'css2c', 'cssetp', 'cssgrid', 'csstri',
+                'csvoro', 'cumsum', 'cz2ccm', 'datatondc', 'day_of_week',
+                'day_of_year', 'days_in_month', 'default_fillvalue', 'delete',
+                'depth_to_pres', 'destroy', 'determinant', 'dewtemp_trh',
+                'dgeevx_lapack', 'dim_acumrun_n', 'dim_avg', 'dim_avg_n',
+                'dim_avg_wgt', 'dim_avg_wgt_n', 'dim_cumsum', 'dim_cumsum_n',
+                'dim_gamfit_n', 'dim_gbits', 'dim_max', 'dim_max_n', 'dim_median',
+                'dim_median_n', 'dim_min', 'dim_min_n', 'dim_num', 'dim_num_n',
+                'dim_numrun_n', 'dim_pqsort', 'dim_pqsort_n', 'dim_product',
+                'dim_product_n', 'dim_rmsd', 'dim_rmsd_n', 'dim_rmvmean',
+                'dim_rmvmean_n', 'dim_rmvmed', 'dim_rmvmed_n', 'dim_spi_n',
+                'dim_standardize', 'dim_standardize_n', 'dim_stat4', 'dim_stat4_n',
+                'dim_stddev', 'dim_stddev_n', 'dim_sum', 'dim_sum_n', 'dim_sum_wgt',
+                'dim_sum_wgt_n', 'dim_variance', 'dim_variance_n', 'dimsizes',
+                'doubletobyte', 'doubletochar', 'doubletocharacter',
+                'doubletofloat', 'doubletoint', 'doubletointeger', 'doubletolong',
+                'doubletoshort', 'dpres_hybrid_ccm', 'dpres_plevel', 'draw',
+                'draw_color_palette', 'dsgetp', 'dsgrid2', 'dsgrid2d', 'dsgrid2s',
+                'dsgrid3', 'dsgrid3d', 'dsgrid3s', 'dspnt2', 'dspnt2d', 'dspnt2s',
+                'dspnt3', 'dspnt3d', 'dspnt3s', 'dssetp', 'dtrend', 'dtrend_msg',
+                'dtrend_msg_n', 'dtrend_n', 'dtrend_quadratic',
+                'dtrend_quadratic_msg_n', 'dv2uvf', 'dv2uvg', 'dz_height',
+                'echo_off', 'echo_on', 'eof2data', 'eof_varimax', 'eofcor',
+                'eofcor_pcmsg', 'eofcor_ts', 'eofcov', 'eofcov_pcmsg', 'eofcov_ts',
+                'eofunc', 'eofunc_ts', 'eofunc_varimax', 'equiv_sample_size', 'erf',
+                'erfc', 'esacr', 'esacv', 'esccr', 'esccv', 'escorc', 'escorc_n',
+                'escovc', 'exit', 'exp', 'exp_tapersh', 'exp_tapersh_wgts',
+                'exp_tapershC', 'ezfftb', 'ezfftb_n', 'ezfftf', 'ezfftf_n',
+                'f2fosh', 'f2foshv', 'f2fsh', 'f2fshv', 'f2gsh', 'f2gshv', 'fabs',
+                'fbindirread', 'fbindirwrite', 'fbinnumrec', 'fbinread',
+                'fbinrecread', 'fbinrecwrite', 'fbinwrite', 'fft2db', 'fft2df',
+                'fftshift', 'fileattdef', 'filechunkdimdef', 'filedimdef',
+                'fileexists', 'filegrpdef', 'filevarattdef', 'filevarchunkdef',
+                'filevarcompressleveldef', 'filevardef', 'filevardimsizes',
+                'filwgts_lancos', 'filwgts_lanczos', 'filwgts_normal',
+                'floattobyte', 'floattochar', 'floattocharacter', 'floattoint',
+                'floattointeger', 'floattolong', 'floattoshort', 'floor',
+                'fluxEddy', 'fo2fsh', 'fo2fshv', 'fourier_info', 'frame', 'fspan',
+                'ftcurv', 'ftcurvd', 'ftcurvi', 'ftcurvp', 'ftcurvpi', 'ftcurvps',
+                'ftcurvs', 'ftest', 'ftgetp', 'ftkurv', 'ftkurvd', 'ftkurvp',
+                'ftkurvpd', 'ftsetp', 'ftsurf', 'g2fsh', 'g2fshv', 'g2gsh',
+                'g2gshv', 'gamma', 'gammainc', 'gaus', 'gaus_lobat',
+                'gaus_lobat_wgt', 'gc_aangle', 'gc_clkwise', 'gc_dangle',
+                'gc_inout', 'gc_latlon', 'gc_onarc', 'gc_pnt2gc', 'gc_qarea',
+                'gc_tarea', 'generate_2d_array', 'get_color_index',
+                'get_color_rgba', 'get_cpu_time', 'get_isolines', 'get_ncl_version',
+                'get_script_name', 'get_script_prefix_name', 'get_sphere_radius',
+                'get_unique_values', 'getbitsone', 'getenv', 'getfiledimsizes',
+                'getfilegrpnames', 'getfilepath', 'getfilevaratts',
+                'getfilevarchunkdimsizes', 'getfilevardims', 'getfilevardimsizes',
+                'getfilevarnames', 'getfilevartypes', 'getvaratts', 'getvardims',
+                'gradsf', 'gradsg', 'greg2jul', 'grid2triple', 'hlsrgb', 'hsvrgb',
+                'hydro', 'hyi2hyo', 'idsfft', 'igradsf', 'igradsg', 'ilapsf',
+                'ilapsg', 'ilapvf', 'ilapvg', 'ind', 'ind_resolve', 'int2p',
+                'int2p_n', 'integertobyte', 'integertochar', 'integertocharacter',
+                'integertoshort', 'inttobyte', 'inttochar', 'inttoshort',
+                'inverse_matrix', 'isatt', 'isbigendian', 'isbyte', 'ischar',
+                'iscoord', 'isdefined', 'isdim', 'isdimnamed', 'isdouble',
+                'isenumeric', 'isfile', 'isfilepresent', 'isfilevar',
+                'isfilevaratt', 'isfilevarcoord', 'isfilevardim', 'isfloat',
+                'isfunc', 'isgraphic', 'isint', 'isint64', 'isinteger',
+                'isleapyear', 'islogical', 'islong', 'ismissing', 'isnan_ieee',
+                'isnumeric', 'ispan', 'isproc', 'isshort', 'issnumeric', 'isstring',
+                'isubyte', 'isuint', 'isuint64', 'isulong', 'isunlimited',
+                'isunsigned', 'isushort', 'isvar', 'jul2greg', 'kmeans_as136',
+                'kolsm2_n', 'kron_product', 'lapsf', 'lapsg', 'lapvf', 'lapvg',
+                'latlon2utm', 'lclvl', 'lderuvf', 'lderuvg', 'linint1', 'linint1_n',
+                'linint2', 'linint2_points', 'linmsg', 'linmsg_n', 'linrood_latwgt',
+                'linrood_wgt', 'list_files', 'list_filevars', 'list_hlus',
+                'list_procfuncs', 'list_vars', 'ListAppend', 'ListCount',
+                'ListGetType', 'ListIndex', 'ListIndexFromName', 'ListPop',
+                'ListPush', 'ListSetType', 'loadscript', 'local_max', 'local_min',
+                'log', 'log10', 'longtobyte', 'longtochar', 'longtocharacter',
+                'longtoint', 'longtointeger', 'longtoshort', 'lspoly', 'lspoly_n',
+                'mask', 'max', 'maxind', 'min', 'minind', 'mixed_layer_depth',
+                'mixhum_ptd', 'mixhum_ptrh', 'mjo_cross_coh2pha',
+                'mjo_cross_segment', 'moc_globe_atl', 'monthday', 'natgrid',
+                'natgridd', 'natgrids', 'ncargpath', 'ncargversion', 'ndctodata',
+                'ndtooned', 'new', 'NewList', 'ngezlogo', 'nggcog', 'nggetp',
+                'nglogo', 'ngsetp', 'NhlAddAnnotation', 'NhlAddData',
+                'NhlAddOverlay', 'NhlAddPrimitive', 'NhlAppGetDefaultParentId',
+                'NhlChangeWorkstation', 'NhlClassName', 'NhlClearWorkstation',
+                'NhlDataPolygon', 'NhlDataPolyline', 'NhlDataPolymarker',
+                'NhlDataToNDC', 'NhlDestroy', 'NhlDraw', 'NhlFrame', 'NhlFreeColor',
+                'NhlGetBB', 'NhlGetClassResources', 'NhlGetErrorObjectId',
+                'NhlGetNamedColorIndex', 'NhlGetParentId',
+                'NhlGetParentWorkstation', 'NhlGetWorkspaceObjectId',
+                'NhlIsAllocatedColor', 'NhlIsApp', 'NhlIsDataComm', 'NhlIsDataItem',
+                'NhlIsDataSpec', 'NhlIsTransform', 'NhlIsView', 'NhlIsWorkstation',
+                'NhlName', 'NhlNDCPolygon', 'NhlNDCPolyline', 'NhlNDCPolymarker',
+                'NhlNDCToData', 'NhlNewColor', 'NhlNewDashPattern', 'NhlNewMarker',
+                'NhlPalGetDefined', 'NhlRemoveAnnotation', 'NhlRemoveData',
+                'NhlRemoveOverlay', 'NhlRemovePrimitive', 'NhlSetColor',
+                'NhlSetDashPattern', 'NhlSetMarker', 'NhlUpdateData',
+                'NhlUpdateWorkstation', 'nice_mnmxintvl', 'nngetaspectd',
+                'nngetaspects', 'nngetp', 'nngetsloped', 'nngetslopes', 'nngetwts',
+                'nngetwtsd', 'nnpnt', 'nnpntd', 'nnpntend', 'nnpntendd',
+                'nnpntinit', 'nnpntinitd', 'nnpntinits', 'nnpnts', 'nnsetp', 'num',
+                'obj_anal_ic', 'omega_ccm', 'onedtond', 'overlay', 'paleo_outline',
+                'pdfxy_bin', 'poisson_grid_fill', 'pop_remap', 'potmp_insitu_ocn',
+                'prcwater_dp', 'pres2hybrid', 'pres_hybrid_ccm', 'pres_sigma',
+                'print', 'print_table', 'printFileVarSummary', 'printVarSummary',
+                'product', 'pslec', 'pslhor', 'pslhyp', 'qsort', 'rand',
+                'random_chi', 'random_gamma', 'random_normal', 'random_setallseed',
+                'random_uniform', 'rcm2points', 'rcm2rgrid', 'rdsstoi',
+                'read_colormap_file', 'reg_multlin', 'regcoef', 'regCoef_n',
+                'regline', 'relhum', 'replace_ieeenan', 'reshape', 'reshape_ind',
+                'rgba_to_color_index', 'rgbhls', 'rgbhsv', 'rgbyiq', 'rgrid2rcm',
+                'rhomb_trunc', 'rip_cape_2d', 'rip_cape_3d', 'round', 'rtest',
+                'runave', 'runave_n', 'set_default_fillvalue', 'set_sphere_radius',
+                'setfileoption', 'sfvp2uvf', 'sfvp2uvg', 'shaec', 'shagc',
+                'shgetnp', 'shgetp', 'shgrid', 'shorttobyte', 'shorttochar',
+                'shorttocharacter', 'show_ascii', 'shsec', 'shsetp', 'shsgc',
+                'shsgc_R42', 'sigma2hybrid', 'simpeq', 'simpne', 'sin',
+                'sindex_yrmo', 'sinh', 'sizeof', 'sleep', 'smth9', 'snindex_yrmo',
+                'solve_linsys', 'span_color_indexes', 'span_color_rgba',
+                'sparse_matrix_mult', 'spcorr', 'spcorr_n', 'specx_anal',
+                'specxy_anal', 'spei', 'sprintf', 'sprinti', 'sqrt', 'sqsort',
+                'srand', 'stat2', 'stat4', 'stat_medrng', 'stat_trim',
+                'status_exit', 'stdatmus_p2tdz', 'stdatmus_z2tdp', 'stddev',
+                'str_capital', 'str_concat', 'str_fields_count', 'str_get_cols',
+                'str_get_dq', 'str_get_field', 'str_get_nl', 'str_get_sq',
+                'str_get_tab', 'str_index_of_substr', 'str_insert', 'str_is_blank',
+                'str_join', 'str_left_strip', 'str_lower', 'str_match',
+                'str_match_ic', 'str_match_ic_regex', 'str_match_ind',
+                'str_match_ind_ic', 'str_match_ind_ic_regex', 'str_match_ind_regex',
+                'str_match_regex', 'str_right_strip', 'str_split',
+                'str_split_by_length', 'str_split_csv', 'str_squeeze', 'str_strip',
+                'str_sub_str', 'str_switch', 'str_upper', 'stringtochar',
+                'stringtocharacter', 'stringtodouble', 'stringtofloat',
+                'stringtoint', 'stringtointeger', 'stringtolong', 'stringtoshort',
+                'strlen', 'student_t', 'sum', 'svd_lapack', 'svdcov', 'svdcov_sv',
+                'svdstd', 'svdstd_sv', 'system', 'systemfunc', 'tan', 'tanh',
+                'taper', 'taper_n', 'tdclrs', 'tdctri', 'tdcudp', 'tdcurv',
+                'tddtri', 'tdez2d', 'tdez3d', 'tdgetp', 'tdgrds', 'tdgrid',
+                'tdgtrs', 'tdinit', 'tditri', 'tdlbla', 'tdlblp', 'tdlbls',
+                'tdline', 'tdlndp', 'tdlnpa', 'tdlpdp', 'tdmtri', 'tdotri',
+                'tdpara', 'tdplch', 'tdprpa', 'tdprpi', 'tdprpt', 'tdsetp',
+                'tdsort', 'tdstri', 'tdstrs', 'tdttri', 'thornthwaite', 'tobyte',
+                'tochar', 'todouble', 'tofloat', 'toint', 'toint64', 'tointeger',
+                'tolong', 'toshort', 'tosigned', 'tostring', 'tostring_with_format',
+                'totype', 'toubyte', 'touint', 'touint64', 'toulong', 'tounsigned',
+                'toushort', 'trend_manken', 'tri_trunc', 'triple2grid',
+                'triple2grid2d', 'trop_wmo', 'ttest', 'typeof', 'undef',
+                'unique_string', 'update', 'ushorttoint', 'ut_calendar',
+                'ut_inv_calendar', 'utm2latlon', 'uv2dv_cfd', 'uv2dvf', 'uv2dvg',
+                'uv2sfvpf', 'uv2sfvpg', 'uv2vr_cfd', 'uv2vrdvf', 'uv2vrdvg',
+                'uv2vrf', 'uv2vrg', 'v5d_close', 'v5d_create', 'v5d_setLowLev',
+                'v5d_setUnits', 'v5d_write', 'v5d_write_var', 'variance', 'vhaec',
+                'vhagc', 'vhsec', 'vhsgc', 'vibeta', 'vinth2p', 'vinth2p_ecmwf',
+                'vinth2p_ecmwf_nodes', 'vinth2p_nodes', 'vintp2p_ecmwf', 'vr2uvf',
+                'vr2uvg', 'vrdv2uvf', 'vrdv2uvg', 'wavelet', 'wavelet_default',
+                'weibull', 'wgt_area_smooth', 'wgt_areaave', 'wgt_areaave2',
+                'wgt_arearmse', 'wgt_arearmse2', 'wgt_areasum2', 'wgt_runave',
+                'wgt_runave_n', 'wgt_vert_avg_beta', 'wgt_volave', 'wgt_volave_ccm',
+                'wgt_volrmse', 'wgt_volrmse_ccm', 'where', 'wk_smooth121', 'wmbarb',
+                'wmbarbmap', 'wmdrft', 'wmgetp', 'wmlabs', 'wmsetp', 'wmstnm',
+                'wmvect', 'wmvectmap', 'wmvlbl', 'wrf_avo', 'wrf_cape_2d',
+                'wrf_cape_3d', 'wrf_dbz', 'wrf_eth', 'wrf_helicity', 'wrf_ij_to_ll',
+                'wrf_interp_1d', 'wrf_interp_2d_xy', 'wrf_interp_3d_z',
+                'wrf_latlon_to_ij', 'wrf_ll_to_ij', 'wrf_omega', 'wrf_pvo',
+                'wrf_rh', 'wrf_slp', 'wrf_smooth_2d', 'wrf_td', 'wrf_tk',
+                'wrf_updraft_helicity', 'wrf_uvmet', 'wrf_virtual_temp',
+                'wrf_wetbulb', 'wrf_wps_close_int', 'wrf_wps_open_int',
+                'wrf_wps_rddata_int', 'wrf_wps_rdhead_int', 'wrf_wps_read_int',
+                'wrf_wps_write_int', 'write_matrix', 'write_table', 'yiqrgb',
+                'z2geouv', 'zonal_mpsi', 'addfiles_GetVar', 'advect_variable',
+                'area_conserve_remap_Wrap', 'area_hi2lores_Wrap',
+                'array_append_record', 'assignFillValue', 'byte2flt',
+                'byte2flt_hdf', 'calcDayAnomTLL', 'calcMonAnomLLLT',
+                'calcMonAnomLLT', 'calcMonAnomTLL', 'calcMonAnomTLLL',
+                'calculate_monthly_values', 'cd_convert', 'changeCase',
+                'changeCaseChar', 'clmDayTLL', 'clmDayTLLL', 'clmMon2clmDay',
+                'clmMonLLLT', 'clmMonLLT', 'clmMonTLL', 'clmMonTLLL', 'closest_val',
+                'copy_VarAtts', 'copy_VarCoords', 'copy_VarCoords_1',
+                'copy_VarCoords_2', 'copy_VarMeta', 'copyatt', 'crossp3',
+                'cshstringtolist', 'cssgrid_Wrap', 'dble2flt', 'decimalPlaces',
+                'delete_VarAtts', 'dim_avg_n_Wrap', 'dim_avg_wgt_n_Wrap',
+                'dim_avg_wgt_Wrap', 'dim_avg_Wrap', 'dim_cumsum_n_Wrap',
+                'dim_cumsum_Wrap', 'dim_max_n_Wrap', 'dim_min_n_Wrap',
+                'dim_rmsd_n_Wrap', 'dim_rmsd_Wrap', 'dim_rmvmean_n_Wrap',
+                'dim_rmvmean_Wrap', 'dim_rmvmed_n_Wrap', 'dim_rmvmed_Wrap',
+                'dim_standardize_n_Wrap', 'dim_standardize_Wrap',
+                'dim_stddev_n_Wrap', 'dim_stddev_Wrap', 'dim_sum_n_Wrap',
+                'dim_sum_wgt_n_Wrap', 'dim_sum_wgt_Wrap', 'dim_sum_Wrap',
+                'dim_variance_n_Wrap', 'dim_variance_Wrap', 'dpres_plevel_Wrap',
+                'dtrend_leftdim', 'dv2uvF_Wrap', 'dv2uvG_Wrap', 'eof_north',
+                'eofcor_Wrap', 'eofcov_Wrap', 'eofunc_north', 'eofunc_ts_Wrap',
+                'eofunc_varimax_reorder', 'eofunc_varimax_Wrap', 'eofunc_Wrap',
+                'epsZero', 'f2fosh_Wrap', 'f2foshv_Wrap', 'f2fsh_Wrap',
+                'f2fshv_Wrap', 'f2gsh_Wrap', 'f2gshv_Wrap', 'fbindirSwap',
+                'fbinseqSwap1', 'fbinseqSwap2', 'flt2dble', 'flt2string',
+                'fo2fsh_Wrap', 'fo2fshv_Wrap', 'g2fsh_Wrap', 'g2fshv_Wrap',
+                'g2gsh_Wrap', 'g2gshv_Wrap', 'generate_resample_indices',
+                'generate_sample_indices', 'generate_unique_indices',
+                'genNormalDist', 'get1Dindex', 'get1Dindex_Collapse',
+                'get1Dindex_Exclude', 'get_file_suffix', 'GetFillColor',
+                'GetFillColorIndex', 'getFillValue', 'getind_latlon2d',
+                'getVarDimNames', 'getVarFillValue', 'grib_stime2itime',
+                'hyi2hyo_Wrap', 'ilapsF_Wrap', 'ilapsG_Wrap', 'ind_nearest_coord',
+                'indStrSubset', 'int2dble', 'int2flt', 'int2p_n_Wrap', 'int2p_Wrap',
+                'isMonotonic', 'isStrSubset', 'latGau', 'latGauWgt', 'latGlobeF',
+                'latGlobeFo', 'latRegWgt', 'linint1_n_Wrap', 'linint1_Wrap',
+                'linint2_points_Wrap', 'linint2_Wrap', 'local_max_1d',
+                'local_min_1d', 'lonFlip', 'lonGlobeF', 'lonGlobeFo', 'lonPivot',
+                'merge_levels_sfc', 'mod', 'month_to_annual',
+                'month_to_annual_weighted', 'month_to_season', 'month_to_season12',
+                'month_to_seasonN', 'monthly_total_to_daily_mean', 'nameDim',
+                'natgrid_Wrap', 'NewCosWeight', 'niceLatLon2D', 'NormCosWgtGlobe',
+                'numAsciiCol', 'numAsciiRow', 'numeric2int',
+                'obj_anal_ic_deprecated', 'obj_anal_ic_Wrap', 'omega_ccm_driver',
+                'omega_to_w', 'oneDtostring', 'pack_values', 'pattern_cor', 'pdfx',
+                'pdfxy', 'pdfxy_conform', 'pot_temp', 'pot_vort_hybrid',
+                'pot_vort_isobaric', 'pres2hybrid_Wrap', 'print_clock',
+                'printMinMax', 'quadroots', 'rcm2points_Wrap', 'rcm2rgrid_Wrap',
+                'readAsciiHead', 'readAsciiTable', 'reg_multlin_stats',
+                'region_ind', 'regline_stats', 'relhum_ttd', 'replaceSingleChar',
+                'RGBtoCmap', 'rgrid2rcm_Wrap', 'rho_mwjf', 'rm_single_dims',
+                'rmAnnCycle1D', 'rmInsufData', 'rmMonAnnCycLLLT', 'rmMonAnnCycLLT',
+                'rmMonAnnCycTLL', 'runave_n_Wrap', 'runave_Wrap', 'short2flt',
+                'short2flt_hdf', 'shsgc_R42_Wrap', 'sign_f90', 'sign_matlab',
+                'smth9_Wrap', 'smthClmDayTLL', 'smthClmDayTLLL', 'SqrtCosWeight',
+                'stat_dispersion', 'static_stability', 'stdMonLLLT', 'stdMonLLT',
+                'stdMonTLL', 'stdMonTLLL', 'symMinMaxPlt', 'table_attach_columns',
+                'table_attach_rows', 'time_to_newtime', 'transpose',
+                'triple2grid_Wrap', 'ut_convert', 'uv2dvF_Wrap', 'uv2dvG_Wrap',
+                'uv2vrF_Wrap', 'uv2vrG_Wrap', 'vr2uvF_Wrap', 'vr2uvG_Wrap',
+                'w_to_omega', 'wallClockElapseTime', 'wave_number_spc',
+                'wgt_areaave_Wrap', 'wgt_runave_leftdim', 'wgt_runave_n_Wrap',
+                'wgt_runave_Wrap', 'wgt_vertical_n', 'wind_component',
+                'wind_direction', 'yyyyddd_to_yyyymmdd', 'yyyymm_time',
+                'yyyymm_to_yyyyfrac', 'yyyymmdd_time', 'yyyymmdd_to_yyyyddd',
+                'yyyymmdd_to_yyyyfrac', 'yyyymmddhh_time', 'yyyymmddhh_to_yyyyfrac',
+                'zonal_mpsi_Wrap', 'zonalAve', 'calendar_decode2', 'cd_string',
+                'kf_filter', 'run_cor', 'time_axis_labels', 'ut_string',
+                'wrf_contour', 'wrf_map', 'wrf_map_overlay', 'wrf_map_overlays',
+                'wrf_map_resources', 'wrf_map_zoom', 'wrf_overlay', 'wrf_overlays',
+                'wrf_user_getvar', 'wrf_user_ij_to_ll', 'wrf_user_intrp2d',
+                'wrf_user_intrp3d', 'wrf_user_latlon_to_ij', 'wrf_user_list_times',
+                'wrf_user_ll_to_ij', 'wrf_user_unstagger', 'wrf_user_vert_interp',
+                'wrf_vector', 'gsn_add_annotation', 'gsn_add_polygon',
+                'gsn_add_polyline', 'gsn_add_polymarker',
+                'gsn_add_shapefile_polygons', 'gsn_add_shapefile_polylines',
+                'gsn_add_shapefile_polymarkers', 'gsn_add_text', 'gsn_attach_plots',
+                'gsn_blank_plot', 'gsn_contour', 'gsn_contour_map',
+                'gsn_contour_shade', 'gsn_coordinates', 'gsn_create_labelbar',
+                'gsn_create_legend', 'gsn_create_text',
+                'gsn_csm_attach_zonal_means', 'gsn_csm_blank_plot',
+                'gsn_csm_contour', 'gsn_csm_contour_map', 'gsn_csm_contour_map_ce',
+                'gsn_csm_contour_map_overlay', 'gsn_csm_contour_map_polar',
+                'gsn_csm_hov', 'gsn_csm_lat_time', 'gsn_csm_map', 'gsn_csm_map_ce',
+                'gsn_csm_map_polar', 'gsn_csm_pres_hgt',
+                'gsn_csm_pres_hgt_streamline', 'gsn_csm_pres_hgt_vector',
+                'gsn_csm_streamline', 'gsn_csm_streamline_contour_map',
+                'gsn_csm_streamline_contour_map_ce',
+                'gsn_csm_streamline_contour_map_polar', 'gsn_csm_streamline_map',
+                'gsn_csm_streamline_map_ce', 'gsn_csm_streamline_map_polar',
+                'gsn_csm_streamline_scalar', 'gsn_csm_streamline_scalar_map',
+                'gsn_csm_streamline_scalar_map_ce',
+                'gsn_csm_streamline_scalar_map_polar', 'gsn_csm_time_lat',
+                'gsn_csm_vector', 'gsn_csm_vector_map', 'gsn_csm_vector_map_ce',
+                'gsn_csm_vector_map_polar', 'gsn_csm_vector_scalar',
+                'gsn_csm_vector_scalar_map', 'gsn_csm_vector_scalar_map_ce',
+                'gsn_csm_vector_scalar_map_polar', 'gsn_csm_x2y', 'gsn_csm_x2y2',
+                'gsn_csm_xy', 'gsn_csm_xy2', 'gsn_csm_xy3', 'gsn_csm_y',
+                'gsn_define_colormap', 'gsn_draw_colormap', 'gsn_draw_named_colors',
+                'gsn_histogram', 'gsn_labelbar_ndc', 'gsn_legend_ndc', 'gsn_map',
+                'gsn_merge_colormaps', 'gsn_open_wks', 'gsn_panel', 'gsn_polygon',
+                'gsn_polygon_ndc', 'gsn_polyline', 'gsn_polyline_ndc',
+                'gsn_polymarker', 'gsn_polymarker_ndc', 'gsn_retrieve_colormap',
+                'gsn_reverse_colormap', 'gsn_streamline', 'gsn_streamline_map',
+                'gsn_streamline_scalar', 'gsn_streamline_scalar_map', 'gsn_table',
+                'gsn_text', 'gsn_text_ndc', 'gsn_vector', 'gsn_vector_map',
+                'gsn_vector_scalar', 'gsn_vector_scalar_map', 'gsn_xy', 'gsn_y',
+                'hsv2rgb', 'maximize_output', 'namedcolor2rgb', 'namedcolor2rgba',
+                'reset_device_coordinates', 'span_named_colors'), prefix=r'\b'),
+             Name.Builtin),
+
+            # Resources
+            (words((
+                'amDataXF', 'amDataYF', 'amJust', 'amOn', 'amOrthogonalPosF',
+                'amParallelPosF', 'amResizeNotify', 'amSide', 'amTrackData',
+                'amViewId', 'amZone', 'appDefaultParent', 'appFileSuffix',
+                'appResources', 'appSysDir', 'appUsrDir', 'caCopyArrays',
+                'caXArray', 'caXCast', 'caXMaxV', 'caXMinV', 'caXMissingV',
+                'caYArray', 'caYCast', 'caYMaxV', 'caYMinV', 'caYMissingV',
+                'cnCellFillEdgeColor', 'cnCellFillMissingValEdgeColor',
+                'cnConpackParams', 'cnConstFEnableFill', 'cnConstFLabelAngleF',
+                'cnConstFLabelBackgroundColor', 'cnConstFLabelConstantSpacingF',
+                'cnConstFLabelFont', 'cnConstFLabelFontAspectF',
+                'cnConstFLabelFontColor', 'cnConstFLabelFontHeightF',
+                'cnConstFLabelFontQuality', 'cnConstFLabelFontThicknessF',
+                'cnConstFLabelFormat', 'cnConstFLabelFuncCode', 'cnConstFLabelJust',
+                'cnConstFLabelOn', 'cnConstFLabelOrthogonalPosF',
+                'cnConstFLabelParallelPosF', 'cnConstFLabelPerimColor',
+                'cnConstFLabelPerimOn', 'cnConstFLabelPerimSpaceF',
+                'cnConstFLabelPerimThicknessF', 'cnConstFLabelSide',
+                'cnConstFLabelString', 'cnConstFLabelTextDirection',
+                'cnConstFLabelZone', 'cnConstFUseInfoLabelRes',
+                'cnExplicitLabelBarLabelsOn', 'cnExplicitLegendLabelsOn',
+                'cnExplicitLineLabelsOn', 'cnFillBackgroundColor', 'cnFillColor',
+                'cnFillColors', 'cnFillDotSizeF', 'cnFillDrawOrder', 'cnFillMode',
+                'cnFillOn', 'cnFillOpacityF', 'cnFillPalette', 'cnFillPattern',
+                'cnFillPatterns', 'cnFillScaleF', 'cnFillScales', 'cnFixFillBleed',
+                'cnGridBoundFillColor', 'cnGridBoundFillPattern',
+                'cnGridBoundFillScaleF', 'cnGridBoundPerimColor',
+                'cnGridBoundPerimDashPattern', 'cnGridBoundPerimOn',
+                'cnGridBoundPerimThicknessF', 'cnHighLabelAngleF',
+                'cnHighLabelBackgroundColor', 'cnHighLabelConstantSpacingF',
+                'cnHighLabelCount', 'cnHighLabelFont', 'cnHighLabelFontAspectF',
+                'cnHighLabelFontColor', 'cnHighLabelFontHeightF',
+                'cnHighLabelFontQuality', 'cnHighLabelFontThicknessF',
+                'cnHighLabelFormat', 'cnHighLabelFuncCode', 'cnHighLabelPerimColor',
+                'cnHighLabelPerimOn', 'cnHighLabelPerimSpaceF',
+                'cnHighLabelPerimThicknessF', 'cnHighLabelString', 'cnHighLabelsOn',
+                'cnHighLowLabelOverlapMode', 'cnHighUseLineLabelRes',
+                'cnInfoLabelAngleF', 'cnInfoLabelBackgroundColor',
+                'cnInfoLabelConstantSpacingF', 'cnInfoLabelFont',
+                'cnInfoLabelFontAspectF', 'cnInfoLabelFontColor',
+                'cnInfoLabelFontHeightF', 'cnInfoLabelFontQuality',
+                'cnInfoLabelFontThicknessF', 'cnInfoLabelFormat',
+                'cnInfoLabelFuncCode', 'cnInfoLabelJust', 'cnInfoLabelOn',
+                'cnInfoLabelOrthogonalPosF', 'cnInfoLabelParallelPosF',
+                'cnInfoLabelPerimColor', 'cnInfoLabelPerimOn',
+                'cnInfoLabelPerimSpaceF', 'cnInfoLabelPerimThicknessF',
+                'cnInfoLabelSide', 'cnInfoLabelString', 'cnInfoLabelTextDirection',
+                'cnInfoLabelZone', 'cnLabelBarEndLabelsOn', 'cnLabelBarEndStyle',
+                'cnLabelDrawOrder', 'cnLabelMasking', 'cnLabelScaleFactorF',
+                'cnLabelScaleValueF', 'cnLabelScalingMode', 'cnLegendLevelFlags',
+                'cnLevelCount', 'cnLevelFlag', 'cnLevelFlags', 'cnLevelSelectionMode',
+                'cnLevelSpacingF', 'cnLevels', 'cnLineColor', 'cnLineColors',
+                'cnLineDashPattern', 'cnLineDashPatterns', 'cnLineDashSegLenF',
+                'cnLineDrawOrder', 'cnLineLabelAngleF', 'cnLineLabelBackgroundColor',
+                'cnLineLabelConstantSpacingF', 'cnLineLabelCount',
+                'cnLineLabelDensityF', 'cnLineLabelFont', 'cnLineLabelFontAspectF',
+                'cnLineLabelFontColor', 'cnLineLabelFontColors',
+                'cnLineLabelFontHeightF', 'cnLineLabelFontQuality',
+                'cnLineLabelFontThicknessF', 'cnLineLabelFormat',
+                'cnLineLabelFuncCode', 'cnLineLabelInterval', 'cnLineLabelPerimColor',
+                'cnLineLabelPerimOn', 'cnLineLabelPerimSpaceF',
+                'cnLineLabelPerimThicknessF', 'cnLineLabelPlacementMode',
+                'cnLineLabelStrings', 'cnLineLabelsOn', 'cnLinePalette',
+                'cnLineThicknessF', 'cnLineThicknesses', 'cnLinesOn',
+                'cnLowLabelAngleF', 'cnLowLabelBackgroundColor',
+                'cnLowLabelConstantSpacingF', 'cnLowLabelCount', 'cnLowLabelFont',
+                'cnLowLabelFontAspectF', 'cnLowLabelFontColor',
+                'cnLowLabelFontHeightF', 'cnLowLabelFontQuality',
+                'cnLowLabelFontThicknessF', 'cnLowLabelFormat', 'cnLowLabelFuncCode',
+                'cnLowLabelPerimColor', 'cnLowLabelPerimOn', 'cnLowLabelPerimSpaceF',
+                'cnLowLabelPerimThicknessF', 'cnLowLabelString', 'cnLowLabelsOn',
+                'cnLowUseHighLabelRes', 'cnMaxDataValueFormat', 'cnMaxLevelCount',
+                'cnMaxLevelValF', 'cnMaxPointDistanceF', 'cnMinLevelValF',
+                'cnMissingValFillColor', 'cnMissingValFillPattern',
+                'cnMissingValFillScaleF', 'cnMissingValPerimColor',
+                'cnMissingValPerimDashPattern', 'cnMissingValPerimGridBoundOn',
+                'cnMissingValPerimOn', 'cnMissingValPerimThicknessF',
+                'cnMonoFillColor', 'cnMonoFillPattern', 'cnMonoFillScale',
+                'cnMonoLevelFlag', 'cnMonoLineColor', 'cnMonoLineDashPattern',
+                'cnMonoLineLabelFontColor', 'cnMonoLineThickness', 'cnNoDataLabelOn',
+                'cnNoDataLabelString', 'cnOutOfRangeFillColor',
+                'cnOutOfRangeFillPattern', 'cnOutOfRangeFillScaleF',
+                'cnOutOfRangePerimColor', 'cnOutOfRangePerimDashPattern',
+                'cnOutOfRangePerimOn', 'cnOutOfRangePerimThicknessF',
+                'cnRasterCellSizeF', 'cnRasterMinCellSizeF', 'cnRasterModeOn',
+                'cnRasterSampleFactorF', 'cnRasterSmoothingOn', 'cnScalarFieldData',
+                'cnSmoothingDistanceF', 'cnSmoothingOn', 'cnSmoothingTensionF',
+                'cnSpanFillPalette', 'cnSpanLinePalette', 'ctCopyTables',
+                'ctXElementSize', 'ctXMaxV', 'ctXMinV', 'ctXMissingV', 'ctXTable',
+                'ctXTableLengths', 'ctXTableType', 'ctYElementSize', 'ctYMaxV',
+                'ctYMinV', 'ctYMissingV', 'ctYTable', 'ctYTableLengths',
+                'ctYTableType', 'dcDelayCompute', 'errBuffer',
+                'errFileName', 'errFilePtr', 'errLevel', 'errPrint', 'errUnitNumber',
+                'gsClipOn', 'gsColors', 'gsEdgeColor', 'gsEdgeDashPattern',
+                'gsEdgeDashSegLenF', 'gsEdgeThicknessF', 'gsEdgesOn',
+                'gsFillBackgroundColor', 'gsFillColor', 'gsFillDotSizeF',
+                'gsFillIndex', 'gsFillLineThicknessF', 'gsFillOpacityF',
+                'gsFillScaleF', 'gsFont', 'gsFontAspectF', 'gsFontColor',
+                'gsFontHeightF', 'gsFontOpacityF', 'gsFontQuality',
+                'gsFontThicknessF', 'gsLineColor', 'gsLineDashPattern',
+                'gsLineDashSegLenF', 'gsLineLabelConstantSpacingF', 'gsLineLabelFont',
+                'gsLineLabelFontAspectF', 'gsLineLabelFontColor',
+                'gsLineLabelFontHeightF', 'gsLineLabelFontQuality',
+                'gsLineLabelFontThicknessF', 'gsLineLabelFuncCode',
+                'gsLineLabelString', 'gsLineOpacityF', 'gsLineThicknessF',
+                'gsMarkerColor', 'gsMarkerIndex', 'gsMarkerOpacityF', 'gsMarkerSizeF',
+                'gsMarkerThicknessF', 'gsSegments', 'gsTextAngleF',
+                'gsTextConstantSpacingF', 'gsTextDirection', 'gsTextFuncCode',
+                'gsTextJustification', 'gsnAboveYRefLineBarColors',
+                'gsnAboveYRefLineBarFillScales', 'gsnAboveYRefLineBarPatterns',
+                'gsnAboveYRefLineColor', 'gsnAddCyclic', 'gsnAttachBorderOn',
+                'gsnAttachPlotsXAxis', 'gsnBelowYRefLineBarColors',
+                'gsnBelowYRefLineBarFillScales', 'gsnBelowYRefLineBarPatterns',
+                'gsnBelowYRefLineColor', 'gsnBoxMargin', 'gsnCenterString',
+                'gsnCenterStringFontColor', 'gsnCenterStringFontHeightF',
+                'gsnCenterStringFuncCode', 'gsnCenterStringOrthogonalPosF',
+                'gsnCenterStringParallelPosF', 'gsnContourLineThicknessesScale',
+                'gsnContourNegLineDashPattern', 'gsnContourPosLineDashPattern',
+                'gsnContourZeroLineThicknessF', 'gsnDebugWriteFileName', 'gsnDraw',
+                'gsnFrame', 'gsnHistogramBarWidthPercent', 'gsnHistogramBinIntervals',
+                'gsnHistogramBinMissing', 'gsnHistogramBinWidth',
+                'gsnHistogramClassIntervals', 'gsnHistogramCompare',
+                'gsnHistogramComputePercentages',
+                'gsnHistogramComputePercentagesNoMissing',
+                'gsnHistogramDiscreteBinValues', 'gsnHistogramDiscreteClassValues',
+                'gsnHistogramHorizontal', 'gsnHistogramMinMaxBinsOn',
+                'gsnHistogramNumberOfBins', 'gsnHistogramPercentSign',
+                'gsnHistogramSelectNiceIntervals', 'gsnLeftString',
+                'gsnLeftStringFontColor', 'gsnLeftStringFontHeightF',
+                'gsnLeftStringFuncCode', 'gsnLeftStringOrthogonalPosF',
+                'gsnLeftStringParallelPosF', 'gsnMajorLatSpacing',
+                'gsnMajorLonSpacing', 'gsnMaskLambertConformal',
+                'gsnMaskLambertConformalOutlineOn', 'gsnMaximize',
+                'gsnMinorLatSpacing', 'gsnMinorLonSpacing', 'gsnPanelBottom',
+                'gsnPanelCenter', 'gsnPanelDebug', 'gsnPanelFigureStrings',
+                'gsnPanelFigureStringsBackgroundFillColor',
+                'gsnPanelFigureStringsFontHeightF', 'gsnPanelFigureStringsJust',
+                'gsnPanelFigureStringsPerimOn', 'gsnPanelLabelBar', 'gsnPanelLeft',
+                'gsnPanelMainFont', 'gsnPanelMainFontColor',
+                'gsnPanelMainFontHeightF', 'gsnPanelMainString', 'gsnPanelRight',
+                'gsnPanelRowSpec', 'gsnPanelScalePlotIndex', 'gsnPanelTop',
+                'gsnPanelXF', 'gsnPanelXWhiteSpacePercent', 'gsnPanelYF',
+                'gsnPanelYWhiteSpacePercent', 'gsnPaperHeight', 'gsnPaperMargin',
+                'gsnPaperOrientation', 'gsnPaperWidth', 'gsnPolar',
+                'gsnPolarLabelDistance', 'gsnPolarLabelFont',
+                'gsnPolarLabelFontHeightF', 'gsnPolarLabelSpacing', 'gsnPolarTime',
+                'gsnPolarUT', 'gsnRightString', 'gsnRightStringFontColor',
+                'gsnRightStringFontHeightF', 'gsnRightStringFuncCode',
+                'gsnRightStringOrthogonalPosF', 'gsnRightStringParallelPosF',
+                'gsnScalarContour', 'gsnScale', 'gsnShape', 'gsnSpreadColorEnd',
+                'gsnSpreadColorStart', 'gsnSpreadColors', 'gsnStringFont',
+                'gsnStringFontColor', 'gsnStringFontHeightF', 'gsnStringFuncCode',
+                'gsnTickMarksOn', 'gsnXAxisIrregular2Linear', 'gsnXAxisIrregular2Log',
+                'gsnXRefLine', 'gsnXRefLineColor', 'gsnXRefLineDashPattern',
+                'gsnXRefLineThicknessF', 'gsnXYAboveFillColors', 'gsnXYBarChart',
+                'gsnXYBarChartBarWidth', 'gsnXYBarChartColors',
+                'gsnXYBarChartColors2', 'gsnXYBarChartFillDotSizeF',
+                'gsnXYBarChartFillLineThicknessF', 'gsnXYBarChartFillOpacityF',
+                'gsnXYBarChartFillScaleF', 'gsnXYBarChartOutlineOnly',
+                'gsnXYBarChartOutlineThicknessF', 'gsnXYBarChartPatterns',
+                'gsnXYBarChartPatterns2', 'gsnXYBelowFillColors', 'gsnXYFillColors',
+                'gsnXYFillOpacities', 'gsnXYLeftFillColors', 'gsnXYRightFillColors',
+                'gsnYAxisIrregular2Linear', 'gsnYAxisIrregular2Log', 'gsnYRefLine',
+                'gsnYRefLineColor', 'gsnYRefLineColors', 'gsnYRefLineDashPattern',
+                'gsnYRefLineDashPatterns', 'gsnYRefLineThicknessF',
+                'gsnYRefLineThicknesses', 'gsnZonalMean', 'gsnZonalMeanXMaxF',
+                'gsnZonalMeanXMinF', 'gsnZonalMeanYRefLine', 'lbAutoManage',
+                'lbBottomMarginF', 'lbBoxCount', 'lbBoxEndCapStyle', 'lbBoxFractions',
+                'lbBoxLineColor', 'lbBoxLineDashPattern', 'lbBoxLineDashSegLenF',
+                'lbBoxLineThicknessF', 'lbBoxLinesOn', 'lbBoxMajorExtentF',
+                'lbBoxMinorExtentF', 'lbBoxSeparatorLinesOn', 'lbBoxSizing',
+                'lbFillBackground', 'lbFillColor', 'lbFillColors', 'lbFillDotSizeF',
+                'lbFillLineThicknessF', 'lbFillPattern', 'lbFillPatterns',
+                'lbFillScaleF', 'lbFillScales', 'lbJustification', 'lbLabelAlignment',
+                'lbLabelAngleF', 'lbLabelAutoStride', 'lbLabelBarOn',
+                'lbLabelConstantSpacingF', 'lbLabelDirection', 'lbLabelFont',
+                'lbLabelFontAspectF', 'lbLabelFontColor', 'lbLabelFontHeightF',
+                'lbLabelFontQuality', 'lbLabelFontThicknessF', 'lbLabelFuncCode',
+                'lbLabelJust', 'lbLabelOffsetF', 'lbLabelPosition', 'lbLabelStride',
+                'lbLabelStrings', 'lbLabelsOn', 'lbLeftMarginF', 'lbMaxLabelLenF',
+                'lbMinLabelSpacingF', 'lbMonoFillColor', 'lbMonoFillPattern',
+                'lbMonoFillScale', 'lbOrientation', 'lbPerimColor',
+                'lbPerimDashPattern', 'lbPerimDashSegLenF', 'lbPerimFill',
+                'lbPerimFillColor', 'lbPerimOn', 'lbPerimThicknessF',
+                'lbRasterFillOn', 'lbRightMarginF', 'lbTitleAngleF',
+                'lbTitleConstantSpacingF', 'lbTitleDirection', 'lbTitleExtentF',
+                'lbTitleFont', 'lbTitleFontAspectF', 'lbTitleFontColor',
+                'lbTitleFontHeightF', 'lbTitleFontQuality', 'lbTitleFontThicknessF',
+                'lbTitleFuncCode', 'lbTitleJust', 'lbTitleOffsetF', 'lbTitleOn',
+                'lbTitlePosition', 'lbTitleString', 'lbTopMarginF', 'lgAutoManage',
+                'lgBottomMarginF', 'lgBoxBackground', 'lgBoxLineColor',
+                'lgBoxLineDashPattern', 'lgBoxLineDashSegLenF', 'lgBoxLineThicknessF',
+                'lgBoxLinesOn', 'lgBoxMajorExtentF', 'lgBoxMinorExtentF',
+                'lgDashIndex', 'lgDashIndexes', 'lgItemCount', 'lgItemOrder',
+                'lgItemPlacement', 'lgItemPositions', 'lgItemType', 'lgItemTypes',
+                'lgJustification', 'lgLabelAlignment', 'lgLabelAngleF',
+                'lgLabelAutoStride', 'lgLabelConstantSpacingF', 'lgLabelDirection',
+                'lgLabelFont', 'lgLabelFontAspectF', 'lgLabelFontColor',
+                'lgLabelFontHeightF', 'lgLabelFontQuality', 'lgLabelFontThicknessF',
+                'lgLabelFuncCode', 'lgLabelJust', 'lgLabelOffsetF', 'lgLabelPosition',
+                'lgLabelStride', 'lgLabelStrings', 'lgLabelsOn', 'lgLeftMarginF',
+                'lgLegendOn', 'lgLineColor', 'lgLineColors', 'lgLineDashSegLenF',
+                'lgLineDashSegLens', 'lgLineLabelConstantSpacingF', 'lgLineLabelFont',
+                'lgLineLabelFontAspectF', 'lgLineLabelFontColor',
+                'lgLineLabelFontColors', 'lgLineLabelFontHeightF',
+                'lgLineLabelFontHeights', 'lgLineLabelFontQuality',
+                'lgLineLabelFontThicknessF', 'lgLineLabelFuncCode',
+                'lgLineLabelStrings', 'lgLineLabelsOn', 'lgLineThicknessF',
+                'lgLineThicknesses', 'lgMarkerColor', 'lgMarkerColors',
+                'lgMarkerIndex', 'lgMarkerIndexes', 'lgMarkerSizeF', 'lgMarkerSizes',
+                'lgMarkerThicknessF', 'lgMarkerThicknesses', 'lgMonoDashIndex',
+                'lgMonoItemType', 'lgMonoLineColor', 'lgMonoLineDashSegLen',
+                'lgMonoLineLabelFontColor', 'lgMonoLineLabelFontHeight',
+                'lgMonoLineThickness', 'lgMonoMarkerColor', 'lgMonoMarkerIndex',
+                'lgMonoMarkerSize', 'lgMonoMarkerThickness', 'lgOrientation',
+                'lgPerimColor', 'lgPerimDashPattern', 'lgPerimDashSegLenF',
+                'lgPerimFill', 'lgPerimFillColor', 'lgPerimOn', 'lgPerimThicknessF',
+                'lgRightMarginF', 'lgTitleAngleF', 'lgTitleConstantSpacingF',
+                'lgTitleDirection', 'lgTitleExtentF', 'lgTitleFont',
+                'lgTitleFontAspectF', 'lgTitleFontColor', 'lgTitleFontHeightF',
+                'lgTitleFontQuality', 'lgTitleFontThicknessF', 'lgTitleFuncCode',
+                'lgTitleJust', 'lgTitleOffsetF', 'lgTitleOn', 'lgTitlePosition',
+                'lgTitleString', 'lgTopMarginF', 'mpAreaGroupCount',
+                'mpAreaMaskingOn', 'mpAreaNames', 'mpAreaTypes', 'mpBottomAngleF',
+                'mpBottomMapPosF', 'mpBottomNDCF', 'mpBottomNPCF',
+                'mpBottomPointLatF', 'mpBottomPointLonF', 'mpBottomWindowF',
+                'mpCenterLatF', 'mpCenterLonF', 'mpCenterRotF', 'mpCountyLineColor',
+                'mpCountyLineDashPattern', 'mpCountyLineDashSegLenF',
+                'mpCountyLineThicknessF', 'mpDataBaseVersion', 'mpDataResolution',
+                'mpDataSetName', 'mpDefaultFillColor', 'mpDefaultFillPattern',
+                'mpDefaultFillScaleF', 'mpDynamicAreaGroups', 'mpEllipticalBoundary',
+                'mpFillAreaSpecifiers', 'mpFillBoundarySets', 'mpFillColor',
+                'mpFillColors', 'mpFillColors-default', 'mpFillDotSizeF',
+                'mpFillDrawOrder', 'mpFillOn', 'mpFillPatternBackground',
+                'mpFillPattern', 'mpFillPatterns', 'mpFillPatterns-default',
+                'mpFillScaleF', 'mpFillScales', 'mpFillScales-default',
+                'mpFixedAreaGroups', 'mpGeophysicalLineColor',
+                'mpGeophysicalLineDashPattern', 'mpGeophysicalLineDashSegLenF',
+                'mpGeophysicalLineThicknessF', 'mpGreatCircleLinesOn',
+                'mpGridAndLimbDrawOrder', 'mpGridAndLimbOn', 'mpGridLatSpacingF',
+                'mpGridLineColor', 'mpGridLineDashPattern', 'mpGridLineDashSegLenF',
+                'mpGridLineThicknessF', 'mpGridLonSpacingF', 'mpGridMaskMode',
+                'mpGridMaxLatF', 'mpGridPolarLonSpacingF', 'mpGridSpacingF',
+                'mpInlandWaterFillColor', 'mpInlandWaterFillPattern',
+                'mpInlandWaterFillScaleF', 'mpLabelDrawOrder', 'mpLabelFontColor',
+                'mpLabelFontHeightF', 'mpLabelsOn', 'mpLambertMeridianF',
+                'mpLambertParallel1F', 'mpLambertParallel2F', 'mpLandFillColor',
+                'mpLandFillPattern', 'mpLandFillScaleF', 'mpLeftAngleF',
+                'mpLeftCornerLatF', 'mpLeftCornerLonF', 'mpLeftMapPosF',
+                'mpLeftNDCF', 'mpLeftNPCF', 'mpLeftPointLatF',
+                'mpLeftPointLonF', 'mpLeftWindowF', 'mpLimbLineColor',
+                'mpLimbLineDashPattern', 'mpLimbLineDashSegLenF',
+                'mpLimbLineThicknessF', 'mpLimitMode', 'mpMaskAreaSpecifiers',
+                'mpMaskOutlineSpecifiers', 'mpMaxLatF', 'mpMaxLonF',
+                'mpMinLatF', 'mpMinLonF', 'mpMonoFillColor', 'mpMonoFillPattern',
+                'mpMonoFillScale', 'mpNationalLineColor', 'mpNationalLineDashPattern',
+                'mpNationalLineThicknessF', 'mpOceanFillColor', 'mpOceanFillPattern',
+                'mpOceanFillScaleF', 'mpOutlineBoundarySets', 'mpOutlineDrawOrder',
+                'mpOutlineMaskingOn', 'mpOutlineOn', 'mpOutlineSpecifiers',
+                'mpPerimDrawOrder', 'mpPerimLineColor', 'mpPerimLineDashPattern',
+                'mpPerimLineDashSegLenF', 'mpPerimLineThicknessF', 'mpPerimOn',
+                'mpPolyMode', 'mpProjection', 'mpProvincialLineColor',
+                'mpProvincialLineDashPattern', 'mpProvincialLineDashSegLenF',
+                'mpProvincialLineThicknessF', 'mpRelativeCenterLat',
+                'mpRelativeCenterLon', 'mpRightAngleF', 'mpRightCornerLatF',
+                'mpRightCornerLonF', 'mpRightMapPosF', 'mpRightNDCF',
+                'mpRightNPCF', 'mpRightPointLatF', 'mpRightPointLonF',
+                'mpRightWindowF', 'mpSatelliteAngle1F', 'mpSatelliteAngle2F',
+                'mpSatelliteDistF', 'mpShapeMode', 'mpSpecifiedFillColors',
+                'mpSpecifiedFillDirectIndexing', 'mpSpecifiedFillPatterns',
+                'mpSpecifiedFillPriority', 'mpSpecifiedFillScales',
+                'mpTopAngleF', 'mpTopMapPosF', 'mpTopNDCF', 'mpTopNPCF',
+                'mpTopPointLatF', 'mpTopPointLonF', 'mpTopWindowF',
+                'mpUSStateLineColor', 'mpUSStateLineDashPattern',
+                'mpUSStateLineDashSegLenF', 'mpUSStateLineThicknessF',
+                'pmAnnoManagers', 'pmAnnoViews', 'pmLabelBarDisplayMode',
+                'pmLabelBarHeightF', 'pmLabelBarKeepAspect', 'pmLabelBarOrthogonalPosF',
+                'pmLabelBarParallelPosF', 'pmLabelBarSide', 'pmLabelBarWidthF',
+                'pmLabelBarZone', 'pmLegendDisplayMode', 'pmLegendHeightF',
+                'pmLegendKeepAspect', 'pmLegendOrthogonalPosF',
+                'pmLegendParallelPosF', 'pmLegendSide', 'pmLegendWidthF',
+                'pmLegendZone', 'pmOverlaySequenceIds', 'pmTickMarkDisplayMode',
+                'pmTickMarkZone', 'pmTitleDisplayMode', 'pmTitleZone',
+                'prGraphicStyle', 'prPolyType', 'prXArray', 'prYArray',
+                'sfCopyData', 'sfDataArray', 'sfDataMaxV', 'sfDataMinV',
+                'sfElementNodes', 'sfExchangeDimensions', 'sfFirstNodeIndex',
+                'sfMissingValueV', 'sfXArray', 'sfXCActualEndF', 'sfXCActualStartF',
+                'sfXCEndIndex', 'sfXCEndSubsetV', 'sfXCEndV', 'sfXCStartIndex',
+                'sfXCStartSubsetV', 'sfXCStartV', 'sfXCStride', 'sfXCellBounds',
+                'sfYArray', 'sfYCActualEndF', 'sfYCActualStartF', 'sfYCEndIndex',
+                'sfYCEndSubsetV', 'sfYCEndV', 'sfYCStartIndex', 'sfYCStartSubsetV',
+                'sfYCStartV', 'sfYCStride', 'sfYCellBounds', 'stArrowLengthF',
+                'stArrowStride', 'stCrossoverCheckCount',
+                'stExplicitLabelBarLabelsOn', 'stLabelBarEndLabelsOn',
+                'stLabelFormat', 'stLengthCheckCount', 'stLevelColors',
+                'stLevelCount', 'stLevelPalette', 'stLevelSelectionMode',
+                'stLevelSpacingF', 'stLevels', 'stLineColor', 'stLineOpacityF',
+                'stLineStartStride', 'stLineThicknessF', 'stMapDirection',
+                'stMaxLevelCount', 'stMaxLevelValF', 'stMinArrowSpacingF',
+                'stMinDistanceF', 'stMinLevelValF', 'stMinLineSpacingF',
+                'stMinStepFactorF', 'stMonoLineColor', 'stNoDataLabelOn',
+                'stNoDataLabelString', 'stScalarFieldData', 'stScalarMissingValColor',
+                'stSpanLevelPalette', 'stStepSizeF', 'stStreamlineDrawOrder',
+                'stUseScalarArray', 'stVectorFieldData', 'stZeroFLabelAngleF',
+                'stZeroFLabelBackgroundColor', 'stZeroFLabelConstantSpacingF',
+                'stZeroFLabelFont', 'stZeroFLabelFontAspectF',
+                'stZeroFLabelFontColor', 'stZeroFLabelFontHeightF',
+                'stZeroFLabelFontQuality', 'stZeroFLabelFontThicknessF',
+                'stZeroFLabelFuncCode', 'stZeroFLabelJust', 'stZeroFLabelOn',
+                'stZeroFLabelOrthogonalPosF', 'stZeroFLabelParallelPosF',
+                'stZeroFLabelPerimColor', 'stZeroFLabelPerimOn',
+                'stZeroFLabelPerimSpaceF', 'stZeroFLabelPerimThicknessF',
+                'stZeroFLabelSide', 'stZeroFLabelString', 'stZeroFLabelTextDirection',
+                'stZeroFLabelZone', 'tfDoNDCOverlay', 'tfPlotManagerOn',
+                'tfPolyDrawList', 'tfPolyDrawOrder', 'tiDeltaF', 'tiMainAngleF',
+                'tiMainConstantSpacingF', 'tiMainDirection', 'tiMainFont',
+                'tiMainFontAspectF', 'tiMainFontColor', 'tiMainFontHeightF',
+                'tiMainFontQuality', 'tiMainFontThicknessF', 'tiMainFuncCode',
+                'tiMainJust', 'tiMainOffsetXF', 'tiMainOffsetYF', 'tiMainOn',
+                'tiMainPosition', 'tiMainSide', 'tiMainString', 'tiUseMainAttributes',
+                'tiXAxisAngleF', 'tiXAxisConstantSpacingF', 'tiXAxisDirection',
+                'tiXAxisFont', 'tiXAxisFontAspectF', 'tiXAxisFontColor',
+                'tiXAxisFontHeightF', 'tiXAxisFontQuality', 'tiXAxisFontThicknessF',
+                'tiXAxisFuncCode', 'tiXAxisJust', 'tiXAxisOffsetXF',
+                'tiXAxisOffsetYF', 'tiXAxisOn', 'tiXAxisPosition', 'tiXAxisSide',
+                'tiXAxisString', 'tiYAxisAngleF', 'tiYAxisConstantSpacingF',
+                'tiYAxisDirection', 'tiYAxisFont', 'tiYAxisFontAspectF',
+                'tiYAxisFontColor', 'tiYAxisFontHeightF', 'tiYAxisFontQuality',
+                'tiYAxisFontThicknessF', 'tiYAxisFuncCode', 'tiYAxisJust',
+                'tiYAxisOffsetXF', 'tiYAxisOffsetYF', 'tiYAxisOn', 'tiYAxisPosition',
+                'tiYAxisSide', 'tiYAxisString', 'tmBorderLineColor',
+                'tmBorderThicknessF', 'tmEqualizeXYSizes', 'tmLabelAutoStride',
+                'tmSciNoteCutoff', 'tmXBAutoPrecision', 'tmXBBorderOn',
+                'tmXBDataLeftF', 'tmXBDataRightF', 'tmXBFormat', 'tmXBIrrTensionF',
+                'tmXBIrregularPoints', 'tmXBLabelAngleF', 'tmXBLabelConstantSpacingF',
+                'tmXBLabelDeltaF', 'tmXBLabelDirection', 'tmXBLabelFont',
+                'tmXBLabelFontAspectF', 'tmXBLabelFontColor', 'tmXBLabelFontHeightF',
+                'tmXBLabelFontQuality', 'tmXBLabelFontThicknessF',
+                'tmXBLabelFuncCode', 'tmXBLabelJust', 'tmXBLabelStride', 'tmXBLabels',
+                'tmXBLabelsOn', 'tmXBMajorLengthF', 'tmXBMajorLineColor',
+                'tmXBMajorOutwardLengthF', 'tmXBMajorThicknessF', 'tmXBMaxLabelLenF',
+                'tmXBMaxTicks', 'tmXBMinLabelSpacingF', 'tmXBMinorLengthF',
+                'tmXBMinorLineColor', 'tmXBMinorOn', 'tmXBMinorOutwardLengthF',
+                'tmXBMinorPerMajor', 'tmXBMinorThicknessF', 'tmXBMinorValues',
+                'tmXBMode', 'tmXBOn', 'tmXBPrecision', 'tmXBStyle', 'tmXBTickEndF',
+                'tmXBTickSpacingF', 'tmXBTickStartF', 'tmXBValues', 'tmXMajorGrid',
+                'tmXMajorGridLineColor', 'tmXMajorGridLineDashPattern',
+                'tmXMajorGridThicknessF', 'tmXMinorGrid', 'tmXMinorGridLineColor',
+                'tmXMinorGridLineDashPattern', 'tmXMinorGridThicknessF',
+                'tmXTAutoPrecision', 'tmXTBorderOn', 'tmXTDataLeftF',
+                'tmXTDataRightF', 'tmXTFormat', 'tmXTIrrTensionF',
+                'tmXTIrregularPoints', 'tmXTLabelAngleF', 'tmXTLabelConstantSpacingF',
+                'tmXTLabelDeltaF', 'tmXTLabelDirection', 'tmXTLabelFont',
+                'tmXTLabelFontAspectF', 'tmXTLabelFontColor', 'tmXTLabelFontHeightF',
+                'tmXTLabelFontQuality', 'tmXTLabelFontThicknessF',
+                'tmXTLabelFuncCode', 'tmXTLabelJust', 'tmXTLabelStride', 'tmXTLabels',
+                'tmXTLabelsOn', 'tmXTMajorLengthF', 'tmXTMajorLineColor',
+                'tmXTMajorOutwardLengthF', 'tmXTMajorThicknessF', 'tmXTMaxLabelLenF',
+                'tmXTMaxTicks', 'tmXTMinLabelSpacingF', 'tmXTMinorLengthF',
+                'tmXTMinorLineColor', 'tmXTMinorOn', 'tmXTMinorOutwardLengthF',
+                'tmXTMinorPerMajor', 'tmXTMinorThicknessF', 'tmXTMinorValues',
+                'tmXTMode', 'tmXTOn', 'tmXTPrecision', 'tmXTStyle', 'tmXTTickEndF',
+                'tmXTTickSpacingF', 'tmXTTickStartF', 'tmXTValues', 'tmXUseBottom',
+                'tmYLAutoPrecision', 'tmYLBorderOn', 'tmYLDataBottomF',
+                'tmYLDataTopF', 'tmYLFormat', 'tmYLIrrTensionF',
+                'tmYLIrregularPoints', 'tmYLLabelAngleF', 'tmYLLabelConstantSpacingF',
+                'tmYLLabelDeltaF', 'tmYLLabelDirection', 'tmYLLabelFont',
+                'tmYLLabelFontAspectF', 'tmYLLabelFontColor', 'tmYLLabelFontHeightF',
+                'tmYLLabelFontQuality', 'tmYLLabelFontThicknessF',
+                'tmYLLabelFuncCode', 'tmYLLabelJust', 'tmYLLabelStride', 'tmYLLabels',
+                'tmYLLabelsOn', 'tmYLMajorLengthF', 'tmYLMajorLineColor',
+                'tmYLMajorOutwardLengthF', 'tmYLMajorThicknessF', 'tmYLMaxLabelLenF',
+                'tmYLMaxTicks', 'tmYLMinLabelSpacingF', 'tmYLMinorLengthF',
+                'tmYLMinorLineColor', 'tmYLMinorOn', 'tmYLMinorOutwardLengthF',
+                'tmYLMinorPerMajor', 'tmYLMinorThicknessF', 'tmYLMinorValues',
+                'tmYLMode', 'tmYLOn', 'tmYLPrecision', 'tmYLStyle', 'tmYLTickEndF',
+                'tmYLTickSpacingF', 'tmYLTickStartF', 'tmYLValues', 'tmYMajorGrid',
+                'tmYMajorGridLineColor', 'tmYMajorGridLineDashPattern',
+                'tmYMajorGridThicknessF', 'tmYMinorGrid', 'tmYMinorGridLineColor',
+                'tmYMinorGridLineDashPattern', 'tmYMinorGridThicknessF',
+                'tmYRAutoPrecision', 'tmYRBorderOn', 'tmYRDataBottomF',
+                'tmYRDataTopF', 'tmYRFormat', 'tmYRIrrTensionF',
+                'tmYRIrregularPoints', 'tmYRLabelAngleF', 'tmYRLabelConstantSpacingF',
+                'tmYRLabelDeltaF', 'tmYRLabelDirection', 'tmYRLabelFont',
+                'tmYRLabelFontAspectF', 'tmYRLabelFontColor', 'tmYRLabelFontHeightF',
+                'tmYRLabelFontQuality', 'tmYRLabelFontThicknessF',
+                'tmYRLabelFuncCode', 'tmYRLabelJust', 'tmYRLabelStride', 'tmYRLabels',
+                'tmYRLabelsOn', 'tmYRMajorLengthF', 'tmYRMajorLineColor',
+                'tmYRMajorOutwardLengthF', 'tmYRMajorThicknessF', 'tmYRMaxLabelLenF',
+                'tmYRMaxTicks', 'tmYRMinLabelSpacingF', 'tmYRMinorLengthF',
+                'tmYRMinorLineColor', 'tmYRMinorOn', 'tmYRMinorOutwardLengthF',
+                'tmYRMinorPerMajor', 'tmYRMinorThicknessF', 'tmYRMinorValues',
+                'tmYRMode', 'tmYROn', 'tmYRPrecision', 'tmYRStyle', 'tmYRTickEndF',
+                'tmYRTickSpacingF', 'tmYRTickStartF', 'tmYRValues', 'tmYUseLeft',
+                'trGridType', 'trLineInterpolationOn',
+                'trXAxisType', 'trXCoordPoints', 'trXInterPoints', 'trXLog',
+                'trXMaxF', 'trXMinF', 'trXReverse', 'trXSamples', 'trXTensionF',
+                'trYAxisType', 'trYCoordPoints', 'trYInterPoints', 'trYLog',
+                'trYMaxF', 'trYMinF', 'trYReverse', 'trYSamples', 'trYTensionF',
+                'txAngleF', 'txBackgroundFillColor', 'txConstantSpacingF', 'txDirection',
+                'txFont', 'HLU-Fonts', 'txFontAspectF', 'txFontColor',
+                'txFontHeightF', 'txFontOpacityF', 'txFontQuality',
+                'txFontThicknessF', 'txFuncCode', 'txJust', 'txPerimColor',
+                'txPerimDashLengthF', 'txPerimDashPattern', 'txPerimOn',
+                'txPerimSpaceF', 'txPerimThicknessF', 'txPosXF', 'txPosYF',
+                'txString', 'vcExplicitLabelBarLabelsOn', 'vcFillArrowEdgeColor',
+                'vcFillArrowEdgeThicknessF', 'vcFillArrowFillColor',
+                'vcFillArrowHeadInteriorXF', 'vcFillArrowHeadMinFracXF',
+                'vcFillArrowHeadMinFracYF', 'vcFillArrowHeadXF', 'vcFillArrowHeadYF',
+                'vcFillArrowMinFracWidthF', 'vcFillArrowWidthF', 'vcFillArrowsOn',
+                'vcFillOverEdge', 'vcGlyphOpacityF', 'vcGlyphStyle',
+                'vcLabelBarEndLabelsOn', 'vcLabelFontColor', 'vcLabelFontHeightF',
+                'vcLabelsOn', 'vcLabelsUseVectorColor', 'vcLevelColors',
+                'vcLevelCount', 'vcLevelPalette', 'vcLevelSelectionMode',
+                'vcLevelSpacingF', 'vcLevels', 'vcLineArrowColor',
+                'vcLineArrowHeadMaxSizeF', 'vcLineArrowHeadMinSizeF',
+                'vcLineArrowThicknessF', 'vcMagnitudeFormat',
+                'vcMagnitudeScaleFactorF', 'vcMagnitudeScaleValueF',
+                'vcMagnitudeScalingMode', 'vcMapDirection', 'vcMaxLevelCount',
+                'vcMaxLevelValF', 'vcMaxMagnitudeF', 'vcMinAnnoAngleF',
+                'vcMinAnnoArrowAngleF', 'vcMinAnnoArrowEdgeColor',
+                'vcMinAnnoArrowFillColor', 'vcMinAnnoArrowLineColor',
+                'vcMinAnnoArrowMinOffsetF', 'vcMinAnnoArrowSpaceF',
+                'vcMinAnnoArrowUseVecColor', 'vcMinAnnoBackgroundColor',
+                'vcMinAnnoConstantSpacingF', 'vcMinAnnoExplicitMagnitudeF',
+                'vcMinAnnoFont', 'vcMinAnnoFontAspectF', 'vcMinAnnoFontColor',
+                'vcMinAnnoFontHeightF', 'vcMinAnnoFontQuality',
+                'vcMinAnnoFontThicknessF', 'vcMinAnnoFuncCode', 'vcMinAnnoJust',
+                'vcMinAnnoOn', 'vcMinAnnoOrientation', 'vcMinAnnoOrthogonalPosF',
+                'vcMinAnnoParallelPosF', 'vcMinAnnoPerimColor', 'vcMinAnnoPerimOn',
+                'vcMinAnnoPerimSpaceF', 'vcMinAnnoPerimThicknessF', 'vcMinAnnoSide',
+                'vcMinAnnoString1', 'vcMinAnnoString1On', 'vcMinAnnoString2',
+                'vcMinAnnoString2On', 'vcMinAnnoTextDirection', 'vcMinAnnoZone',
+                'vcMinDistanceF', 'vcMinFracLengthF', 'vcMinLevelValF',
+                'vcMinMagnitudeF', 'vcMonoFillArrowEdgeColor',
+                'vcMonoFillArrowFillColor', 'vcMonoLineArrowColor',
+                'vcMonoWindBarbColor', 'vcNoDataLabelOn', 'vcNoDataLabelString',
+                'vcPositionMode', 'vcRefAnnoAngleF', 'vcRefAnnoArrowAngleF',
+                'vcRefAnnoArrowEdgeColor', 'vcRefAnnoArrowFillColor',
+                'vcRefAnnoArrowLineColor', 'vcRefAnnoArrowMinOffsetF',
+                'vcRefAnnoArrowSpaceF', 'vcRefAnnoArrowUseVecColor',
+                'vcRefAnnoBackgroundColor', 'vcRefAnnoConstantSpacingF',
+                'vcRefAnnoExplicitMagnitudeF', 'vcRefAnnoFont',
+                'vcRefAnnoFontAspectF', 'vcRefAnnoFontColor', 'vcRefAnnoFontHeightF',
+                'vcRefAnnoFontQuality', 'vcRefAnnoFontThicknessF',
+                'vcRefAnnoFuncCode', 'vcRefAnnoJust', 'vcRefAnnoOn',
+                'vcRefAnnoOrientation', 'vcRefAnnoOrthogonalPosF',
+                'vcRefAnnoParallelPosF', 'vcRefAnnoPerimColor', 'vcRefAnnoPerimOn',
+                'vcRefAnnoPerimSpaceF', 'vcRefAnnoPerimThicknessF', 'vcRefAnnoSide',
+                'vcRefAnnoString1', 'vcRefAnnoString1On', 'vcRefAnnoString2',
+                'vcRefAnnoString2On', 'vcRefAnnoTextDirection', 'vcRefAnnoZone',
+                'vcRefLengthF', 'vcRefMagnitudeF', 'vcScalarFieldData',
+                'vcScalarMissingValColor', 'vcScalarValueFormat',
+                'vcScalarValueScaleFactorF', 'vcScalarValueScaleValueF',
+                'vcScalarValueScalingMode', 'vcSpanLevelPalette', 'vcUseRefAnnoRes',
+                'vcUseScalarArray', 'vcVectorDrawOrder', 'vcVectorFieldData',
+                'vcWindBarbCalmCircleSizeF', 'vcWindBarbColor',
+                'vcWindBarbLineThicknessF', 'vcWindBarbScaleFactorF',
+                'vcWindBarbTickAngleF', 'vcWindBarbTickLengthF',
+                'vcWindBarbTickSpacingF', 'vcZeroFLabelAngleF',
+                'vcZeroFLabelBackgroundColor', 'vcZeroFLabelConstantSpacingF',
+                'vcZeroFLabelFont', 'vcZeroFLabelFontAspectF',
+                'vcZeroFLabelFontColor', 'vcZeroFLabelFontHeightF',
+                'vcZeroFLabelFontQuality', 'vcZeroFLabelFontThicknessF',
+                'vcZeroFLabelFuncCode', 'vcZeroFLabelJust', 'vcZeroFLabelOn',
+                'vcZeroFLabelOrthogonalPosF', 'vcZeroFLabelParallelPosF',
+                'vcZeroFLabelPerimColor', 'vcZeroFLabelPerimOn',
+                'vcZeroFLabelPerimSpaceF', 'vcZeroFLabelPerimThicknessF',
+                'vcZeroFLabelSide', 'vcZeroFLabelString', 'vcZeroFLabelTextDirection',
+                'vcZeroFLabelZone', 'vfCopyData', 'vfDataArray',
+                'vfExchangeDimensions', 'vfExchangeUVData', 'vfMagMaxV', 'vfMagMinV',
+                'vfMissingUValueV', 'vfMissingVValueV', 'vfPolarData',
+                'vfSingleMissingValue', 'vfUDataArray', 'vfUMaxV', 'vfUMinV',
+                'vfVDataArray', 'vfVMaxV', 'vfVMinV', 'vfXArray', 'vfXCActualEndF',
+                'vfXCActualStartF', 'vfXCEndIndex', 'vfXCEndSubsetV', 'vfXCEndV',
+                'vfXCStartIndex', 'vfXCStartSubsetV', 'vfXCStartV', 'vfXCStride',
+                'vfYArray', 'vfYCActualEndF', 'vfYCActualStartF', 'vfYCEndIndex',
+                'vfYCEndSubsetV', 'vfYCEndV', 'vfYCStartIndex', 'vfYCStartSubsetV',
+                'vfYCStartV', 'vfYCStride', 'vpAnnoManagerId', 'vpClipOn',
+                'vpHeightF', 'vpKeepAspect', 'vpOn', 'vpUseSegments', 'vpWidthF',
+                'vpXF', 'vpYF', 'wkAntiAlias', 'wkBackgroundColor', 'wkBackgroundOpacityF',
+                'wkColorMapLen', 'wkColorMap', 'wkColorModel', 'wkDashTableLength',
+                'wkDefGraphicStyleId', 'wkDeviceLowerX', 'wkDeviceLowerY',
+                'wkDeviceUpperX', 'wkDeviceUpperY', 'wkFileName', 'wkFillTableLength',
+                'wkForegroundColor', 'wkFormat', 'wkFullBackground', 'wkGksWorkId',
+                'wkHeight', 'wkMarkerTableLength', 'wkMetaName', 'wkOrientation',
+                'wkPDFFileName', 'wkPDFFormat', 'wkPDFResolution', 'wkPSFileName',
+                'wkPSFormat', 'wkPSResolution', 'wkPaperHeightF', 'wkPaperSize',
+                'wkPaperWidthF', 'wkPause', 'wkTopLevelViews', 'wkViews',
+                'wkVisualType', 'wkWidth', 'wkWindowId', 'wkXColorMode', 'wsCurrentSize',
+                'wsMaximumSize', 'wsThresholdSize', 'xyComputeXMax',
+                'xyComputeXMin', 'xyComputeYMax', 'xyComputeYMin', 'xyCoordData',
+                'xyCoordDataSpec', 'xyCurveDrawOrder', 'xyDashPattern',
+                'xyDashPatterns', 'xyExplicitLabels', 'xyExplicitLegendLabels',
+                'xyLabelMode', 'xyLineColor', 'xyLineColors', 'xyLineDashSegLenF',
+                'xyLineLabelConstantSpacingF', 'xyLineLabelFont',
+                'xyLineLabelFontAspectF', 'xyLineLabelFontColor',
+                'xyLineLabelFontColors', 'xyLineLabelFontHeightF',
+                'xyLineLabelFontQuality', 'xyLineLabelFontThicknessF',
+                'xyLineLabelFuncCode', 'xyLineThicknessF', 'xyLineThicknesses',
+                'xyMarkLineMode', 'xyMarkLineModes', 'xyMarker', 'xyMarkerColor',
+                'xyMarkerColors', 'xyMarkerSizeF', 'xyMarkerSizes',
+                'xyMarkerThicknessF', 'xyMarkerThicknesses', 'xyMarkers',
+                'xyMonoDashPattern', 'xyMonoLineColor', 'xyMonoLineLabelFontColor',
+                'xyMonoLineThickness', 'xyMonoMarkLineMode', 'xyMonoMarker',
+                'xyMonoMarkerColor', 'xyMonoMarkerSize', 'xyMonoMarkerThickness',
+                'xyXIrrTensionF', 'xyXIrregularPoints', 'xyXStyle', 'xyYIrrTensionF',
+                'xyYIrregularPoints', 'xyYStyle'), prefix=r'\b'),
+             Name.Builtin),
+
+            # Booleans
+            (r'\.(True|False)\.', Name.Builtin),
+            # Comparing Operators
+            (r'\.(eq|ne|lt|le|gt|ge|not|and|or|xor)\.', Operator.Word),
+        ],
+
+        'strings': [
+            (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
+        ],
+
+        'nums': [
+            (r'\d+(?![.e])(_[a-z]\w+)?', Number.Integer),
+            (r'[+-]?\d*\.\d+(e[-+]?\d+)?(_[a-z]\w+)?', Number.Float),
+            (r'[+-]?\d+\.\d*(e[-+]?\d+)?(_[a-z]\w+)?', Number.Float),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/nimrod.py b/lib/python3.11/site-packages/pygments/lexers/nimrod.py
new file mode 100644
index 0000000000000000000000000000000000000000..b99e246d707f30d4c0c3fab50d7293fcd34e3510
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/nimrod.py
@@ -0,0 +1,199 @@
+"""
+    pygments.lexers.nimrod
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for the Nim language (formerly known as Nimrod).
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, default, bygroups
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Error
+
+__all__ = ['NimrodLexer']
+
+
+class NimrodLexer(RegexLexer):
+    """
+    For Nim source code.
+    """
+
+    name = 'Nimrod'
+    url = 'http://nim-lang.org/'
+    aliases = ['nimrod', 'nim']
+    filenames = ['*.nim', '*.nimrod']
+    mimetypes = ['text/x-nim']
+    version_added = '1.5'
+
+    flags = re.MULTILINE | re.IGNORECASE
+
+    def underscorize(words):
+        newWords = []
+        new = []
+        for word in words:
+            for ch in word:
+                new.append(ch)
+                new.append("_?")
+            newWords.append(''.join(new))
+            new = []
+        return "|".join(newWords)
+
+    keywords = [
+        'addr', 'and', 'as', 'asm', 'bind', 'block', 'break', 'case',
+        'cast', 'concept', 'const', 'continue', 'converter', 'defer', 'discard',
+        'distinct', 'div', 'do', 'elif', 'else', 'end', 'enum', 'except',
+        'export', 'finally', 'for', 'if', 'in', 'yield', 'interface',
+        'is', 'isnot', 'iterator', 'let', 'mixin', 'mod',
+        'not', 'notin', 'object', 'of', 'or', 'out', 'ptr', 'raise',
+        'ref', 'return', 'shl', 'shr', 'static', 'try',
+        'tuple', 'type', 'using', 'when', 'while', 'xor'
+    ]
+
+    keywordsPseudo = [
+        'nil', 'true', 'false'
+    ]
+
+    opWords = [
+        'and', 'or', 'not', 'xor', 'shl', 'shr', 'div', 'mod', 'in',
+        'notin', 'is', 'isnot'
+    ]
+
+    types = [
+        'int', 'int8', 'int16', 'int32', 'int64', 'float', 'float32', 'float64',
+        'bool', 'char', 'range', 'array', 'seq', 'set', 'string'
+    ]
+
+    tokens = {
+        'root': [
+            # Comments
+            (r'##\[', String.Doc, 'doccomment'),
+            (r'##.*$', String.Doc),
+            (r'#\[', Comment.Multiline, 'comment'),
+            (r'#.*$', Comment),
+
+            # Pragmas
+            (r'\{\.', String.Other, 'pragma'),
+
+            # Operators
+            (r'[*=><+\-/@$~&%!?|\\\[\]]', Operator),
+            (r'\.\.|\.|,|\[\.|\.\]|\{\.|\.\}|\(\.|\.\)|\{|\}|\(|\)|:|\^|`|;',
+             Punctuation),
+
+            # Case statement branch
+            (r'(\n\s*)(of)(\s)', bygroups(Text.Whitespace, Keyword,
+                                          Text.Whitespace), 'casebranch'),
+
+            # Strings
+            (r'(?:[\w]+)"', String, 'rdqs'),
+            (r'"""', String.Double, 'tdqs'),
+            ('"', String, 'dqs'),
+
+            # Char
+            ("'", String.Char, 'chars'),
+
+            # Keywords
+            (rf'({underscorize(opWords)})\b', Operator.Word),
+            (r'(proc|func|method|macro|template)(\s)(?![(\[\]])',
+             bygroups(Keyword, Text.Whitespace), 'funcname'),
+            (rf'({underscorize(keywords)})\b', Keyword),
+            (r'({})\b'.format(underscorize(['from', 'import', 'include', 'export'])),
+             Keyword.Namespace),
+            (r'(v_?a_?r)\b', Keyword.Declaration),
+            (rf'({underscorize(types)})\b', Name.Builtin),
+            (rf'({underscorize(keywordsPseudo)})\b', Keyword.Pseudo),
+
+            # Identifiers
+            (r'\b((?![_\d])\w)(((?!_)\w)|(_(?!_)\w))*', Name),
+
+            # Numbers
+            (r'[0-9][0-9_]*(?=([e.]|\'f(32|64)))',
+             Number.Float, ('float-suffix', 'float-number')),
+            (r'0x[a-f0-9][a-f0-9_]*', Number.Hex, 'int-suffix'),
+            (r'0b[01][01_]*', Number.Bin, 'int-suffix'),
+            (r'0o[0-7][0-7_]*', Number.Oct, 'int-suffix'),
+            (r'[0-9][0-9_]*', Number.Integer, 'int-suffix'),
+
+            # Whitespace
+            (r'\s+', Text.Whitespace),
+            (r'.+$', Error),
+        ],
+        'chars': [
+            (r'\\([\\abcefnrtvl"\']|x[a-f0-9]{2}|[0-9]{1,3})', String.Escape),
+            (r"'", String.Char, '#pop'),
+            (r".", String.Char)
+        ],
+        'strings': [
+            (r'(?|>=|>>|>|<=|<<|<|\+|-|=|/|\*|%|\+=|-=|!|@', Operator),
+            (r'\(|\)|\[|\]|,|\.\.\.|\.\.|\.|::|:', Punctuation),
+            (r'`\{[^`]*`\}', Text),  # Extern blocks won't be Lexed by Nit
+            (r'[\r\n\t ]+', Text),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/nix.py b/lib/python3.11/site-packages/pygments/lexers/nix.py
new file mode 100644
index 0000000000000000000000000000000000000000..16572afe48a097271dcf017a1d1f53e89b000916
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/nix.py
@@ -0,0 +1,144 @@
+"""
+    pygments.lexers.nix
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the NixOS Nix language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Literal
+
+__all__ = ['NixLexer']
+
+
+class NixLexer(RegexLexer):
+    """
+    For the Nix language.
+    """
+
+    name = 'Nix'
+    url = 'http://nixos.org/nix/'
+    aliases = ['nixos', 'nix']
+    filenames = ['*.nix']
+    mimetypes = ['text/x-nix']
+    version_added = '2.0'
+
+    keywords = ['rec', 'with', 'let', 'in', 'inherit', 'assert', 'if',
+                'else', 'then', '...']
+    builtins = ['import', 'abort', 'baseNameOf', 'dirOf', 'isNull', 'builtins',
+                'map', 'removeAttrs', 'throw', 'toString', 'derivation']
+    operators = ['++', '+', '?', '.', '!', '//', '==', '/',
+                 '!=', '&&', '||', '->', '=', '<', '>', '*', '-']
+
+    punctuations = ["(", ")", "[", "]", ";", "{", "}", ":", ",", "@"]
+
+    tokens = {
+        'root': [
+            # comments starting with #
+            (r'#.*$', Comment.Single),
+
+            # multiline comments
+            (r'/\*', Comment.Multiline, 'comment'),
+
+            # whitespace
+            (r'\s+', Text),
+
+            # keywords
+            ('({})'.format('|'.join(re.escape(entry) + '\\b' for entry in keywords)), Keyword),
+
+            # highlight the builtins
+            ('({})'.format('|'.join(re.escape(entry) + '\\b' for entry in builtins)),
+             Name.Builtin),
+
+            (r'\b(true|false|null)\b', Name.Constant),
+
+            # floats
+            (r'-?(\d+\.\d*|\.\d+)([eE][-+]?\d+)?', Number.Float),
+
+            # integers
+            (r'-?[0-9]+', Number.Integer),
+
+            # paths
+            (r'[\w.+-]*(\/[\w.+-]+)+', Literal),
+            (r'~(\/[\w.+-]+)+', Literal),
+            (r'\<[\w.+-]+(\/[\w.+-]+)*\>', Literal),
+
+            # operators
+            ('({})'.format('|'.join(re.escape(entry) for entry in operators)),
+             Operator),
+
+            # word operators
+            (r'\b(or|and)\b', Operator.Word),
+
+            (r'\{', Punctuation, 'block'),
+
+            # punctuations
+            ('({})'.format('|'.join(re.escape(entry) for entry in punctuations)), Punctuation),
+
+            # strings
+            (r'"', String.Double, 'doublequote'),
+            (r"''", String.Multiline, 'multiline'),
+
+            # urls
+            (r'[a-zA-Z][a-zA-Z0-9\+\-\.]*\:[\w%/?:@&=+$,\\.!~*\'-]+', Literal),
+
+            # names of variables
+            (r'[\w-]+(?=\s*=)', String.Symbol),
+            (r'[a-zA-Z_][\w\'-]*', Text),
+
+            (r"\$\{", String.Interpol, 'antiquote'),
+        ],
+        'comment': [
+            (r'[^/*]+', Comment.Multiline),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'[*/]', Comment.Multiline),
+        ],
+        'multiline': [
+            (r"''(\$|'|\\n|\\r|\\t|\\)", String.Escape),
+            (r"''", String.Multiline, '#pop'),
+            (r'\$\{', String.Interpol, 'antiquote'),
+            (r"[^'\$]+", String.Multiline),
+            (r"\$[^\{']", String.Multiline),
+            (r"'[^']", String.Multiline),
+            (r"\$(?=')", String.Multiline),
+        ],
+        'doublequote': [
+            (r'\\(\\|"|\$|n)', String.Escape),
+            (r'"', String.Double, '#pop'),
+            (r'\$\{', String.Interpol, 'antiquote'),
+            (r'[^"\\\$]+', String.Double),
+            (r'\$[^\{"]', String.Double),
+            (r'\$(?=")', String.Double),
+            (r'\\', String.Double),
+        ],
+        'antiquote': [
+            (r"\}", String.Interpol, '#pop'),
+            # TODO: we should probably escape also here ''${ \${
+            (r"\$\{", String.Interpol, '#push'),
+            include('root'),
+        ],
+        'block': [
+            (r"\}", Punctuation, '#pop'),
+            include('root'),
+        ],
+    }
+
+    def analyse_text(text):
+        rv = 0.0
+        # TODO: let/in
+        if re.search(r'import.+?<[^>]+>', text):
+            rv += 0.4
+        if re.search(r'mkDerivation\s+(\(|\{|rec)', text):
+            rv += 0.4
+        if re.search(r'=\s+mkIf\s+', text):
+            rv += 0.4
+        if re.search(r'\{[a-zA-Z,\s]+\}:', text):
+            rv += 0.1
+        return rv
diff --git a/lib/python3.11/site-packages/pygments/lexers/numbair.py b/lib/python3.11/site-packages/pygments/lexers/numbair.py
new file mode 100644
index 0000000000000000000000000000000000000000..28395b41a4d302aadba80c4413293dd288779407
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/numbair.py
@@ -0,0 +1,63 @@
+"""
+    pygments.lexers.numbair
+    ~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for other Numba Intermediate Representation.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, include, bygroups, words
+from pygments.token import Whitespace, Name, String,  Punctuation, Keyword, \
+    Operator, Number
+
+__all__ = ["NumbaIRLexer"]
+
+class NumbaIRLexer(RegexLexer):
+    """
+    Lexer for Numba IR
+    """
+    name = 'Numba_IR'
+    url = "https://numba.readthedocs.io/en/stable/developer/architecture.html#stage-2-generate-the-numba-ir"
+    aliases = ['numba_ir', 'numbair']
+    filenames = ['*.numba_ir']
+    mimetypes = ['text/x-numba_ir', 'text/x-numbair']
+    version_added = '2.19'
+
+    identifier = r'\$[a-zA-Z0-9._]+'
+    fun_or_var = r'([a-zA-Z_]+[a-zA-Z0-9]*)'
+
+    tokens = {
+        'root' : [
+            (r'(label)(\ [0-9]+)(:)$',
+                bygroups(Keyword, Name.Label, Punctuation)),
+
+            (r'=', Operator),
+            include('whitespace'),
+            include('keyword'),
+
+            (identifier, Name.Variable),
+            (fun_or_var + r'(\()',
+                bygroups(Name.Function, Punctuation)),
+            (fun_or_var + r'(\=)',
+                bygroups(Name.Attribute, Punctuation)),
+            (fun_or_var, Name.Constant),
+            (r'[0-9]+', Number),
+
+            # 
+            (r'<[^>\n]*>', String),
+
+            (r'[=<>{}\[\]()*.,!\':]|x\b', Punctuation)
+        ],
+
+        'keyword':[
+            (words((
+                'del', 'jump', 'call', 'branch',
+            ), suffix=' '), Keyword),
+        ],
+
+        'whitespace': [
+            (r'(\n|\s)+', Whitespace),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/oberon.py b/lib/python3.11/site-packages/pygments/lexers/oberon.py
new file mode 100644
index 0000000000000000000000000000000000000000..11cf571dfd6097354117f2842246eeb06ff696ea
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/oberon.py
@@ -0,0 +1,120 @@
+"""
+    pygments.lexers.oberon
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Oberon family languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['ComponentPascalLexer']
+
+
+class ComponentPascalLexer(RegexLexer):
+    """
+    For Component Pascal source code.
+    """
+    name = 'Component Pascal'
+    aliases = ['componentpascal', 'cp']
+    filenames = ['*.cp', '*.cps']
+    mimetypes = ['text/x-component-pascal']
+    url = 'https://blackboxframework.org'
+    version_added = '2.1'
+
+    flags = re.MULTILINE | re.DOTALL
+
+    tokens = {
+        'root': [
+            include('whitespace'),
+            include('comments'),
+            include('punctuation'),
+            include('numliterals'),
+            include('strings'),
+            include('operators'),
+            include('builtins'),
+            include('identifiers'),
+        ],
+        'whitespace': [
+            (r'\n+', Text),  # blank lines
+            (r'\s+', Text),  # whitespace
+        ],
+        'comments': [
+            (r'\(\*([^$].*?)\*\)', Comment.Multiline),
+            # TODO: nested comments (* (* ... *) ... (* ... *) *) not supported!
+        ],
+        'punctuation': [
+            (r'[()\[\]{},.:;|]', Punctuation),
+        ],
+        'numliterals': [
+            (r'[0-9A-F]+X\b', Number.Hex),                 # char code
+            (r'[0-9A-F]+[HL]\b', Number.Hex),              # hexadecimal number
+            (r'[0-9]+\.[0-9]+E[+-][0-9]+', Number.Float),  # real number
+            (r'[0-9]+\.[0-9]+', Number.Float),             # real number
+            (r'[0-9]+', Number.Integer),                   # decimal whole number
+        ],
+        'strings': [
+            (r"'[^\n']*'", String),  # single quoted string
+            (r'"[^\n"]*"', String),  # double quoted string
+        ],
+        'operators': [
+            # Arithmetic Operators
+            (r'[+-]', Operator),
+            (r'[*/]', Operator),
+            # Relational Operators
+            (r'[=#<>]', Operator),
+            # Dereferencing Operator
+            (r'\^', Operator),
+            # Logical AND Operator
+            (r'&', Operator),
+            # Logical NOT Operator
+            (r'~', Operator),
+            # Assignment Symbol
+            (r':=', Operator),
+            # Range Constructor
+            (r'\.\.', Operator),
+            (r'\$', Operator),
+        ],
+        'identifiers': [
+            (r'([a-zA-Z_$][\w$]*)', Name),
+        ],
+        'builtins': [
+            (words((
+                'ANYPTR', 'ANYREC', 'BOOLEAN', 'BYTE', 'CHAR', 'INTEGER', 'LONGINT',
+                'REAL', 'SET', 'SHORTCHAR', 'SHORTINT', 'SHORTREAL'
+                ), suffix=r'\b'), Keyword.Type),
+            (words((
+                'ABS', 'ABSTRACT', 'ARRAY', 'ASH', 'ASSERT', 'BEGIN', 'BITS', 'BY',
+                'CAP', 'CASE', 'CHR', 'CLOSE', 'CONST', 'DEC', 'DIV', 'DO', 'ELSE',
+                'ELSIF', 'EMPTY', 'END', 'ENTIER', 'EXCL', 'EXIT', 'EXTENSIBLE', 'FOR',
+                'HALT', 'IF', 'IMPORT', 'IN', 'INC', 'INCL', 'IS', 'LEN', 'LIMITED',
+                'LONG', 'LOOP', 'MAX', 'MIN', 'MOD', 'MODULE', 'NEW', 'ODD', 'OF',
+                'OR', 'ORD', 'OUT', 'POINTER', 'PROCEDURE', 'RECORD', 'REPEAT', 'RETURN',
+                'SHORT', 'SHORTCHAR', 'SHORTINT', 'SIZE', 'THEN', 'TYPE', 'TO', 'UNTIL',
+                'VAR', 'WHILE', 'WITH'
+                ), suffix=r'\b'), Keyword.Reserved),
+            (r'(TRUE|FALSE|NIL|INF)\b', Keyword.Constant),
+        ]
+    }
+
+    def analyse_text(text):
+        """The only other lexer using .cp is the C++ one, so we check if for
+        a few common Pascal keywords here. Those are unfortunately quite
+        common across various business languages as well."""
+        result = 0
+        if 'BEGIN' in text:
+            result += 0.01
+        if 'END' in text:
+            result += 0.01
+        if 'PROCEDURE' in text:
+            result += 0.01
+        if 'MODULE' in text:
+            result += 0.01
+
+        return result
diff --git a/lib/python3.11/site-packages/pygments/lexers/objective.py b/lib/python3.11/site-packages/pygments/lexers/objective.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce281fbd198802ba63742086f850b339d82e3b0d
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/objective.py
@@ -0,0 +1,513 @@
+"""
+    pygments.lexers.objective
+    ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Objective-C family languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, bygroups, using, this, words, \
+    inherit, default
+from pygments.token import Text, Keyword, Name, String, Operator, \
+    Number, Punctuation, Literal, Comment, Whitespace
+
+from pygments.lexers.c_cpp import CLexer, CppLexer
+
+__all__ = ['ObjectiveCLexer', 'ObjectiveCppLexer', 'LogosLexer', 'SwiftLexer']
+
+
+def objective(baselexer):
+    """
+    Generate a subclass of baselexer that accepts the Objective-C syntax
+    extensions.
+    """
+
+    # Have to be careful not to accidentally match JavaDoc/Doxygen syntax here,
+    # since that's quite common in ordinary C/C++ files.  It's OK to match
+    # JavaDoc/Doxygen keywords that only apply to Objective-C, mind.
+    #
+    # The upshot of this is that we CANNOT match @class or @interface
+    _oc_keywords = re.compile(r'@(?:end|implementation|protocol)')
+
+    # Matches [ ? identifier  ( identifier ? ] |  identifier? : )
+    # (note the identifier is *optional* when there is a ':'!)
+    _oc_message = re.compile(r'\[\s*[a-zA-Z_]\w*\s+'
+                             r'(?:[a-zA-Z_]\w*\s*\]|'
+                             r'(?:[a-zA-Z_]\w*)?:)')
+
+    class GeneratedObjectiveCVariant(baselexer):
+        """
+        Implements Objective-C syntax on top of an existing C family lexer.
+        """
+
+        tokens = {
+            'statements': [
+                (r'@"', String, 'string'),
+                (r'@(YES|NO)', Number),
+                (r"@'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char),
+                (r'@(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[lL]?', Number.Float),
+                (r'@(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
+                (r'@0x[0-9a-fA-F]+[Ll]?', Number.Hex),
+                (r'@0[0-7]+[Ll]?', Number.Oct),
+                (r'@\d+[Ll]?', Number.Integer),
+                (r'@\(', Literal, 'literal_number'),
+                (r'@\[', Literal, 'literal_array'),
+                (r'@\{', Literal, 'literal_dictionary'),
+                (words((
+                    '@selector', '@private', '@protected', '@public', '@encode',
+                    '@synchronized', '@try', '@throw', '@catch', '@finally',
+                    '@end', '@property', '@synthesize', '__bridge', '__bridge_transfer',
+                    '__autoreleasing', '__block', '__weak', '__strong', 'weak', 'strong',
+                    'copy', 'retain', 'assign', 'unsafe_unretained', 'atomic', 'nonatomic',
+                    'readonly', 'readwrite', 'setter', 'getter', 'typeof', 'in',
+                    'out', 'inout', 'release', 'class', '@dynamic', '@optional',
+                    '@required', '@autoreleasepool', '@import'), suffix=r'\b'),
+                 Keyword),
+                (words(('id', 'instancetype', 'Class', 'IMP', 'SEL', 'BOOL',
+                        'IBOutlet', 'IBAction', 'unichar'), suffix=r'\b'),
+                 Keyword.Type),
+                (r'@(true|false|YES|NO)\n', Name.Builtin),
+                (r'(YES|NO|nil|self|super)\b', Name.Builtin),
+                # Carbon types
+                (r'(Boolean|UInt8|SInt8|UInt16|SInt16|UInt32|SInt32)\b', Keyword.Type),
+                # Carbon built-ins
+                (r'(TRUE|FALSE)\b', Name.Builtin),
+                (r'(@interface|@implementation)(\s+)', bygroups(Keyword, Text),
+                 ('#pop', 'oc_classname')),
+                (r'(@class|@protocol)(\s+)', bygroups(Keyword, Text),
+                 ('#pop', 'oc_forward_classname')),
+                # @ can also prefix other expressions like @{...} or @(...)
+                (r'@', Punctuation),
+                inherit,
+            ],
+            'oc_classname': [
+                # interface definition that inherits
+                (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?(\s*)(\{)',
+                 bygroups(Name.Class, Text, Name.Class, Text, Punctuation),
+                 ('#pop', 'oc_ivars')),
+                (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?',
+                 bygroups(Name.Class, Text, Name.Class), '#pop'),
+                # interface definition for a category
+                (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))(\s*)(\{)',
+                 bygroups(Name.Class, Text, Name.Label, Text, Punctuation),
+                 ('#pop', 'oc_ivars')),
+                (r'([a-zA-Z$_][\w$]*)(\s*)(\([a-zA-Z$_][\w$]*\))',
+                 bygroups(Name.Class, Text, Name.Label), '#pop'),
+                # simple interface / implementation
+                (r'([a-zA-Z$_][\w$]*)(\s*)(\{)',
+                 bygroups(Name.Class, Text, Punctuation), ('#pop', 'oc_ivars')),
+                (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop')
+            ],
+            'oc_forward_classname': [
+                (r'([a-zA-Z$_][\w$]*)(\s*,\s*)',
+                 bygroups(Name.Class, Text), 'oc_forward_classname'),
+                (r'([a-zA-Z$_][\w$]*)(\s*;?)',
+                 bygroups(Name.Class, Text), '#pop')
+            ],
+            'oc_ivars': [
+                include('whitespace'),
+                include('statements'),
+                (';', Punctuation),
+                (r'\{', Punctuation, '#push'),
+                (r'\}', Punctuation, '#pop'),
+            ],
+            'root': [
+                # methods
+                (r'^([-+])(\s*)'                         # method marker
+                 r'(\(.*?\))?(\s*)'                      # return type
+                 r'([a-zA-Z$_][\w$]*:?)',        # begin of method name
+                 bygroups(Punctuation, Text, using(this),
+                          Text, Name.Function),
+                 'method'),
+                inherit,
+            ],
+            'method': [
+                include('whitespace'),
+                # TODO unsure if ellipses are allowed elsewhere, see
+                # discussion in Issue 789
+                (r',', Punctuation),
+                (r'\.\.\.', Punctuation),
+                (r'(\(.*?\))(\s*)([a-zA-Z$_][\w$]*)',
+                 bygroups(using(this), Text, Name.Variable)),
+                (r'[a-zA-Z$_][\w$]*:', Name.Function),
+                (';', Punctuation, '#pop'),
+                (r'\{', Punctuation, 'function'),
+                default('#pop'),
+            ],
+            'literal_number': [
+                (r'\(', Punctuation, 'literal_number_inner'),
+                (r'\)', Literal, '#pop'),
+                include('statement'),
+            ],
+            'literal_number_inner': [
+                (r'\(', Punctuation, '#push'),
+                (r'\)', Punctuation, '#pop'),
+                include('statement'),
+            ],
+            'literal_array': [
+                (r'\[', Punctuation, 'literal_array_inner'),
+                (r'\]', Literal, '#pop'),
+                include('statement'),
+            ],
+            'literal_array_inner': [
+                (r'\[', Punctuation, '#push'),
+                (r'\]', Punctuation, '#pop'),
+                include('statement'),
+            ],
+            'literal_dictionary': [
+                (r'\}', Literal, '#pop'),
+                include('statement'),
+            ],
+        }
+
+        def analyse_text(text):
+            if _oc_keywords.search(text):
+                return 1.0
+            elif '@"' in text:  # strings
+                return 0.8
+            elif re.search('@[0-9]+', text):
+                return 0.7
+            elif _oc_message.search(text):
+                return 0.8
+            return 0
+
+        def get_tokens_unprocessed(self, text, stack=('root',)):
+            from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \
+                COCOA_PROTOCOLS, COCOA_PRIMITIVES
+
+            for index, token, value in \
+                    baselexer.get_tokens_unprocessed(self, text, stack):
+                if token is Name or token is Name.Class:
+                    if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \
+                       or value in COCOA_PRIMITIVES:
+                        token = Name.Builtin.Pseudo
+
+                yield index, token, value
+
+    return GeneratedObjectiveCVariant
+
+
+class ObjectiveCLexer(objective(CLexer)):
+    """
+    For Objective-C source code with preprocessor directives.
+    """
+
+    name = 'Objective-C'
+    url = 'https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html'
+    aliases = ['objective-c', 'objectivec', 'obj-c', 'objc']
+    filenames = ['*.m', '*.h']
+    mimetypes = ['text/x-objective-c']
+    version_added = ''
+    priority = 0.05    # Lower than C
+
+
+class ObjectiveCppLexer(objective(CppLexer)):
+    """
+    For Objective-C++ source code with preprocessor directives.
+    """
+
+    name = 'Objective-C++'
+    aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++']
+    filenames = ['*.mm', '*.hh']
+    mimetypes = ['text/x-objective-c++']
+    version_added = ''
+    priority = 0.05    # Lower than C++
+
+
+class LogosLexer(ObjectiveCppLexer):
+    """
+    For Logos + Objective-C source code with preprocessor directives.
+    """
+
+    name = 'Logos'
+    aliases = ['logos']
+    filenames = ['*.x', '*.xi', '*.xm', '*.xmi']
+    mimetypes = ['text/x-logos']
+    version_added = '1.6'
+    priority = 0.25
+
+    tokens = {
+        'statements': [
+            (r'(%orig|%log)\b', Keyword),
+            (r'(%c)\b(\()(\s*)([a-zA-Z$_][\w$]*)(\s*)(\))',
+             bygroups(Keyword, Punctuation, Text, Name.Class, Text, Punctuation)),
+            (r'(%init)\b(\()',
+             bygroups(Keyword, Punctuation), 'logos_init_directive'),
+            (r'(%init)(?=\s*;)', bygroups(Keyword)),
+            (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)',
+             bygroups(Keyword, Text, Name.Class), '#pop'),
+            (r'(%subclass)(\s+)', bygroups(Keyword, Text),
+             ('#pop', 'logos_classname')),
+            inherit,
+        ],
+        'logos_init_directive': [
+            (r'\s+', Text),
+            (',', Punctuation, ('logos_init_directive', '#pop')),
+            (r'([a-zA-Z$_][\w$]*)(\s*)(=)(\s*)([^);]*)',
+             bygroups(Name.Class, Text, Punctuation, Text, Text)),
+            (r'([a-zA-Z$_][\w$]*)', Name.Class),
+            (r'\)', Punctuation, '#pop'),
+        ],
+        'logos_classname': [
+            (r'([a-zA-Z$_][\w$]*)(\s*:\s*)([a-zA-Z$_][\w$]*)?',
+             bygroups(Name.Class, Text, Name.Class), '#pop'),
+            (r'([a-zA-Z$_][\w$]*)', Name.Class, '#pop')
+        ],
+        'root': [
+            (r'(%subclass)(\s+)', bygroups(Keyword, Text),
+             'logos_classname'),
+            (r'(%hook|%group)(\s+)([a-zA-Z$_][\w$]+)',
+             bygroups(Keyword, Text, Name.Class)),
+            (r'(%config)(\s*\(\s*)(\w+)(\s*=)(.*?)(\)\s*)',
+             bygroups(Keyword, Text, Name.Variable, Text, String, Text)),
+            (r'(%ctor)(\s*)(\{)', bygroups(Keyword, Text, Punctuation),
+             'function'),
+            (r'(%new)(\s*)(\()(.*?)(\))',
+             bygroups(Keyword, Text, Keyword, String, Keyword)),
+            (r'(\s*)(%end)(\s*)', bygroups(Text, Keyword, Text)),
+            inherit,
+        ],
+    }
+
+    _logos_keywords = re.compile(r'%(?:hook|ctor|init|c\()')
+
+    def analyse_text(text):
+        if LogosLexer._logos_keywords.search(text):
+            return 1.0
+        return 0
+
+
+class SwiftLexer(RegexLexer):
+    """
+    For Swift source.
+    """
+    name = 'Swift'
+    url = 'https://www.swift.org/'
+    filenames = ['*.swift']
+    aliases = ['swift']
+    mimetypes = ['text/x-swift']
+    version_added = '2.0'
+
+    tokens = {
+        'root': [
+            # Whitespace and Comments
+            (r'\n', Text),
+            (r'\s+', Whitespace),
+            (r'//', Comment.Single, 'comment-single'),
+            (r'/\*', Comment.Multiline, 'comment-multi'),
+            (r'#(if|elseif|else|endif|available)\b', Comment.Preproc, 'preproc'),
+
+            # Keywords
+            include('keywords'),
+
+            # Global Types
+            (words((
+                'Array', 'AutoreleasingUnsafeMutablePointer', 'BidirectionalReverseView',
+                'Bit', 'Bool', 'CFunctionPointer', 'COpaquePointer', 'CVaListPointer',
+                'Character', 'ClosedInterval', 'CollectionOfOne', 'ContiguousArray',
+                'Dictionary', 'DictionaryGenerator', 'DictionaryIndex', 'Double',
+                'EmptyCollection', 'EmptyGenerator', 'EnumerateGenerator',
+                'EnumerateSequence', 'FilterCollectionView',
+                'FilterCollectionViewIndex', 'FilterGenerator', 'FilterSequenceView',
+                'Float', 'Float80', 'FloatingPointClassification', 'GeneratorOf',
+                'GeneratorOfOne', 'GeneratorSequence', 'HalfOpenInterval', 'HeapBuffer',
+                'HeapBufferStorage', 'ImplicitlyUnwrappedOptional', 'IndexingGenerator',
+                'Int', 'Int16', 'Int32', 'Int64', 'Int8', 'LazyBidirectionalCollection',
+                'LazyForwardCollection', 'LazyRandomAccessCollection',
+                'LazySequence', 'MapCollectionView', 'MapSequenceGenerator',
+                'MapSequenceView', 'MirrorDisposition', 'ObjectIdentifier', 'OnHeap',
+                'Optional', 'PermutationGenerator', 'QuickLookObject',
+                'RandomAccessReverseView', 'Range', 'RangeGenerator', 'RawByte', 'Repeat',
+                'ReverseBidirectionalIndex', 'ReverseRandomAccessIndex', 'SequenceOf',
+                'SinkOf', 'Slice', 'StaticString', 'StrideThrough', 'StrideThroughGenerator',
+                'StrideTo', 'StrideToGenerator', 'String', 'UInt', 'UInt16', 'UInt32',
+                'UInt64', 'UInt8', 'UTF16', 'UTF32', 'UTF8', 'UnicodeDecodingResult',
+                'UnicodeScalar', 'Unmanaged', 'UnsafeBufferPointer',
+                'UnsafeBufferPointerGenerator', 'UnsafeMutableBufferPointer',
+                'UnsafeMutablePointer', 'UnsafePointer', 'Zip2', 'ZipGenerator2',
+                # Protocols
+                'AbsoluteValuable', 'AnyObject', 'ArrayLiteralConvertible',
+                'BidirectionalIndexType', 'BitwiseOperationsType',
+                'BooleanLiteralConvertible', 'BooleanType', 'CVarArgType',
+                'CollectionType', 'Comparable', 'DebugPrintable',
+                'DictionaryLiteralConvertible', 'Equatable',
+                'ExtendedGraphemeClusterLiteralConvertible',
+                'ExtensibleCollectionType', 'FloatLiteralConvertible',
+                'FloatingPointType', 'ForwardIndexType', 'GeneratorType', 'Hashable',
+                'IntegerArithmeticType', 'IntegerLiteralConvertible', 'IntegerType',
+                'IntervalType', 'MirrorType', 'MutableCollectionType', 'MutableSliceable',
+                'NilLiteralConvertible', 'OutputStreamType', 'Printable',
+                'RandomAccessIndexType', 'RangeReplaceableCollectionType',
+                'RawOptionSetType', 'RawRepresentable', 'Reflectable', 'SequenceType',
+                'SignedIntegerType', 'SignedNumberType', 'SinkType', 'Sliceable',
+                'Streamable', 'Strideable', 'StringInterpolationConvertible',
+                'StringLiteralConvertible', 'UnicodeCodecType',
+                'UnicodeScalarLiteralConvertible', 'UnsignedIntegerType',
+                '_ArrayBufferType', '_BidirectionalIndexType', '_CocoaStringType',
+                '_CollectionType', '_Comparable', '_ExtensibleCollectionType',
+                '_ForwardIndexType', '_Incrementable', '_IntegerArithmeticType',
+                '_IntegerType', '_ObjectiveCBridgeable', '_RandomAccessIndexType',
+                '_RawOptionSetType', '_SequenceType', '_Sequence_Type',
+                '_SignedIntegerType', '_SignedNumberType', '_Sliceable', '_Strideable',
+                '_SwiftNSArrayRequiredOverridesType', '_SwiftNSArrayType',
+                '_SwiftNSCopyingType', '_SwiftNSDictionaryRequiredOverridesType',
+                '_SwiftNSDictionaryType', '_SwiftNSEnumeratorType',
+                '_SwiftNSFastEnumerationType', '_SwiftNSStringRequiredOverridesType',
+                '_SwiftNSStringType', '_UnsignedIntegerType',
+                # Variables
+                'C_ARGC', 'C_ARGV', 'Process',
+                # Typealiases
+                'Any', 'AnyClass', 'BooleanLiteralType', 'CBool', 'CChar', 'CChar16',
+                'CChar32', 'CDouble', 'CFloat', 'CInt', 'CLong', 'CLongLong', 'CShort',
+                'CSignedChar', 'CUnsignedInt', 'CUnsignedLong', 'CUnsignedShort',
+                'CWideChar', 'ExtendedGraphemeClusterType', 'Float32', 'Float64',
+                'FloatLiteralType', 'IntMax', 'IntegerLiteralType', 'StringLiteralType',
+                'UIntMax', 'UWord', 'UnicodeScalarType', 'Void', 'Word',
+                # Foundation/Cocoa
+                'NSErrorPointer', 'NSObjectProtocol', 'Selector'), suffix=r'\b'),
+             Name.Builtin),
+            # Functions
+            (words((
+                'abs', 'advance', 'alignof', 'alignofValue', 'assert', 'assertionFailure',
+                'contains', 'count', 'countElements', 'debugPrint', 'debugPrintln',
+                'distance', 'dropFirst', 'dropLast', 'dump', 'enumerate', 'equal',
+                'extend', 'fatalError', 'filter', 'find', 'first', 'getVaList', 'indices',
+                'insert', 'isEmpty', 'join', 'last', 'lazy', 'lexicographicalCompare',
+                'map', 'max', 'maxElement', 'min', 'minElement', 'numericCast', 'overlaps',
+                'partition', 'precondition', 'preconditionFailure', 'prefix', 'print',
+                'println', 'reduce', 'reflect', 'removeAll', 'removeAtIndex', 'removeLast',
+                'removeRange', 'reverse', 'sizeof', 'sizeofValue', 'sort', 'sorted',
+                'splice', 'split', 'startsWith', 'stride', 'strideof', 'strideofValue',
+                'suffix', 'swap', 'toDebugString', 'toString', 'transcode',
+                'underestimateCount', 'unsafeAddressOf', 'unsafeBitCast', 'unsafeDowncast',
+                'withExtendedLifetime', 'withUnsafeMutablePointer',
+                'withUnsafeMutablePointers', 'withUnsafePointer', 'withUnsafePointers',
+                'withVaList'), suffix=r'\b'),
+             Name.Builtin.Pseudo),
+
+            # Implicit Block Variables
+            (r'\$\d+', Name.Variable),
+
+            # Binary Literal
+            (r'0b[01_]+', Number.Bin),
+            # Octal Literal
+            (r'0o[0-7_]+', Number.Oct),
+            # Hexadecimal Literal
+            (r'0x[0-9a-fA-F_]+', Number.Hex),
+            # Decimal Literal
+            (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
+             r'\.[0-9_]*|[eE][+\-]?[0-9_]+)', Number.Float),
+            (r'[0-9][0-9_]*', Number.Integer),
+            # String Literal
+            (r'"""', String, 'string-multi'),
+            (r'"', String, 'string'),
+
+            # Operators and Punctuation
+            (r'[(){}\[\].,:;=@#`?]|->|[<&?](?=\w)|(?<=\w)[>!?]', Punctuation),
+            (r'[/=\-+!*%<>&|^?~]+', Operator),
+
+            # Identifier
+            (r'[a-zA-Z_]\w*', Name)
+        ],
+        'keywords': [
+            (words((
+                'as', 'async', 'await', 'break', 'case', 'catch', 'continue', 'default', 'defer',
+                'do', 'else', 'fallthrough', 'for', 'guard', 'if', 'in', 'is',
+                'repeat', 'return', '#selector', 'switch', 'throw', 'try',
+                'where', 'while'), suffix=r'\b'),
+             Keyword),
+            (r'@availability\([^)]+\)', Keyword.Reserved),
+            (words((
+                'associativity', 'convenience', 'dynamic', 'didSet', 'final',
+                'get', 'indirect', 'infix', 'inout', 'lazy', 'left', 'mutating',
+                'none', 'nonmutating', 'optional', 'override', 'postfix',
+                'precedence', 'prefix', 'Protocol', 'required', 'rethrows',
+                'right', 'set', 'throws', 'Type', 'unowned', 'weak', 'willSet',
+                '@availability', '@autoclosure', '@noreturn',
+                '@NSApplicationMain', '@NSCopying', '@NSManaged', '@objc',
+                '@UIApplicationMain', '@IBAction', '@IBDesignable',
+                '@IBInspectable', '@IBOutlet'), suffix=r'\b'),
+             Keyword.Reserved),
+            (r'(as|dynamicType|false|is|nil|self|Self|super|true|__COLUMN__'
+             r'|__FILE__|__FUNCTION__|__LINE__|_'
+             r'|#(?:file|line|column|function))\b', Keyword.Constant),
+            (r'import\b', Keyword.Declaration, 'module'),
+            (r'(class|enum|extension|struct|protocol)(\s+)([a-zA-Z_]\w*)',
+             bygroups(Keyword.Declaration, Whitespace, Name.Class)),
+            (r'(func)(\s+)([a-zA-Z_]\w*)',
+             bygroups(Keyword.Declaration, Whitespace, Name.Function)),
+            (r'(var|let)(\s+)([a-zA-Z_]\w*)', bygroups(Keyword.Declaration,
+             Whitespace, Name.Variable)),
+            (words((
+                'actor', 'associatedtype', 'class', 'deinit', 'enum', 'extension', 'func', 'import',
+                'init', 'internal', 'let', 'operator', 'private', 'protocol', 'public',
+                'static', 'struct', 'subscript', 'typealias', 'var'), suffix=r'\b'),
+             Keyword.Declaration)
+        ],
+        'comment': [
+            (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):',
+             Comment.Special)
+        ],
+
+        # Nested
+        'comment-single': [
+            (r'\n', Whitespace, '#pop'),
+            include('comment'),
+            (r'[^\n]+', Comment.Single)
+        ],
+        'comment-multi': [
+            include('comment'),
+            (r'[^*/]+', Comment.Multiline),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'[*/]+', Comment.Multiline)
+        ],
+        'module': [
+            (r'\n', Whitespace, '#pop'),
+            (r'[a-zA-Z_]\w*', Name.Class),
+            include('root')
+        ],
+        'preproc': [
+            (r'\n', Whitespace, '#pop'),
+            include('keywords'),
+            (r'[A-Za-z]\w*', Comment.Preproc),
+            include('root')
+        ],
+        'string': [
+            (r'"', String, '#pop'),
+            include("string-common"),
+        ],
+        'string-multi': [
+            (r'"""', String, '#pop'),
+            include("string-common"),
+        ],
+        'string-common': [
+            (r'\\\(', String.Interpol, 'string-intp'),
+            (r"""\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}"""
+             r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}""", String.Escape),
+            (r'[^\\"]+', String),
+            (r'\\', String)
+        ],
+        'string-intp': [
+            (r'\(', String.Interpol, '#push'),
+            (r'\)', String.Interpol, '#pop'),
+            include('root')
+        ]
+    }
+
+    def get_tokens_unprocessed(self, text):
+        from pygments.lexers._cocoa_builtins import COCOA_INTERFACES, \
+            COCOA_PROTOCOLS, COCOA_PRIMITIVES
+
+        for index, token, value in \
+                RegexLexer.get_tokens_unprocessed(self, text):
+            if token is Name or token is Name.Class:
+                if value in COCOA_INTERFACES or value in COCOA_PROTOCOLS \
+                   or value in COCOA_PRIMITIVES:
+                    token = Name.Builtin.Pseudo
+
+            yield index, token, value
diff --git a/lib/python3.11/site-packages/pygments/lexers/ooc.py b/lib/python3.11/site-packages/pygments/lexers/ooc.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6aea8c830689523903c913699927004208652bb
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/ooc.py
@@ -0,0 +1,84 @@
+"""
+    pygments.lexers.ooc
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Ooc language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['OocLexer']
+
+
+class OocLexer(RegexLexer):
+    """
+    For Ooc source code
+    """
+    name = 'Ooc'
+    url = 'https://ooc-lang.github.io/'
+    aliases = ['ooc']
+    filenames = ['*.ooc']
+    mimetypes = ['text/x-ooc']
+    version_added = '1.2'
+
+    tokens = {
+        'root': [
+            (words((
+                'class', 'interface', 'implement', 'abstract', 'extends', 'from',
+                'this', 'super', 'new', 'const', 'final', 'static', 'import',
+                'use', 'extern', 'inline', 'proto', 'break', 'continue',
+                'fallthrough', 'operator', 'if', 'else', 'for', 'while', 'do',
+                'switch', 'case', 'as', 'in', 'version', 'return', 'true',
+                'false', 'null'), prefix=r'\b', suffix=r'\b'),
+             Keyword),
+            (r'include\b', Keyword, 'include'),
+            (r'(cover)([ \t]+)(from)([ \t]+)(\w+[*@]?)',
+             bygroups(Keyword, Text, Keyword, Text, Name.Class)),
+            (r'(func)((?:[ \t]|\\\n)+)(~[a-z_]\w*)',
+             bygroups(Keyword, Text, Name.Function)),
+            (r'\bfunc\b', Keyword),
+            # Note: %= not listed on https://ooc-lang.github.io/docs/lang/operators/
+            (r'//.*', Comment),
+            (r'(?s)/\*.*?\*/', Comment.Multiline),
+            (r'(==?|\+=?|-[=>]?|\*=?|/=?|:=|!=?|%=?|\?|>{1,3}=?|<{1,3}=?|\.\.|'
+             r'&&?|\|\|?|\^=?)', Operator),
+            (r'(\.)([ \t]*)([a-z]\w*)', bygroups(Operator, Text,
+                                                 Name.Function)),
+            (r'[A-Z][A-Z0-9_]+', Name.Constant),
+            (r'[A-Z]\w*([@*]|\[[ \t]*\])?', Name.Class),
+
+            (r'([a-z]\w*(?:~[a-z]\w*)?)((?:[ \t]|\\\n)*)(?=\()',
+             bygroups(Name.Function, Text)),
+            (r'[a-z]\w*', Name.Variable),
+
+            # : introduces types
+            (r'[:(){}\[\];,]', Punctuation),
+
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'0c[0-9]+', Number.Oct),
+            (r'0b[01]+', Number.Bin),
+            (r'[0-9_]\.[0-9_]*(?!\.)', Number.Float),
+            (r'[0-9_]+', Number.Decimal),
+
+            (r'"(?:\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\"])*"',
+             String.Double),
+            (r"'(?:\\.|\\[0-9]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'",
+             String.Char),
+            (r'@', Punctuation),  # pointer dereference
+            (r'\.', Punctuation),  # imports or chain operator
+
+            (r'\\[ \t\n]', Text),
+            (r'[ \t]+', Text),
+        ],
+        'include': [
+            (r'[\w/]+', Name),
+            (r',', Punctuation),
+            (r'[ \t]', Text),
+            (r'[;\n]', Text, '#pop'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/openscad.py b/lib/python3.11/site-packages/pygments/lexers/openscad.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ec8fea051ca0d0c1e13a281158bfe85c63ec365
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/openscad.py
@@ -0,0 +1,96 @@
+"""
+    pygments.lexers.openscad
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the OpenSCAD languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, words, include
+from pygments.token import Text, Comment, Punctuation, Operator, Keyword, Name, Number, Whitespace, Literal, String
+
+__all__ = ['OpenScadLexer']
+
+
+class OpenScadLexer(RegexLexer):
+    """For openSCAD code.
+    """
+    name = "OpenSCAD"
+    url = "https://openscad.org/"
+    aliases = ["openscad"]
+    filenames = ["*.scad"]
+    mimetypes = ["application/x-openscad"]
+    version_added = '2.16'
+
+    tokens = {
+        "root": [
+            (r"[^\S\n]+", Whitespace),
+            (r'//', Comment.Single, 'comment-single'),
+            (r'/\*', Comment.Multiline, 'comment-multi'),
+            (r"[{}\[\]\(\),;:]", Punctuation),
+            (r"[*!#%\-+=?/]", Operator),
+            (r"<=|<|==|!=|>=|>|&&|\|\|", Operator),
+            (r"\$(f[asn]|t|vp[rtd]|children)", Operator),
+            (r"(undef|PI)\b", Keyword.Constant),
+            (
+                r"(use|include)((?:\s|\\\\s)+)",
+                bygroups(Keyword.Namespace, Text),
+                "includes",
+            ),
+            (r"(module)(\s*)([^\s\(]+)",
+             bygroups(Keyword.Namespace, Whitespace, Name.Namespace)),
+            (r"(function)(\s*)([^\s\(]+)",
+             bygroups(Keyword.Declaration, Whitespace, Name.Function)),
+            (words(("true", "false"), prefix=r"\b", suffix=r"\b"), Literal),
+            (words((
+                "function", "module", "include", "use", "for",
+                "intersection_for", "if", "else", "return"
+                ), prefix=r"\b", suffix=r"\b"), Keyword
+            ),
+            (words((
+                "circle", "square", "polygon", "text", "sphere", "cube",
+                "cylinder", "polyhedron", "translate", "rotate", "scale",
+                "resize", "mirror", "multmatrix", "color", "offset", "hull",
+                "minkowski", "union", "difference", "intersection", "abs",
+                "sign", "sin", "cos", "tan", "acos", "asin", "atan", "atan2",
+                "floor", "round", "ceil", "ln", "log", "pow", "sqrt", "exp",
+                "rands", "min", "max", "concat", "lookup", "str", "chr",
+                "search", "version", "version_num", "norm", "cross",
+                "parent_module", "echo", "import", "import_dxf",
+                "dxf_linear_extrude", "linear_extrude", "rotate_extrude",
+                "surface", "projection", "render", "dxf_cross",
+                "dxf_dim", "let", "assign", "len"
+                ), prefix=r"\b", suffix=r"\b"),
+                Name.Builtin
+            ),
+            (r"\bchildren\b", Name.Builtin.Pseudo),
+            (r'""".*?"""', String.Double),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (r"-?\d+(\.\d+)?(e[+-]?\d+)?", Number),
+            (r"\w+", Name),
+        ],
+        "includes": [
+            (
+                r"(<)([^>]*)(>)",
+                bygroups(Punctuation, Comment.PreprocFile, Punctuation),
+            ),
+        ],
+        'comment': [
+            (r':param: [a-zA-Z_]\w*|:returns?:|(FIXME|MARK|TODO):',
+             Comment.Special)
+        ],
+        'comment-single': [
+            (r'\n', Text, '#pop'),
+            include('comment'),
+            (r'[^\n]+', Comment.Single)
+        ],
+        'comment-multi': [
+            include('comment'),
+            (r'[^*/]+', Comment.Multiline),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'[*/]', Comment.Multiline)
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/other.py b/lib/python3.11/site-packages/pygments/lexers/other.py
new file mode 100644
index 0000000000000000000000000000000000000000..8767d73037b75095486aa46ad3b89a002156fc8b
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/other.py
@@ -0,0 +1,41 @@
+"""
+    pygments.lexers.other
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Just export lexer classes previously contained in this module.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+# ruff: noqa: F401
+from pygments.lexers.sql import SqlLexer, MySqlLexer, SqliteConsoleLexer
+from pygments.lexers.shell import BashLexer, BashSessionLexer, BatchLexer, \
+    TcshLexer
+from pygments.lexers.robotframework import RobotFrameworkLexer
+from pygments.lexers.testing import GherkinLexer
+from pygments.lexers.esoteric import BrainfuckLexer, BefungeLexer, RedcodeLexer
+from pygments.lexers.prolog import LogtalkLexer
+from pygments.lexers.snobol import SnobolLexer
+from pygments.lexers.rebol import RebolLexer
+from pygments.lexers.configs import KconfigLexer, Cfengine3Lexer
+from pygments.lexers.modeling import ModelicaLexer
+from pygments.lexers.scripting import AppleScriptLexer, MOOCodeLexer, \
+    HybrisLexer
+from pygments.lexers.graphics import PostScriptLexer, GnuplotLexer, \
+    AsymptoteLexer, PovrayLexer
+from pygments.lexers.business import ABAPLexer, OpenEdgeLexer, \
+    GoodDataCLLexer, MaqlLexer
+from pygments.lexers.automation import AutoItLexer, AutohotkeyLexer
+from pygments.lexers.dsls import ProtoBufLexer, BroLexer, PuppetLexer, \
+    MscgenLexer, VGLLexer
+from pygments.lexers.basic import CbmBasicV2Lexer
+from pygments.lexers.pawn import SourcePawnLexer, PawnLexer
+from pygments.lexers.ecl import ECLLexer
+from pygments.lexers.urbi import UrbiscriptLexer
+from pygments.lexers.smalltalk import SmalltalkLexer, NewspeakLexer
+from pygments.lexers.installers import NSISLexer, RPMSpecLexer
+from pygments.lexers.textedit import AwkLexer
+from pygments.lexers.smv import NuSMVLexer
+
+__all__ = []
diff --git a/lib/python3.11/site-packages/pygments/lexers/parasail.py b/lib/python3.11/site-packages/pygments/lexers/parasail.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b409609f8b1ea3211f0364273dd8280b65e0d0c
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/parasail.py
@@ -0,0 +1,78 @@
+"""
+    pygments.lexers.parasail
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for ParaSail.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Literal
+
+__all__ = ['ParaSailLexer']
+
+
+class ParaSailLexer(RegexLexer):
+    """
+    For ParaSail source code.
+    """
+
+    name = 'ParaSail'
+    url = 'http://www.parasail-lang.org'
+    aliases = ['parasail']
+    filenames = ['*.psi', '*.psl']
+    mimetypes = ['text/x-parasail']
+    version_added = '2.1'
+
+    flags = re.MULTILINE
+
+    tokens = {
+        'root': [
+            (r'[^\S\n]+', Text),
+            (r'//.*?\n', Comment.Single),
+            (r'\b(and|or|xor)=', Operator.Word),
+            (r'\b(and(\s+then)?|or(\s+else)?|xor|rem|mod|'
+             r'(is|not)\s+null)\b',
+             Operator.Word),
+            # Keywords
+            (r'\b(abs|abstract|all|block|class|concurrent|const|continue|'
+             r'each|end|exit|extends|exports|forward|func|global|implements|'
+             r'import|in|interface|is|lambda|locked|new|not|null|of|op|'
+             r'optional|private|queued|ref|return|reverse|separate|some|'
+             r'type|until|var|with|'
+             # Control flow
+             r'if|then|else|elsif|case|for|while|loop)\b',
+             Keyword.Reserved),
+            (r'(abstract\s+)?(interface|class|op|func|type)',
+             Keyword.Declaration),
+            # Literals
+            (r'"[^"]*"', String),
+            (r'\\[\'ntrf"0]', String.Escape),
+            (r'#[a-zA-Z]\w*', Literal),       # Enumeration
+            include('numbers'),
+            (r"'[^']'", String.Char),
+            (r'[a-zA-Z]\w*', Name),
+            # Operators and Punctuation
+            (r'(<==|==>|<=>|\*\*=|<\|=|<<=|>>=|==|!=|=\?|<=|>=|'
+             r'\*\*|<<|>>|=>|:=|\+=|-=|\*=|\|=|\||/=|\+|-|\*|/|'
+             r'\.\.|<\.\.|\.\.<|<\.\.<)',
+             Operator),
+            (r'(<|>|\[|\]|\(|\)|\||:|;|,|.|\{|\}|->)',
+             Punctuation),
+            (r'\n+', Text),
+        ],
+        'numbers': [
+            (r'\d[0-9_]*#[0-9a-fA-F][0-9a-fA-F_]*#', Number.Hex),  # any base
+            (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex),        # C-like hex
+            (r'0[bB][01][01_]*', Number.Bin),                      # C-like bin
+            (r'\d[0-9_]*\.\d[0-9_]*[eE][+-]\d[0-9_]*',             # float exp
+             Number.Float),
+            (r'\d[0-9_]*\.\d[0-9_]*', Number.Float),               # float
+            (r'\d[0-9_]*', Number.Integer),                        # integer
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/parsers.py b/lib/python3.11/site-packages/pygments/lexers/parsers.py
new file mode 100644
index 0000000000000000000000000000000000000000..baa49b05407cbb85e9f0b72d653fd862f0323d34
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/parsers.py
@@ -0,0 +1,798 @@
+"""
+    pygments.lexers.parsers
+    ~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for parser generators.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, DelegatingLexer, \
+    include, bygroups, using
+from pygments.token import Punctuation, Other, Text, Comment, Operator, \
+    Keyword, Name, String, Number, Whitespace
+from pygments.lexers.jvm import JavaLexer
+from pygments.lexers.c_cpp import CLexer, CppLexer
+from pygments.lexers.objective import ObjectiveCLexer
+from pygments.lexers.d import DLexer
+from pygments.lexers.dotnet import CSharpLexer
+from pygments.lexers.ruby import RubyLexer
+from pygments.lexers.python import PythonLexer
+from pygments.lexers.perl import PerlLexer
+
+__all__ = ['RagelLexer', 'RagelEmbeddedLexer', 'RagelCLexer', 'RagelDLexer',
+           'RagelCppLexer', 'RagelObjectiveCLexer', 'RagelRubyLexer',
+           'RagelJavaLexer', 'AntlrLexer', 'AntlrPythonLexer',
+           'AntlrPerlLexer', 'AntlrRubyLexer', 'AntlrCppLexer',
+           'AntlrCSharpLexer', 'AntlrObjectiveCLexer',
+           'AntlrJavaLexer', 'AntlrActionScriptLexer',
+           'TreetopLexer', 'EbnfLexer']
+
+
+class RagelLexer(RegexLexer):
+    """A pure `Ragel `_ lexer.
+
+    Use this for fragments of Ragel.  For ``.rl`` files, use
+    :class:`RagelEmbeddedLexer` instead (or one of the language-specific
+    subclasses).
+    """
+
+    name = 'Ragel'
+    url = 'http://www.colm.net/open-source/ragel/'
+    aliases = ['ragel']
+    filenames = []
+    version_added = '1.1'
+
+    tokens = {
+        'whitespace': [
+            (r'\s+', Whitespace)
+        ],
+        'comments': [
+            (r'\#.*$', Comment),
+        ],
+        'keywords': [
+            (r'(access|action|alphtype)\b', Keyword),
+            (r'(getkey|write|machine|include)\b', Keyword),
+            (r'(any|ascii|extend|alpha|digit|alnum|lower|upper)\b', Keyword),
+            (r'(xdigit|cntrl|graph|print|punct|space|zlen|empty)\b', Keyword)
+        ],
+        'numbers': [
+            (r'0x[0-9A-Fa-f]+', Number.Hex),
+            (r'[+-]?[0-9]+', Number.Integer),
+        ],
+        'literals': [
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
+            (r'\[(\\\\|\\[^\\]|[^\\\]])*\]', String),          # square bracket literals
+            (r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/', String.Regex),  # regular expressions
+        ],
+        'identifiers': [
+            (r'[a-zA-Z_]\w*', Name.Variable),
+        ],
+        'operators': [
+            (r',', Operator),                           # Join
+            (r'\||&|--?', Operator),                    # Union, Intersection and Subtraction
+            (r'\.|<:|:>>?', Operator),                  # Concatention
+            (r':', Operator),                           # Label
+            (r'->', Operator),                          # Epsilon Transition
+            (r'(>|\$|%|<|@|<>)(/|eof\b)', Operator),    # EOF Actions
+            (r'(>|\$|%|<|@|<>)(!|err\b)', Operator),    # Global Error Actions
+            (r'(>|\$|%|<|@|<>)(\^|lerr\b)', Operator),  # Local Error Actions
+            (r'(>|\$|%|<|@|<>)(~|to\b)', Operator),     # To-State Actions
+            (r'(>|\$|%|<|@|<>)(\*|from\b)', Operator),  # From-State Actions
+            (r'>|@|\$|%', Operator),                    # Transition Actions and Priorities
+            (r'\*|\?|\+|\{[0-9]*,[0-9]*\}', Operator),  # Repetition
+            (r'!|\^', Operator),                        # Negation
+            (r'\(|\)', Operator),                       # Grouping
+        ],
+        'root': [
+            include('literals'),
+            include('whitespace'),
+            include('comments'),
+            include('keywords'),
+            include('numbers'),
+            include('identifiers'),
+            include('operators'),
+            (r'\{', Punctuation, 'host'),
+            (r'=', Operator),
+            (r';', Punctuation),
+        ],
+        'host': [
+            (r'(' + r'|'.join((  # keep host code in largest possible chunks
+                r'[^{}\'"/#]+',  # exclude unsafe characters
+                r'[^\\]\\[{}]',  # allow escaped { or }
+
+                # strings and comments may safely contain unsafe characters
+                r'"(\\\\|\\[^\\]|[^"\\])*"',
+                r"'(\\\\|\\[^\\]|[^'\\])*'",
+                r'//.*$\n?',            # single line comment
+                r'/\*(.|\n)*?\*/',      # multi-line javadoc-style comment
+                r'\#.*$\n?',            # ruby comment
+
+                # regular expression: There's no reason for it to start
+                # with a * and this stops confusion with comments.
+                r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
+
+                # / is safe now that we've handled regex and javadoc comments
+                r'/',
+            )) + r')+', Other),
+
+            (r'\{', Punctuation, '#push'),
+            (r'\}', Punctuation, '#pop'),
+        ],
+    }
+
+
+class RagelEmbeddedLexer(RegexLexer):
+    """
+    A lexer for Ragel embedded in a host language file.
+
+    This will only highlight Ragel statements. If you want host language
+    highlighting then call the language-specific Ragel lexer.
+    """
+
+    name = 'Embedded Ragel'
+    aliases = ['ragel-em']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    tokens = {
+        'root': [
+            (r'(' + r'|'.join((   # keep host code in largest possible chunks
+                r'[^%\'"/#]+',    # exclude unsafe characters
+                r'%(?=[^%]|$)',   # a single % sign is okay, just not 2 of them
+
+                # strings and comments may safely contain unsafe characters
+                r'"(\\\\|\\[^\\]|[^"\\])*"',
+                r"'(\\\\|\\[^\\]|[^'\\])*'",
+                r'/\*(.|\n)*?\*/',      # multi-line javadoc-style comment
+                r'//.*$\n?',  # single line comment
+                r'\#.*$\n?',  # ruby/ragel comment
+                r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',  # regular expression
+
+                # / is safe now that we've handled regex and javadoc comments
+                r'/',
+            )) + r')+', Other),
+
+            # Single Line FSM.
+            # Please don't put a quoted newline in a single line FSM.
+            # That's just mean. It will break this.
+            (r'(%%)(?![{%])(.*)($|;)(\n?)', bygroups(Punctuation,
+                                                     using(RagelLexer),
+                                                     Punctuation, Text)),
+
+            # Multi Line FSM.
+            (r'(%%%%|%%)\{', Punctuation, 'multi-line-fsm'),
+        ],
+        'multi-line-fsm': [
+            (r'(' + r'|'.join((  # keep ragel code in largest possible chunks.
+                r'(' + r'|'.join((
+                    r'[^}\'"\[/#]',   # exclude unsafe characters
+                    r'\}(?=[^%]|$)',   # } is okay as long as it's not followed by %
+                    r'\}%(?=[^%]|$)',  # ...well, one %'s okay, just not two...
+                    r'[^\\]\\[{}]',   # ...and } is okay if it's escaped
+
+                    # allow / if it's preceded with one of these symbols
+                    # (ragel EOF actions)
+                    r'(>|\$|%|<|@|<>)/',
+
+                    # specifically allow regex followed immediately by *
+                    # so it doesn't get mistaken for a comment
+                    r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/\*',
+
+                    # allow / as long as it's not followed by another / or by a *
+                    r'/(?=[^/*]|$)',
+
+                    # We want to match as many of these as we can in one block.
+                    # Not sure if we need the + sign here,
+                    # does it help performance?
+                )) + r')+',
+
+                # strings and comments may safely contain unsafe characters
+                r'"(\\\\|\\[^\\]|[^"\\])*"',
+                r"'(\\\\|\\[^\\]|[^'\\])*'",
+                r"\[(\\\\|\\[^\\]|[^\]\\])*\]",  # square bracket literal
+                r'/\*(.|\n)*?\*/',          # multi-line javadoc-style comment
+                r'//.*$\n?',                # single line comment
+                r'\#.*$\n?',                # ruby/ragel comment
+            )) + r')+', using(RagelLexer)),
+
+            (r'\}%%', Punctuation, '#pop'),
+        ]
+    }
+
+    def analyse_text(text):
+        return '@LANG: indep' in text
+
+
+class RagelRubyLexer(DelegatingLexer):
+    """
+    A lexer for Ragel in a Ruby host file.
+    """
+
+    name = 'Ragel in Ruby Host'
+    aliases = ['ragel-ruby', 'ragel-rb']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(RubyLexer, RagelEmbeddedLexer, **options)
+
+    def analyse_text(text):
+        return '@LANG: ruby' in text
+
+
+class RagelCLexer(DelegatingLexer):
+    """
+    A lexer for Ragel in a C host file.
+    """
+
+    name = 'Ragel in C Host'
+    aliases = ['ragel-c']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(CLexer, RagelEmbeddedLexer, **options)
+
+    def analyse_text(text):
+        return '@LANG: c' in text
+
+
+class RagelDLexer(DelegatingLexer):
+    """
+    A lexer for Ragel in a D host file.
+    """
+
+    name = 'Ragel in D Host'
+    aliases = ['ragel-d']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(DLexer, RagelEmbeddedLexer, **options)
+
+    def analyse_text(text):
+        return '@LANG: d' in text
+
+
+class RagelCppLexer(DelegatingLexer):
+    """
+    A lexer for Ragel in a C++ host file.
+    """
+
+    name = 'Ragel in CPP Host'
+    aliases = ['ragel-cpp']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(CppLexer, RagelEmbeddedLexer, **options)
+
+    def analyse_text(text):
+        return '@LANG: c++' in text
+
+
+class RagelObjectiveCLexer(DelegatingLexer):
+    """
+    A lexer for Ragel in an Objective C host file.
+    """
+
+    name = 'Ragel in Objective C Host'
+    aliases = ['ragel-objc']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(ObjectiveCLexer, RagelEmbeddedLexer, **options)
+
+    def analyse_text(text):
+        return '@LANG: objc' in text
+
+
+class RagelJavaLexer(DelegatingLexer):
+    """
+    A lexer for Ragel in a Java host file.
+    """
+
+    name = 'Ragel in Java Host'
+    aliases = ['ragel-java']
+    filenames = ['*.rl']
+    url = 'http://www.colm.net/open-source/ragel/'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(JavaLexer, RagelEmbeddedLexer, **options)
+
+    def analyse_text(text):
+        return '@LANG: java' in text
+
+
+class AntlrLexer(RegexLexer):
+    """
+    Generic ANTLR Lexer.
+    Should not be called directly, instead
+    use DelegatingLexer for your target language.
+    """
+
+    name = 'ANTLR'
+    aliases = ['antlr']
+    filenames = []
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    _id = r'[A-Za-z]\w*'
+    _TOKEN_REF = r'[A-Z]\w*'
+    _RULE_REF = r'[a-z]\w*'
+    _STRING_LITERAL = r'\'(?:\\\\|\\\'|[^\']*)\''
+    _INT = r'[0-9]+'
+
+    tokens = {
+        'whitespace': [
+            (r'\s+', Whitespace),
+        ],
+        'comments': [
+            (r'//.*$', Comment),
+            (r'/\*(.|\n)*?\*/', Comment),
+        ],
+        'root': [
+            include('whitespace'),
+            include('comments'),
+
+            (r'(lexer|parser|tree)?(\s*)(grammar\b)(\s*)(' + _id + ')(;)',
+             bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Class,
+                      Punctuation)),
+            # optionsSpec
+            (r'options\b', Keyword, 'options'),
+            # tokensSpec
+            (r'tokens\b', Keyword, 'tokens'),
+            # attrScope
+            (r'(scope)(\s*)(' + _id + r')(\s*)(\{)',
+             bygroups(Keyword, Whitespace, Name.Variable, Whitespace,
+                      Punctuation), 'action'),
+            # exception
+            (r'(catch|finally)\b', Keyword, 'exception'),
+            # action
+            (r'(@' + _id + r')(\s*)(::)?(\s*)(' + _id + r')(\s*)(\{)',
+             bygroups(Name.Label, Whitespace, Punctuation, Whitespace,
+                      Name.Label, Whitespace, Punctuation), 'action'),
+            # rule
+            (r'((?:protected|private|public|fragment)\b)?(\s*)(' + _id + ')(!)?',
+             bygroups(Keyword, Whitespace, Name.Label, Punctuation),
+             ('rule-alts', 'rule-prelims')),
+        ],
+        'exception': [
+            (r'\n', Whitespace, '#pop'),
+            (r'\s', Whitespace),
+            include('comments'),
+
+            (r'\[', Punctuation, 'nested-arg-action'),
+            (r'\{', Punctuation, 'action'),
+        ],
+        'rule-prelims': [
+            include('whitespace'),
+            include('comments'),
+
+            (r'returns\b', Keyword),
+            (r'\[', Punctuation, 'nested-arg-action'),
+            (r'\{', Punctuation, 'action'),
+            # throwsSpec
+            (r'(throws)(\s+)(' + _id + ')',
+             bygroups(Keyword, Whitespace, Name.Label)),
+            (r'(,)(\s*)(' + _id + ')',
+             bygroups(Punctuation, Whitespace, Name.Label)),  # Additional throws
+            # optionsSpec
+            (r'options\b', Keyword, 'options'),
+            # ruleScopeSpec - scope followed by target language code or name of action
+            # TODO finish implementing other possibilities for scope
+            # L173 ANTLRv3.g from ANTLR book
+            (r'(scope)(\s+)(\{)', bygroups(Keyword, Whitespace, Punctuation),
+             'action'),
+            (r'(scope)(\s+)(' + _id + r')(\s*)(;)',
+             bygroups(Keyword, Whitespace, Name.Label, Whitespace, Punctuation)),
+            # ruleAction
+            (r'(@' + _id + r')(\s*)(\{)',
+             bygroups(Name.Label, Whitespace, Punctuation), 'action'),
+            # finished prelims, go to rule alts!
+            (r':', Punctuation, '#pop')
+        ],
+        'rule-alts': [
+            include('whitespace'),
+            include('comments'),
+
+            # These might need to go in a separate 'block' state triggered by (
+            (r'options\b', Keyword, 'options'),
+            (r':', Punctuation),
+
+            # literals
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
+            (r'<<([^>]|>[^>])>>', String),
+            # identifiers
+            # Tokens start with capital letter.
+            (r'\$?[A-Z_]\w*', Name.Constant),
+            # Rules start with small letter.
+            (r'\$?[a-z_]\w*', Name.Variable),
+            # operators
+            (r'(\+|\||->|=>|=|\(|\)|\.\.|\.|\?|\*|\^|!|\#|~)', Operator),
+            (r',', Punctuation),
+            (r'\[', Punctuation, 'nested-arg-action'),
+            (r'\{', Punctuation, 'action'),
+            (r';', Punctuation, '#pop')
+        ],
+        'tokens': [
+            include('whitespace'),
+            include('comments'),
+            (r'\{', Punctuation),
+            (r'(' + _TOKEN_REF + r')(\s*)(=)?(\s*)(' + _STRING_LITERAL
+             + r')?(\s*)(;)',
+             bygroups(Name.Label, Whitespace, Punctuation, Whitespace,
+                      String, Whitespace, Punctuation)),
+            (r'\}', Punctuation, '#pop'),
+        ],
+        'options': [
+            include('whitespace'),
+            include('comments'),
+            (r'\{', Punctuation),
+            (r'(' + _id + r')(\s*)(=)(\s*)(' +
+             '|'.join((_id, _STRING_LITERAL, _INT, r'\*')) + r')(\s*)(;)',
+             bygroups(Name.Variable, Whitespace, Punctuation, Whitespace,
+                      Text, Whitespace, Punctuation)),
+            (r'\}', Punctuation, '#pop'),
+        ],
+        'action': [
+            (r'(' + r'|'.join((    # keep host code in largest possible chunks
+                r'[^${}\'"/\\]+',  # exclude unsafe characters
+
+                # strings and comments may safely contain unsafe characters
+                r'"(\\\\|\\[^\\]|[^"\\])*"',
+                r"'(\\\\|\\[^\\]|[^'\\])*'",
+                r'//.*$\n?',            # single line comment
+                r'/\*(.|\n)*?\*/',      # multi-line javadoc-style comment
+
+                # regular expression: There's no reason for it to start
+                # with a * and this stops confusion with comments.
+                r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
+
+                # backslashes are okay, as long as we are not backslashing a %
+                r'\\(?!%)',
+
+                # Now that we've handled regex and javadoc comments
+                # it's safe to let / through.
+                r'/',
+            )) + r')+', Other),
+            (r'(\\)(%)', bygroups(Punctuation, Other)),
+            (r'(\$[a-zA-Z]+)(\.?)(text|value)?',
+             bygroups(Name.Variable, Punctuation, Name.Property)),
+            (r'\{', Punctuation, '#push'),
+            (r'\}', Punctuation, '#pop'),
+        ],
+        'nested-arg-action': [
+            (r'(' + r'|'.join((    # keep host code in largest possible chunks.
+                r'[^$\[\]\'"/]+',  # exclude unsafe characters
+
+                # strings and comments may safely contain unsafe characters
+                r'"(\\\\|\\[^\\]|[^"\\])*"',
+                r"'(\\\\|\\[^\\]|[^'\\])*'",
+                r'//.*$\n?',            # single line comment
+                r'/\*(.|\n)*?\*/',      # multi-line javadoc-style comment
+
+                # regular expression: There's no reason for it to start
+                # with a * and this stops confusion with comments.
+                r'/(?!\*)(\\\\|\\[^\\]|[^/\\])*/',
+
+                # Now that we've handled regex and javadoc comments
+                # it's safe to let / through.
+                r'/',
+            )) + r')+', Other),
+
+
+            (r'\[', Punctuation, '#push'),
+            (r'\]', Punctuation, '#pop'),
+            (r'(\$[a-zA-Z]+)(\.?)(text|value)?',
+             bygroups(Name.Variable, Punctuation, Name.Property)),
+            (r'(\\\\|\\\]|\\\[|[^\[\]])+', Other),
+        ]
+    }
+
+    def analyse_text(text):
+        return re.search(r'^\s*grammar\s+[a-zA-Z0-9]+\s*;', text, re.M)
+
+
+# http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets
+
+class AntlrCppLexer(DelegatingLexer):
+    """
+    ANTLR with C++ Target
+    """
+
+    name = 'ANTLR With CPP Target'
+    aliases = ['antlr-cpp']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(CppLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*C\s*;', text, re.M)
+
+
+class AntlrObjectiveCLexer(DelegatingLexer):
+    """
+    ANTLR with Objective-C Target
+    """
+
+    name = 'ANTLR With ObjectiveC Target'
+    aliases = ['antlr-objc']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(ObjectiveCLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*ObjC\s*;', text)
+
+
+class AntlrCSharpLexer(DelegatingLexer):
+    """
+    ANTLR with C# Target
+    """
+
+    name = 'ANTLR With C# Target'
+    aliases = ['antlr-csharp', 'antlr-c#']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(CSharpLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*CSharp2\s*;', text, re.M)
+
+
+class AntlrPythonLexer(DelegatingLexer):
+    """
+    ANTLR with Python Target
+    """
+
+    name = 'ANTLR With Python Target'
+    aliases = ['antlr-python']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(PythonLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*Python\s*;', text, re.M)
+
+
+class AntlrJavaLexer(DelegatingLexer):
+    """
+    ANTLR with Java Target
+    """
+
+    name = 'ANTLR With Java Target'
+    aliases = ['antlr-java']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(JavaLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        # Antlr language is Java by default
+        return AntlrLexer.analyse_text(text) and 0.9
+
+
+class AntlrRubyLexer(DelegatingLexer):
+    """
+    ANTLR with Ruby Target
+    """
+
+    name = 'ANTLR With Ruby Target'
+    aliases = ['antlr-ruby', 'antlr-rb']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(RubyLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*Ruby\s*;', text, re.M)
+
+
+class AntlrPerlLexer(DelegatingLexer):
+    """
+    ANTLR with Perl Target
+    """
+
+    name = 'ANTLR With Perl Target'
+    aliases = ['antlr-perl']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        super().__init__(PerlLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*Perl5\s*;', text, re.M)
+
+
+class AntlrActionScriptLexer(DelegatingLexer):
+    """
+    ANTLR with ActionScript Target
+    """
+
+    name = 'ANTLR With ActionScript Target'
+    aliases = ['antlr-actionscript', 'antlr-as']
+    filenames = ['*.G', '*.g']
+    url = 'https://www.antlr.org'
+    version_added = '1.1'
+
+    def __init__(self, **options):
+        from pygments.lexers.actionscript import ActionScriptLexer
+        super().__init__(ActionScriptLexer, AntlrLexer, **options)
+
+    def analyse_text(text):
+        return AntlrLexer.analyse_text(text) and \
+            re.search(r'^\s*language\s*=\s*ActionScript\s*;', text, re.M)
+
+
+class TreetopBaseLexer(RegexLexer):
+    """
+    A base lexer for `Treetop `_ grammars.
+    Not for direct use; use :class:`TreetopLexer` instead.
+
+    .. versionadded:: 1.6
+    """
+
+    tokens = {
+        'root': [
+            include('space'),
+            (r'require[ \t]+[^\n\r]+[\n\r]', Other),
+            (r'module\b', Keyword.Namespace, 'module'),
+            (r'grammar\b', Keyword, 'grammar'),
+        ],
+        'module': [
+            include('space'),
+            include('end'),
+            (r'module\b', Keyword, '#push'),
+            (r'grammar\b', Keyword, 'grammar'),
+            (r'[A-Z]\w*(?:::[A-Z]\w*)*', Name.Namespace),
+        ],
+        'grammar': [
+            include('space'),
+            include('end'),
+            (r'rule\b', Keyword, 'rule'),
+            (r'include\b', Keyword, 'include'),
+            (r'[A-Z]\w*', Name),
+        ],
+        'include': [
+            include('space'),
+            (r'[A-Z]\w*(?:::[A-Z]\w*)*', Name.Class, '#pop'),
+        ],
+        'rule': [
+            include('space'),
+            include('end'),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
+            (r'([A-Za-z_]\w*)(:)', bygroups(Name.Label, Punctuation)),
+            (r'[A-Za-z_]\w*', Name),
+            (r'[()]', Punctuation),
+            (r'[?+*/&!~]', Operator),
+            (r'\[(?:\\.|\[:\^?[a-z]+:\]|[^\\\]])+\]', String.Regex),
+            (r'([0-9]*)(\.\.)([0-9]*)',
+             bygroups(Number.Integer, Operator, Number.Integer)),
+            (r'(<)([^>]+)(>)', bygroups(Punctuation, Name.Class, Punctuation)),
+            (r'\{', Punctuation, 'inline_module'),
+            (r'\.', String.Regex),
+        ],
+        'inline_module': [
+            (r'\{', Other, 'ruby'),
+            (r'\}', Punctuation, '#pop'),
+            (r'[^{}]+', Other),
+        ],
+        'ruby': [
+            (r'\{', Other, '#push'),
+            (r'\}', Other, '#pop'),
+            (r'[^{}]+', Other),
+        ],
+        'space': [
+            (r'[ \t\n\r]+', Whitespace),
+            (r'#[^\n]*', Comment.Single),
+        ],
+        'end': [
+            (r'end\b', Keyword, '#pop'),
+        ],
+    }
+
+
+class TreetopLexer(DelegatingLexer):
+    """
+    A lexer for Treetop grammars.
+    """
+
+    name = 'Treetop'
+    aliases = ['treetop']
+    filenames = ['*.treetop', '*.tt']
+    url = 'https://cjheath.github.io/treetop'
+    version_added = '1.6'
+
+    def __init__(self, **options):
+        super().__init__(RubyLexer, TreetopBaseLexer, **options)
+
+
+class EbnfLexer(RegexLexer):
+    """
+    Lexer for `ISO/IEC 14977 EBNF
+    `_
+    grammars.
+    """
+
+    name = 'EBNF'
+    aliases = ['ebnf']
+    filenames = ['*.ebnf']
+    mimetypes = ['text/x-ebnf']
+    url = 'https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form'
+    version_added = '2.0'
+
+    tokens = {
+        'root': [
+            include('whitespace'),
+            include('comment_start'),
+            include('identifier'),
+            (r'=', Operator, 'production'),
+        ],
+        'production': [
+            include('whitespace'),
+            include('comment_start'),
+            include('identifier'),
+            (r'"[^"]*"', String.Double),
+            (r"'[^']*'", String.Single),
+            (r'(\?[^?]*\?)', Name.Entity),
+            (r'[\[\]{}(),|]', Punctuation),
+            (r'-', Operator),
+            (r';', Punctuation, '#pop'),
+            (r'\.', Punctuation, '#pop'),
+        ],
+        'whitespace': [
+            (r'\s+', Text),
+        ],
+        'comment_start': [
+            (r'\(\*', Comment.Multiline, 'comment'),
+        ],
+        'comment': [
+            (r'[^*)]', Comment.Multiline),
+            include('comment_start'),
+            (r'\*\)', Comment.Multiline, '#pop'),
+            (r'[*)]', Comment.Multiline),
+        ],
+        'identifier': [
+            (r'([a-zA-Z][\w \-]*)', Keyword),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/pascal.py b/lib/python3.11/site-packages/pygments/lexers/pascal.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad8a0aec62a515a601b0b866ae4d64cf62c28afb
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/pascal.py
@@ -0,0 +1,644 @@
+"""
+    pygments.lexers.pascal
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Pascal family languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import Lexer
+from pygments.util import get_bool_opt, get_list_opt
+from pygments.token import Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Error, Whitespace
+from pygments.scanner import Scanner
+
+# compatibility import
+from pygments.lexers.modula2 import Modula2Lexer # noqa: F401
+
+__all__ = ['DelphiLexer', 'PortugolLexer']
+
+
+class PortugolLexer(Lexer):
+    """For Portugol, a Pascal dialect with keywords in Portuguese."""
+    name = 'Portugol'
+    aliases = ['portugol']
+    filenames = ['*.alg', '*.portugol']
+    mimetypes = []
+    url = "https://www.apoioinformatica.inf.br/produtos/visualg/linguagem"
+    version_added = ''
+
+    def __init__(self, **options):
+        Lexer.__init__(self, **options)
+        self.lexer = DelphiLexer(**options, portugol=True)
+
+    def get_tokens_unprocessed(self, text):
+        return self.lexer.get_tokens_unprocessed(text)
+
+
+class DelphiLexer(Lexer):
+    """
+    For Delphi (Borland Object Pascal),
+    Turbo Pascal and Free Pascal source code.
+
+    Additional options accepted:
+
+    `turbopascal`
+        Highlight Turbo Pascal specific keywords (default: ``True``).
+    `delphi`
+        Highlight Borland Delphi specific keywords (default: ``True``).
+    `freepascal`
+        Highlight Free Pascal specific keywords (default: ``True``).
+    `units`
+        A list of units that should be considered builtin, supported are
+        ``System``, ``SysUtils``, ``Classes`` and ``Math``.
+        Default is to consider all of them builtin.
+    """
+    name = 'Delphi'
+    aliases = ['delphi', 'pas', 'pascal', 'objectpascal']
+    filenames = ['*.pas', '*.dpr']
+    mimetypes = ['text/x-pascal']
+    url = 'https://www.embarcadero.com/products/delphi'
+    version_added = ''
+
+    TURBO_PASCAL_KEYWORDS = (
+        'absolute', 'and', 'array', 'asm', 'begin', 'break', 'case',
+        'const', 'constructor', 'continue', 'destructor', 'div', 'do',
+        'downto', 'else', 'end', 'file', 'for', 'function', 'goto',
+        'if', 'implementation', 'in', 'inherited', 'inline', 'interface',
+        'label', 'mod', 'nil', 'not', 'object', 'of', 'on', 'operator',
+        'or', 'packed', 'procedure', 'program', 'record', 'reintroduce',
+        'repeat', 'self', 'set', 'shl', 'shr', 'string', 'then', 'to',
+        'type', 'unit', 'until', 'uses', 'var', 'while', 'with', 'xor'
+    )
+
+    DELPHI_KEYWORDS = (
+        'as', 'class', 'except', 'exports', 'finalization', 'finally',
+        'initialization', 'is', 'library', 'on', 'property', 'raise',
+        'threadvar', 'try'
+    )
+
+    FREE_PASCAL_KEYWORDS = (
+        'dispose', 'exit', 'false', 'new', 'true'
+    )
+
+    BLOCK_KEYWORDS = {
+        'begin', 'class', 'const', 'constructor', 'destructor', 'end',
+        'finalization', 'function', 'implementation', 'initialization',
+        'label', 'library', 'operator', 'procedure', 'program', 'property',
+        'record', 'threadvar', 'type', 'unit', 'uses', 'var'
+    }
+
+    FUNCTION_MODIFIERS = {
+        'alias', 'cdecl', 'export', 'inline', 'interrupt', 'nostackframe',
+        'pascal', 'register', 'safecall', 'softfloat', 'stdcall',
+        'varargs', 'name', 'dynamic', 'near', 'virtual', 'external',
+        'override', 'assembler'
+    }
+
+    # XXX: those aren't global. but currently we know no way for defining
+    #      them just for the type context.
+    DIRECTIVES = {
+        'absolute', 'abstract', 'assembler', 'cppdecl', 'default', 'far',
+        'far16', 'forward', 'index', 'oldfpccall', 'private', 'protected',
+        'published', 'public'
+    }
+
+    BUILTIN_TYPES = {
+        'ansichar', 'ansistring', 'bool', 'boolean', 'byte', 'bytebool',
+        'cardinal', 'char', 'comp', 'currency', 'double', 'dword',
+        'extended', 'int64', 'integer', 'iunknown', 'longbool', 'longint',
+        'longword', 'pansichar', 'pansistring', 'pbool', 'pboolean',
+        'pbyte', 'pbytearray', 'pcardinal', 'pchar', 'pcomp', 'pcurrency',
+        'pdate', 'pdatetime', 'pdouble', 'pdword', 'pextended', 'phandle',
+        'pint64', 'pinteger', 'plongint', 'plongword', 'pointer',
+        'ppointer', 'pshortint', 'pshortstring', 'psingle', 'psmallint',
+        'pstring', 'pvariant', 'pwidechar', 'pwidestring', 'pword',
+        'pwordarray', 'pwordbool', 'real', 'real48', 'shortint',
+        'shortstring', 'single', 'smallint', 'string', 'tclass', 'tdate',
+        'tdatetime', 'textfile', 'thandle', 'tobject', 'ttime', 'variant',
+        'widechar', 'widestring', 'word', 'wordbool'
+    }
+
+    BUILTIN_UNITS = {
+        'System': (
+            'abs', 'acquireexceptionobject', 'addr', 'ansitoutf8',
+            'append', 'arctan', 'assert', 'assigned', 'assignfile',
+            'beginthread', 'blockread', 'blockwrite', 'break', 'chdir',
+            'chr', 'close', 'closefile', 'comptocurrency', 'comptodouble',
+            'concat', 'continue', 'copy', 'cos', 'dec', 'delete',
+            'dispose', 'doubletocomp', 'endthread', 'enummodules',
+            'enumresourcemodules', 'eof', 'eoln', 'erase', 'exceptaddr',
+            'exceptobject', 'exclude', 'exit', 'exp', 'filepos', 'filesize',
+            'fillchar', 'finalize', 'findclasshinstance', 'findhinstance',
+            'findresourcehinstance', 'flush', 'frac', 'freemem',
+            'get8087cw', 'getdir', 'getlasterror', 'getmem',
+            'getmemorymanager', 'getmodulefilename', 'getvariantmanager',
+            'halt', 'hi', 'high', 'inc', 'include', 'initialize', 'insert',
+            'int', 'ioresult', 'ismemorymanagerset', 'isvariantmanagerset',
+            'length', 'ln', 'lo', 'low', 'mkdir', 'move', 'new', 'odd',
+            'olestrtostring', 'olestrtostrvar', 'ord', 'paramcount',
+            'paramstr', 'pi', 'pos', 'pred', 'ptr', 'pucs4chars', 'random',
+            'randomize', 'read', 'readln', 'reallocmem',
+            'releaseexceptionobject', 'rename', 'reset', 'rewrite', 'rmdir',
+            'round', 'runerror', 'seek', 'seekeof', 'seekeoln',
+            'set8087cw', 'setlength', 'setlinebreakstyle',
+            'setmemorymanager', 'setstring', 'settextbuf',
+            'setvariantmanager', 'sin', 'sizeof', 'slice', 'sqr', 'sqrt',
+            'str', 'stringofchar', 'stringtoolestr', 'stringtowidechar',
+            'succ', 'swap', 'trunc', 'truncate', 'typeinfo',
+            'ucs4stringtowidestring', 'unicodetoutf8', 'uniquestring',
+            'upcase', 'utf8decode', 'utf8encode', 'utf8toansi',
+            'utf8tounicode', 'val', 'vararrayredim', 'varclear',
+            'widecharlentostring', 'widecharlentostrvar',
+            'widechartostring', 'widechartostrvar',
+            'widestringtoucs4string', 'write', 'writeln'
+        ),
+        'SysUtils': (
+            'abort', 'addexitproc', 'addterminateproc', 'adjustlinebreaks',
+            'allocmem', 'ansicomparefilename', 'ansicomparestr',
+            'ansicomparetext', 'ansidequotedstr', 'ansiextractquotedstr',
+            'ansilastchar', 'ansilowercase', 'ansilowercasefilename',
+            'ansipos', 'ansiquotedstr', 'ansisamestr', 'ansisametext',
+            'ansistrcomp', 'ansistricomp', 'ansistrlastchar', 'ansistrlcomp',
+            'ansistrlicomp', 'ansistrlower', 'ansistrpos', 'ansistrrscan',
+            'ansistrscan', 'ansistrupper', 'ansiuppercase',
+            'ansiuppercasefilename', 'appendstr', 'assignstr', 'beep',
+            'booltostr', 'bytetocharindex', 'bytetocharlen', 'bytetype',
+            'callterminateprocs', 'changefileext', 'charlength',
+            'chartobyteindex', 'chartobytelen', 'comparemem', 'comparestr',
+            'comparetext', 'createdir', 'createguid', 'currentyear',
+            'currtostr', 'currtostrf', 'date', 'datetimetofiledate',
+            'datetimetostr', 'datetimetostring', 'datetimetosystemtime',
+            'datetimetotimestamp', 'datetostr', 'dayofweek', 'decodedate',
+            'decodedatefully', 'decodetime', 'deletefile', 'directoryexists',
+            'diskfree', 'disksize', 'disposestr', 'encodedate', 'encodetime',
+            'exceptionerrormessage', 'excludetrailingbackslash',
+            'excludetrailingpathdelimiter', 'expandfilename',
+            'expandfilenamecase', 'expanduncfilename', 'extractfiledir',
+            'extractfiledrive', 'extractfileext', 'extractfilename',
+            'extractfilepath', 'extractrelativepath', 'extractshortpathname',
+            'fileage', 'fileclose', 'filecreate', 'filedatetodatetime',
+            'fileexists', 'filegetattr', 'filegetdate', 'fileisreadonly',
+            'fileopen', 'fileread', 'filesearch', 'fileseek', 'filesetattr',
+            'filesetdate', 'filesetreadonly', 'filewrite', 'finalizepackage',
+            'findclose', 'findcmdlineswitch', 'findfirst', 'findnext',
+            'floattocurr', 'floattodatetime', 'floattodecimal', 'floattostr',
+            'floattostrf', 'floattotext', 'floattotextfmt', 'fmtloadstr',
+            'fmtstr', 'forcedirectories', 'format', 'formatbuf', 'formatcurr',
+            'formatdatetime', 'formatfloat', 'freeandnil', 'getcurrentdir',
+            'getenvironmentvariable', 'getfileversion', 'getformatsettings',
+            'getlocaleformatsettings', 'getmodulename', 'getpackagedescription',
+            'getpackageinfo', 'gettime', 'guidtostring', 'incamonth',
+            'includetrailingbackslash', 'includetrailingpathdelimiter',
+            'incmonth', 'initializepackage', 'interlockeddecrement',
+            'interlockedexchange', 'interlockedexchangeadd',
+            'interlockedincrement', 'inttohex', 'inttostr', 'isdelimiter',
+            'isequalguid', 'isleapyear', 'ispathdelimiter', 'isvalidident',
+            'languages', 'lastdelimiter', 'loadpackage', 'loadstr',
+            'lowercase', 'msecstotimestamp', 'newstr', 'nextcharindex', 'now',
+            'outofmemoryerror', 'quotedstr', 'raiselastoserror',
+            'raiselastwin32error', 'removedir', 'renamefile', 'replacedate',
+            'replacetime', 'safeloadlibrary', 'samefilename', 'sametext',
+            'setcurrentdir', 'showexception', 'sleep', 'stralloc', 'strbufsize',
+            'strbytetype', 'strcat', 'strcharlength', 'strcomp', 'strcopy',
+            'strdispose', 'strecopy', 'strend', 'strfmt', 'stricomp',
+            'stringreplace', 'stringtoguid', 'strlcat', 'strlcomp', 'strlcopy',
+            'strlen', 'strlfmt', 'strlicomp', 'strlower', 'strmove', 'strnew',
+            'strnextchar', 'strpas', 'strpcopy', 'strplcopy', 'strpos',
+            'strrscan', 'strscan', 'strtobool', 'strtobooldef', 'strtocurr',
+            'strtocurrdef', 'strtodate', 'strtodatedef', 'strtodatetime',
+            'strtodatetimedef', 'strtofloat', 'strtofloatdef', 'strtoint',
+            'strtoint64', 'strtoint64def', 'strtointdef', 'strtotime',
+            'strtotimedef', 'strupper', 'supports', 'syserrormessage',
+            'systemtimetodatetime', 'texttofloat', 'time', 'timestamptodatetime',
+            'timestamptomsecs', 'timetostr', 'trim', 'trimleft', 'trimright',
+            'tryencodedate', 'tryencodetime', 'tryfloattocurr', 'tryfloattodatetime',
+            'trystrtobool', 'trystrtocurr', 'trystrtodate', 'trystrtodatetime',
+            'trystrtofloat', 'trystrtoint', 'trystrtoint64', 'trystrtotime',
+            'unloadpackage', 'uppercase', 'widecomparestr', 'widecomparetext',
+            'widefmtstr', 'wideformat', 'wideformatbuf', 'widelowercase',
+            'widesamestr', 'widesametext', 'wideuppercase', 'win32check',
+            'wraptext'
+        ),
+        'Classes': (
+            'activateclassgroup', 'allocatehwnd', 'bintohex', 'checksynchronize',
+            'collectionsequal', 'countgenerations', 'deallocatehwnd', 'equalrect',
+            'extractstrings', 'findclass', 'findglobalcomponent', 'getclass',
+            'groupdescendantswith', 'hextobin', 'identtoint',
+            'initinheritedcomponent', 'inttoident', 'invalidpoint',
+            'isuniqueglobalcomponentname', 'linestart', 'objectbinarytotext',
+            'objectresourcetotext', 'objecttexttobinary', 'objecttexttoresource',
+            'pointsequal', 'readcomponentres', 'readcomponentresex',
+            'readcomponentresfile', 'rect', 'registerclass', 'registerclassalias',
+            'registerclasses', 'registercomponents', 'registerintegerconsts',
+            'registernoicon', 'registernonactivex', 'smallpoint', 'startclassgroup',
+            'teststreamformat', 'unregisterclass', 'unregisterclasses',
+            'unregisterintegerconsts', 'unregistermoduleclasses',
+            'writecomponentresfile'
+        ),
+        'Math': (
+            'arccos', 'arccosh', 'arccot', 'arccoth', 'arccsc', 'arccsch', 'arcsec',
+            'arcsech', 'arcsin', 'arcsinh', 'arctan2', 'arctanh', 'ceil',
+            'comparevalue', 'cosecant', 'cosh', 'cot', 'cotan', 'coth', 'csc',
+            'csch', 'cycletodeg', 'cycletograd', 'cycletorad', 'degtocycle',
+            'degtograd', 'degtorad', 'divmod', 'doubledecliningbalance',
+            'ensurerange', 'floor', 'frexp', 'futurevalue', 'getexceptionmask',
+            'getprecisionmode', 'getroundmode', 'gradtocycle', 'gradtodeg',
+            'gradtorad', 'hypot', 'inrange', 'interestpayment', 'interestrate',
+            'internalrateofreturn', 'intpower', 'isinfinite', 'isnan', 'iszero',
+            'ldexp', 'lnxp1', 'log10', 'log2', 'logn', 'max', 'maxintvalue',
+            'maxvalue', 'mean', 'meanandstddev', 'min', 'minintvalue', 'minvalue',
+            'momentskewkurtosis', 'netpresentvalue', 'norm', 'numberofperiods',
+            'payment', 'periodpayment', 'poly', 'popnstddev', 'popnvariance',
+            'power', 'presentvalue', 'radtocycle', 'radtodeg', 'radtograd',
+            'randg', 'randomrange', 'roundto', 'samevalue', 'sec', 'secant',
+            'sech', 'setexceptionmask', 'setprecisionmode', 'setroundmode',
+            'sign', 'simpleroundto', 'sincos', 'sinh', 'slndepreciation', 'stddev',
+            'sum', 'sumint', 'sumofsquares', 'sumsandsquares', 'syddepreciation',
+            'tan', 'tanh', 'totalvariance', 'variance'
+        )
+    }
+
+    ASM_REGISTERS = {
+        'ah', 'al', 'ax', 'bh', 'bl', 'bp', 'bx', 'ch', 'cl', 'cr0',
+        'cr1', 'cr2', 'cr3', 'cr4', 'cs', 'cx', 'dh', 'di', 'dl', 'dr0',
+        'dr1', 'dr2', 'dr3', 'dr4', 'dr5', 'dr6', 'dr7', 'ds', 'dx',
+        'eax', 'ebp', 'ebx', 'ecx', 'edi', 'edx', 'es', 'esi', 'esp',
+        'fs', 'gs', 'mm0', 'mm1', 'mm2', 'mm3', 'mm4', 'mm5', 'mm6',
+        'mm7', 'si', 'sp', 'ss', 'st0', 'st1', 'st2', 'st3', 'st4', 'st5',
+        'st6', 'st7', 'xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5',
+        'xmm6', 'xmm7'
+    }
+
+    ASM_INSTRUCTIONS = {
+        'aaa', 'aad', 'aam', 'aas', 'adc', 'add', 'and', 'arpl', 'bound',
+        'bsf', 'bsr', 'bswap', 'bt', 'btc', 'btr', 'bts', 'call', 'cbw',
+        'cdq', 'clc', 'cld', 'cli', 'clts', 'cmc', 'cmova', 'cmovae',
+        'cmovb', 'cmovbe', 'cmovc', 'cmovcxz', 'cmove', 'cmovg',
+        'cmovge', 'cmovl', 'cmovle', 'cmovna', 'cmovnae', 'cmovnb',
+        'cmovnbe', 'cmovnc', 'cmovne', 'cmovng', 'cmovnge', 'cmovnl',
+        'cmovnle', 'cmovno', 'cmovnp', 'cmovns', 'cmovnz', 'cmovo',
+        'cmovp', 'cmovpe', 'cmovpo', 'cmovs', 'cmovz', 'cmp', 'cmpsb',
+        'cmpsd', 'cmpsw', 'cmpxchg', 'cmpxchg486', 'cmpxchg8b', 'cpuid',
+        'cwd', 'cwde', 'daa', 'das', 'dec', 'div', 'emms', 'enter', 'hlt',
+        'ibts', 'icebp', 'idiv', 'imul', 'in', 'inc', 'insb', 'insd',
+        'insw', 'int', 'int01', 'int03', 'int1', 'int3', 'into', 'invd',
+        'invlpg', 'iret', 'iretd', 'iretw', 'ja', 'jae', 'jb', 'jbe',
+        'jc', 'jcxz', 'jcxz', 'je', 'jecxz', 'jg', 'jge', 'jl', 'jle',
+        'jmp', 'jna', 'jnae', 'jnb', 'jnbe', 'jnc', 'jne', 'jng', 'jnge',
+        'jnl', 'jnle', 'jno', 'jnp', 'jns', 'jnz', 'jo', 'jp', 'jpe',
+        'jpo', 'js', 'jz', 'lahf', 'lar', 'lcall', 'lds', 'lea', 'leave',
+        'les', 'lfs', 'lgdt', 'lgs', 'lidt', 'ljmp', 'lldt', 'lmsw',
+        'loadall', 'loadall286', 'lock', 'lodsb', 'lodsd', 'lodsw',
+        'loop', 'loope', 'loopne', 'loopnz', 'loopz', 'lsl', 'lss', 'ltr',
+        'mov', 'movd', 'movq', 'movsb', 'movsd', 'movsw', 'movsx',
+        'movzx', 'mul', 'neg', 'nop', 'not', 'or', 'out', 'outsb', 'outsd',
+        'outsw', 'pop', 'popa', 'popad', 'popaw', 'popf', 'popfd', 'popfw',
+        'push', 'pusha', 'pushad', 'pushaw', 'pushf', 'pushfd', 'pushfw',
+        'rcl', 'rcr', 'rdmsr', 'rdpmc', 'rdshr', 'rdtsc', 'rep', 'repe',
+        'repne', 'repnz', 'repz', 'ret', 'retf', 'retn', 'rol', 'ror',
+        'rsdc', 'rsldt', 'rsm', 'sahf', 'sal', 'salc', 'sar', 'sbb',
+        'scasb', 'scasd', 'scasw', 'seta', 'setae', 'setb', 'setbe',
+        'setc', 'setcxz', 'sete', 'setg', 'setge', 'setl', 'setle',
+        'setna', 'setnae', 'setnb', 'setnbe', 'setnc', 'setne', 'setng',
+        'setnge', 'setnl', 'setnle', 'setno', 'setnp', 'setns', 'setnz',
+        'seto', 'setp', 'setpe', 'setpo', 'sets', 'setz', 'sgdt', 'shl',
+        'shld', 'shr', 'shrd', 'sidt', 'sldt', 'smi', 'smint', 'smintold',
+        'smsw', 'stc', 'std', 'sti', 'stosb', 'stosd', 'stosw', 'str',
+        'sub', 'svdc', 'svldt', 'svts', 'syscall', 'sysenter', 'sysexit',
+        'sysret', 'test', 'ud1', 'ud2', 'umov', 'verr', 'verw', 'wait',
+        'wbinvd', 'wrmsr', 'wrshr', 'xadd', 'xbts', 'xchg', 'xlat',
+        'xlatb', 'xor'
+    }
+
+    PORTUGOL_KEYWORDS = (
+        'aleatorio',
+        'algoritmo',
+        'arquivo',
+        'ate',
+        'caso',
+        'cronometro',
+        'debug',
+        'e',
+        'eco',
+        'enquanto',
+        'entao',
+        'escolha',
+        'escreva',
+        'escreval',
+        'faca',
+        'falso',
+        'fimalgoritmo',
+        'fimenquanto',
+        'fimescolha',
+        'fimfuncao',
+        'fimpara',
+        'fimprocedimento',
+        'fimrepita',
+        'fimse',
+        'funcao',
+        'inicio',
+        'int',
+        'interrompa',
+        'leia',
+        'limpatela',
+        'mod',
+        'nao',
+        'ou',
+        'outrocaso',
+        'para',
+        'passo',
+        'pausa',
+        'procedimento',
+        'repita',
+        'retorne',
+        'se',
+        'senao',
+        'timer',
+        'var',
+        'vetor',
+        'verdadeiro',
+        'xou',
+        'div',
+        'mod',
+        'abs',
+        'arccos',
+        'arcsen',
+        'arctan',
+        'cos',
+        'cotan',
+        'Exp',
+        'grauprad',
+        'int',
+        'log',
+        'logn',
+        'pi',
+        'quad',
+        'radpgrau',
+        'raizq',
+        'rand',
+        'randi',
+        'sen',
+        'Tan',
+        'asc',
+        'carac',
+        'caracpnum',
+        'compr',
+        'copia',
+        'maiusc',
+        'minusc',
+        'numpcarac',
+        'pos',
+    )
+
+    PORTUGOL_BUILTIN_TYPES = {
+        'inteiro', 'real', 'caractere', 'logico'
+    }
+
+    def __init__(self, **options):
+        Lexer.__init__(self, **options)
+        self.keywords = set()
+        self.builtins = set()
+        if get_bool_opt(options, 'portugol', False):
+            self.keywords.update(self.PORTUGOL_KEYWORDS)
+            self.builtins.update(self.PORTUGOL_BUILTIN_TYPES)
+            self.is_portugol = True
+        else:
+            self.is_portugol = False
+
+            if get_bool_opt(options, 'turbopascal', True):
+                self.keywords.update(self.TURBO_PASCAL_KEYWORDS)
+            if get_bool_opt(options, 'delphi', True):
+                self.keywords.update(self.DELPHI_KEYWORDS)
+            if get_bool_opt(options, 'freepascal', True):
+                self.keywords.update(self.FREE_PASCAL_KEYWORDS)
+            for unit in get_list_opt(options, 'units', list(self.BUILTIN_UNITS)):
+                self.builtins.update(self.BUILTIN_UNITS[unit])
+
+    def get_tokens_unprocessed(self, text):
+        scanner = Scanner(text, re.DOTALL | re.MULTILINE | re.IGNORECASE)
+        stack = ['initial']
+        in_function_block = False
+        in_property_block = False
+        was_dot = False
+        next_token_is_function = False
+        next_token_is_property = False
+        collect_labels = False
+        block_labels = set()
+        brace_balance = [0, 0]
+
+        while not scanner.eos:
+            token = Error
+
+            if stack[-1] == 'initial':
+                if scanner.scan(r'\s+'):
+                    token = Whitespace
+                elif not self.is_portugol and scanner.scan(r'\{.*?\}|\(\*.*?\*\)'):
+                    if scanner.match.startswith('$'):
+                        token = Comment.Preproc
+                    else:
+                        token = Comment.Multiline
+                elif scanner.scan(r'//.*?$'):
+                    token = Comment.Single
+                elif self.is_portugol and scanner.scan(r'(<\-)|(>=)|(<=)|%|<|>|-|\+|\*|\=|(<>)|\/|\.|:|,'):
+                    token = Operator
+                elif not self.is_portugol and scanner.scan(r'[-+*\/=<>:;,.@\^]'):
+                    token = Operator
+                    # stop label highlighting on next ";"
+                    if collect_labels and scanner.match == ';':
+                        collect_labels = False
+                elif scanner.scan(r'[\(\)\[\]]+'):
+                    token = Punctuation
+                    # abort function naming ``foo = Function(...)``
+                    next_token_is_function = False
+                    # if we are in a function block we count the open
+                    # braces because ootherwise it's impossible to
+                    # determine the end of the modifier context
+                    if in_function_block or in_property_block:
+                        if scanner.match == '(':
+                            brace_balance[0] += 1
+                        elif scanner.match == ')':
+                            brace_balance[0] -= 1
+                        elif scanner.match == '[':
+                            brace_balance[1] += 1
+                        elif scanner.match == ']':
+                            brace_balance[1] -= 1
+                elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'):
+                    lowercase_name = scanner.match.lower()
+                    if lowercase_name == 'result':
+                        token = Name.Builtin.Pseudo
+                    elif lowercase_name in self.keywords:
+                        token = Keyword
+                        # if we are in a special block and a
+                        # block ending keyword occurs (and the parenthesis
+                        # is balanced) we end the current block context
+                        if self.is_portugol:
+                            if lowercase_name in ('funcao', 'procedimento'):
+                                in_function_block = True
+                                next_token_is_function = True
+                        else:
+                            if (in_function_block or in_property_block) and \
+                                    lowercase_name in self.BLOCK_KEYWORDS and \
+                                    brace_balance[0] <= 0 and \
+                                    brace_balance[1] <= 0:
+                                in_function_block = False
+                                in_property_block = False
+                                brace_balance = [0, 0]
+                                block_labels = set()
+                            if lowercase_name in ('label', 'goto'):
+                                collect_labels = True
+                            elif lowercase_name == 'asm':
+                                stack.append('asm')
+                            elif lowercase_name == 'property':
+                                in_property_block = True
+                                next_token_is_property = True
+                            elif lowercase_name in ('procedure', 'operator',
+                                                    'function', 'constructor',
+                                                    'destructor'):
+                                in_function_block = True
+                                next_token_is_function = True
+                    # we are in a function block and the current name
+                    # is in the set of registered modifiers. highlight
+                    # it as pseudo keyword
+                    elif not self.is_portugol and in_function_block and \
+                            lowercase_name in self.FUNCTION_MODIFIERS:
+                        token = Keyword.Pseudo
+                    # if we are in a property highlight some more
+                    # modifiers
+                    elif not self.is_portugol and in_property_block and \
+                            lowercase_name in ('read', 'write'):
+                        token = Keyword.Pseudo
+                        next_token_is_function = True
+                    # if the last iteration set next_token_is_function
+                    # to true we now want this name highlighted as
+                    # function. so do that and reset the state
+                    elif next_token_is_function:
+                        # Look if the next token is a dot. If yes it's
+                        # not a function, but a class name and the
+                        # part after the dot a function name
+                        if not self.is_portugol and scanner.test(r'\s*\.\s*'):
+                            token = Name.Class
+                        # it's not a dot, our job is done
+                        else:
+                            token = Name.Function
+                            next_token_is_function = False
+
+                            if self.is_portugol:
+                                block_labels.add(scanner.match.lower())
+
+                    # same for properties
+                    elif not self.is_portugol and next_token_is_property:
+                        token = Name.Property
+                        next_token_is_property = False
+                    # Highlight this token as label and add it
+                    # to the list of known labels
+                    elif not self.is_portugol and collect_labels:
+                        token = Name.Label
+                        block_labels.add(scanner.match.lower())
+                    # name is in list of known labels
+                    elif lowercase_name in block_labels:
+                        token = Name.Label
+                    elif self.is_portugol and lowercase_name in self.PORTUGOL_BUILTIN_TYPES:
+                        token = Keyword.Type
+                    elif not self.is_portugol and lowercase_name in self.BUILTIN_TYPES:
+                        token = Keyword.Type
+                    elif not self.is_portugol and lowercase_name in self.DIRECTIVES:
+                        token = Keyword.Pseudo
+                    # builtins are just builtins if the token
+                    # before isn't a dot
+                    elif not self.is_portugol and not was_dot and lowercase_name in self.builtins:
+                        token = Name.Builtin
+                    else:
+                        token = Name
+                elif self.is_portugol and scanner.scan(r"\""):
+                    token = String
+                    stack.append('string')
+                elif not self.is_portugol and scanner.scan(r"'"):
+                    token = String
+                    stack.append('string')
+                elif not self.is_portugol and scanner.scan(r'\#(\d+|\$[0-9A-Fa-f]+)'):
+                    token = String.Char
+                elif not self.is_portugol and scanner.scan(r'\$[0-9A-Fa-f]+'):
+                    token = Number.Hex
+                elif scanner.scan(r'\d+(?![eE]|\.[^.])'):
+                    token = Number.Integer
+                elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'):
+                    token = Number.Float
+                else:
+                    # if the stack depth is deeper than once, pop
+                    if len(stack) > 1:
+                        stack.pop()
+                    scanner.get_char()
+
+            elif stack[-1] == 'string':
+                if self.is_portugol:
+                    if scanner.scan(r"''"):
+                        token = String.Escape
+                    elif scanner.scan(r"\""):
+                        token = String
+                        stack.pop()
+                    elif scanner.scan(r"[^\"]*"):
+                        token = String
+                    else:
+                        scanner.get_char()
+                        stack.pop()
+                else:
+                    if scanner.scan(r"''"):
+                        token = String.Escape
+                    elif scanner.scan(r"'"):
+                        token = String
+                        stack.pop()
+                    elif scanner.scan(r"[^']*"):
+                        token = String
+                    else:
+                        scanner.get_char()
+                        stack.pop()
+            elif not self.is_portugol and stack[-1] == 'asm':
+                if scanner.scan(r'\s+'):
+                    token = Whitespace
+                elif scanner.scan(r'end'):
+                    token = Keyword
+                    stack.pop()
+                elif scanner.scan(r'\{.*?\}|\(\*.*?\*\)'):
+                    if scanner.match.startswith('$'):
+                        token = Comment.Preproc
+                    else:
+                        token = Comment.Multiline
+                elif scanner.scan(r'//.*?$'):
+                    token = Comment.Single
+                elif scanner.scan(r"'"):
+                    token = String
+                    stack.append('string')
+                elif scanner.scan(r'@@[A-Za-z_][A-Za-z_0-9]*'):
+                    token = Name.Label
+                elif scanner.scan(r'[A-Za-z_][A-Za-z_0-9]*'):
+                    lowercase_name = scanner.match.lower()
+                    if lowercase_name in self.ASM_INSTRUCTIONS:
+                        token = Keyword
+                    elif lowercase_name in self.ASM_REGISTERS:
+                        token = Name.Builtin
+                    else:
+                        token = Name
+                elif scanner.scan(r'[-+*\/=<>:;,.@\^]+'):
+                    token = Operator
+                elif scanner.scan(r'[\(\)\[\]]+'):
+                    token = Punctuation
+                elif scanner.scan(r'\$[0-9A-Fa-f]+'):
+                    token = Number.Hex
+                elif scanner.scan(r'\d+(?![eE]|\.[^.])'):
+                    token = Number.Integer
+                elif scanner.scan(r'\d+(\.\d+([eE][+-]?\d+)?|[eE][+-]?\d+)'):
+                    token = Number.Float
+                else:
+                    scanner.get_char()
+                    stack.pop()
+
+            # save the dot!!!11
+            if not self.is_portugol and scanner.match.strip():
+                was_dot = scanner.match == '.'
+
+            yield scanner.start_pos, token, scanner.match or ''
diff --git a/lib/python3.11/site-packages/pygments/lexers/pawn.py b/lib/python3.11/site-packages/pygments/lexers/pawn.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b4234c3a274ed46b01f0aee17df86e7868e1502
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/pawn.py
@@ -0,0 +1,202 @@
+"""
+    pygments.lexers.pawn
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Pawn languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+from pygments.util import get_bool_opt
+
+__all__ = ['SourcePawnLexer', 'PawnLexer']
+
+
+class SourcePawnLexer(RegexLexer):
+    """
+    For SourcePawn source code with preprocessor directives.
+    """
+    name = 'SourcePawn'
+    aliases = ['sp']
+    filenames = ['*.sp']
+    mimetypes = ['text/x-sourcepawn']
+    url = 'https://github.com/alliedmodders/sourcepawn'
+    version_added = '1.6'
+
+    #: optional Comment or Whitespace
+    _ws = r'(?:\s|//.*?\n|/\*.*?\*/)+'
+    #: only one /* */ style comment
+    _ws1 = r'\s*(?:/[*].*?[*]/\s*)*'
+
+    tokens = {
+        'root': [
+            # preprocessor directives: without whitespace
+            (r'^#if\s+0', Comment.Preproc, 'if0'),
+            ('^#', Comment.Preproc, 'macro'),
+            # or with whitespace
+            ('^' + _ws1 + r'#if\s+0', Comment.Preproc, 'if0'),
+            ('^' + _ws1 + '#', Comment.Preproc, 'macro'),
+            (r'\n', Text),
+            (r'\s+', Text),
+            (r'\\\n', Text),  # line continuation
+            (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single),
+            (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline),
+            (r'[{}]', Punctuation),
+            (r'L?"', String, 'string'),
+            (r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char),
+            (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float),
+            (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
+            (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex),
+            (r'0[0-7]+[LlUu]*', Number.Oct),
+            (r'\d+[LlUu]*', Number.Integer),
+            (r'[~!%^&*+=|?:<>/-]', Operator),
+            (r'[()\[\],.;]', Punctuation),
+            (r'(case|const|continue|native|'
+             r'default|else|enum|for|if|new|operator|'
+             r'public|return|sizeof|static|decl|struct|switch)\b', Keyword),
+            (r'(bool|Float)\b', Keyword.Type),
+            (r'(true|false)\b', Keyword.Constant),
+            (r'[a-zA-Z_]\w*', Name),
+        ],
+        'string': [
+            (r'"', String, '#pop'),
+            (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
+            (r'[^\\"\n]+', String),  # all other characters
+            (r'\\\n', String),       # line continuation
+            (r'\\', String),         # stray backslash
+        ],
+        'macro': [
+            (r'[^/\n]+', Comment.Preproc),
+            (r'/\*(.|\n)*?\*/', Comment.Multiline),
+            (r'//.*?\n', Comment.Single, '#pop'),
+            (r'/', Comment.Preproc),
+            (r'(?<=\\)\n', Comment.Preproc),
+            (r'\n', Comment.Preproc, '#pop'),
+        ],
+        'if0': [
+            (r'^\s*#if.*?(?/-]', Operator),
+            (r'[()\[\],.;]', Punctuation),
+            (r'(switch|case|default|const|new|static|char|continue|break|'
+             r'if|else|for|while|do|operator|enum|'
+             r'public|return|sizeof|tagof|state|goto)\b', Keyword),
+            (r'(bool|Float)\b', Keyword.Type),
+            (r'(true|false)\b', Keyword.Constant),
+            (r'[a-zA-Z_]\w*', Name),
+        ],
+        'string': [
+            (r'"', String, '#pop'),
+            (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
+            (r'[^\\"\n]+', String),  # all other characters
+            (r'\\\n', String),       # line continuation
+            (r'\\', String),         # stray backslash
+        ],
+        'macro': [
+            (r'[^/\n]+', Comment.Preproc),
+            (r'/\*(.|\n)*?\*/', Comment.Multiline),
+            (r'//.*?\n', Comment.Single, '#pop'),
+            (r'/', Comment.Preproc),
+            (r'(?<=\\)\n', Comment.Preproc),
+            (r'\n', Comment.Preproc, '#pop'),
+        ],
+        'if0': [
+            (r'^\s*#if.*?(?<-]', Operator),
+            (r'[a-zA-Z][a-zA-Z0-9_-]*', Name),
+            (r'\?[a-zA-Z][a-zA-Z0-9_-]*', Name.Variable),
+            (r'[0-9]+\.[0-9]+', Number.Float),
+            (r'[0-9]+', Number.Integer),
+        ],
+        'keywords': [
+            (words((
+                ':requirements', ':types', ':constants',
+                ':predicates', ':functions', ':action', ':agent',
+                ':parameters', ':precondition', ':effect',
+                ':durative-action', ':duration', ':condition',
+                ':derived', ':domain', ':objects', ':init',
+                ':goal', ':metric', ':length', ':serial', ':parallel',
+                # the following are requirements
+                ':strips', ':typing', ':negative-preconditions',
+                ':disjunctive-preconditions', ':equality',
+                ':existential-preconditions', ':universal-preconditions',
+                ':conditional-effects', ':fluents', ':numeric-fluents',
+                ':object-fluents', ':adl', ':durative-actions',
+                ':continuous-effects', ':derived-predicates',
+                ':time-intial-literals', ':preferences',
+                ':constraints', ':action-costs', ':multi-agent',
+                ':unfactored-privacy', ':factored-privacy',
+                ':non-deterministic'
+                ), suffix=r'\b'), Keyword)
+        ],
+        'builtins': [
+            (words((
+                'define', 'domain', 'object', 'either', 'and',
+                'forall', 'preference', 'imply', 'or', 'exists',
+                'not', 'when', 'assign', 'scale-up', 'scale-down',
+                'increase', 'decrease', 'at', 'over', 'start',
+                'end', 'all', 'problem', 'always', 'sometime',
+                'within', 'at-most-once', 'sometime-after',
+                'sometime-before', 'always-within', 'hold-during',
+                'hold-after', 'minimize', 'maximize',
+                'total-time', 'is-violated'), suffix=r'\b'),
+                Name.Builtin)
+        ]
+    }
+
diff --git a/lib/python3.11/site-packages/pygments/lexers/perl.py b/lib/python3.11/site-packages/pygments/lexers/perl.py
new file mode 100644
index 0000000000000000000000000000000000000000..7448d2a1e2bb822837079cfec4690b56825bf0b7
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/perl.py
@@ -0,0 +1,733 @@
+"""
+    pygments.lexers.perl
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Perl, Raku and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, ExtendedRegexLexer, include, bygroups, \
+    using, this, default, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Whitespace
+from pygments.util import shebang_matches
+
+__all__ = ['PerlLexer', 'Perl6Lexer']
+
+
+class PerlLexer(RegexLexer):
+    """
+    For Perl source code.
+    """
+
+    name = 'Perl'
+    url = 'https://www.perl.org'
+    aliases = ['perl', 'pl']
+    filenames = ['*.pl', '*.pm', '*.t', '*.perl']
+    mimetypes = ['text/x-perl', 'application/x-perl']
+    version_added = ''
+
+    flags = re.DOTALL | re.MULTILINE
+    # TODO: give this to a perl guy who knows how to parse perl...
+    tokens = {
+        'balanced-regex': [
+            (r'/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*', String.Regex, '#pop'),
+            (r'!(\\\\|\\[^\\]|[^\\!])*![egimosx]*', String.Regex, '#pop'),
+            (r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'),
+            (r'\{(\\\\|\\[^\\]|[^\\}])*\}[egimosx]*', String.Regex, '#pop'),
+            (r'<(\\\\|\\[^\\]|[^\\>])*>[egimosx]*', String.Regex, '#pop'),
+            (r'\[(\\\\|\\[^\\]|[^\\\]])*\][egimosx]*', String.Regex, '#pop'),
+            (r'\((\\\\|\\[^\\]|[^\\)])*\)[egimosx]*', String.Regex, '#pop'),
+            (r'@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*', String.Regex, '#pop'),
+            (r'%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*', String.Regex, '#pop'),
+            (r'\$(\\\\|\\[^\\]|[^\\$])*\$[egimosx]*', String.Regex, '#pop'),
+        ],
+        'root': [
+            (r'\A\#!.+?$', Comment.Hashbang),
+            (r'\#.*?$', Comment.Single),
+            (r'^=[a-zA-Z0-9]+\s+.*?\n=cut', Comment.Multiline),
+            (words((
+                'case', 'continue', 'do', 'else', 'elsif', 'for', 'foreach',
+                'if', 'last', 'my', 'next', 'our', 'redo', 'reset', 'then',
+                'unless', 'until', 'while', 'print', 'new', 'BEGIN',
+                'CHECK', 'INIT', 'END', 'return'), suffix=r'\b'),
+             Keyword),
+            (r'(format)(\s+)(\w+)(\s*)(=)(\s*\n)',
+             bygroups(Keyword, Whitespace, Name, Whitespace, Punctuation, Whitespace), 'format'),
+            (r'(eq|lt|gt|le|ge|ne|not|and|or|cmp)\b', Operator.Word),
+            # common delimiters
+            (r's/(\\\\|\\[^\\]|[^\\/])*/(\\\\|\\[^\\]|[^\\/])*/[egimosx]*',
+                String.Regex),
+            (r's!(\\\\|\\!|[^!])*!(\\\\|\\!|[^!])*![egimosx]*', String.Regex),
+            (r's\\(\\\\|[^\\])*\\(\\\\|[^\\])*\\[egimosx]*', String.Regex),
+            (r's@(\\\\|\\[^\\]|[^\\@])*@(\\\\|\\[^\\]|[^\\@])*@[egimosx]*',
+                String.Regex),
+            (r's%(\\\\|\\[^\\]|[^\\%])*%(\\\\|\\[^\\]|[^\\%])*%[egimosx]*',
+                String.Regex),
+            # balanced delimiters
+            (r's\{(\\\\|\\[^\\]|[^\\}])*\}\s*', String.Regex, 'balanced-regex'),
+            (r's<(\\\\|\\[^\\]|[^\\>])*>\s*', String.Regex, 'balanced-regex'),
+            (r's\[(\\\\|\\[^\\]|[^\\\]])*\]\s*', String.Regex,
+                'balanced-regex'),
+            (r's\((\\\\|\\[^\\]|[^\\)])*\)\s*', String.Regex,
+                'balanced-regex'),
+
+            (r'm?/(\\\\|\\[^\\]|[^\\/\n])*/[gcimosx]*', String.Regex),
+            (r'm(?=[/!\\{<\[(@%$])', String.Regex, 'balanced-regex'),
+            (r'((?<==~)|(?<=\())\s*/(\\\\|\\[^\\]|[^\\/])*/[gcimosx]*',
+                String.Regex),
+            (r'\s+', Whitespace),
+            (words((
+                'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir',
+                'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'close', 'closedir', 'connect',
+                'continue', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die',
+                'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent',
+                'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl',
+                'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid',
+                'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin',
+                'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp',
+                'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber',
+                'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname',
+                'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime',
+                'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'last',
+                'lc', 'lcfirst', 'length', 'link', 'listen', 'local', 'localtime', 'log', 'lstat',
+                'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'my', 'next', 'oct', 'open',
+                'opendir', 'ord', 'our', 'pack', 'pipe', 'pop', 'pos', 'printf',
+                'prototype', 'push', 'quotemeta', 'rand', 'read', 'readdir',
+                'readline', 'readlink', 'readpipe', 'recv', 'redo', 'ref', 'rename',
+                'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seek', 'seekdir',
+                'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent',
+                'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent',
+                'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown',
+                'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt',
+                'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysopen', 'sysread',
+                'sysseek', 'system', 'syswrite', 'tell', 'telldir', 'tie', 'tied', 'time', 'times', 'tr',
+                'truncate', 'uc', 'ucfirst', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie',
+                'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write'), suffix=r'\b'),
+             Name.Builtin),
+            (r'((__(DATA|DIE|WARN)__)|(STD(IN|OUT|ERR)))\b', Name.Builtin.Pseudo),
+            (r'(<<)([\'"]?)([a-zA-Z_]\w*)(\2;?\n.*?\n)(\3)(\n)',
+             bygroups(String, String, String.Delimiter, String, String.Delimiter, Whitespace)),
+            (r'__END__', Comment.Preproc, 'end-part'),
+            (r'\$\^[ADEFHILMOPSTWX]', Name.Variable.Global),
+            (r"\$[\\\"\[\]'&`+*.,;=%~?@$!<>(^|/-](?!\w)", Name.Variable.Global),
+            (r'[$@%#]+', Name.Variable, 'varname'),
+            (r'0_?[0-7]+(_[0-7]+)*', Number.Oct),
+            (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex),
+            (r'0b[01]+(_[01]+)*', Number.Bin),
+            (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?',
+             Number.Float),
+            (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float),
+            (r'\d+(_\d+)*', Number.Integer),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
+            (r'`(\\\\|\\[^\\]|[^`\\])*`', String.Backtick),
+            (r'<([^\s>]+)>', String.Regex),
+            (r'(q|qq|qw|qr|qx)\{', String.Other, 'cb-string'),
+            (r'(q|qq|qw|qr|qx)\(', String.Other, 'rb-string'),
+            (r'(q|qq|qw|qr|qx)\[', String.Other, 'sb-string'),
+            (r'(q|qq|qw|qr|qx)\<', String.Other, 'lt-string'),
+            (r'(q|qq|qw|qr|qx)([\W_])(.|\n)*?\2', String.Other),
+            (r'(package)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)',
+             bygroups(Keyword, Whitespace, Name.Namespace)),
+            (r'(use|require|no)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)',
+             bygroups(Keyword, Whitespace, Name.Namespace)),
+            (r'(sub)(\s+)', bygroups(Keyword, Whitespace), 'funcname'),
+            (words((
+                'no', 'package', 'require', 'use'), suffix=r'\b'),
+             Keyword),
+            (r'(\[\]|\*\*|::|<<|>>|>=|<=>|<=|={3}|!=|=~|'
+             r'!~|&&?|\|\||\.{1,3})', Operator),
+            (r'[-+/*%=<>&^|!\\~]=?', Operator),
+            (r'[()\[\]:;,<>/?{}]', Punctuation),  # yes, there's no shortage
+                                                  # of punctuation in Perl!
+            (r'(?=\w)', Name, 'name'),
+        ],
+        'format': [
+            (r'\.\n', String.Interpol, '#pop'),
+            (r'[^\n]*\n', String.Interpol),
+        ],
+        'varname': [
+            (r'\s+', Whitespace),
+            (r'\{', Punctuation, '#pop'),    # hash syntax?
+            (r'\)|,', Punctuation, '#pop'),  # argument specifier
+            (r'\w+::', Name.Namespace),
+            (r'[\w:]+', Name.Variable, '#pop'),
+        ],
+        'name': [
+            (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*(::)?(?=\s*->)', Name.Namespace, '#pop'),
+            (r'[a-zA-Z_]\w*(::[a-zA-Z_]\w*)*::', Name.Namespace, '#pop'),
+            (r'[\w:]+', Name, '#pop'),
+            (r'[A-Z_]+(?=\W)', Name.Constant, '#pop'),
+            (r'(?=\W)', Text, '#pop'),
+        ],
+        'funcname': [
+            (r'[a-zA-Z_]\w*[!?]?', Name.Function),
+            (r'\s+', Whitespace),
+            # argument declaration
+            (r'(\([$@%]*\))(\s*)', bygroups(Punctuation, Whitespace)),
+            (r';', Punctuation, '#pop'),
+            (r'.*?\{', Punctuation, '#pop'),
+        ],
+        'cb-string': [
+            (r'\\[{}\\]', String.Other),
+            (r'\\', String.Other),
+            (r'\{', String.Other, 'cb-string'),
+            (r'\}', String.Other, '#pop'),
+            (r'[^{}\\]+', String.Other)
+        ],
+        'rb-string': [
+            (r'\\[()\\]', String.Other),
+            (r'\\', String.Other),
+            (r'\(', String.Other, 'rb-string'),
+            (r'\)', String.Other, '#pop'),
+            (r'[^()]+', String.Other)
+        ],
+        'sb-string': [
+            (r'\\[\[\]\\]', String.Other),
+            (r'\\', String.Other),
+            (r'\[', String.Other, 'sb-string'),
+            (r'\]', String.Other, '#pop'),
+            (r'[^\[\]]+', String.Other)
+        ],
+        'lt-string': [
+            (r'\\[<>\\]', String.Other),
+            (r'\\', String.Other),
+            (r'\<', String.Other, 'lt-string'),
+            (r'\>', String.Other, '#pop'),
+            (r'[^<>]+', String.Other)
+        ],
+        'end-part': [
+            (r'.+', Comment.Preproc, '#pop')
+        ]
+    }
+
+    def analyse_text(text):
+        if shebang_matches(text, r'perl'):
+            return True
+
+        result = 0
+
+        if re.search(r'(?:my|our)\s+[$@%(]', text):
+            result += 0.9
+
+        if ':=' in text:
+            # := is not valid Perl, but it appears in unicon, so we should
+            # become less confident if we think we found Perl with :=
+            result /= 2
+
+        return result
+
+
+class Perl6Lexer(ExtendedRegexLexer):
+    """
+    For Raku (a.k.a. Perl 6) source code.
+    """
+
+    name = 'Perl6'
+    url = 'https://www.raku.org'
+    aliases = ['perl6', 'pl6', 'raku']
+    filenames = ['*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6',
+                 '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod',
+                 '*.rakutest', '*.rakudoc']
+    mimetypes = ['text/x-perl6', 'application/x-perl6']
+    version_added = '2.0'
+    flags = re.MULTILINE | re.DOTALL
+
+    PERL6_IDENTIFIER_RANGE = r"['\w:-]"
+
+    PERL6_KEYWORDS = (
+        #Phasers
+        'BEGIN','CATCH','CHECK','CLOSE','CONTROL','DOC','END','ENTER','FIRST',
+        'INIT','KEEP','LAST','LEAVE','NEXT','POST','PRE','QUIT','UNDO',
+        #Keywords
+        'anon','augment','but','class','constant','default','does','else',
+        'elsif','enum','for','gather','given','grammar','has','if','import',
+        'is','let','loop','made','make','method','module','multi','my','need',
+        'orwith','our','proceed','proto','repeat','require','return',
+        'return-rw','returns','role','rule','state','sub','submethod','subset',
+        'succeed','supersede','token','try','unit','unless','until','use',
+        'when','while','with','without',
+        #Traits
+        'export','native','repr','required','rw','symbol',
+    )
+
+    PERL6_BUILTINS = (
+        'ACCEPTS','abs','abs2rel','absolute','accept','accessed','acos',
+        'acosec','acosech','acosh','acotan','acotanh','acquire','act','action',
+        'actions','add','add_attribute','add_enum_value','add_fallback',
+        'add_method','add_parent','add_private_method','add_role','add_trustee',
+        'adverb','after','all','allocate','allof','allowed','alternative-names',
+        'annotations','antipair','antipairs','any','anyof','app_lifetime',
+        'append','arch','archname','args','arity','Array','asec','asech','asin',
+        'asinh','ASSIGN-KEY','ASSIGN-POS','assuming','ast','at','atan','atan2',
+        'atanh','AT-KEY','atomic-assign','atomic-dec-fetch','atomic-fetch',
+        'atomic-fetch-add','atomic-fetch-dec','atomic-fetch-inc',
+        'atomic-fetch-sub','atomic-inc-fetch','AT-POS','attributes','auth',
+        'await','backtrace','Bag','BagHash','bail-out','base','basename',
+        'base-repeating','batch','BIND-KEY','BIND-POS','bind-stderr',
+        'bind-stdin','bind-stdout','bind-udp','bits','bless','block','Bool',
+        'bool-only','bounds','break','Bridge','broken','BUILD','build-date',
+        'bytes','cache','callframe','calling-package','CALL-ME','callsame',
+        'callwith','can','cancel','candidates','cando','can-ok','canonpath',
+        'caps','caption','Capture','cas','catdir','categorize','categorize-list',
+        'catfile','catpath','cause','ceiling','cglobal','changed','Channel',
+        'chars','chdir','child','child-name','child-typename','chmod','chomp',
+        'chop','chr','chrs','chunks','cis','classify','classify-list','cleanup',
+        'clone','close','closed','close-stdin','cmp-ok','code','codes','collate',
+        'column','comb','combinations','command','comment','compiler','Complex',
+        'compose','compose_type','composer','condition','config',
+        'configure_destroy','configure_type_checking','conj','connect',
+        'constraints','construct','contains','contents','copy','cos','cosec',
+        'cosech','cosh','cotan','cotanh','count','count-only','cpu-cores',
+        'cpu-usage','CREATE','create_type','cross','cue','curdir','curupdir','d',
+        'Date','DateTime','day','daycount','day-of-month','day-of-week',
+        'day-of-year','days-in-month','declaration','decode','decoder','deepmap',
+        'default','defined','DEFINITE','delayed','DELETE-KEY','DELETE-POS',
+        'denominator','desc','DESTROY','destroyers','devnull','diag',
+        'did-you-mean','die','dies-ok','dir','dirname','dir-sep','DISTROnames',
+        'do','does','does-ok','done','done-testing','duckmap','dynamic','e',
+        'eager','earlier','elems','emit','enclosing','encode','encoder',
+        'encoding','end','ends-with','enum_from_value','enum_value_list',
+        'enum_values','enums','eof','EVAL','eval-dies-ok','EVALFILE',
+        'eval-lives-ok','exception','excludes-max','excludes-min','EXISTS-KEY',
+        'EXISTS-POS','exit','exitcode','exp','expected','explicitly-manage',
+        'expmod','extension','f','fail','fails-like','fc','feature','file',
+        'filename','find_method','find_method_qualified','finish','first','flat',
+        'flatmap','flip','floor','flunk','flush','fmt','format','formatter',
+        'freeze','from','from-list','from-loop','from-posix','full',
+        'full-barrier','get','get_value','getc','gist','got','grab','grabpairs',
+        'grep','handle','handled','handles','hardware','has_accessor','Hash',
+        'head','headers','hh-mm-ss','hidden','hides','hour','how','hyper','id',
+        'illegal','im','in','indent','index','indices','indir','infinite',
+        'infix','infix:<+>','infix:<->','install_method_cache','Instant',
+        'instead','Int','int-bounds','interval','in-timezone','invalid-str',
+        'invert','invocant','IO','IO::Notification.watch-path','is_trusted',
+        'is_type','isa','is-absolute','isa-ok','is-approx','is-deeply',
+        'is-hidden','is-initial-thread','is-int','is-lazy','is-leap-year',
+        'isNaN','isnt','is-prime','is-relative','is-routine','is-setting',
+        'is-win','item','iterator','join','keep','kept','KERNELnames','key',
+        'keyof','keys','kill','kv','kxxv','l','lang','last','lastcall','later',
+        'lazy','lc','leading','level','like','line','lines','link','List',
+        'listen','live','lives-ok','local','lock','log','log10','lookup','lsb',
+        'made','MAIN','make','Map','match','max','maxpairs','merge','message',
+        'method','method_table','methods','migrate','min','minmax','minpairs',
+        'minute','misplaced','Mix','MixHash','mkdir','mode','modified','month',
+        'move','mro','msb','multi','multiness','my','name','named','named_names',
+        'narrow','nativecast','native-descriptor','nativesizeof','new','new_type',
+        'new-from-daycount','new-from-pairs','next','nextcallee','next-handle',
+        'nextsame','nextwith','NFC','NFD','NFKC','NFKD','nl-in','nl-out',
+        'nodemap','nok','none','norm','not','note','now','nude','Num',
+        'numerator','Numeric','of','offset','offset-in-hours','offset-in-minutes',
+        'ok','old','on-close','one','on-switch','open','opened','operation',
+        'optional','ord','ords','orig','os-error','osname','out-buffer','pack',
+        'package','package-kind','package-name','packages','pair','pairs',
+        'pairup','parameter','params','parent','parent-name','parents','parse',
+        'parse-base','parsefile','parse-names','parts','pass','path','path-sep',
+        'payload','peer-host','peer-port','periods','perl','permutations','phaser',
+        'pick','pickpairs','pid','placeholder','plan','plus','polar','poll',
+        'polymod','pop','pos','positional','posix','postfix','postmatch',
+        'precomp-ext','precomp-target','pred','prefix','prematch','prepend',
+        'print','printf','print-nl','print-to','private','private_method_table',
+        'proc','produce','Promise','prompt','protect','pull-one','push',
+        'push-all','push-at-least','push-exactly','push-until-lazy','put',
+        'qualifier-type','quit','r','race','radix','rand','range','Rat','raw',
+        're','read','readchars','readonly','ready','Real','reallocate','reals',
+        'reason','rebless','receive','recv','redispatcher','redo','reduce',
+        'rel2abs','relative','release','rename','repeated','replacement',
+        'report','reserved','resolve','restore','result','resume','rethrow',
+        'reverse','right','rindex','rmdir','role','roles_to_compose','rolish',
+        'roll','rootdir','roots','rotate','rotor','round','roundrobin',
+        'routine-type','run','rwx','s','samecase','samemark','samewith','say',
+        'schedule-on','scheduler','scope','sec','sech','second','seek','self',
+        'send','Set','set_hidden','set_name','set_package','set_rw','set_value',
+        'SetHash','set-instruments','setup_finalization','shape','share','shell',
+        'shift','sibling','sigil','sign','signal','signals','signature','sin',
+        'sinh','sink','sink-all','skip','skip-at-least','skip-at-least-pull-one',
+        'skip-one','skip-rest','sleep','sleep-timer','sleep-until','Slip','slurp',
+        'slurp-rest','slurpy','snap','snapper','so','socket-host','socket-port',
+        'sort','source','source-package','spawn','SPEC','splice','split',
+        'splitdir','splitpath','sprintf','spurt','sqrt','squish','srand','stable',
+        'start','started','starts-with','status','stderr','stdout','Str',
+        'sub_signature','subbuf','subbuf-rw','subname','subparse','subst',
+        'subst-mutate','substr','substr-eq','substr-rw','subtest','succ','sum',
+        'Supply','symlink','t','tail','take','take-rw','tan','tanh','tap',
+        'target','target-name','tc','tclc','tell','then','throttle','throw',
+        'throws-like','timezone','tmpdir','to','today','todo','toggle','to-posix',
+        'total','trailing','trans','tree','trim','trim-leading','trim-trailing',
+        'truncate','truncated-to','trusts','try_acquire','trying','twigil','type',
+        'type_captures','typename','uc','udp','uncaught_handler','unimatch',
+        'uniname','uninames','uniparse','uniprop','uniprops','unique','unival',
+        'univals','unlike','unlink','unlock','unpack','unpolar','unshift',
+        'unwrap','updir','USAGE','use-ok','utc','val','value','values','VAR',
+        'variable','verbose-config','version','VMnames','volume','vow','w','wait',
+        'warn','watch','watch-path','week','weekday-of-month','week-number',
+        'week-year','WHAT','when','WHERE','WHEREFORE','WHICH','WHO',
+        'whole-second','WHY','wordcase','words','workaround','wrap','write',
+        'write-to','x','yada','year','yield','yyyy-mm-dd','z','zip','zip-latest',
+
+    )
+
+    PERL6_BUILTIN_CLASSES = (
+        #Booleans
+        'False','True',
+        #Classes
+        'Any','Array','Associative','AST','atomicint','Attribute','Backtrace',
+        'Backtrace::Frame','Bag','Baggy','BagHash','Blob','Block','Bool','Buf',
+        'Callable','CallFrame','Cancellation','Capture','CArray','Channel','Code',
+        'compiler','Complex','ComplexStr','Cool','CurrentThreadScheduler',
+        'Cursor','Date','Dateish','DateTime','Distro','Duration','Encoding',
+        'Exception','Failure','FatRat','Grammar','Hash','HyperWhatever','Instant',
+        'Int','int16','int32','int64','int8','IntStr','IO','IO::ArgFiles',
+        'IO::CatHandle','IO::Handle','IO::Notification','IO::Path',
+        'IO::Path::Cygwin','IO::Path::QNX','IO::Path::Unix','IO::Path::Win32',
+        'IO::Pipe','IO::Socket','IO::Socket::Async','IO::Socket::INET','IO::Spec',
+        'IO::Spec::Cygwin','IO::Spec::QNX','IO::Spec::Unix','IO::Spec::Win32',
+        'IO::Special','Iterable','Iterator','Junction','Kernel','Label','List',
+        'Lock','Lock::Async','long','longlong','Macro','Map','Match',
+        'Metamodel::AttributeContainer','Metamodel::C3MRO','Metamodel::ClassHOW',
+        'Metamodel::EnumHOW','Metamodel::Finalization','Metamodel::MethodContainer',
+        'Metamodel::MROBasedMethodDispatch','Metamodel::MultipleInheritance',
+        'Metamodel::Naming','Metamodel::Primitives','Metamodel::PrivateMethodContainer',
+        'Metamodel::RoleContainer','Metamodel::Trusting','Method','Mix','MixHash',
+        'Mixy','Mu','NFC','NFD','NFKC','NFKD','Nil','Num','num32','num64',
+        'Numeric','NumStr','ObjAt','Order','Pair','Parameter','Perl','Pod::Block',
+        'Pod::Block::Code','Pod::Block::Comment','Pod::Block::Declarator',
+        'Pod::Block::Named','Pod::Block::Para','Pod::Block::Table','Pod::Heading',
+        'Pod::Item','Pointer','Positional','PositionalBindFailover','Proc',
+        'Proc::Async','Promise','Proxy','PseudoStash','QuantHash','Range','Rat',
+        'Rational','RatStr','Real','Regex','Routine','Scalar','Scheduler',
+        'Semaphore','Seq','Set','SetHash','Setty','Signature','size_t','Slip',
+        'Stash','Str','StrDistance','Stringy','Sub','Submethod','Supplier',
+        'Supplier::Preserving','Supply','Systemic','Tap','Telemetry',
+        'Telemetry::Instrument::Thread','Telemetry::Instrument::Usage',
+        'Telemetry::Period','Telemetry::Sampler','Thread','ThreadPoolScheduler',
+        'UInt','uint16','uint32','uint64','uint8','Uni','utf8','Variable',
+        'Version','VM','Whatever','WhateverCode','WrapHandle'
+    )
+
+    PERL6_OPERATORS = (
+        'X', 'Z', 'after', 'also', 'and', 'andthen', 'before', 'cmp', 'div',
+        'eq', 'eqv', 'extra', 'ff', 'fff', 'ge', 'gt', 'le', 'leg', 'lt', 'm',
+        'mm', 'mod', 'ne', 'or', 'orelse', 'rx', 's', 'tr', 'x', 'xor', 'xx',
+        '++', '--', '**', '!', '+', '-', '~', '?', '|', '||', '+^', '~^', '?^',
+        '^', '*', '/', '%', '%%', '+&', '+<', '+>', '~&', '~<', '~>', '?&',
+        'gcd', 'lcm', '+', '-', '+|', '+^', '~|', '~^', '?|', '?^',
+        '~', '&', '^', 'but', 'does', '<=>', '..', '..^', '^..', '^..^',
+        '!=', '==', '<', '<=', '>', '>=', '~~', '===', '!eqv',
+        '&&', '||', '^^', '//', 'min', 'max', '??', '!!', 'ff', 'fff', 'so',
+        'not', '<==', '==>', '<<==', '==>>','unicmp',
+    )
+
+    # Perl 6 has a *lot* of possible bracketing characters
+    # this list was lifted from STD.pm6 (https://github.com/perl6/std)
+    PERL6_BRACKETS = {
+        '\u0028': '\u0029', '\u003c': '\u003e', '\u005b': '\u005d',
+        '\u007b': '\u007d', '\u00ab': '\u00bb', '\u0f3a': '\u0f3b',
+        '\u0f3c': '\u0f3d', '\u169b': '\u169c', '\u2018': '\u2019',
+        '\u201a': '\u2019', '\u201b': '\u2019', '\u201c': '\u201d',
+        '\u201e': '\u201d', '\u201f': '\u201d', '\u2039': '\u203a',
+        '\u2045': '\u2046', '\u207d': '\u207e', '\u208d': '\u208e',
+        '\u2208': '\u220b', '\u2209': '\u220c', '\u220a': '\u220d',
+        '\u2215': '\u29f5', '\u223c': '\u223d', '\u2243': '\u22cd',
+        '\u2252': '\u2253', '\u2254': '\u2255', '\u2264': '\u2265',
+        '\u2266': '\u2267', '\u2268': '\u2269', '\u226a': '\u226b',
+        '\u226e': '\u226f', '\u2270': '\u2271', '\u2272': '\u2273',
+        '\u2274': '\u2275', '\u2276': '\u2277', '\u2278': '\u2279',
+        '\u227a': '\u227b', '\u227c': '\u227d', '\u227e': '\u227f',
+        '\u2280': '\u2281', '\u2282': '\u2283', '\u2284': '\u2285',
+        '\u2286': '\u2287', '\u2288': '\u2289', '\u228a': '\u228b',
+        '\u228f': '\u2290', '\u2291': '\u2292', '\u2298': '\u29b8',
+        '\u22a2': '\u22a3', '\u22a6': '\u2ade', '\u22a8': '\u2ae4',
+        '\u22a9': '\u2ae3', '\u22ab': '\u2ae5', '\u22b0': '\u22b1',
+        '\u22b2': '\u22b3', '\u22b4': '\u22b5', '\u22b6': '\u22b7',
+        '\u22c9': '\u22ca', '\u22cb': '\u22cc', '\u22d0': '\u22d1',
+        '\u22d6': '\u22d7', '\u22d8': '\u22d9', '\u22da': '\u22db',
+        '\u22dc': '\u22dd', '\u22de': '\u22df', '\u22e0': '\u22e1',
+        '\u22e2': '\u22e3', '\u22e4': '\u22e5', '\u22e6': '\u22e7',
+        '\u22e8': '\u22e9', '\u22ea': '\u22eb', '\u22ec': '\u22ed',
+        '\u22f0': '\u22f1', '\u22f2': '\u22fa', '\u22f3': '\u22fb',
+        '\u22f4': '\u22fc', '\u22f6': '\u22fd', '\u22f7': '\u22fe',
+        '\u2308': '\u2309', '\u230a': '\u230b', '\u2329': '\u232a',
+        '\u23b4': '\u23b5', '\u2768': '\u2769', '\u276a': '\u276b',
+        '\u276c': '\u276d', '\u276e': '\u276f', '\u2770': '\u2771',
+        '\u2772': '\u2773', '\u2774': '\u2775', '\u27c3': '\u27c4',
+        '\u27c5': '\u27c6', '\u27d5': '\u27d6', '\u27dd': '\u27de',
+        '\u27e2': '\u27e3', '\u27e4': '\u27e5', '\u27e6': '\u27e7',
+        '\u27e8': '\u27e9', '\u27ea': '\u27eb', '\u2983': '\u2984',
+        '\u2985': '\u2986', '\u2987': '\u2988', '\u2989': '\u298a',
+        '\u298b': '\u298c', '\u298d': '\u298e', '\u298f': '\u2990',
+        '\u2991': '\u2992', '\u2993': '\u2994', '\u2995': '\u2996',
+        '\u2997': '\u2998', '\u29c0': '\u29c1', '\u29c4': '\u29c5',
+        '\u29cf': '\u29d0', '\u29d1': '\u29d2', '\u29d4': '\u29d5',
+        '\u29d8': '\u29d9', '\u29da': '\u29db', '\u29f8': '\u29f9',
+        '\u29fc': '\u29fd', '\u2a2b': '\u2a2c', '\u2a2d': '\u2a2e',
+        '\u2a34': '\u2a35', '\u2a3c': '\u2a3d', '\u2a64': '\u2a65',
+        '\u2a79': '\u2a7a', '\u2a7d': '\u2a7e', '\u2a7f': '\u2a80',
+        '\u2a81': '\u2a82', '\u2a83': '\u2a84', '\u2a8b': '\u2a8c',
+        '\u2a91': '\u2a92', '\u2a93': '\u2a94', '\u2a95': '\u2a96',
+        '\u2a97': '\u2a98', '\u2a99': '\u2a9a', '\u2a9b': '\u2a9c',
+        '\u2aa1': '\u2aa2', '\u2aa6': '\u2aa7', '\u2aa8': '\u2aa9',
+        '\u2aaa': '\u2aab', '\u2aac': '\u2aad', '\u2aaf': '\u2ab0',
+        '\u2ab3': '\u2ab4', '\u2abb': '\u2abc', '\u2abd': '\u2abe',
+        '\u2abf': '\u2ac0', '\u2ac1': '\u2ac2', '\u2ac3': '\u2ac4',
+        '\u2ac5': '\u2ac6', '\u2acd': '\u2ace', '\u2acf': '\u2ad0',
+        '\u2ad1': '\u2ad2', '\u2ad3': '\u2ad4', '\u2ad5': '\u2ad6',
+        '\u2aec': '\u2aed', '\u2af7': '\u2af8', '\u2af9': '\u2afa',
+        '\u2e02': '\u2e03', '\u2e04': '\u2e05', '\u2e09': '\u2e0a',
+        '\u2e0c': '\u2e0d', '\u2e1c': '\u2e1d', '\u2e20': '\u2e21',
+        '\u3008': '\u3009', '\u300a': '\u300b', '\u300c': '\u300d',
+        '\u300e': '\u300f', '\u3010': '\u3011', '\u3014': '\u3015',
+        '\u3016': '\u3017', '\u3018': '\u3019', '\u301a': '\u301b',
+        '\u301d': '\u301e', '\ufd3e': '\ufd3f', '\ufe17': '\ufe18',
+        '\ufe35': '\ufe36', '\ufe37': '\ufe38', '\ufe39': '\ufe3a',
+        '\ufe3b': '\ufe3c', '\ufe3d': '\ufe3e', '\ufe3f': '\ufe40',
+        '\ufe41': '\ufe42', '\ufe43': '\ufe44', '\ufe47': '\ufe48',
+        '\ufe59': '\ufe5a', '\ufe5b': '\ufe5c', '\ufe5d': '\ufe5e',
+        '\uff08': '\uff09', '\uff1c': '\uff1e', '\uff3b': '\uff3d',
+        '\uff5b': '\uff5d', '\uff5f': '\uff60', '\uff62': '\uff63',
+    }
+
+    def _build_word_match(words, boundary_regex_fragment=None, prefix='', suffix=''):
+        if boundary_regex_fragment is None:
+            return r'\b(' + prefix + r'|'.join(re.escape(x) for x in words) + \
+                suffix + r')\b'
+        else:
+            return r'(? 0:
+                    next_open_pos = text.find(opening_chars, search_pos + n_chars)
+                    next_close_pos = text.find(closing_chars, search_pos + n_chars)
+
+                    if next_close_pos == -1:
+                        next_close_pos = len(text)
+                        nesting_level = 0
+                    elif next_open_pos != -1 and next_open_pos < next_close_pos:
+                        nesting_level += 1
+                        search_pos = next_open_pos
+                    else:  # next_close_pos < next_open_pos
+                        nesting_level -= 1
+                        search_pos = next_close_pos
+
+                end_pos = next_close_pos
+
+            if end_pos < 0:     # if we didn't find a closer, just highlight the
+                                # rest of the text in this class
+                end_pos = len(text)
+
+            if adverbs is not None and re.search(r':to\b', adverbs):
+                heredoc_terminator = text[match.start('delimiter') + n_chars:end_pos]
+                end_heredoc = re.search(r'^\s*' + re.escape(heredoc_terminator) +
+                                        r'\s*$', text[end_pos:], re.MULTILINE)
+
+                if end_heredoc:
+                    end_pos += end_heredoc.end()
+                else:
+                    end_pos = len(text)
+
+            yield match.start(), token_class, text[match.start():end_pos + n_chars]
+            context.pos = end_pos + n_chars
+
+        return callback
+
+    def opening_brace_callback(lexer, match, context):
+        stack = context.stack
+
+        yield match.start(), Text, context.text[match.start():match.end()]
+        context.pos = match.end()
+
+        # if we encounter an opening brace and we're one level
+        # below a token state, it means we need to increment
+        # the nesting level for braces so we know later when
+        # we should return to the token rules.
+        if len(stack) > 2 and stack[-2] == 'token':
+            context.perl6_token_nesting_level += 1
+
+    def closing_brace_callback(lexer, match, context):
+        stack = context.stack
+
+        yield match.start(), Text, context.text[match.start():match.end()]
+        context.pos = match.end()
+
+        # if we encounter a free closing brace and we're one level
+        # below a token state, it means we need to check the nesting
+        # level to see if we need to return to the token state.
+        if len(stack) > 2 and stack[-2] == 'token':
+            context.perl6_token_nesting_level -= 1
+            if context.perl6_token_nesting_level == 0:
+                stack.pop()
+
+    def embedded_perl6_callback(lexer, match, context):
+        context.perl6_token_nesting_level = 1
+        yield match.start(), Text, context.text[match.start():match.end()]
+        context.pos = match.end()
+        context.stack.append('root')
+
+    # If you're modifying these rules, be careful if you need to process '{' or '}'
+    # characters. We have special logic for processing these characters (due to the fact
+    # that you can nest Perl 6 code in regex blocks), so if you need to process one of
+    # them, make sure you also process the corresponding one!
+    tokens = {
+        'common': [
+            (r'#[`|=](?P(?P[' + ''.join(PERL6_BRACKETS) + r'])(?P=first_char)*)',
+             brackets_callback(Comment.Multiline)),
+            (r'#[^\n]*$', Comment.Single),
+            (r'^(\s*)=begin\s+(\w+)\b.*?^\1=end\s+\2', Comment.Multiline),
+            (r'^(\s*)=for.*?\n\s*?\n', Comment.Multiline),
+            (r'^=.*?\n\s*?\n', Comment.Multiline),
+            (r'(regex|token|rule)(\s*' + PERL6_IDENTIFIER_RANGE + '+:sym)',
+             bygroups(Keyword, Name), 'token-sym-brackets'),
+            (r'(regex|token|rule)(?!' + PERL6_IDENTIFIER_RANGE + r')(\s*' + PERL6_IDENTIFIER_RANGE + '+)?',
+             bygroups(Keyword, Name), 'pre-token'),
+            # deal with a special case in the Perl 6 grammar (role q { ... })
+            (r'(role)(\s+)(q)(\s*)', bygroups(Keyword, Whitespace, Name, Whitespace)),
+            (_build_word_match(PERL6_KEYWORDS, PERL6_IDENTIFIER_RANGE), Keyword),
+            (_build_word_match(PERL6_BUILTIN_CLASSES, PERL6_IDENTIFIER_RANGE, suffix='(?::[UD])?'),
+             Name.Builtin),
+            (_build_word_match(PERL6_BUILTINS, PERL6_IDENTIFIER_RANGE), Name.Builtin),
+            # copied from PerlLexer
+            (r'[$@%&][.^:?=!~]?' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*',
+             Name.Variable),
+            (r'\$[!/](?:<<.*?>>|<.*?>|«.*?»)*', Name.Variable.Global),
+            (r'::\?\w+', Name.Variable.Global),
+            (r'[$@%&]\*' + PERL6_IDENTIFIER_RANGE + '+(?:<<.*?>>|<.*?>|«.*?»)*',
+             Name.Variable.Global),
+            (r'\$(?:<.*?>)+', Name.Variable),
+            (r'(?:q|qq|Q)[a-zA-Z]?\s*(?P:[\w\s:]+)?\s*(?P(?P[^0-9a-zA-Z:\s])'
+             r'(?P=first_char)*)', brackets_callback(String)),
+            # copied from PerlLexer
+            (r'0_?[0-7]+(_[0-7]+)*', Number.Oct),
+            (r'0x[0-9A-Fa-f]+(_[0-9A-Fa-f]+)*', Number.Hex),
+            (r'0b[01]+(_[01]+)*', Number.Bin),
+            (r'(?i)(\d*(_\d*)*\.\d+(_\d*)*|\d+(_\d*)*\.\d+(_\d*)*)(e[+-]?\d+)?',
+             Number.Float),
+            (r'(?i)\d+(_\d*)*e[+-]?\d+(_\d*)*', Number.Float),
+            (r'\d+(_\d+)*', Number.Integer),
+            (r'(?<=~~)\s*/(?:\\\\|\\/|.)*?/', String.Regex),
+            (r'(?<=[=(,])\s*/(?:\\\\|\\/|.)*?/', String.Regex),
+            (r'm\w+(?=\()', Name),
+            (r'(?:m|ms|rx)\s*(?P:[\w\s:]+)?\s*(?P(?P[^\w:\s])'
+             r'(?P=first_char)*)', brackets_callback(String.Regex)),
+            (r'(?:s|ss|tr)\s*(?::[\w\s:]+)?\s*/(?:\\\\|\\/|.)*?/(?:\\\\|\\/|.)*?/',
+             String.Regex),
+            (r'<[^\s=].*?\S>', String),
+            (_build_word_match(PERL6_OPERATORS), Operator),
+            (r'\w' + PERL6_IDENTIFIER_RANGE + '*', Name),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
+        ],
+        'root': [
+            include('common'),
+            (r'\{', opening_brace_callback),
+            (r'\}', closing_brace_callback),
+            (r'.+?', Text),
+        ],
+        'pre-token': [
+            include('common'),
+            (r'\{', Text, ('#pop', 'token')),
+            (r'.+?', Text),
+        ],
+        'token-sym-brackets': [
+            (r'(?P(?P[' + ''.join(PERL6_BRACKETS) + '])(?P=first_char)*)',
+             brackets_callback(Name), ('#pop', 'pre-token')),
+            default(('#pop', 'pre-token')),
+        ],
+        'token': [
+            (r'\}', Text, '#pop'),
+            (r'(?<=:)(?:my|our|state|constant|temp|let).*?;', using(this)),
+            # make sure that quotes in character classes aren't treated as strings
+            (r'<(?:[-!?+.]\s*)?\[.*?\]>', String.Regex),
+            # make sure that '#' characters in quotes aren't treated as comments
+            (r"(?my|our)\s+)?(?:module|class|role|enum|grammar)', line)
+            if class_decl:
+                if saw_perl_decl or class_decl.group('scope') is not None:
+                    return True
+                rating = 0.05
+                continue
+            break
+
+        if ':=' in text:
+            # Same logic as above for PerlLexer
+            rating /= 2
+
+        return rating
+
+    def __init__(self, **options):
+        super().__init__(**options)
+        self.encoding = options.get('encoding', 'utf-8')
diff --git a/lib/python3.11/site-packages/pygments/lexers/phix.py b/lib/python3.11/site-packages/pygments/lexers/phix.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4cb35d5b13c96d4619a2801715117b788b47226
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/phix.py
@@ -0,0 +1,363 @@
+"""
+    pygments.lexers.phix
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Phix.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Whitespace
+
+__all__ = ['PhixLexer']
+
+
+class PhixLexer(RegexLexer):
+    """
+    Pygments Lexer for Phix files (.exw).
+    See http://phix.x10.mx
+    """
+
+    name = 'Phix'
+    url = 'http://phix.x10.mx'
+    aliases = ['phix']
+    filenames = ['*.exw']
+    mimetypes = ['text/x-phix']
+    version_added = '2.14'
+
+    flags = re.MULTILINE    # nb: **NOT** re.DOTALL! (totally spanners comment handling)
+
+    preproc = (
+        'ifdef', 'elsifdef', 'elsedef'
+    )
+    # Note these lists are auto-generated by pwa/p2js.exw, when pwa\src\p2js_keywords.e (etc)
+    #     change, though of course subsequent copy/commit/pull requests are all manual steps.
+    types = (
+        'string', 'nullable_string', 'atom_string', 'atom', 'bool', 'boolean',
+        'cdCanvan', 'cdCanvas', 'complex', 'CURLcode', 'dictionary', 'int',
+        'integer', 'Ihandle', 'Ihandles', 'Ihandln', 'mpfr', 'mpq', 'mpz',
+        'mpz_or_string', 'number', 'rid_string', 'seq', 'sequence', 'timedate',
+        'object'
+    )
+    keywords = (
+        'abstract', 'class', 'continue', 'export', 'extends', 'nullable',
+        'private', 'public', 'static', 'struct', 'trace',
+        'and', 'break', 'by', 'case', 'catch', 'const', 'constant', 'debug',
+        'default', 'do', 'else', 'elsif', 'end', 'enum', 'exit', 'fallthru',
+        'fallthrough', 'for', 'forward', 'function', 'global', 'if', 'in',
+        'include', 'js', 'javascript', 'javascript_semantics', 'let', 'not',
+        'or', 'procedure', 'profile', 'profile_time', 'return', 'safe_mode',
+        'switch', 'then', 'to', 'try', 'type', 'type_check', 'until', 'warning',
+        'while', 'with', 'without', 'xor'
+    )
+    routines = (
+        'abort', 'abs', 'adjust_timedate', 'and_bits', 'and_bitsu', 'apply',
+        'append', 'arccos', 'arcsin', 'arctan', 'assert', 'atan2',
+        'atom_to_float32', 'atom_to_float64', 'bankers_rounding', 'beep',
+        'begins', 'binary_search', 'bits_to_int', 'bk_color', 'bytes_to_int',
+        'call_func', 'call_proc', 'cdCanvasActivate', 'cdCanvasArc',
+        'cdCanvasBegin', 'cdCanvasBox', 'cdCanvasChord', 'cdCanvasCircle',
+        'cdCanvasClear', 'cdCanvasEnd', 'cdCanvasFlush', 'cdCanvasFont',
+        'cdCanvasGetImageRGB', 'cdCanvasGetSize', 'cdCanvasGetTextAlignment',
+        'cdCanvasGetTextSize', 'cdCanvasLine', 'cdCanvasMark',
+        'cdCanvasMarkSize', 'cdCanvasMultiLineVectorText', 'cdCanvasPixel',
+        'cdCanvasRect', 'cdCanvasRoundedBox', 'cdCanvasRoundedRect',
+        'cdCanvasSector', 'cdCanvasSetAttribute', 'cdCanvasSetBackground',
+        'cdCanvasSetFillMode', 'cdCanvasSetForeground',
+        'cdCanvasSetInteriorStyle', 'cdCanvasSetLineStyle',
+        'cdCanvasSetLineWidth', 'cdCanvasSetTextAlignment', 'cdCanvasText',
+        'cdCanvasSetTextOrientation', 'cdCanvasGetTextOrientation',
+        'cdCanvasVectorText', 'cdCanvasVectorTextDirection',
+        'cdCanvasVectorTextSize', 'cdCanvasVertex', 'cdCreateCanvas',
+        'cdDecodeAlpha', 'cdDecodeColor', 'cdDecodeColorAlpha', 'cdEncodeAlpha',
+        'cdEncodeColor', 'cdEncodeColorAlpha', 'cdKillCanvas', 'cdVersion',
+        'cdVersionDate', 'ceil', 'change_timezone', 'choose', 'clear_screen',
+        'columnize', 'command_line', 'compare', 'complex_abs', 'complex_add',
+        'complex_arg', 'complex_conjugate', 'complex_cos', 'complex_cosh',
+        'complex_div', 'complex_exp', 'complex_imag', 'complex_inv',
+        'complex_log', 'complex_mul', 'complex_neg', 'complex_new',
+        'complex_norm', 'complex_power', 'complex_rho', 'complex_real',
+        'complex_round', 'complex_sin', 'complex_sinh', 'complex_sprint',
+        'complex_sqrt', 'complex_sub', 'complex_theta', 'concat', 'cos',
+        'crash', 'custom_sort', 'date', 'day_of_week', 'day_of_year',
+        'days_in_month', 'decode_base64', 'decode_flags', 'deep_copy', 'deld',
+        'deserialize', 'destroy_dict', 'destroy_queue', 'destroy_stack',
+        'dict_name', 'dict_size', 'elapsed', 'elapsed_short', 'encode_base64',
+        'equal', 'even', 'exp', 'extract', 'factorial', 'factors',
+        'file_size_k', 'find', 'find_all', 'find_any', 'find_replace', 'filter',
+        'flatten', 'float32_to_atom', 'float64_to_atom', 'floor',
+        'format_timedate', 'free_console', 'from_polar', 'gcd', 'get_file_base',
+        'get_file_extension', 'get_file_name', 'get_file_name_and_path',
+        'get_file_path', 'get_file_path_and_name', 'get_maxprime', 'get_prime',
+        'get_primes', 'get_primes_le', 'get_proper_dir', 'get_proper_path',
+        'get_rand', 'get_routine_info', 'get_test_abort', 'get_test_logfile',
+        'get_test_pause', 'get_test_verbosity', 'get_tzid', 'getd', 'getdd',
+        'getd_all_keys', 'getd_by_index', 'getd_index', 'getd_partial_key',
+        'glAttachShader', 'glBindBuffer', 'glBindTexture', 'glBufferData',
+        'glCanvasSpecialText', 'glClear', 'glClearColor', 'glColor',
+        'glCompileShader', 'glCreateBuffer', 'glCreateProgram',
+        'glCreateShader', 'glCreateTexture', 'glDeleteProgram',
+        'glDeleteShader', 'glDrawArrays', 'glEnable',
+        'glEnableVertexAttribArray', 'glFloat32Array', 'glInt32Array',
+        'glFlush', 'glGetAttribLocation', 'glGetError', 'glGetProgramInfoLog',
+        'glGetProgramParameter', 'glGetShaderInfoLog', 'glGetShaderParameter',
+        'glGetUniformLocation', 'glLinkProgram', 'glLoadIdentity',
+        'glMatrixMode', 'glOrtho', 'glRotatef', 'glShadeModel',
+        'glShaderSource', 'glSimpleA7texcoords', 'glTexImage2Dc',
+        'glTexParameteri', 'glTranslate', 'glUniform1f', 'glUniform1i',
+        'glUniformMatrix4fv', 'glUseProgram', 'glVertex',
+        'glVertexAttribPointer', 'glViewport', 'head', 'hsv_to_rgb', 'iff',
+        'iif', 'include_file', 'incl0de_file', 'insert', 'instance',
+        'int_to_bits', 'int_to_bytes', 'is_dict', 'is_integer', 's_leap_year',
+        'is_prime', 'is_prime2', 'islower', 'isupper', 'Icallback',
+        'iup_isdouble', 'iup_isprint', 'iup_XkeyBase', 'IupAppend', 'IupAlarm',
+        'IupBackgroundBox', 'IupButton', 'IupCalendar', 'IupCanvas',
+        'IupClipboard', 'IupClose', 'IupCloseOnEscape', 'IupControlsOpen',
+        'IupDatePick', 'IupDestroy', 'IupDialog', 'IupDrawArc', 'IupDrawBegin',
+        'IupDrawEnd', 'IupDrawGetSize', 'IupDrawGetTextSize', 'IupDrawLine',
+        'IupDrawRectangle', 'IupDrawText', 'IupExpander', 'IupFill',
+        'IupFlatLabel', 'IupFlatList', 'IupFlatTree', 'IupFlush', 'IupFrame',
+        'IupGetAttribute', 'IupGetAttributeId', 'IupGetAttributePtr',
+        'IupGetBrother', 'IupGetChild', 'IupGetChildCount', 'IupGetClassName',
+        'IupGetDialog', 'IupGetDialogChild', 'IupGetDouble', 'IupGetFocus',
+        'IupGetGlobal', 'IupGetGlobalInt', 'IupGetGlobalIntInt', 'IupGetInt',
+        'IupGetInt2', 'IupGetIntId', 'IupGetIntInt', 'IupGetParent',
+        'IupGLCanvas', 'IupGLCanvasOpen', 'IupGLMakeCurrent', 'IupGraph',
+        'IupHbox', 'IupHide', 'IupImage', 'IupImageRGBA', 'IupItem',
+        'iupKeyCodeToName', 'IupLabel', 'IupLink', 'IupList', 'IupMap',
+        'IupMenu', 'IupMenuItem', 'IupMessage', 'IupMessageDlg', 'IupMultiBox',
+        'IupMultiLine', 'IupNextField', 'IupNormaliser', 'IupOpen',
+        'IupPlayInput', 'IupPopup', 'IupPreviousField', 'IupProgressBar',
+        'IupRadio', 'IupRecordInput', 'IupRedraw', 'IupRefresh',
+        'IupRefreshChildren', 'IupSeparator', 'IupSetAttribute',
+        'IupSetAttributes', 'IupSetAttributeHandle', 'IupSetAttributeId',
+        'IupSetAttributePtr', 'IupSetCallback', 'IupSetCallbacks',
+        'IupSetDouble', 'IupSetFocus', 'IupSetGlobal', 'IupSetGlobalInt',
+        'IupSetGlobalFunction', 'IupSetHandle', 'IupSetInt',
+        'IupSetStrAttribute', 'IupSetStrGlobal', 'IupShow', 'IupShowXY',
+        'IupSplit', 'IupStoreAttribute', 'IupSubmenu', 'IupTable',
+        'IupTableClearSelected', 'IupTableClick_cb', 'IupTableGetSelected',
+        'IupTableResize_cb', 'IupTableSetData', 'IupTabs', 'IupText',
+        'IupTimer', 'IupToggle', 'IupTreeAddNodes', 'IupTreeView', 'IupUpdate',
+        'IupValuator', 'IupVbox', 'join', 'join_by', 'join_path', 'k_perm',
+        'largest', 'lcm', 'length', 'log', 'log10', 'log2', 'lower',
+        'm4_crossProduct', 'm4_inverse', 'm4_lookAt', 'm4_multiply',
+        'm4_normalize', 'm4_perspective', 'm4_subtractVectors', 'm4_xRotate',
+        'm4_yRotate', 'machine_bits', 'machine_word', 'match', 'match_all',
+        'match_replace', 'max', 'maxsq', 'min', 'minsq', 'mod', 'mpfr_add',
+        'mpfr_ceil', 'mpfr_cmp', 'mpfr_cmp_si', 'mpfr_const_pi', 'mpfr_div',
+        'mpfr_div_si', 'mpfr_div_z', 'mpfr_floor', 'mpfr_free', 'mpfr_get_d',
+        'mpfr_get_default_precision', 'mpfr_get_default_rounding_mode',
+        'mpfr_get_fixed', 'mpfr_get_precision', 'mpfr_get_si', 'mpfr_init',
+        'mpfr_inits', 'mpfr_init_set', 'mpfr_init_set_q', 'mpfr_init_set_z',
+        'mpfr_mul', 'mpfr_mul_si', 'mpfr_pow_si', 'mpfr_set', 'mpfr_set_d',
+        'mpfr_set_default_precision', 'mpfr_set_default_rounding_mode',
+        'mpfr_set_precision', 'mpfr_set_q', 'mpfr_set_si', 'mpfr_set_str',
+        'mpfr_set_z', 'mpfr_si_div', 'mpfr_si_sub', 'mpfr_sqrt', 'mpfr_sub',
+        'mpfr_sub_si', 'mpq_abs', 'mpq_add', 'mpq_add_si', 'mpq_canonicalize',
+        'mpq_cmp', 'mpq_cmp_si', 'mpq_div', 'mpq_div_2exp', 'mpq_free',
+        'mpq_get_den', 'mpq_get_num', 'mpq_get_str', 'mpq_init', 'mpq_init_set',
+        'mpq_init_set_si', 'mpq_init_set_str', 'mpq_init_set_z', 'mpq_inits',
+        'mpq_inv', 'mpq_mul', 'mpq_neg', 'mpq_set', 'mpq_set_si', 'mpq_set_str',
+        'mpq_set_z', 'mpq_sub', 'mpz_abs', 'mpz_add', 'mpz_addmul',
+        'mpz_addmul_ui', 'mpz_addmul_si', 'mpz_add_si', 'mpz_add_ui', 'mpz_and',
+        'mpz_bin_uiui', 'mpz_cdiv_q', 'mpz_cmp', 'mpz_cmp_si', 'mpz_divexact',
+        'mpz_divexact_ui', 'mpz_divisible_p', 'mpz_divisible_ui_p', 'mpz_even',
+        'mpz_fac_ui', 'mpz_factorstring', 'mpz_fdiv_q', 'mpz_fdiv_q_2exp',
+        'mpz_fdiv_q_ui', 'mpz_fdiv_qr', 'mpz_fdiv_r', 'mpz_fdiv_ui',
+        'mpz_fib_ui', 'mpz_fib2_ui', 'mpz_fits_atom', 'mpz_fits_integer',
+        'mpz_free', 'mpz_gcd', 'mpz_gcd_ui', 'mpz_get_atom', 'mpz_get_integer',
+        'mpz_get_short_str', 'mpz_get_str', 'mpz_init', 'mpz_init_set',
+        'mpz_inits', 'mpz_invert', 'mpz_lcm', 'mpz_lcm_ui', 'mpz_max',
+        'mpz_min', 'mpz_mod', 'mpz_mod_ui', 'mpz_mul', 'mpz_mul_2exp',
+        'mpz_mul_d', 'mpz_mul_si', 'mpz_neg', 'mpz_nthroot', 'mpz_odd',
+        'mpz_pollard_rho', 'mpz_pow_ui', 'mpz_powm', 'mpz_powm_ui', 'mpz_prime',
+        'mpz_prime_factors', 'mpz_prime_mr', 'mpz_rand', 'mpz_rand_ui',
+        'mpz_re_compose', 'mpz_remove', 'mpz_scan0', 'mpz_scan1', 'mpz_set',
+        'mpz_set_d', 'mpz_set_si', 'mpz_set_str', 'mpz_set_v', 'mpz_sign',
+        'mpz_sizeinbase', 'mpz_sqrt', 'mpz_sub', 'mpz_sub_si', 'mpz_sub_ui',
+        'mpz_si_sub', 'mpz_tdiv_q_2exp', 'mpz_tdiv_r_2exp', 'mpz_tstbit',
+        'mpz_ui_pow_ui', 'mpz_xor', 'named_dict', 'new_dict', 'new_queue',
+        'new_stack', 'not_bits', 'not_bitsu', 'odd', 'or_all', 'or_allu',
+        'or_bits', 'or_bitsu', 'ord', 'ordinal', 'ordinant',
+        'override_timezone', 'pad', 'pad_head', 'pad_tail', 'parse_date_string',
+        'papply', 'peep', 'peepn', 'peep_dict', 'permute', 'permutes',
+        'platform', 'pop', 'popn', 'pop_dict', 'power', 'pp', 'ppEx', 'ppExf',
+        'ppf', 'ppOpt', 'pq_add', 'pq_destroy', 'pq_empty', 'pq_new', 'pq_peek',
+        'pq_pop', 'pq_pop_data', 'pq_size', 'prepend', 'prime_factors',
+        'printf', 'product', 'proper', 'push', 'pushn', 'putd', 'puts',
+        'queue_empty', 'queue_size', 'rand', 'rand_range', 'reinstate',
+        'remainder', 'remove', 'remove_all', 'repeat', 'repeatch', 'replace',
+        'requires', 'reverse', 'rfind', 'rgb', 'rmatch', 'rmdr', 'rnd', 'round',
+        'routine_id', 'scanf', 'serialize', 'series', 'set_rand',
+        'set_test_abort', 'set_test_logfile', 'set_test_module',
+        'set_test_pause', 'set_test_verbosity', 'set_timedate_formats',
+        'set_timezone', 'setd', 'setd_default', 'shorten', 'sha256',
+        'shift_bits', 'shuffle', 'sign', 'sin', 'smallest', 'sort',
+        'sort_columns', 'speak', 'splice', 'split', 'split_any', 'split_by',
+        'sprint', 'sprintf', 'sq_abs', 'sq_add', 'sq_and', 'sq_and_bits',
+        'sq_arccos', 'sq_arcsin', 'sq_arctan', 'sq_atom', 'sq_ceil', 'sq_cmp',
+        'sq_cos', 'sq_div', 'sq_even', 'sq_eq', 'sq_floor', 'sq_floor_div',
+        'sq_ge', 'sq_gt', 'sq_int', 'sq_le', 'sq_log', 'sq_log10', 'sq_log2',
+        'sq_lt', 'sq_max', 'sq_min', 'sq_mod', 'sq_mul', 'sq_ne', 'sq_not',
+        'sq_not_bits', 'sq_odd', 'sq_or', 'sq_or_bits', 'sq_power', 'sq_rand',
+        'sq_remainder', 'sq_rmdr', 'sq_rnd', 'sq_round', 'sq_seq', 'sq_sign',
+        'sq_sin', 'sq_sqrt', 'sq_str', 'sq_sub', 'sq_tan', 'sq_trunc',
+        'sq_uminus', 'sq_xor', 'sq_xor_bits', 'sqrt', 'square_free',
+        'stack_empty', 'stack_size', 'substitute', 'substitute_all', 'sum',
+        'tail', 'tan', 'test_equal', 'test_fail', 'test_false',
+        'test_not_equal', 'test_pass', 'test_summary', 'test_true',
+        'text_color', 'throw', 'time', 'timedate_diff', 'timedelta',
+        'to_integer', 'to_number', 'to_rgb', 'to_string', 'traverse_dict',
+        'traverse_dict_partial_key', 'trim', 'trim_head', 'trim_tail', 'trunc',
+        'tagset', 'tagstart', 'typeof', 'unique', 'unix_dict', 'upper',
+        'utf8_to_utf32', 'utf32_to_utf8', 'version', 'vlookup', 'vslice',
+        'wglGetProcAddress', 'wildcard_file', 'wildcard_match', 'with_rho',
+        'with_theta', 'xml_new_doc', 'xml_new_element', 'xml_set_attribute',
+        'xml_sprint', 'xor_bits', 'xor_bitsu',
+        'accept', 'allocate', 'allocate_string', 'allow_break', 'ARM',
+        'atom_to_float80', 'c_func', 'c_proc', 'call_back', 'chdir',
+        'check_break', 'clearDib', 'close', 'closesocket', 'console',
+        'copy_file', 'create', 'create_directory', 'create_thread',
+        'curl_easy_cleanup', 'curl_easy_get_file', 'curl_easy_init',
+        'curl_easy_perform', 'curl_easy_perform_ex', 'curl_easy_setopt',
+        'curl_easy_strerror', 'curl_global_cleanup', 'curl_global_init',
+        'curl_slist_append', 'curl_slist_free_all', 'current_dir', 'cursor',
+        'define_c_func', 'define_c_proc', 'delete', 'delete_cs', 'delete_file',
+        'dir', 'DLL', 'drawDib', 'drawShadedPolygonToDib', 'ELF32', 'ELF64',
+        'enter_cs', 'eval', 'exit_thread', 'free', 'file_exists', 'final',
+        'float80_to_atom', 'format', 'get_bytes', 'get_file_date',
+        'get_file_size', 'get_file_type', 'get_interpreter', 'get_key',
+        'get_socket_error', 'get_text', 'get_thread_exitcode', 'get_thread_id',
+        'getc', 'getenv', 'gets', 'getsockaddr', 'glBegin', 'glCallList',
+        'glFrustum', 'glGenLists', 'glGetString', 'glLight', 'glMaterial',
+        'glNewList', 'glNormal', 'glPopMatrix', 'glPushMatrix', 'glRotate',
+        'glEnd', 'glEndList', 'glTexImage2D', 'goto', 'GUI', 'icons', 'ilASM',
+        'include_files', 'include_paths', 'init_cs', 'ip_to_string',
+        'IupConfig', 'IupConfigDialogClosed', 'IupConfigDialogShow',
+        'IupConfigGetVariableInt', 'IupConfigLoad', 'IupConfigSave',
+        'IupConfigSetVariableInt', 'IupExitLoop', 'IupFileDlg', 'IupFileList',
+        'IupGLSwapBuffers', 'IupHelp', 'IupLoopStep', 'IupMainLoop',
+        'IupNormalizer', 'IupPlot', 'IupPlotAdd', 'IupPlotBegin', 'IupPlotEnd',
+        'IupPlotInsert', 'IupSaveImage', 'IupTreeGetUserId', 'IupUser',
+        'IupVersion', 'IupVersionDate', 'IupVersionNumber', 'IupVersionShow',
+        'killDib', 'leave_cs', 'listen', 'manifest', 'mem_copy', 'mem_set',
+        'mpfr_gamma', 'mpfr_printf', 'mpfr_sprintf', 'mpz_export', 'mpz_import',
+        'namespace', 'new', 'newDib', 'open', 'open_dll', 'PE32', 'PE64',
+        'peek', 'peek_string', 'peek1s', 'peek1u', 'peek2s', 'peek2u', 'peek4s',
+        'peek4u', 'peek8s', 'peek8u', 'peekNS', 'peekns', 'peeknu', 'poke',
+        'poke2', 'poke4', 'poke8', 'pokeN', 'poke_string', 'poke_wstring',
+        'position', 'progress', 'prompt_number', 'prompt_string', 'read_file',
+        'read_lines', 'recv', 'resume_thread', 'seek', 'select', 'send',
+        'setHandler', 'shutdown', 'sleep', 'SO', 'sockaddr_in', 'socket',
+        'split_path', 'suspend_thread', 'system', 'system_exec', 'system_open',
+        'system_wait', 'task_clock_start', 'task_clock_stop', 'task_create',
+        'task_delay', 'task_list', 'task_schedule', 'task_self', 'task_status',
+        'task_suspend', 'task_yield', 'thread_safe_string', 'try_cs',
+        'utf8_to_utf16', 'utf16_to_utf8', 'utf16_to_utf32', 'utf32_to_utf16',
+        'video_config', 'WSACleanup', 'wait_thread', 'walk_dir', 'where',
+        'write_lines', 'wait_key'
+    )
+    constants = (
+        'ANY_QUEUE', 'ASCENDING', 'BLACK', 'BLOCK_CURSOR', 'BLUE',
+        'BRIGHT_CYAN', 'BRIGHT_BLUE', 'BRIGHT_GREEN', 'BRIGHT_MAGENTA',
+        'BRIGHT_RED', 'BRIGHT_WHITE', 'BROWN', 'C_DWORD', 'C_INT', 'C_POINTER',
+        'C_USHORT', 'C_WORD', 'CD_AMBER', 'CD_BLACK', 'CD_BLUE', 'CD_BOLD',
+        'CD_BOLD_ITALIC', 'CD_BOX', 'CD_CENTER', 'CD_CIRCLE', 'CD_CLOSED_LINES',
+        'CD_CONTINUOUS', 'CD_CUSTOM', 'CD_CYAN', 'CD_DARK_BLUE', 'CD_DARK_CYAN',
+        'CD_DARK_GRAY', 'CD_DARK_GREY', 'CD_DARK_GREEN', 'CD_DARK_MAGENTA',
+        'CD_DARK_RED', 'CD_DARK_YELLOW', 'CD_DASH_DOT', 'CD_DASH_DOT_DOT',
+        'CD_DASHED', 'CD_DBUFFER', 'CD_DEG2RAD', 'CD_DIAMOND', 'CD_DOTTED',
+        'CD_EAST', 'CD_EVENODD', 'CD_FILL', 'CD_GL', 'CD_GRAY', 'CD_GREY',
+        'CD_GREEN', 'CD_HATCH', 'CD_HOLLOW', 'CD_HOLLOW_BOX',
+        'CD_HOLLOW_CIRCLE', 'CD_HOLLOW_DIAMOND', 'CD_INDIGO', 'CD_ITALIC',
+        'CD_IUP', 'CD_IUPDBUFFER', 'CD_LIGHT_BLUE', 'CD_LIGHT_GRAY',
+        'CD_LIGHT_GREY', 'CD_LIGHT_GREEN', 'CD_LIGHT_PARCHMENT', 'CD_MAGENTA',
+        'CD_NAVY', 'CD_NORTH', 'CD_NORTH_EAST', 'CD_NORTH_WEST', 'CD_OLIVE',
+        'CD_OPEN_LINES', 'CD_ORANGE', 'CD_PARCHMENT', 'CD_PATTERN',
+        'CD_PRINTER', 'CD_PURPLE', 'CD_PLAIN', 'CD_PLUS', 'CD_QUERY',
+        'CD_RAD2DEG', 'CD_RED', 'CD_SILVER', 'CD_SOLID', 'CD_SOUTH_EAST',
+        'CD_SOUTH_WEST', 'CD_STAR', 'CD_STIPPLE', 'CD_STRIKEOUT',
+        'CD_UNDERLINE', 'CD_WEST', 'CD_WHITE', 'CD_WINDING', 'CD_VIOLET',
+        'CD_X', 'CD_YELLOW', 'CURLE_OK', 'CURLOPT_MAIL_FROM',
+        'CURLOPT_MAIL_RCPT', 'CURLOPT_PASSWORD', 'CURLOPT_READDATA',
+        'CURLOPT_READFUNCTION', 'CURLOPT_SSL_VERIFYPEER',
+        'CURLOPT_SSL_VERIFYHOST', 'CURLOPT_UPLOAD', 'CURLOPT_URL',
+        'CURLOPT_USE_SSL', 'CURLOPT_USERNAME', 'CURLOPT_VERBOSE',
+        'CURLOPT_WRITEFUNCTION', 'CURLUSESSL_ALL', 'CYAN', 'D_NAME',
+        'D_ATTRIBUTES', 'D_SIZE', 'D_YEAR', 'D_MONTH', 'D_DAY', 'D_HOUR',
+        'D_MINUTE', 'D_SECOND', 'D_CREATION', 'D_LASTACCESS', 'D_MODIFICATION',
+        'DT_YEAR', 'DT_MONTH', 'DT_DAY', 'DT_HOUR', 'DT_MINUTE', 'DT_SECOND',
+        'DT_DOW', 'DT_MSEC', 'DT_DOY', 'DT_GMT', 'EULER', 'E_CODE', 'E_ADDR',
+        'E_LINE', 'E_RTN', 'E_NAME', 'E_FILE', 'E_PATH', 'E_USER', 'false',
+        'False', 'FALSE', 'FIFO_QUEUE', 'FILETYPE_DIRECTORY', 'FILETYPE_FILE',
+        'GET_EOF', 'GET_FAIL', 'GET_IGNORE', 'GET_SUCCESS',
+        'GL_AMBIENT_AND_DIFFUSE', 'GL_ARRAY_BUFFER', 'GL_CLAMP',
+        'GL_CLAMP_TO_BORDER', 'GL_CLAMP_TO_EDGE', 'GL_COLOR_BUFFER_BIT',
+        'GL_COMPILE', 'GL_COMPILE_STATUS', 'GL_CULL_FACE',
+        'GL_DEPTH_BUFFER_BIT', 'GL_DEPTH_TEST', 'GL_EXTENSIONS', 'GL_FLAT',
+        'GL_FLOAT', 'GL_FRAGMENT_SHADER', 'GL_FRONT', 'GL_LIGHT0',
+        'GL_LIGHTING', 'GL_LINEAR', 'GL_LINK_STATUS', 'GL_MODELVIEW',
+        'GL_NEAREST', 'GL_NO_ERROR', 'GL_NORMALIZE', 'GL_POSITION',
+        'GL_PROJECTION', 'GL_QUAD_STRIP', 'GL_QUADS', 'GL_RENDERER',
+        'GL_REPEAT', 'GL_RGB', 'GL_RGBA', 'GL_SMOOTH', 'GL_STATIC_DRAW',
+        'GL_TEXTURE_2D', 'GL_TEXTURE_MAG_FILTER', 'GL_TEXTURE_MIN_FILTER',
+        'GL_TEXTURE_WRAP_S', 'GL_TEXTURE_WRAP_T', 'GL_TRIANGLES',
+        'GL_UNSIGNED_BYTE', 'GL_VENDOR', 'GL_VERSION', 'GL_VERTEX_SHADER',
+        'GRAY', 'GREEN', 'GT_LF_STRIPPED', 'GT_WHOLE_FILE', 'INVLN10',
+        'IUP_CLOSE', 'IUP_CONTINUE', 'IUP_DEFAULT', 'IUP_BLACK', 'IUP_BLUE',
+        'IUP_BUTTON1', 'IUP_BUTTON3', 'IUP_CENTER', 'IUP_CYAN', 'IUP_DARK_BLUE',
+        'IUP_DARK_CYAN', 'IUP_DARK_GRAY', 'IUP_DARK_GREY', 'IUP_DARK_GREEN',
+        'IUP_DARK_MAGENTA', 'IUP_DARK_RED', 'IUP_GRAY', 'IUP_GREY', 'IUP_GREEN',
+        'IUP_IGNORE', 'IUP_INDIGO', 'IUP_MAGENTA', 'IUP_MASK_INT',
+        'IUP_MASK_UINT', 'IUP_MOUSEPOS', 'IUP_NAVY', 'IUP_OLIVE', 'IUP_RECTEXT',
+        'IUP_RED', 'IUP_LIGHT_BLUE', 'IUP_LIGHT_GRAY', 'IUP_LIGHT_GREY',
+        'IUP_LIGHT_GREEN', 'IUP_ORANGE', 'IUP_PARCHMENT', 'IUP_PURPLE',
+        'IUP_SILVER', 'IUP_TEAL', 'IUP_VIOLET', 'IUP_WHITE', 'IUP_YELLOW',
+        'K_BS', 'K_cA', 'K_cC', 'K_cD', 'K_cF5', 'K_cK', 'K_cM', 'K_cN', 'K_cO',
+        'K_cP', 'K_cR', 'K_cS', 'K_cT', 'K_cW', 'K_CR', 'K_DEL', 'K_DOWN',
+        'K_END', 'K_ESC', 'K_F1', 'K_F2', 'K_F3', 'K_F4', 'K_F5', 'K_F6',
+        'K_F7', 'K_F8', 'K_F9', 'K_F10', 'K_F11', 'K_F12', 'K_HOME', 'K_INS',
+        'K_LEFT', 'K_MIDDLE', 'K_PGDN', 'K_PGUP', 'K_RIGHT', 'K_SP', 'K_TAB',
+        'K_UP', 'K_h', 'K_i', 'K_j', 'K_p', 'K_r', 'K_s', 'JS', 'LIFO_QUEUE',
+        'LINUX', 'MAX_HEAP', 'MAGENTA', 'MIN_HEAP', 'Nan', 'NO_CURSOR', 'null',
+        'NULL', 'PI', 'pp_Ascii', 'pp_Brkt', 'pp_Date', 'pp_File', 'pp_FltFmt',
+        'pp_Indent', 'pp_IntCh', 'pp_IntFmt', 'pp_Maxlen', 'pp_Nest',
+        'pp_Pause', 'pp_Q22', 'pp_StrFmt', 'RED', 'SEEK_OK', 'SLASH',
+        'TEST_ABORT', 'TEST_CRASH', 'TEST_PAUSE', 'TEST_PAUSE_FAIL',
+        'TEST_QUIET', 'TEST_SHOW_ALL', 'TEST_SHOW_FAILED', 'TEST_SUMMARY',
+        'true', 'True', 'TRUE', 'VC_SCRNLINES', 'WHITE', 'WINDOWS', 'YELLOW'
+    )
+
+    tokens = {
+        'root': [
+            (r"\s+", Whitespace),
+            (r'/\*|--/\*|#\[', Comment.Multiline, 'comment'),
+            (r'(?://|--|#!).*$', Comment.Single),
+#Alt:
+#           (r'//.*$|--.*$|#!.*$', Comment.Single),
+            (r'"([^"\\]|\\.)*"', String.Other),
+            (r'\'[^\']*\'', String.Other),
+            (r'`[^`]*`', String.Other),
+
+            (words(types, prefix=r'\b', suffix=r'\b'), Name.Function),
+            (words(routines, prefix=r'\b', suffix=r'\b'), Name.Function),
+            (words(preproc, prefix=r'\b', suffix=r'\b'), Keyword.Declaration),
+            (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword.Declaration),
+            (words(constants, prefix=r'\b', suffix=r'\b'), Name.Constant),
+            # Aside: Phix only supports/uses the ascii/non-unicode tilde
+            (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|\.(){},?:\[\]$\\;#]', Operator),
+            (r'[\w-]+', Text)
+        ],
+        'comment': [
+            (r'[^*/#]+', Comment.Multiline),
+            (r'/\*|#\[', Comment.Multiline, '#push'),
+            (r'\*/|#\]', Comment.Multiline, '#pop'),
+            (r'[*/#]', Comment.Multiline)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/php.py b/lib/python3.11/site-packages/pygments/lexers/php.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac935c4717498a7c2c3acb40156f80c2fc69d901
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/php.py
@@ -0,0 +1,335 @@
+"""
+    pygments.lexers.php
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for PHP and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import Lexer, RegexLexer, include, bygroups, default, \
+    using, this, words, do_insertions, line_re
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Other, Generic
+from pygments.util import get_bool_opt, get_list_opt, shebang_matches
+
+__all__ = ['ZephirLexer', 'PsyshConsoleLexer', 'PhpLexer']
+
+
+class ZephirLexer(RegexLexer):
+    """
+    For Zephir language source code.
+
+    Zephir is a compiled high level language aimed
+    to the creation of C-extensions for PHP.
+    """
+
+    name = 'Zephir'
+    url = 'http://zephir-lang.com/'
+    aliases = ['zephir']
+    filenames = ['*.zep']
+    version_added = '2.0'
+
+    zephir_keywords = ['fetch', 'echo', 'isset', 'empty']
+    zephir_type = ['bit', 'bits', 'string']
+
+    flags = re.DOTALL | re.MULTILINE
+
+    tokens = {
+        'commentsandwhitespace': [
+            (r'\s+', Text),
+            (r'//.*?\n', Comment.Single),
+            (r'/\*.*?\*/', Comment.Multiline)
+        ],
+        'slashstartsregex': [
+            include('commentsandwhitespace'),
+            (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
+             r'([gim]+\b|\B)', String.Regex, '#pop'),
+            (r'/', Operator, '#pop'),
+            default('#pop')
+        ],
+        'badregex': [
+            (r'\n', Text, '#pop')
+        ],
+        'root': [
+            (r'^(?=\s|/)', Text, 'slashstartsregex'),
+            include('commentsandwhitespace'),
+            (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|'
+             r'(<<|>>>?|==?|!=?|->|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
+            (r'[{(\[;,]', Punctuation, 'slashstartsregex'),
+            (r'[})\].]', Punctuation),
+            (r'(for|in|while|do|break|return|continue|switch|case|default|if|else|loop|'
+             r'require|inline|throw|try|catch|finally|new|delete|typeof|instanceof|void|'
+             r'namespace|use|extends|this|fetch|isset|unset|echo|fetch|likely|unlikely|'
+             r'empty)\b', Keyword, 'slashstartsregex'),
+            (r'(var|let|with|function)\b', Keyword.Declaration, 'slashstartsregex'),
+            (r'(abstract|boolean|bool|char|class|const|double|enum|export|extends|final|'
+             r'native|goto|implements|import|int|string|interface|long|ulong|char|uchar|'
+             r'float|unsigned|private|protected|public|short|static|self|throws|reverse|'
+             r'transient|volatile|readonly)\b', Keyword.Reserved),
+            (r'(true|false|null|undefined)\b', Keyword.Constant),
+            (r'(Array|Boolean|Date|_REQUEST|_COOKIE|_SESSION|'
+             r'_GET|_POST|_SERVER|this|stdClass|range|count|iterator|'
+             r'window)\b', Name.Builtin),
+            (r'[$a-zA-Z_][\w\\]*', Name.Other),
+            (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'[0-9]+', Number.Integer),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
+        ]
+    }
+
+
+class PsyshConsoleLexer(Lexer):
+    """
+    For PsySH console output, such as:
+
+    .. sourcecode:: psysh
+
+        >>> $greeting = function($name): string {
+        ...     return "Hello, {$name}";
+        ... };
+        => Closure($name): string {#2371 …3}
+        >>> $greeting('World')
+        => "Hello, World"
+    """
+    name = 'PsySH console session for PHP'
+    url = 'https://psysh.org/'
+    aliases = ['psysh']
+    version_added = '2.7'
+
+    def __init__(self, **options):
+        options['startinline'] = True
+        Lexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        phplexer = PhpLexer(**self.options)
+        curcode = ''
+        insertions = []
+        for match in line_re.finditer(text):
+            line = match.group()
+            if line.startswith('>>> ') or line.startswith('... '):
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, line[:4])]))
+                curcode += line[4:]
+            elif line.rstrip() == '...':
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, '...')]))
+                curcode += line[3:]
+            else:
+                if curcode:
+                    yield from do_insertions(
+                        insertions, phplexer.get_tokens_unprocessed(curcode))
+                    curcode = ''
+                    insertions = []
+                yield match.start(), Generic.Output, line
+        if curcode:
+            yield from do_insertions(insertions,
+                                     phplexer.get_tokens_unprocessed(curcode))
+
+
+class PhpLexer(RegexLexer):
+    """
+    For PHP source code.
+    For PHP embedded in HTML, use the `HtmlPhpLexer`.
+
+    Additional options accepted:
+
+    `startinline`
+        If given and ``True`` the lexer starts highlighting with
+        php code (i.e.: no starting ``>> from pygments.lexers._php_builtins import MODULES
+            >>> MODULES.keys()
+            ['PHP Options/Info', 'Zip', 'dba', ...]
+
+        In fact the names of those modules match the module names from
+        the php documentation.
+    """
+
+    name = 'PHP'
+    url = 'https://www.php.net/'
+    aliases = ['php', 'php3', 'php4', 'php5']
+    filenames = ['*.php', '*.php[345]', '*.inc']
+    mimetypes = ['text/x-php']
+    version_added = ''
+
+    # Note that a backslash is included, PHP uses a backslash as a namespace
+    # separator.
+    _ident_inner = r'(?:[\\_a-z]|[^\x00-\x7f])(?:[\\\w]|[^\x00-\x7f])*'
+    # But not inside strings.
+    _ident_nons = r'(?:[_a-z]|[^\x00-\x7f])(?:\w|[^\x00-\x7f])*'
+
+    flags = re.IGNORECASE | re.DOTALL | re.MULTILINE
+    tokens = {
+        'root': [
+            (r'<\?(php)?', Comment.Preproc, 'php'),
+            (r'[^<]+', Other),
+            (r'<', Other)
+        ],
+        'php': [
+            (r'\?>', Comment.Preproc, '#pop'),
+            (r'(<<<)([\'"]?)(' + _ident_nons + r')(\2\n.*?\n\s*)(\3)(;?)(\n)',
+             bygroups(String, String, String.Delimiter, String, String.Delimiter,
+                      Punctuation, Text)),
+            (r'\s+', Text),
+            (r'#\[', Punctuation, 'attribute'),
+            (r'#.*?\n', Comment.Single),
+            (r'//.*?\n', Comment.Single),
+            # put the empty comment here, it is otherwise seen as
+            # the start of a docstring
+            (r'/\*\*/', Comment.Multiline),
+            (r'/\*\*.*?\*/', String.Doc),
+            (r'/\*.*?\*/', Comment.Multiline),
+            (r'(->|::)(\s*)(' + _ident_nons + ')',
+             bygroups(Operator, Text, Name.Attribute)),
+            (r'[~!%^&*+=|:.<>/@-]+', Operator),
+            (r'\?', Operator),  # don't add to the charclass above!
+            (r'[\[\]{}();,]+', Punctuation),
+            (r'(new)(\s+)(class)\b', bygroups(Keyword, Text, Keyword)),
+            (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
+            (r'(function)(\s*)(?=\()', bygroups(Keyword, Text)),
+            (r'(function)(\s+)(&?)(\s*)',
+             bygroups(Keyword, Text, Operator, Text), 'functionname'),
+            (r'(const)(\s+)(' + _ident_inner + ')',
+             bygroups(Keyword, Text, Name.Constant)),
+            # source: https://www.php.net/manual/en/reserved.keywords.php
+            (r'(and|E_PARSE|old_function|E_ERROR|or|as|E_WARNING|parent|'
+             r'eval|PHP_OS|break|exit|case|extends|PHP_VERSION|cfunction|'
+             r'FALSE|print|for|require|continue|foreach|require_once|'
+             r'declare|return|default|static|do|switch|die|stdClass|'
+             r'echo|else|TRUE|elseif|var|empty|if|xor|enddeclare|include|'
+             r'virtual|endfor|include_once|while|endforeach|global|'
+             r'endif|list|endswitch|new|endwhile|not|'
+             r'array|E_ALL|NULL|final|php_user_filter|interface|'
+             r'implements|public|private|protected|abstract|clone|try|'
+             r'catch|throw|this|use|namespace|trait|yield( from)?|'
+             r'finally|match|readonly)\b', Keyword),
+            (r'(true|false|null)\b', Keyword.Constant),
+            include('magicconstants'),
+            (r'\$\{', Name.Variable, 'variablevariable'),
+            (r'\$+' + _ident_inner, Name.Variable),
+            (_ident_inner, Name.Other),
+            (r'(\d+\.\d*|\d*\.\d+)(e[+-]?[0-9]+)?', Number.Float),
+            (r'\d+e[+-]?[0-9]+', Number.Float),
+            (r'0[0-7]+', Number.Oct),
+            (r'0x[a-f0-9]+', Number.Hex),
+            (r'\d+', Number.Integer),
+            (r'0b[01]+', Number.Bin),
+            (r"'([^'\\]*(?:\\.[^'\\]*)*)'", String.Single),
+            (r'`([^`\\]*(?:\\.[^`\\]*)*)`', String.Backtick),
+            (r'"', String.Double, 'string'),
+        ],
+        'variablevariable': [
+            (r'\}', Name.Variable, '#pop'),
+            include('php')
+        ],
+        'magicfuncs': [
+            # source: http://php.net/manual/en/language.oop5.magic.php
+            (words((
+                '__construct', '__destruct', '__call', '__callStatic', '__get', '__set',
+                '__isset', '__unset', '__sleep', '__wakeup', '__toString', '__invoke',
+                '__set_state', '__clone', '__debugInfo',), suffix=r'\b'),
+             Name.Function.Magic),
+        ],
+        'magicconstants': [
+            # source: https://www.php.net/manual/en/language.constants.magic.php
+            (words((
+                '__LINE__', '__FILE__', '__DIR__', '__FUNCTION__', '__CLASS__',
+                '__TRAIT__', '__METHOD__', '__NAMESPACE__', '__PROPERTY__',),
+                suffix=r'\b'),
+             Name.Constant),
+        ],
+        'classname': [
+            (_ident_inner, Name.Class, '#pop')
+        ],
+        'functionname': [
+            include('magicfuncs'),
+            (_ident_inner, Name.Function, '#pop'),
+            default('#pop')
+        ],
+        'string': [
+            (r'"', String.Double, '#pop'),
+            (r'[^{$"\\]+', String.Double),
+            (r'\\([nrt"$\\]|[0-7]{1,3}|x[0-9a-f]{1,2})', String.Escape),
+            (r'\$' + _ident_nons + r'(\[\S+?\]|->' + _ident_nons + ')?',
+             String.Interpol),
+            (r'(\{\$\{)(.*?)(\}\})',
+             bygroups(String.Interpol, using(this, _startinline=True),
+                      String.Interpol)),
+            (r'(\{)(\$.*?)(\})',
+             bygroups(String.Interpol, using(this, _startinline=True),
+                      String.Interpol)),
+            (r'(\$\{)(\S+)(\})',
+             bygroups(String.Interpol, Name.Variable, String.Interpol)),
+            (r'[${\\]', String.Double)
+        ],
+        'attribute': [
+            (r'\]', Punctuation, '#pop'),
+            (r'\(', Punctuation, 'attributeparams'),
+            (_ident_inner, Name.Decorator),
+            include('php')
+        ],
+        'attributeparams': [
+            (r'\)', Punctuation, '#pop'),
+            include('php')
+        ],
+    }
+
+    def __init__(self, **options):
+        self.funcnamehighlighting = get_bool_opt(
+            options, 'funcnamehighlighting', True)
+        self.disabledmodules = get_list_opt(
+            options, 'disabledmodules', ['unknown'])
+        self.startinline = get_bool_opt(options, 'startinline', False)
+
+        # private option argument for the lexer itself
+        if '_startinline' in options:
+            self.startinline = options.pop('_startinline')
+
+        # collect activated functions in a set
+        self._functions = set()
+        if self.funcnamehighlighting:
+            from pygments.lexers._php_builtins import MODULES
+            for key, value in MODULES.items():
+                if key not in self.disabledmodules:
+                    self._functions.update(value)
+        RegexLexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        stack = ['root']
+        if self.startinline:
+            stack.append('php')
+        for index, token, value in \
+                RegexLexer.get_tokens_unprocessed(self, text, stack):
+            if token is Name.Other:
+                if value in self._functions:
+                    yield index, Name.Builtin, value
+                    continue
+            yield index, token, value
+
+    def analyse_text(text):
+        if shebang_matches(text, r'php'):
+            return True
+        rv = 0.0
+        if re.search(r'<\?(?!xml)', text):
+            rv += 0.3
+        return rv
diff --git a/lib/python3.11/site-packages/pygments/lexers/pointless.py b/lib/python3.11/site-packages/pygments/lexers/pointless.py
new file mode 100644
index 0000000000000000000000000000000000000000..aab0a5684fe7b6c7c37372fefbf48630d2c96d4f
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/pointless.py
@@ -0,0 +1,70 @@
+"""
+    pygments.lexers.pointless
+    ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Pointless.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words
+from pygments.token import Comment, Error, Keyword, Name, Number, Operator, \
+    Punctuation, String, Text
+
+__all__ = ['PointlessLexer']
+
+
+class PointlessLexer(RegexLexer):
+    """
+    For Pointless source code.
+    """
+
+    name = 'Pointless'
+    url = 'https://ptls.dev'
+    aliases = ['pointless']
+    filenames = ['*.ptls']
+    version_added = '2.7'
+
+    ops = words([
+        "+", "-", "*", "/", "**", "%", "+=", "-=", "*=",
+        "/=", "**=", "%=", "|>", "=", "==", "!=", "<", ">",
+        "<=", ">=", "=>", "$", "++",
+    ])
+
+    keywords = words([
+        "if", "then", "else", "where", "with", "cond",
+        "case", "and", "or", "not", "in", "as", "for",
+        "requires", "throw", "try", "catch", "when",
+        "yield", "upval",
+    ], suffix=r'\b')
+
+    tokens = {
+        'root': [
+            (r'[ \n\r]+', Text),
+            (r'--.*$', Comment.Single),
+            (r'"""', String, 'multiString'),
+            (r'"', String, 'string'),
+            (r'[\[\](){}:;,.]', Punctuation),
+            (ops, Operator),
+            (keywords, Keyword),
+            (r'\d+|\d*\.\d+', Number),
+            (r'(true|false)\b', Name.Builtin),
+            (r'[A-Z][a-zA-Z0-9]*\b', String.Symbol),
+            (r'output\b', Name.Variable.Magic),
+            (r'(export|import)\b', Keyword.Namespace),
+            (r'[a-z][a-zA-Z0-9]*\b', Name.Variable)
+        ],
+        'multiString': [
+            (r'\\.', String.Escape),
+            (r'"""', String, '#pop'),
+            (r'"', String),
+            (r'[^\\"]+', String),
+        ],
+        'string': [
+            (r'\\.', String.Escape),
+            (r'"', String, '#pop'),
+            (r'\n', Error),
+            (r'[^\\"]+', String),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/pony.py b/lib/python3.11/site-packages/pygments/lexers/pony.py
new file mode 100644
index 0000000000000000000000000000000000000000..62d16d7d651b3395c761ecef98fe3f43d59ca33d
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/pony.py
@@ -0,0 +1,93 @@
+"""
+    pygments.lexers.pony
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Pony and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['PonyLexer']
+
+
+class PonyLexer(RegexLexer):
+    """
+    For Pony source code.
+    """
+
+    name = 'Pony'
+    aliases = ['pony']
+    filenames = ['*.pony']
+    url = 'https://www.ponylang.io'
+    version_added = '2.4'
+
+    _caps = r'(iso|trn|ref|val|box|tag)'
+
+    tokens = {
+        'root': [
+            (r'\n', Text),
+            (r'[^\S\n]+', Text),
+            (r'//.*\n', Comment.Single),
+            (r'/\*', Comment.Multiline, 'nested_comment'),
+            (r'"""(?:.|\n)*?"""', String.Doc),
+            (r'"', String, 'string'),
+            (r'\'.*\'', String.Char),
+            (r'=>|[]{}:().~;,|&!^?[]', Punctuation),
+            (words((
+                'addressof', 'and', 'as', 'consume', 'digestof', 'is', 'isnt',
+                'not', 'or'),
+                suffix=r'\b'),
+             Operator.Word),
+            (r'!=|==|<<|>>|[-+/*%=<>]', Operator),
+            (words((
+                'box', 'break', 'compile_error', 'compile_intrinsic',
+                'continue', 'do', 'else', 'elseif', 'embed', 'end', 'error',
+                'for', 'if', 'ifdef', 'in', 'iso', 'lambda', 'let', 'match',
+                'object', 'recover', 'ref', 'repeat', 'return', 'tag', 'then',
+                'this', 'trn', 'try', 'until', 'use', 'var', 'val', 'where',
+                'while', 'with', '#any', '#read', '#send', '#share'),
+                suffix=r'\b'),
+             Keyword),
+            (r'(actor|class|struct|primitive|interface|trait|type)((?:\s)+)',
+             bygroups(Keyword, Text), 'typename'),
+            (r'(new|fun|be)((?:\s)+)', bygroups(Keyword, Text), 'methodname'),
+            (words((
+                'I8', 'U8', 'I16', 'U16', 'I32', 'U32', 'I64', 'U64', 'I128',
+                'U128', 'ILong', 'ULong', 'ISize', 'USize', 'F32', 'F64',
+                'Bool', 'Pointer', 'None', 'Any', 'Array', 'String',
+                'Iterator'),
+                suffix=r'\b'),
+             Name.Builtin.Type),
+            (r'_?[A-Z]\w*', Name.Type),
+            (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float),
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'\d+', Number.Integer),
+            (r'(true|false)\b', Name.Builtin),
+            (r'_\d*', Name),
+            (r'_?[a-z][\w\']*', Name)
+        ],
+        'typename': [
+            (_caps + r'?((?:\s)*)(_?[A-Z]\w*)',
+             bygroups(Keyword, Text, Name.Class), '#pop')
+        ],
+        'methodname': [
+            (_caps + r'?((?:\s)*)(_?[a-z]\w*)',
+             bygroups(Keyword, Text, Name.Function), '#pop')
+        ],
+        'nested_comment': [
+            (r'[^*/]+', Comment.Multiline),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'[*/]', Comment.Multiline)
+        ],
+        'string': [
+            (r'"', String, '#pop'),
+            (r'\\"', String),
+            (r'[^\\"]+', String)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/praat.py b/lib/python3.11/site-packages/pygments/lexers/praat.py
new file mode 100644
index 0000000000000000000000000000000000000000..c50e9279f88c4f235262f748f62563b099f58d0b
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/praat.py
@@ -0,0 +1,303 @@
+"""
+    pygments.lexers.praat
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Praat
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words, bygroups, include
+from pygments.token import Name, Text, Comment, Keyword, String, Punctuation, \
+    Number, Operator, Whitespace
+
+__all__ = ['PraatLexer']
+
+
+class PraatLexer(RegexLexer):
+    """
+    For Praat scripts.
+    """
+
+    name = 'Praat'
+    url = 'http://www.praat.org'
+    aliases = ['praat']
+    filenames = ['*.praat', '*.proc', '*.psc']
+    version_added = '2.1'
+
+    keywords = (
+        'if', 'then', 'else', 'elsif', 'elif', 'endif', 'fi', 'for', 'from', 'to',
+        'endfor', 'endproc', 'while', 'endwhile', 'repeat', 'until', 'select', 'plus',
+        'minus', 'demo', 'assert', 'stopwatch', 'nocheck', 'nowarn', 'noprogress',
+        'editor', 'endeditor', 'clearinfo',
+    )
+
+    functions_string = (
+        'backslashTrigraphsToUnicode', 'chooseDirectory', 'chooseReadFile',
+        'chooseWriteFile', 'date', 'demoKey', 'do', 'environment', 'extractLine',
+        'extractWord', 'fixed', 'info', 'left', 'mid', 'percent', 'readFile', 'replace',
+        'replace_regex', 'right', 'selected', 'string', 'unicodeToBackslashTrigraphs',
+    )
+
+    functions_numeric = (
+        'abs', 'appendFile', 'appendFileLine', 'appendInfo', 'appendInfoLine', 'arccos',
+        'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'barkToHertz',
+        'beginPause', 'beginSendPraat', 'besselI', 'besselK', 'beta', 'beta2',
+        'binomialP', 'binomialQ', 'boolean', 'ceiling', 'chiSquareP', 'chiSquareQ',
+        'choice', 'comment', 'cos', 'cosh', 'createDirectory', 'deleteFile',
+        'demoClicked', 'demoClickedIn', 'demoCommandKeyPressed',
+        'demoExtraControlKeyPressed', 'demoInput', 'demoKeyPressed',
+        'demoOptionKeyPressed', 'demoShiftKeyPressed', 'demoShow', 'demoWaitForInput',
+        'demoWindowTitle', 'demoX', 'demoY', 'differenceLimensToPhon', 'do', 'editor',
+        'endPause', 'endSendPraat', 'endsWith', 'erb', 'erbToHertz', 'erf', 'erfc',
+        'exitScript', 'exp', 'extractNumber', 'fileReadable', 'fisherP', 'fisherQ',
+        'floor', 'gaussP', 'gaussQ', 'hertzToBark', 'hertzToErb', 'hertzToMel',
+        'hertzToSemitones', 'imax', 'imin', 'incompleteBeta', 'incompleteGammaP', 'index',
+        'index_regex', 'integer', 'invBinomialP', 'invBinomialQ', 'invChiSquareQ', 'invFisherQ',
+        'invGaussQ', 'invSigmoid', 'invStudentQ', 'length', 'ln', 'lnBeta', 'lnGamma',
+        'log10', 'log2', 'max', 'melToHertz', 'min', 'minusObject', 'natural', 'number',
+        'numberOfColumns', 'numberOfRows', 'numberOfSelected', 'objectsAreIdentical',
+        'option', 'optionMenu', 'pauseScript', 'phonToDifferenceLimens', 'plusObject',
+        'positive', 'randomBinomial', 'randomGauss', 'randomInteger', 'randomPoisson',
+        'randomUniform', 'real', 'readFile', 'removeObject', 'rindex', 'rindex_regex',
+        'round', 'runScript', 'runSystem', 'runSystem_nocheck', 'selectObject',
+        'selected', 'semitonesToHertz', 'sentence', 'sentencetext', 'sigmoid', 'sin', 'sinc',
+        'sincpi', 'sinh', 'soundPressureToPhon', 'sqrt', 'startsWith', 'studentP',
+        'studentQ', 'tan', 'tanh', 'text', 'variableExists', 'word', 'writeFile', 'writeFileLine',
+        'writeInfo', 'writeInfoLine',
+    )
+
+    functions_array = (
+        'linear', 'randomGauss', 'randomInteger', 'randomUniform', 'zero',
+    )
+
+    objects = (
+        'Activation', 'AffineTransform', 'AmplitudeTier', 'Art', 'Artword',
+        'Autosegment', 'BarkFilter', 'BarkSpectrogram', 'CCA', 'Categories',
+        'Cepstrogram', 'Cepstrum', 'Cepstrumc', 'ChebyshevSeries', 'ClassificationTable',
+        'Cochleagram', 'Collection', 'ComplexSpectrogram', 'Configuration', 'Confusion',
+        'ContingencyTable', 'Corpus', 'Correlation', 'Covariance',
+        'CrossCorrelationTable', 'CrossCorrelationTables', 'DTW', 'DataModeler',
+        'Diagonalizer', 'Discriminant', 'Dissimilarity', 'Distance', 'Distributions',
+        'DurationTier', 'EEG', 'ERP', 'ERPTier', 'EditCostsTable', 'EditDistanceTable',
+        'Eigen', 'Excitation', 'Excitations', 'ExperimentMFC', 'FFNet', 'FeatureWeights',
+        'FileInMemory', 'FilesInMemory', 'Formant', 'FormantFilter', 'FormantGrid',
+        'FormantModeler', 'FormantPoint', 'FormantTier', 'GaussianMixture', 'HMM',
+        'HMM_Observation', 'HMM_ObservationSequence', 'HMM_State', 'HMM_StateSequence',
+        'Harmonicity', 'ISpline', 'Index', 'Intensity', 'IntensityTier', 'IntervalTier',
+        'KNN', 'KlattGrid', 'KlattTable', 'LFCC', 'LPC', 'Label', 'LegendreSeries',
+        'LinearRegression', 'LogisticRegression', 'LongSound', 'Ltas', 'MFCC', 'MSpline',
+        'ManPages', 'Manipulation', 'Matrix', 'MelFilter', 'MelSpectrogram',
+        'MixingMatrix', 'Movie', 'Network', 'Object', 'OTGrammar', 'OTHistory', 'OTMulti',
+        'PCA', 'PairDistribution', 'ParamCurve', 'Pattern', 'Permutation', 'Photo',
+        'Pitch', 'PitchModeler', 'PitchTier', 'PointProcess', 'Polygon', 'Polynomial',
+        'PowerCepstrogram', 'PowerCepstrum', 'Procrustes', 'RealPoint', 'RealTier',
+        'ResultsMFC', 'Roots', 'SPINET', 'SSCP', 'SVD', 'Salience', 'ScalarProduct',
+        'Similarity', 'SimpleString', 'SortedSetOfString', 'Sound', 'Speaker',
+        'Spectrogram', 'Spectrum', 'SpectrumTier', 'SpeechSynthesizer', 'SpellingChecker',
+        'Strings', 'StringsIndex', 'Table', 'TableOfReal', 'TextGrid', 'TextInterval',
+        'TextPoint', 'TextTier', 'Tier', 'Transition', 'VocalTract', 'VocalTractTier',
+        'Weight', 'WordList',
+    )
+
+    variables_numeric = (
+        'macintosh', 'windows', 'unix', 'praatVersion', 'pi', 'e', 'undefined',
+    )
+
+    variables_string = (
+        'praatVersion', 'tab', 'shellDirectory', 'homeDirectory',
+        'preferencesDirectory', 'newline', 'temporaryDirectory',
+        'defaultDirectory',
+    )
+
+    object_attributes = (
+        'ncol', 'nrow', 'xmin', 'ymin', 'xmax', 'ymax', 'nx', 'ny', 'dx', 'dy',
+    )
+
+    tokens = {
+        'root': [
+            (r'(\s+)(#.*?$)',  bygroups(Whitespace, Comment.Single)),
+            (r'^#.*?$',        Comment.Single),
+            (r';[^\n]*',       Comment.Single),
+            (r'\s+',           Whitespace),
+
+            (r'\bprocedure\b', Keyword,       'procedure_definition'),
+            (r'\bcall\b',      Keyword,       'procedure_call'),
+            (r'@',             Name.Function, 'procedure_call'),
+
+            include('function_call'),
+
+            (words(keywords, suffix=r'\b'), Keyword),
+
+            (r'(\bform\b)(\s+)([^\n]+)',
+             bygroups(Keyword, Whitespace, String), 'old_form'),
+
+            (r'(print(?:line|tab)?|echo|exit|asserterror|pause|send(?:praat|socket)|'
+             r'include|execute|system(?:_nocheck)?)(\s+)',
+             bygroups(Keyword, Whitespace), 'string_unquoted'),
+
+            (r'(goto|label)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Label)),
+
+            include('variable_name'),
+            include('number'),
+
+            (r'"', String, 'string'),
+
+            (words((objects), suffix=r'(?=\s+\S+\n)'), Name.Class, 'string_unquoted'),
+
+            (r'\b[A-Z]', Keyword, 'command'),
+            (r'(\.{3}|[)(,])', Punctuation),
+        ],
+        'command': [
+            (r'( ?[\w()-]+ ?)', Keyword),
+
+            include('string_interpolated'),
+
+            (r'\.{3}', Keyword, ('#pop', 'old_arguments')),
+            (r':', Keyword, ('#pop', 'comma_list')),
+            (r'\s', Whitespace, '#pop'),
+        ],
+        'procedure_call': [
+            (r'\s+', Whitespace),
+            (r'([\w.]+)(?:(:)|(?:(\s*)(\()))',
+             bygroups(Name.Function, Punctuation,
+                      Text.Whitespace, Punctuation), '#pop'),
+            (r'([\w.]+)', Name.Function, ('#pop', 'old_arguments')),
+        ],
+        'procedure_definition': [
+            (r'\s', Whitespace),
+            (r'([\w.]+)(\s*?[(:])',
+             bygroups(Name.Function, Whitespace), '#pop'),
+            (r'([\w.]+)([^\n]*)',
+             bygroups(Name.Function, Text), '#pop'),
+        ],
+        'function_call': [
+            (words(functions_string, suffix=r'\$(?=\s*[:(])'), Name.Function, 'function'),
+            (words(functions_array, suffix=r'#(?=\s*[:(])'),   Name.Function, 'function'),
+            (words(functions_numeric, suffix=r'(?=\s*[:(])'),  Name.Function, 'function'),
+        ],
+        'function': [
+            (r'\s+',   Whitespace),
+            (r':',     Punctuation, ('#pop', 'comma_list')),
+            (r'\s*\(', Punctuation, ('#pop', 'comma_list')),
+        ],
+        'comma_list': [
+            (r'(\s*\n\s*)(\.{3})', bygroups(Whitespace, Punctuation)),
+
+            (r'(\s*)(?:([)\]])|(\n))', bygroups(
+                Whitespace, Punctuation, Whitespace), '#pop'),
+
+            (r'\s+', Whitespace),
+            (r'"',   String, 'string'),
+            (r'\b(if|then|else|fi|endif)\b', Keyword),
+
+            include('function_call'),
+            include('variable_name'),
+            include('operator'),
+            include('number'),
+
+            (r'[()]', Text),
+            (r',', Punctuation),
+        ],
+        'old_arguments': [
+            (r'\n', Whitespace, '#pop'),
+
+            include('variable_name'),
+            include('operator'),
+            include('number'),
+
+            (r'"', String, 'string'),
+            (r'[^\n]', Text),
+        ],
+        'number': [
+            (r'\n', Whitespace, '#pop'),
+            (r'\b\d+(\.\d*)?([eE][-+]?\d+)?%?', Number),
+        ],
+        'object_reference': [
+            include('string_interpolated'),
+            (r'([a-z][a-zA-Z0-9_]*|\d+)', Name.Builtin),
+
+            (words(object_attributes, prefix=r'\.'), Name.Builtin, '#pop'),
+
+            (r'\$', Name.Builtin),
+            (r'\[', Text, '#pop'),
+        ],
+        'variable_name': [
+            include('operator'),
+            include('number'),
+
+            (words(variables_string,  suffix=r'\$'), Name.Variable.Global),
+            (words(variables_numeric,
+             suffix=r'(?=[^a-zA-Z0-9_."\'$#\[:(]|\s|^|$)'),
+             Name.Variable.Global),
+
+            (words(objects, prefix=r'\b', suffix=r"(_)"),
+             bygroups(Name.Builtin, Name.Builtin),
+             'object_reference'),
+
+            (r'\.?_?[a-z][\w.]*(\$|#)?', Text),
+            (r'[\[\]]', Punctuation, 'comma_list'),
+
+            include('string_interpolated'),
+        ],
+        'operator': [
+            (r'([+\/*<>=!-]=?|[&*|][&*|]?|\^|<>)',       Operator),
+            (r'(?', Punctuation),
+            (r'"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|'
+             r'\\[0-7]+\\|\\["\\abcefnrstv]|[^\\"])*"', String.Double),
+            (r"'(?:''|[^'])*'", String.Atom),  # quoted atom
+            # Needs to not be followed by an atom.
+            # (r'=(?=\s|[a-zA-Z\[])', Operator),
+            (r'is\b', Operator),
+            (r'(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])',
+             Operator),
+            (r'(mod|div|not)\b', Operator),
+            (r'_', Keyword),  # The don't-care variable
+            (r'([a-z]+)(:)', bygroups(Name.Namespace, Punctuation)),
+            (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]'
+             r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)'
+             r'(\s*)(:-|-->)',
+             bygroups(Name.Function, Text, Operator)),  # function defn
+            (r'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]'
+             r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)'
+             r'(\s*)(\()',
+             bygroups(Name.Function, Text, Punctuation)),
+            (r'[a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]'
+             r'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*',
+             String.Atom),  # atom, characters
+            # This one includes !
+            (r'[#&*+\-./:<=>?@\\^~\u00a1-\u00bf\u2010-\u303f]+',
+             String.Atom),  # atom, graphics
+            (r'[A-Z_]\w*', Name.Variable),
+            (r'\s+|[\u2000-\u200f\ufff0-\ufffe\uffef]', Text),
+        ],
+        'nested-comment': [
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'[^*/]+', Comment.Multiline),
+            (r'[*/]', Comment.Multiline),
+        ],
+    }
+
+    def analyse_text(text):
+        """Competes with IDL and Visual Prolog on *.pro"""
+        if ':-' in text:
+            # Visual Prolog also uses :-
+            return 0.5
+        else:
+            return 0
+
+
+class LogtalkLexer(RegexLexer):
+    """
+    For Logtalk source code.
+    """
+
+    name = 'Logtalk'
+    url = 'http://logtalk.org/'
+    aliases = ['logtalk']
+    filenames = ['*.lgt', '*.logtalk']
+    mimetypes = ['text/x-logtalk']
+    version_added = '0.10'
+
+    tokens = {
+        'root': [
+            # Directives
+            (r'^\s*:-\s', Punctuation, 'directive'),
+            # Comments
+            (r'%.*?\n', Comment),
+            (r'/\*(.|\n)*?\*/', Comment),
+            # Whitespace
+            (r'\n', Text),
+            (r'\s+', Text),
+            # Numbers
+            (r"0'[\\]?.", Number),
+            (r'0b[01]+', Number.Bin),
+            (r'0o[0-7]+', Number.Oct),
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number),
+            # Variables
+            (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable),
+            # Event handlers
+            (r'(after|before)(?=[(])', Keyword),
+            # Message forwarding handler
+            (r'forward(?=[(])', Keyword),
+            # Execution-context methods
+            (r'(context|parameter|this|se(lf|nder))(?=[(])', Keyword),
+            # Reflection
+            (r'(current_predicate|predicate_property)(?=[(])', Keyword),
+            # DCGs and term expansion
+            (r'(expand_(goal|term)|(goal|term)_expansion|phrase)(?=[(])', Keyword),
+            # Entity
+            (r'(abolish|c(reate|urrent))_(object|protocol|category)(?=[(])', Keyword),
+            (r'(object|protocol|category)_property(?=[(])', Keyword),
+            # Entity relations
+            (r'co(mplements_object|nforms_to_protocol)(?=[(])', Keyword),
+            (r'extends_(object|protocol|category)(?=[(])', Keyword),
+            (r'imp(lements_protocol|orts_category)(?=[(])', Keyword),
+            (r'(instantiat|specializ)es_class(?=[(])', Keyword),
+            # Events
+            (r'(current_event|(abolish|define)_events)(?=[(])', Keyword),
+            # Flags
+            (r'(create|current|set)_logtalk_flag(?=[(])', Keyword),
+            # Compiling, loading, and library paths
+            (r'logtalk_(compile|l(ibrary_path|oad|oad_context)|make(_target_action)?)(?=[(])', Keyword),
+            (r'\blogtalk_make\b', Keyword),
+            # Database
+            (r'(clause|retract(all)?)(?=[(])', Keyword),
+            (r'a(bolish|ssert(a|z))(?=[(])', Keyword),
+            # Control constructs
+            (r'(ca(ll|tch)|throw)(?=[(])', Keyword),
+            (r'(fa(il|lse)|true|(instantiation|system)_error)\b', Keyword),
+            (r'(uninstantiation|type|domain|existence|permission|representation|evaluation|resource|syntax)_error(?=[(])', Keyword),
+            # All solutions
+            (r'((bag|set)of|f(ind|or)all)(?=[(])', Keyword),
+            # Multi-threading predicates
+            (r'threaded(_(ca(ll|ncel)|once|ignore|exit|peek|wait|notify))?(?=[(])', Keyword),
+            # Engine predicates
+            (r'threaded_engine(_(create|destroy|self|next|next_reified|yield|post|fetch))?(?=[(])', Keyword),
+            # Term unification
+            (r'(subsumes_term|unify_with_occurs_check)(?=[(])', Keyword),
+            # Term creation and decomposition
+            (r'(functor|arg|copy_term|numbervars|term_variables)(?=[(])', Keyword),
+            # Evaluable functors
+            (r'(div|rem|m(ax|in|od)|abs|sign)(?=[(])', Keyword),
+            (r'float(_(integer|fractional)_part)?(?=[(])', Keyword),
+            (r'(floor|t(an|runcate)|round|ceiling)(?=[(])', Keyword),
+            # Other arithmetic functors
+            (r'(cos|a(cos|sin|tan|tan2)|exp|log|s(in|qrt)|xor)(?=[(])', Keyword),
+            # Term testing
+            (r'(var|atom(ic)?|integer|float|c(allable|ompound)|n(onvar|umber)|ground|acyclic_term)(?=[(])', Keyword),
+            # Term comparison
+            (r'compare(?=[(])', Keyword),
+            # Stream selection and control
+            (r'(curren|se)t_(in|out)put(?=[(])', Keyword),
+            (r'(open|close)(?=[(])', Keyword),
+            (r'flush_output(?=[(])', Keyword),
+            (r'(at_end_of_stream|flush_output)\b', Keyword),
+            (r'(stream_property|at_end_of_stream|set_stream_position)(?=[(])', Keyword),
+            # Character and byte input/output
+            (r'(nl|(get|peek|put)_(byte|c(har|ode)))(?=[(])', Keyword),
+            (r'\bnl\b', Keyword),
+            # Term input/output
+            (r'read(_term)?(?=[(])', Keyword),
+            (r'write(q|_(canonical|term))?(?=[(])', Keyword),
+            (r'(current_)?op(?=[(])', Keyword),
+            (r'(current_)?char_conversion(?=[(])', Keyword),
+            # Atomic term processing
+            (r'atom_(length|c(hars|o(ncat|des)))(?=[(])', Keyword),
+            (r'(char_code|sub_atom)(?=[(])', Keyword),
+            (r'number_c(har|ode)s(?=[(])', Keyword),
+            # Implementation defined hooks functions
+            (r'(se|curren)t_prolog_flag(?=[(])', Keyword),
+            (r'\bhalt\b', Keyword),
+            (r'halt(?=[(])', Keyword),
+            # Message sending operators
+            (r'(::|:|\^\^)', Operator),
+            # External call
+            (r'[{}]', Keyword),
+            # Logic and control
+            (r'(ignore|once)(?=[(])', Keyword),
+            (r'\brepeat\b', Keyword),
+            # Sorting
+            (r'(key)?sort(?=[(])', Keyword),
+            # Bitwise functors
+            (r'(>>|<<|/\\|\\\\|\\)', Operator),
+            # Predicate aliases
+            (r'\bas\b', Operator),
+            # Arithmetic evaluation
+            (r'\bis\b', Keyword),
+            # Arithmetic comparison
+            (r'(=:=|=\\=|<|=<|>=|>)', Operator),
+            # Term creation and decomposition
+            (r'=\.\.', Operator),
+            # Term unification
+            (r'(=|\\=)', Operator),
+            # Term comparison
+            (r'(==|\\==|@=<|@<|@>=|@>)', Operator),
+            # Evaluable functors
+            (r'(//|[-+*/])', Operator),
+            (r'\b(e|pi|div|mod|rem)\b', Operator),
+            # Other arithmetic functors
+            (r'\b\*\*\b', Operator),
+            # DCG rules
+            (r'-->', Operator),
+            # Control constructs
+            (r'([!;]|->)', Operator),
+            # Logic and control
+            (r'\\+', Operator),
+            # Mode operators
+            (r'[?@]', Operator),
+            # Existential quantifier
+            (r'\^', Operator),
+            # Punctuation
+            (r'[()\[\],.|]', Text),
+            # Atoms
+            (r"[a-z][a-zA-Z0-9_]*", Text),
+            (r"'", String, 'quoted_atom'),
+            # Double-quoted terms
+            (r'"', String, 'double_quoted_term'),
+        ],
+
+        'quoted_atom': [
+            (r"''", String),
+            (r"'", String, '#pop'),
+            (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape),
+            (r"[^\\'\n]+", String),
+            (r'\\', String),
+        ],
+
+        'double_quoted_term': [
+            (r'""', String),
+            (r'"', String, '#pop'),
+            (r'\\([\\abfnrtv"\']|(x[a-fA-F0-9]+|[0-7]+)\\)', String.Escape),
+            (r'[^\\"\n]+', String),
+            (r'\\', String),
+        ],
+
+        'directive': [
+            # Conditional compilation directives
+            (r'(el)?if(?=[(])', Keyword, 'root'),
+            (r'(e(lse|ndif))(?=[.])', Keyword, 'root'),
+            # Entity directives
+            (r'(category|object|protocol)(?=[(])', Keyword, 'entityrelations'),
+            (r'(end_(category|object|protocol))(?=[.])', Keyword, 'root'),
+            # Predicate scope directives
+            (r'(public|protected|private)(?=[(])', Keyword, 'root'),
+            # Other directives
+            (r'e(n(coding|sure_loaded)|xport)(?=[(])', Keyword, 'root'),
+            (r'in(clude|itialization|fo)(?=[(])', Keyword, 'root'),
+            (r'(built_in|dynamic|synchronized|threaded)(?=[.])', Keyword, 'root'),
+            (r'(alias|d(ynamic|iscontiguous)|m(eta_(non_terminal|predicate)|ode|ultifile)|s(et_(logtalk|prolog)_flag|ynchronized))(?=[(])', Keyword, 'root'),
+            (r'op(?=[(])', Keyword, 'root'),
+            (r'(c(alls|oinductive)|module|reexport|use(s|_module))(?=[(])', Keyword, 'root'),
+            (r'[a-z][a-zA-Z0-9_]*(?=[(])', Text, 'root'),
+            (r'[a-z][a-zA-Z0-9_]*(?=[.])', Text, 'root'),
+        ],
+
+        'entityrelations': [
+            (r'(complements|extends|i(nstantiates|mp(lements|orts))|specializes)(?=[(])', Keyword),
+            # Numbers
+            (r"0'[\\]?.", Number),
+            (r'0b[01]+', Number.Bin),
+            (r'0o[0-7]+', Number.Oct),
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'\d+\.?\d*((e|E)(\+|-)?\d+)?', Number),
+            # Variables
+            (r'([A-Z_][a-zA-Z0-9_]*)', Name.Variable),
+            # Atoms
+            (r"[a-z][a-zA-Z0-9_]*", Text),
+            (r"'", String, 'quoted_atom'),
+            # Double-quoted terms
+            (r'"', String, 'double_quoted_term'),
+            # End of entity-opening directive
+            (r'([)]\.)', Text, 'root'),
+            # Scope operator
+            (r'(::)', Operator),
+            # Punctuation
+            (r'[()\[\],.|]', Text),
+            # Comments
+            (r'%.*?\n', Comment),
+            (r'/\*(.|\n)*?\*/', Comment),
+            # Whitespace
+            (r'\n', Text),
+            (r'\s+', Text),
+        ]
+    }
+
+    def analyse_text(text):
+        if ':- object(' in text:
+            return 1.0
+        elif ':- protocol(' in text:
+            return 1.0
+        elif ':- category(' in text:
+            return 1.0
+        elif re.search(r'^:-\s[a-z]', text, re.M):
+            return 0.9
+        else:
+            return 0.0
diff --git a/lib/python3.11/site-packages/pygments/lexers/promql.py b/lib/python3.11/site-packages/pygments/lexers/promql.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cfa73fe1e619918e80828ab1529f268938adcd0
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/promql.py
@@ -0,0 +1,176 @@
+"""
+    pygments.lexers.promql
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Prometheus Query Language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, default, words
+from pygments.token import Comment, Keyword, Name, Number, Operator, \
+    Punctuation, String, Whitespace
+
+__all__ = ["PromQLLexer"]
+
+
+class PromQLLexer(RegexLexer):
+    """
+    For PromQL queries.
+
+    For details about the grammar see:
+    https://github.com/prometheus/prometheus/tree/master/promql/parser
+
+    .. versionadded: 2.7
+    """
+
+    name = "PromQL"
+    url = 'https://prometheus.io/docs/prometheus/latest/querying/basics/'
+    aliases = ["promql"]
+    filenames = ["*.promql"]
+    version_added = ''
+
+    base_keywords = (
+        words(
+            (
+                "bool",
+                "by",
+                "group_left",
+                "group_right",
+                "ignoring",
+                "offset",
+                "on",
+                "without",
+            ),
+            suffix=r"\b",
+        ),
+        Keyword,
+    )
+
+    aggregator_keywords = (
+        words(
+            (
+                "sum",
+                "min",
+                "max",
+                "avg",
+                "group",
+                "stddev",
+                "stdvar",
+                "count",
+                "count_values",
+                "bottomk",
+                "topk",
+                "quantile",
+            ),
+            suffix=r"\b",
+        ),
+        Keyword,
+    )
+
+    function_keywords = (
+        words(
+            (
+                "abs",
+                "absent",
+                "absent_over_time",
+                "avg_over_time",
+                "ceil",
+                "changes",
+                "clamp_max",
+                "clamp_min",
+                "count_over_time",
+                "day_of_month",
+                "day_of_week",
+                "days_in_month",
+                "delta",
+                "deriv",
+                "exp",
+                "floor",
+                "histogram_quantile",
+                "holt_winters",
+                "hour",
+                "idelta",
+                "increase",
+                "irate",
+                "label_join",
+                "label_replace",
+                "ln",
+                "log10",
+                "log2",
+                "max_over_time",
+                "min_over_time",
+                "minute",
+                "month",
+                "predict_linear",
+                "quantile_over_time",
+                "rate",
+                "resets",
+                "round",
+                "scalar",
+                "sort",
+                "sort_desc",
+                "sqrt",
+                "stddev_over_time",
+                "stdvar_over_time",
+                "sum_over_time",
+                "time",
+                "timestamp",
+                "vector",
+                "year",
+            ),
+            suffix=r"\b",
+        ),
+        Keyword.Reserved,
+    )
+
+    tokens = {
+        "root": [
+            (r"\n", Whitespace),
+            (r"\s+", Whitespace),
+            (r",", Punctuation),
+            # Keywords
+            base_keywords,
+            aggregator_keywords,
+            function_keywords,
+            # Offsets
+            (r"[1-9][0-9]*[smhdwy]", String),
+            # Numbers
+            (r"-?[0-9]+\.[0-9]+", Number.Float),
+            (r"-?[0-9]+", Number.Integer),
+            # Comments
+            (r"#.*?$", Comment.Single),
+            # Operators
+            (r"(\+|\-|\*|\/|\%|\^)", Operator),
+            (r"==|!=|>=|<=|<|>", Operator),
+            (r"and|or|unless", Operator.Word),
+            # Metrics
+            (r"[_a-zA-Z][a-zA-Z0-9_]+", Name.Variable),
+            # Params
+            (r'(["\'])(.*?)(["\'])', bygroups(Punctuation, String, Punctuation)),
+            # Other states
+            (r"\(", Operator, "function"),
+            (r"\)", Operator),
+            (r"\{", Punctuation, "labels"),
+            (r"\[", Punctuation, "range"),
+        ],
+        "labels": [
+            (r"\}", Punctuation, "#pop"),
+            (r"\n", Whitespace),
+            (r"\s+", Whitespace),
+            (r",", Punctuation),
+            (r'([_a-zA-Z][a-zA-Z0-9_]*?)(\s*?)(=~|!=|=|!~)(\s*?)("|\')(.*?)("|\')',
+             bygroups(Name.Label, Whitespace, Operator, Whitespace,
+                      Punctuation, String, Punctuation)),
+        ],
+        "range": [
+            (r"\]", Punctuation, "#pop"),
+            (r"[1-9][0-9]*[smhdwy]", String),
+        ],
+        "function": [
+            (r"\)", Operator, "#pop"),
+            (r"\(", Operator, "#push"),
+            default("#pop"),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/prql.py b/lib/python3.11/site-packages/pygments/lexers/prql.py
new file mode 100644
index 0000000000000000000000000000000000000000..a62cb6bcd1a9ff89660b996ebda8106f687d296a
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/prql.py
@@ -0,0 +1,251 @@
+"""
+    pygments.lexers.prql
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for the PRQL query language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, combined, words, include, bygroups
+from pygments.token import Comment, Literal, Keyword, Name, Number, Operator, \
+    Punctuation, String, Text, Whitespace
+
+__all__ = ['PrqlLexer']
+
+
+class PrqlLexer(RegexLexer):
+    """
+    For PRQL source code.
+
+    grammar: https://github.com/PRQL/prql/tree/main/grammars
+    """
+
+    name = 'PRQL'
+    url = 'https://prql-lang.org/'
+    aliases = ['prql']
+    filenames = ['*.prql']
+    mimetypes = ['application/prql', 'application/x-prql']
+    version_added = '2.17'
+
+    builtinTypes = words((
+        "bool",
+        "int",
+        "int8", "int16", "int32", "int64", "int128",
+        "float",
+        "text",
+        "set"), suffix=r'\b')
+
+    def innerstring_rules(ttype):
+        return [
+            # the new style '{}'.format(...) string formatting
+            (r'\{'
+             r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?'  # field name
+             r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?'
+             r'\}', String.Interpol),
+
+            (r'[^\\\'"%{\n]+', ttype),
+            (r'[\'"\\]', ttype),
+            (r'%|(\{{1,2})', ttype)
+        ]
+
+    def fstring_rules(ttype):
+        return [
+            (r'\}', String.Interpol),
+            (r'\{', String.Interpol, 'expr-inside-fstring'),
+            (r'[^\\\'"{}\n]+', ttype),
+            (r'[\'"\\]', ttype),
+        ]
+
+    tokens = {
+        'root': [
+
+            # Comments
+            (r'#!.*', String.Doc),
+            (r'#.*', Comment.Single),
+
+            # Whitespace
+            (r'\s+', Whitespace),
+
+            # Modules
+            (r'^(\s*)(module)(\s*)',
+             bygroups(Whitespace, Keyword.Namespace, Whitespace),
+             'imports'),
+
+            (builtinTypes, Keyword.Type),
+
+            # Main
+            (r'^prql ', Keyword.Reserved),
+
+            ('let', Keyword.Declaration),
+
+            include('keywords'),
+            include('expr'),
+
+            # Transforms
+            (r'^[A-Za-z_][a-zA-Z0-9_]*', Keyword),
+        ],
+        'expr': [
+            # non-raw f-strings
+            ('(f)(""")', bygroups(String.Affix, String.Double),
+             combined('fstringescape', 'tdqf')),
+            ("(f)(''')", bygroups(String.Affix, String.Single),
+             combined('fstringescape', 'tsqf')),
+            ('(f)(")', bygroups(String.Affix, String.Double),
+             combined('fstringescape', 'dqf')),
+            ("(f)(')", bygroups(String.Affix, String.Single),
+             combined('fstringescape', 'sqf')),
+
+            # non-raw s-strings
+            ('(s)(""")', bygroups(String.Affix, String.Double),
+             combined('stringescape', 'tdqf')),
+            ("(s)(''')", bygroups(String.Affix, String.Single),
+             combined('stringescape', 'tsqf')),
+            ('(s)(")', bygroups(String.Affix, String.Double),
+             combined('stringescape', 'dqf')),
+            ("(s)(')", bygroups(String.Affix, String.Single),
+             combined('stringescape', 'sqf')),
+
+            # raw strings
+            ('(?i)(r)(""")',
+             bygroups(String.Affix, String.Double), 'tdqs'),
+            ("(?i)(r)(''')",
+             bygroups(String.Affix, String.Single), 'tsqs'),
+            ('(?i)(r)(")',
+             bygroups(String.Affix, String.Double), 'dqs'),
+            ("(?i)(r)(')",
+             bygroups(String.Affix, String.Single), 'sqs'),
+
+            # non-raw strings
+            ('"""', String.Double, combined('stringescape', 'tdqs')),
+            ("'''", String.Single, combined('stringescape', 'tsqs')),
+            ('"', String.Double, combined('stringescape', 'dqs')),
+            ("'", String.Single, combined('stringescape', 'sqs')),
+
+            # Time and dates
+            (r'@\d{4}-\d{2}-\d{2}T\d{2}(:\d{2})?(:\d{2})?(\.\d{1,6})?(Z|[+-]\d{1,2}(:\d{1,2})?)?', Literal.Date),
+            (r'@\d{4}-\d{2}-\d{2}', Literal.Date),
+            (r'@\d{2}(:\d{2})?(:\d{2})?(\.\d{1,6})?(Z|[+-]\d{1,2}(:\d{1,2})?)?', Literal.Date),
+
+            (r'[^\S\n]+', Text),
+            include('numbers'),
+            (r'->|=>|==|!=|>=|<=|~=|&&|\|\||\?\?|\/\/', Operator),
+            (r'[-~+/*%=<>&^|.@]', Operator),
+            (r'[]{}:(),;[]', Punctuation),
+            include('functions'),
+
+            # Variable Names
+            (r'[A-Za-z_][a-zA-Z0-9_]*', Name.Variable),
+        ],
+        'numbers': [
+            (r'(\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|(?:\d(?:_?\d)*)?\.\d(?:_?\d)*)'
+             r'([eE][+-]?\d(?:_?\d)*)?', Number.Float),
+            (r'\d(?:_?\d)*[eE][+-]?\d(?:_?\d)*j?', Number.Float),
+            (r'0[oO](?:_?[0-7])+', Number.Oct),
+            (r'0[bB](?:_?[01])+', Number.Bin),
+            (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex),
+            (r'\d(?:_?\d)*', Number.Integer),
+        ],
+        'fstringescape': [
+            include('stringescape'),
+        ],
+        'bytesescape': [
+            (r'\\([\\bfnrt"\']|\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
+        ],
+        'stringescape': [
+            (r'\\(N\{.*?\}|u\{[a-fA-F0-9]{1,6}\})', String.Escape),
+            include('bytesescape')
+        ],
+        'fstrings-single': fstring_rules(String.Single),
+        'fstrings-double': fstring_rules(String.Double),
+        'strings-single': innerstring_rules(String.Single),
+        'strings-double': innerstring_rules(String.Double),
+        'dqf': [
+            (r'"', String.Double, '#pop'),
+            (r'\\\\|\\"|\\\n', String.Escape),  # included here for raw strings
+            include('fstrings-double')
+        ],
+        'sqf': [
+            (r"'", String.Single, '#pop'),
+            (r"\\\\|\\'|\\\n", String.Escape),  # included here for raw strings
+            include('fstrings-single')
+        ],
+        'dqs': [
+            (r'"', String.Double, '#pop'),
+            (r'\\\\|\\"|\\\n', String.Escape),  # included here for raw strings
+            include('strings-double')
+        ],
+        'sqs': [
+            (r"'", String.Single, '#pop'),
+            (r"\\\\|\\'|\\\n", String.Escape),  # included here for raw strings
+            include('strings-single')
+        ],
+        'tdqf': [
+            (r'"""', String.Double, '#pop'),
+            include('fstrings-double'),
+            (r'\n', String.Double)
+        ],
+        'tsqf': [
+            (r"'''", String.Single, '#pop'),
+            include('fstrings-single'),
+            (r'\n', String.Single)
+        ],
+        'tdqs': [
+            (r'"""', String.Double, '#pop'),
+            include('strings-double'),
+            (r'\n', String.Double)
+        ],
+        'tsqs': [
+            (r"'''", String.Single, '#pop'),
+            include('strings-single'),
+            (r'\n', String.Single)
+        ],
+
+        'expr-inside-fstring': [
+            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),
+            # without format specifier
+            (r'(=\s*)?'         # debug (https://bugs.python.org/issue36817)
+             r'\}', String.Interpol, '#pop'),
+            # with format specifier
+            # we'll catch the remaining '}' in the outer scope
+            (r'(=\s*)?'         # debug (https://bugs.python.org/issue36817)
+             r':', String.Interpol, '#pop'),
+            (r'\s+', Whitespace),  # allow new lines
+            include('expr'),
+        ],
+        'expr-inside-fstring-inner': [
+            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),
+            (r'[])}]', Punctuation, '#pop'),
+            (r'\s+', Whitespace),  # allow new lines
+            include('expr'),
+        ],
+        'keywords': [
+            (words((
+                'into', 'case', 'type', 'module', 'internal',
+            ), suffix=r'\b'),
+                Keyword),
+            (words(('true', 'false', 'null'), suffix=r'\b'), Keyword.Constant),
+        ],
+        'functions': [
+            (words((
+                "min", "max", "sum", "average", "stddev", "every", "any",
+                "concat_array", "count", "lag", "lead", "first", "last",
+                "rank", "rank_dense", "row_number", "round", "as", "in",
+                "tuple_every", "tuple_map", "tuple_zip", "_eq", "_is_null",
+                "from_text", "lower", "upper", "read_parquet", "read_csv"),
+                suffix=r'\b'),
+             Name.Function),
+        ],
+
+        'comment': [
+            (r'-(?!\})', Comment.Multiline),
+            (r'\{-', Comment.Multiline, 'comment'),
+            (r'[^-}]', Comment.Multiline),
+            (r'-\}', Comment.Multiline, '#pop'),
+        ],
+
+        'imports': [
+            (r'\w+(\.\w+)*', Name.Class, '#pop'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/ptx.py b/lib/python3.11/site-packages/pygments/lexers/ptx.py
new file mode 100644
index 0000000000000000000000000000000000000000..685c7357ecb2548069d3b5506fae5f8ba8ceb65b
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/ptx.py
@@ -0,0 +1,119 @@
+"""
+    pygments.lexers.ptx
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexer for other PTX language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, include, words
+from pygments.token import Comment, Keyword, Name, String, Number, \
+    Punctuation, Whitespace, Operator
+
+__all__ = ["PtxLexer"]
+
+
+class PtxLexer(RegexLexer):
+    """
+    For NVIDIA `PTX `_
+    source.
+    """
+    name = 'PTX'
+    url = "https://docs.nvidia.com/cuda/parallel-thread-execution/"
+    filenames = ['*.ptx']
+    aliases = ['ptx']
+    mimetypes = ['text/x-ptx']
+    version_added = '2.16'
+
+    #: optional Comment or Whitespace
+    string = r'"[^"]*?"'
+    followsym = r'[a-zA-Z0-9_$]'
+    identifier = r'([-a-zA-Z$._][\w\-$.]*|' + string + ')'
+    block_label = r'(' + identifier + r'|(\d+))'
+
+    tokens = {
+        'root': [
+            include('whitespace'),
+
+            (block_label + r'\s*:', Name.Label),
+
+            include('keyword'),
+
+            (r'%' + identifier, Name.Variable),
+            (r'%\d+', Name.Variable.Anonymous),
+            (r'c?' + string, String),
+            (identifier, Name.Variable),
+            (r';', Punctuation),
+            (r'[*+-/]', Operator),
+
+            (r'0[xX][a-fA-F0-9]+', Number),
+            (r'-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?', Number),
+
+            (r'[=<>{}\[\]()*.,!]|x\b', Punctuation)
+
+        ],
+        'whitespace': [
+            (r'(\n|\s+)+', Whitespace),
+            (r'//.*?\n', Comment)
+        ],
+
+        'keyword': [
+            # Instruction keywords
+            (words((
+                'abs', 'discard', 'min', 'shf', 'vadd',
+                'activemask', 'div', 'mma', 'shfl', 'vadd2',
+                'add', 'dp2a', 'mov', 'shl', 'vadd4',
+                'addc', 'dp4a', 'movmatrix', 'shr', 'vavrg2',
+                'alloca', 'elect', 'mul', 'sin', 'vavrg4',
+                'and', 'ex2', 'mul24', 'slct', 'vmad',
+                'applypriority', 'exit', 'multimem', 'sqrt', 'vmax',
+                'atom', 'fence', 'nanosleep', 'st', 'vmax2',
+                'bar', 'fma', 'neg', 'stackrestore', 'vmax4',
+                'barrier', 'fns', 'not', 'stacksave', 'vmin',
+                'bfe', 'getctarank', 'or', 'stmatrix', 'vmin2',
+                'bfi', 'griddepcontrol', 'pmevent', 'sub', 'vmin4',
+                'bfind', 'isspacep', 'popc', 'subc', 'vote',
+                'bmsk', 'istypep', 'prefetch', 'suld', 'vset',
+                'bra', 'ld', 'prefetchu', 'suq', 'vset2',
+                'brev', 'ldmatrix', 'prmt', 'sured', 'vset4',
+                'brkpt', 'ldu', 'rcp', 'sust', 'vshl',
+                'brx', 'lg2', 'red', 'szext', 'vshr',
+                'call', 'lop3', 'redux', 'tanh', 'vsub',
+                'clz', 'mad', 'rem', 'testp', 'vsub2',
+                'cnot', 'mad24', 'ret', 'tex', 'vsub4',
+                'copysign', 'madc', 'rsqrt', 'tld4', 'wgmma',
+                'cos', 'mapa', 'sad', 'trap', 'wmma',
+                'cp', 'match', 'selp', 'txq', 'xor',
+                'createpolicy', 'max', 'set', 'vabsdiff', 'cvt',
+                'mbarrier', 'setmaxnreg', 'vabsdiff2', 'cvta',
+                'membar', 'setp', 'vabsdiff4')), Keyword),
+            # State Spaces and Suffixes
+            (words((
+                'reg', '.sreg', '.const', '.global',
+                '.local', '.param', '.shared', '.tex',
+                '.wide', '.loc'
+            )), Keyword.Pseudo),
+            # PTX Directives
+            (words((
+                '.address_size', '.explicitcluster', '.maxnreg', '.section',
+                '.alias', '.extern', '.maxntid', '.shared',
+                '.align', '.file', '.minnctapersm', '.sreg',
+                '.branchtargets', '.func', '.noreturn', '.target',
+                '.callprototype', '.global', '.param', '.tex',
+                '.calltargets', '.loc', '.pragma', '.version',
+                '.common', '.local', '.reg', '.visible',
+                '.const', '.maxclusterrank', '.reqnctapercluster', '.weak',
+                '.entry', '.maxnctapersm', '.reqntid')), Keyword.Reserved),
+            # Fundamental Types
+            (words((
+                '.s8', '.s16', '.s32', '.s64',
+                '.u8', '.u16', '.u32', '.u64',
+                '.f16', '.f16x2', '.f32', '.f64',
+                '.b8', '.b16', '.b32', '.b64',
+                '.pred'
+            )), Keyword.Type)
+        ],
+
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/python.py b/lib/python3.11/site-packages/pygments/lexers/python.py
new file mode 100644
index 0000000000000000000000000000000000000000..b296c8dbe4ed35625167711800abd9642b61c84b
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/python.py
@@ -0,0 +1,1204 @@
+"""
+    pygments.lexers.python
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Python and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import keyword
+
+from pygments.lexer import DelegatingLexer, RegexLexer, include, \
+    bygroups, using, default, words, combined, this
+from pygments.util import get_bool_opt, shebang_matches
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Generic, Other, Error, Whitespace
+from pygments import unistring as uni
+
+__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer',
+           'Python2Lexer', 'Python2TracebackLexer',
+           'CythonLexer', 'DgLexer', 'NumPyLexer']
+
+
+class PythonLexer(RegexLexer):
+    """
+    For Python source code (version 3.x).
+
+    .. versionchanged:: 2.5
+       This is now the default ``PythonLexer``.  It is still available as the
+       alias ``Python3Lexer``.
+    """
+
+    name = 'Python'
+    url = 'https://www.python.org'
+    aliases = ['python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark', 'pyi']
+    filenames = [
+        '*.py',
+        '*.pyw',
+        # Type stubs
+        '*.pyi',
+        # Jython
+        '*.jy',
+        # Sage
+        '*.sage',
+        # SCons
+        '*.sc',
+        'SConstruct',
+        'SConscript',
+        # Skylark/Starlark (used by Bazel, Buck, and Pants)
+        '*.bzl',
+        'BUCK',
+        'BUILD',
+        'BUILD.bazel',
+        'WORKSPACE',
+        # Twisted Application infrastructure
+        '*.tac',
+        # Execubot level format
+        '*.pye',
+    ]
+    mimetypes = ['text/x-python', 'application/x-python',
+                 'text/x-python3', 'application/x-python3']
+    version_added = '0.10'
+
+    uni_name = f"[{uni.xid_start}][{uni.xid_continue}]*"
+
+    def innerstring_rules(ttype):
+        return [
+            # the old style '%s' % (...) string formatting (still valid in Py3)
+            (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
+             '[hlL]?[E-GXc-giorsaux%]', String.Interpol),
+            # the new style '{}'.format(...) string formatting
+            (r'\{'
+             r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?'  # field name
+             r'(\![sra])?'                       # conversion
+             r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?'
+             r'\}', String.Interpol),
+
+            # backslashes, quotes and formatting signs must be parsed one at a time
+            (r'[^\\\'"%{\n]+', ttype),
+            (r'[\'"\\]', ttype),
+            # unhandled string formatting sign
+            (r'%|(\{{1,2})', ttype)
+            # newlines are an error (use "nl" state)
+        ]
+
+    def fstring_rules(ttype):
+        return [
+            # Assuming that a '}' is the closing brace after format specifier.
+            # Sadly, this means that we won't detect syntax error. But it's
+            # more important to parse correct syntax correctly, than to
+            # highlight invalid syntax.
+            (r'\}', String.Interpol),
+            (r'\{', String.Interpol, 'expr-inside-fstring'),
+            # backslashes, quotes and formatting signs must be parsed one at a time
+            (r'[^\\\'"{}\n]+', ttype),
+            (r'[\'"\\]', ttype),
+            # newlines are an error (use "nl" state)
+        ]
+
+    tokens = {
+        'root': [
+            (r'\n', Whitespace),
+            (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")',
+             bygroups(Whitespace, String.Affix, String.Doc)),
+            (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')",
+             bygroups(Whitespace, String.Affix, String.Doc)),
+            (r'\A#!.+$', Comment.Hashbang),
+            (r'#.*$', Comment.Single),
+            (r'\\\n', Text),
+            (r'\\', Text),
+            include('keywords'),
+            include('soft-keywords'),
+            (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'),
+            (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'classname'),
+            (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace),
+             'fromimport'),
+            (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace),
+             'import'),
+            include('expr'),
+        ],
+        'expr': [
+            # raw f-strings and t-strings
+            ('(?i)(r[ft]|[ft]r)(""")',
+             bygroups(String.Affix, String.Double),
+             combined('rfstringescape', 'tdqf')),
+            ("(?i)(r[ft]|[ft]r)(''')",
+             bygroups(String.Affix, String.Single),
+             combined('rfstringescape', 'tsqf')),
+            ('(?i)(r[ft]|[ft]r)(")',
+             bygroups(String.Affix, String.Double),
+             combined('rfstringescape', 'dqf')),
+            ("(?i)(r[ft]|[ft]r)(')",
+             bygroups(String.Affix, String.Single),
+             combined('rfstringescape', 'sqf')),
+            # non-raw f-strings and t-strings
+            ('([fFtT])(""")', bygroups(String.Affix, String.Double),
+             combined('fstringescape', 'tdqf')),
+            ("([fFtT])(''')", bygroups(String.Affix, String.Single),
+             combined('fstringescape', 'tsqf')),
+            ('([fFtT])(")', bygroups(String.Affix, String.Double),
+             combined('fstringescape', 'dqf')),
+            ("([fFtT])(')", bygroups(String.Affix, String.Single),
+             combined('fstringescape', 'sqf')),
+            # raw bytes and strings
+            ('(?i)(rb|br|r)(""")',
+             bygroups(String.Affix, String.Double), 'tdqs'),
+            ("(?i)(rb|br|r)(''')",
+             bygroups(String.Affix, String.Single), 'tsqs'),
+            ('(?i)(rb|br|r)(")',
+             bygroups(String.Affix, String.Double), 'dqs'),
+            ("(?i)(rb|br|r)(')",
+             bygroups(String.Affix, String.Single), 'sqs'),
+            # non-raw strings
+            ('([uU]?)(""")', bygroups(String.Affix, String.Double),
+             combined('stringescape', 'tdqs')),
+            ("([uU]?)(''')", bygroups(String.Affix, String.Single),
+             combined('stringescape', 'tsqs')),
+            ('([uU]?)(")', bygroups(String.Affix, String.Double),
+             combined('stringescape', 'dqs')),
+            ("([uU]?)(')", bygroups(String.Affix, String.Single),
+             combined('stringescape', 'sqs')),
+            # non-raw bytes
+            ('([bB])(""")', bygroups(String.Affix, String.Double),
+             combined('bytesescape', 'tdqs')),
+            ("([bB])(''')", bygroups(String.Affix, String.Single),
+             combined('bytesescape', 'tsqs')),
+            ('([bB])(")', bygroups(String.Affix, String.Double),
+             combined('bytesescape', 'dqs')),
+            ("([bB])(')", bygroups(String.Affix, String.Single),
+             combined('bytesescape', 'sqs')),
+
+            (r'[^\S\n]+', Text),
+            include('numbers'),
+            (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator),
+            (r'[]{}:(),;[]', Punctuation),
+            (r'(in|is|and|or|not)\b', Operator.Word),
+            include('expr-keywords'),
+            include('builtins'),
+            include('magicfuncs'),
+            include('magicvars'),
+            include('name'),
+        ],
+        'expr-inside-fstring': [
+            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),
+            # without format specifier
+            (r'(=\s*)?'         # debug (https://bugs.python.org/issue36817)
+             r'(\![sraf])?'     # conversion
+             r'\}', String.Interpol, '#pop'),
+            # with format specifier
+            # we'll catch the remaining '}' in the outer scope
+            (r'(=\s*)?'         # debug (https://bugs.python.org/issue36817)
+             r'(\![sraf])?'     # conversion
+             r':', String.Interpol, '#pop'),
+            (r'\s+', Whitespace),  # allow new lines
+            include('expr'),
+        ],
+        'expr-inside-fstring-inner': [
+            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),
+            (r'[])}]', Punctuation, '#pop'),
+            (r'\s+', Whitespace),  # allow new lines
+            include('expr'),
+        ],
+        'expr-keywords': [
+            # Based on https://docs.python.org/3/reference/expressions.html
+            (words((
+                'async for', 'await', 'else', 'for', 'if', 'lambda',
+                'yield', 'yield from'), suffix=r'\b'),
+             Keyword),
+            (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant),
+        ],
+        'keywords': [
+            (words((
+                'assert', 'async', 'await', 'break', 'continue', 'del', 'elif',
+                'else', 'except', 'finally', 'for', 'global', 'if', 'lambda',
+                'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield',
+                'yield from', 'as', 'with'), suffix=r'\b'),
+             Keyword),
+            (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant),
+        ],
+        'soft-keywords': [
+            # `match`, `case` and `_` soft keywords
+            (r'(^[ \t]*)'              # at beginning of line + possible indentation
+             r'(match|case)\b'         # a possible keyword
+             r'(?![ \t]*(?:'           # not followed by...
+             r'[:,;=^&|@~)\]}]|(?:' +  # characters and keywords that mean this isn't
+                                       # pattern matching (but None/True/False is ok)
+             r'|'.join(k for k in keyword.kwlist if k[0].islower()) + r')\b))',
+             bygroups(Text, Keyword), 'soft-keywords-inner'),
+        ],
+        'soft-keywords-inner': [
+            # optional `_` keyword
+            (r'(\s+)([^\n_]*)(_\b)', bygroups(Whitespace, using(this), Keyword)),
+            default('#pop')
+        ],
+        'builtins': [
+            (words((
+                '__import__', 'abs', 'aiter', 'all', 'any', 'bin', 'bool', 'bytearray',
+                'breakpoint', 'bytes', 'callable', 'chr', 'classmethod', 'compile',
+                'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',
+                'filter', 'float', 'format', 'frozenset', 'getattr', 'globals',
+                'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance',
+                'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max',
+                'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow',
+                'print', 'property', 'range', 'repr', 'reversed', 'round', 'set',
+                'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
+                'tuple', 'type', 'vars', 'zip'), prefix=r'(?>|[-~+/*%=<>&^|.]', Operator),
+            include('keywords'),
+            (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'funcname'),
+            (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Whitespace), 'classname'),
+            (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace),
+             'fromimport'),
+            (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Whitespace),
+             'import'),
+            include('builtins'),
+            include('magicfuncs'),
+            include('magicvars'),
+            include('backtick'),
+            ('([rR]|[uUbB][rR]|[rR][uUbB])(""")',
+             bygroups(String.Affix, String.Double), 'tdqs'),
+            ("([rR]|[uUbB][rR]|[rR][uUbB])(''')",
+             bygroups(String.Affix, String.Single), 'tsqs'),
+            ('([rR]|[uUbB][rR]|[rR][uUbB])(")',
+             bygroups(String.Affix, String.Double), 'dqs'),
+            ("([rR]|[uUbB][rR]|[rR][uUbB])(')",
+             bygroups(String.Affix, String.Single), 'sqs'),
+            ('([uUbB]?)(""")', bygroups(String.Affix, String.Double),
+             combined('stringescape', 'tdqs')),
+            ("([uUbB]?)(''')", bygroups(String.Affix, String.Single),
+             combined('stringescape', 'tsqs')),
+            ('([uUbB]?)(")', bygroups(String.Affix, String.Double),
+             combined('stringescape', 'dqs')),
+            ("([uUbB]?)(')", bygroups(String.Affix, String.Single),
+             combined('stringescape', 'sqs')),
+            include('name'),
+            include('numbers'),
+        ],
+        'keywords': [
+            (words((
+                'assert', 'break', 'continue', 'del', 'elif', 'else', 'except',
+                'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass',
+                'print', 'raise', 'return', 'try', 'while', 'yield',
+                'yield from', 'as', 'with'), suffix=r'\b'),
+             Keyword),
+        ],
+        'builtins': [
+            (words((
+                '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin',
+                'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod',
+                'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
+                'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
+                'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id',
+                'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',
+                'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object',
+                'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce',
+                'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
+                'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',
+                'unichr', 'unicode', 'vars', 'xrange', 'zip'),
+                prefix=r'(?>> )(.*\n)', bygroups(Generic.Prompt, Other.Code), 'continuations'),
+            # This happens, e.g., when tracebacks are embedded in documentation;
+            # trailing whitespaces are often stripped in such contexts.
+            (r'(>>>)(\n)', bygroups(Generic.Prompt, Whitespace)),
+            (r'(\^C)?Traceback \(most recent call last\):\n', Other.Traceback, 'traceback'),
+            # SyntaxError starts with this
+            (r'  File "[^"]+", line \d+', Other.Traceback, 'traceback'),
+            (r'.*\n', Generic.Output),
+        ],
+        'continuations': [
+            (r'(\.\.\. )(.*\n)', bygroups(Generic.Prompt, Other.Code)),
+            # See above.
+            (r'(\.\.\.)(\n)', bygroups(Generic.Prompt, Whitespace)),
+            default('#pop'),
+        ],
+        'traceback': [
+            # As soon as we see a traceback, consume everything until the next
+            # >>> prompt.
+            (r'(?=>>>( |$))', Text, '#pop'),
+            (r'(KeyboardInterrupt)(\n)', bygroups(Name.Class, Whitespace)),
+            (r'.*\n', Other.Traceback),
+        ],
+    }
+
+
+class PythonConsoleLexer(DelegatingLexer):
+    """
+    For Python console output or doctests, such as:
+
+    .. sourcecode:: pycon
+
+        >>> a = 'foo'
+        >>> print(a)
+        foo
+        >>> 1 / 0
+        Traceback (most recent call last):
+          File "", line 1, in 
+        ZeroDivisionError: integer division or modulo by zero
+
+    Additional options:
+
+    `python3`
+        Use Python 3 lexer for code.  Default is ``True``.
+
+        .. versionadded:: 1.0
+        .. versionchanged:: 2.5
+           Now defaults to ``True``.
+    """
+
+    name = 'Python console session'
+    aliases = ['pycon', 'python-console']
+    mimetypes = ['text/x-python-doctest']
+    url = 'https://python.org'
+    version_added = ''
+
+    def __init__(self, **options):
+        python3 = get_bool_opt(options, 'python3', True)
+        if python3:
+            pylexer = PythonLexer
+            tblexer = PythonTracebackLexer
+        else:
+            pylexer = Python2Lexer
+            tblexer = Python2TracebackLexer
+        # We have two auxiliary lexers. Use DelegatingLexer twice with
+        # different tokens.  TODO: DelegatingLexer should support this
+        # directly, by accepting a tuplet of auxiliary lexers and a tuple of
+        # distinguishing tokens. Then we wouldn't need this intermediary
+        # class.
+        class _ReplaceInnerCode(DelegatingLexer):
+            def __init__(self, **options):
+                super().__init__(pylexer, _PythonConsoleLexerBase, Other.Code, **options)
+        super().__init__(tblexer, _ReplaceInnerCode, Other.Traceback, **options)
+
+
+class PythonTracebackLexer(RegexLexer):
+    """
+    For Python 3.x tracebacks, with support for chained exceptions.
+
+    .. versionchanged:: 2.5
+       This is now the default ``PythonTracebackLexer``.  It is still available
+       as the alias ``Python3TracebackLexer``.
+    """
+
+    name = 'Python Traceback'
+    aliases = ['pytb', 'py3tb']
+    filenames = ['*.pytb', '*.py3tb']
+    mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback']
+    url = 'https://python.org'
+    version_added = '1.0'
+
+    tokens = {
+        'root': [
+            (r'\n', Whitespace),
+            (r'^(\^C)?Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'),
+            (r'^During handling of the above exception, another '
+             r'exception occurred:\n\n', Generic.Traceback),
+            (r'^The above exception was the direct cause of the '
+             r'following exception:\n\n', Generic.Traceback),
+            (r'^(?=  File "[^"]+", line \d+)', Generic.Traceback, 'intb'),
+            (r'^.*\n', Other),
+        ],
+        'intb': [
+            (r'^(  File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)',
+             bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)),
+            (r'^(  File )("[^"]+")(, line )(\d+)(\n)',
+             bygroups(Text, Name.Builtin, Text, Number, Whitespace)),
+            (r'^(    )(.+)(\n)',
+             bygroups(Whitespace, using(PythonLexer), Whitespace), 'markers'),
+            (r'^([ \t]*)(\.\.\.)(\n)',
+             bygroups(Whitespace, Comment, Whitespace)),  # for doctests...
+            (r'^([^:]+)(: )(.+)(\n)',
+             bygroups(Generic.Error, Text, Name, Whitespace), '#pop'),
+            (r'^([a-zA-Z_][\w.]*)(:?\n)',
+             bygroups(Generic.Error, Whitespace), '#pop'),
+            default('#pop'),
+        ],
+        'markers': [
+            # Either `PEP 657 `
+            # error locations in Python 3.11+, or single-caret markers
+            # for syntax errors before that.
+            (r'^( {4,})([~^]+)(\n)',
+             bygroups(Whitespace, Punctuation.Marker, Whitespace),
+             '#pop'),
+            default('#pop'),
+        ],
+    }
+
+
+Python3TracebackLexer = PythonTracebackLexer
+
+
+class Python2TracebackLexer(RegexLexer):
+    """
+    For Python tracebacks.
+
+    .. versionchanged:: 2.5
+       This class has been renamed from ``PythonTracebackLexer``.
+       ``PythonTracebackLexer`` now refers to the Python 3 variant.
+    """
+
+    name = 'Python 2.x Traceback'
+    aliases = ['py2tb']
+    filenames = ['*.py2tb']
+    mimetypes = ['text/x-python2-traceback']
+    url = 'https://python.org'
+    version_added = '0.7'
+
+    tokens = {
+        'root': [
+            # Cover both (most recent call last) and (innermost last)
+            # The optional ^C allows us to catch keyboard interrupt signals.
+            (r'^(\^C)?(Traceback.*\n)',
+             bygroups(Text, Generic.Traceback), 'intb'),
+            # SyntaxError starts with this.
+            (r'^(?=  File "[^"]+", line \d+)', Generic.Traceback, 'intb'),
+            (r'^.*\n', Other),
+        ],
+        'intb': [
+            (r'^(  File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)',
+             bygroups(Text, Name.Builtin, Text, Number, Text, Name, Whitespace)),
+            (r'^(  File )("[^"]+")(, line )(\d+)(\n)',
+             bygroups(Text, Name.Builtin, Text, Number, Whitespace)),
+            (r'^(    )(.+)(\n)',
+             bygroups(Text, using(Python2Lexer), Whitespace), 'marker'),
+            (r'^([ \t]*)(\.\.\.)(\n)',
+             bygroups(Text, Comment, Whitespace)),  # for doctests...
+            (r'^([^:]+)(: )(.+)(\n)',
+             bygroups(Generic.Error, Text, Name, Whitespace), '#pop'),
+            (r'^([a-zA-Z_]\w*)(:?\n)',
+             bygroups(Generic.Error, Whitespace), '#pop')
+        ],
+        'marker': [
+            # For syntax errors.
+            (r'( {4,})(\^)', bygroups(Text, Punctuation.Marker), '#pop'),
+            default('#pop'),
+        ],
+    }
+
+
+class CythonLexer(RegexLexer):
+    """
+    For Pyrex and Cython source code.
+    """
+
+    name = 'Cython'
+    url = 'https://cython.org'
+    aliases = ['cython', 'pyx', 'pyrex']
+    filenames = ['*.pyx', '*.pxd', '*.pxi']
+    mimetypes = ['text/x-cython', 'application/x-cython']
+    version_added = '1.1'
+
+    tokens = {
+        'root': [
+            (r'\n', Whitespace),
+            (r'^(\s*)("""(?:.|\n)*?""")', bygroups(Whitespace, String.Doc)),
+            (r"^(\s*)('''(?:.|\n)*?''')", bygroups(Whitespace, String.Doc)),
+            (r'[^\S\n]+', Text),
+            (r'#.*$', Comment),
+            (r'[]{}:(),;[]', Punctuation),
+            (r'\\\n', Whitespace),
+            (r'\\', Text),
+            (r'(in|is|and|or|not)\b', Operator.Word),
+            (r'(<)([a-zA-Z0-9.?]+)(>)',
+             bygroups(Punctuation, Keyword.Type, Punctuation)),
+            (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator),
+            (r'(from)(\d+)(<=)(\s+)(<)(\d+)(:)',
+             bygroups(Keyword, Number.Integer, Operator, Whitespace, Operator,
+                      Name, Punctuation)),
+            include('keywords'),
+            (r'(def|property)(\s+)', bygroups(Keyword, Whitespace), 'funcname'),
+            (r'(cp?def)(\s+)', bygroups(Keyword, Whitespace), 'cdef'),
+            # (should actually start a block with only cdefs)
+            (r'(cdef)(:)', bygroups(Keyword, Punctuation)),
+            (r'(class|cppclass|struct)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
+            (r'(from)(\s+)', bygroups(Keyword, Whitespace), 'fromimport'),
+            (r'(c?import)(\s+)', bygroups(Keyword, Whitespace), 'import'),
+            include('builtins'),
+            include('backtick'),
+            ('(?:[rR]|[uU][rR]|[rR][uU])"""', String, 'tdqs'),
+            ("(?:[rR]|[uU][rR]|[rR][uU])'''", String, 'tsqs'),
+            ('(?:[rR]|[uU][rR]|[rR][uU])"', String, 'dqs'),
+            ("(?:[rR]|[uU][rR]|[rR][uU])'", String, 'sqs'),
+            ('[uU]?"""', String, combined('stringescape', 'tdqs')),
+            ("[uU]?'''", String, combined('stringescape', 'tsqs')),
+            ('[uU]?"', String, combined('stringescape', 'dqs')),
+            ("[uU]?'", String, combined('stringescape', 'sqs')),
+            include('name'),
+            include('numbers'),
+        ],
+        'keywords': [
+            (words((
+                'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del',
+                'elif', 'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil',
+                'global', 'if', 'include', 'lambda', 'namespace', 'new', 'noexcept','nogil',
+                'pass', 'print', 'raise', 'return', 'try', 'while', 'yield', 'as', 'with'),
+             suffix=r'\b'),
+             Keyword),
+             (words(('True', 'False', 'None', 'NULL'), suffix=r'\b'), Keyword.Constant),
+            (r'(DEF|IF|ELIF|ELSE)\b', Comment.Preproc),
+        ],
+        'builtins': [
+            (words((
+                '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint',
+                'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'char', 'chr',
+                'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr',
+                'dict', 'dir', 'divmod', 'double', 'enumerate', 'eval', 'execfile', 'exit',
+                'file', 'filter', 'float', 'frozenset', 'getattr', 'globals',
+                'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance',
+                'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max',
+                'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property',
+                'Py_ssize_t', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed',
+                'round', 'set', 'setattr', 'size_t', 'slice', 'sorted', 'staticmethod',
+                'ssize_t', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode',
+                'unsigned', 'vars', 'xrange', 'zip'), prefix=r'(??/\\:']?:)(\s*)(\{)",
+             bygroups(Name.Function, Whitespace, Operator, Whitespace, Punctuation),
+             "functions"),
+            # Variable Names
+            (r"([.]?[a-zA-Z][\w.]*)(\s*)([-.~=!@#$%^&*_+|,<>?/\\:']?:)",
+             bygroups(Name.Variable, Whitespace, Operator)),
+            # Functions
+            (r"\{", Punctuation, "functions"),
+            # Parentheses
+            (r"\(", Punctuation, "parentheses"),
+            # Brackets
+            (r"\[", Punctuation, "brackets"),
+            # Errors
+            (r"'`([a-zA-Z][\w.]*)?", Name.Exception),
+            # File Symbols
+            (r"`:([a-zA-Z/][\w./]*)?", String.Symbol),
+            # Symbols
+            (r"`([a-zA-Z][\w.]*)?", String.Symbol),
+            # Numbers
+            include("numbers"),
+            # Variable Names
+            (r"[a-zA-Z][\w.]*", Name),
+            # Operators
+            (r"[-=+*#$%@!~^&:.,<>'\\|/?_]", Operator),
+            # Punctuation
+            (r";", Punctuation),
+        ],
+        "functions": [
+            include("root"),
+            (r"\}", Punctuation, "#pop"),
+        ],
+        "parentheses": [
+            include("root"),
+            (r"\)", Punctuation, "#pop"),
+        ],
+        "brackets": [
+            include("root"),
+            (r"\]", Punctuation, "#pop"),
+        ],
+        "numbers": [
+            # Binary Values
+            (r"[01]+b", Number.Bin),
+            # Nulls/Infinities
+            (r"0[nNwW][cefghijmndzuvtp]?", Number),
+            # Timestamps
+            ((r"(?:[0-9]{4}[.][0-9]{2}[.][0-9]{2}|[0-9]+)"
+              "D(?:[0-9](?:[0-9](?::[0-9]{2}"
+              "(?::[0-9]{2}(?:[.][0-9]*)?)?)?)?)?"), Literal.Date),
+            # Datetimes
+            ((r"[0-9]{4}[.][0-9]{2}"
+              "(?:m|[.][0-9]{2}(?:T(?:[0-9]{2}:[0-9]{2}"
+              "(?::[0-9]{2}(?:[.][0-9]*)?)?)?)?)"), Literal.Date),
+            # Times
+            (r"[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:[.][0-9]{1,3})?)?",
+             Literal.Date),
+            # GUIDs
+            (r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
+             Number.Hex),
+            # Byte Vectors
+            (r"0x[0-9a-fA-F]+", Number.Hex),
+            # Floats
+            (r"([0-9]*[.]?[0-9]+|[0-9]+[.]?[0-9]*)[eE][+-]?[0-9]+[ef]?",
+             Number.Float),
+            (r"([0-9]*[.][0-9]+|[0-9]+[.][0-9]*)[ef]?", Number.Float),
+            (r"[0-9]+[ef]", Number.Float),
+            # Characters
+            (r"[0-9]+c", Number),
+            # Integers
+            (r"[0-9]+[ihtuv]", Number.Integer),
+            # Long Integers
+            (r"[0-9]+[jnp]?", Number.Integer.Long),
+        ],
+        "comments": [
+            (r"[^\\]+", Comment.Multiline),
+            (r"^\\", Comment.Multiline, "#pop"),
+            (r"\\", Comment.Multiline),
+        ],
+        "strings": [
+            (r'[^"\\]+', String.Double),
+            (r"\\.", String.Escape),
+            (r'"', String.Double, "#pop"),
+        ],
+    }
+
+
+class QLexer(KLexer):
+    """
+    For `Q `_ source code.
+    """
+
+    name = "Q"
+    aliases = ["q"]
+    filenames = ["*.q"]
+    version_added = '2.12'
+
+    tokens = {
+        "root": [
+            (words(("aj", "aj0", "ajf", "ajf0", "all", "and", "any", "asc",
+                    "asof", "attr", "avgs", "ceiling", "cols", "count", "cross",
+                    "csv", "cut", "deltas", "desc", "differ", "distinct", "dsave",
+                    "each", "ej", "ema", "eval", "except", "fby", "fills", "first",
+                    "fkeys", "flip", "floor", "get", "group", "gtime", "hclose",
+                    "hcount", "hdel", "hsym", "iasc", "idesc", "ij", "ijf",
+                    "inter", "inv", "key", "keys", "lj", "ljf", "load", "lower",
+                    "lsq", "ltime", "ltrim", "mavg", "maxs", "mcount", "md5",
+                    "mdev", "med", "meta", "mins", "mmax", "mmin", "mmu", "mod",
+                    "msum", "neg", "next", "not", "null", "or", "over", "parse",
+                    "peach", "pj", "prds", "prior", "prev", "rand", "rank", "ratios",
+                    "raze", "read0", "read1", "reciprocal", "reval", "reverse",
+                    "rload", "rotate", "rsave", "rtrim", "save", "scan", "scov",
+                    "sdev", "set", "show", "signum", "ssr", "string", "sublist",
+                    "sums", "sv", "svar", "system", "tables", "til", "trim", "txf",
+                    "type", "uj", "ujf", "ungroup", "union", "upper", "upsert",
+                    "value", "view", "views", "vs", "where", "wj", "wj1", "ww",
+                    "xasc", "xbar", "xcol", "xcols", "xdesc", "xgroup", "xkey",
+                    "xlog", "xprev", "xrank"),
+                    suffix=r"\b"), Name.Builtin,
+            ),
+            inherit,
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/qlik.py b/lib/python3.11/site-packages/pygments/lexers/qlik.py
new file mode 100644
index 0000000000000000000000000000000000000000..6972ed9d03bf447f6215fbba65e96eb4455a8248
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/qlik.py
@@ -0,0 +1,117 @@
+"""
+    pygments.lexers.qlik
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for the qlik scripting language
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, bygroups, words
+from pygments.token import Comment, Keyword, Name, Number, Operator, \
+    Punctuation, String, Text
+from pygments.lexers._qlik_builtins import OPERATORS_LIST, STATEMENT_LIST, \
+    SCRIPT_FUNCTIONS, CONSTANT_LIST
+
+__all__ = ["QlikLexer"]
+
+
+class QlikLexer(RegexLexer):
+    """
+    Lexer for qlik code, including .qvs files
+    """
+
+    name = "Qlik"
+    aliases = ["qlik", "qlikview", "qliksense", "qlikscript"]
+    filenames = ["*.qvs", "*.qvw"]
+    url = "https://qlik.com"
+    version_added = '2.12'
+
+    flags = re.IGNORECASE
+
+    tokens = {
+        # Handle multi-line comments
+        "comment": [
+            (r"\*/", Comment.Multiline, "#pop"),
+            (r"[^*]+", Comment.Multiline),
+        ],
+        # Handle numbers
+        "numerics": [
+            (r"\b\d+\.\d+(e\d+)?[fd]?\b", Number.Float),
+            (r"\b\d+\b", Number.Integer),
+        ],
+        # Handle variable names in things
+        "interp": [
+            (
+                r"(\$\()(\w+)(\))",
+                bygroups(String.Interpol, Name.Variable, String.Interpol),
+            ),
+        ],
+        # Handle strings
+        "string": [
+            (r"'", String, "#pop"),
+            include("interp"),
+            (r"[^'$]+", String),
+            (r"\$", String),
+        ],
+        #
+        "assignment": [
+            (r";", Punctuation, "#pop"),
+            include("root"),
+        ],
+        "field_name_quote": [
+            (r'"', String.Symbol, "#pop"),
+            include("interp"),
+            (r"[^\"$]+", String.Symbol),
+            (r"\$", String.Symbol),
+        ],
+        "field_name_bracket": [
+            (r"\]", String.Symbol, "#pop"),
+            include("interp"),
+            (r"[^\]$]+", String.Symbol),
+            (r"\$", String.Symbol),
+        ],
+        "function": [(r"\)", Punctuation, "#pop"), include("root")],
+        "root": [
+            # Whitespace and comments
+            (r"\s+", Text.Whitespace),
+            (r"/\*", Comment.Multiline, "comment"),
+            (r"//.*\n", Comment.Single),
+            # variable assignment
+            (r"(let|set)(\s+)", bygroups(Keyword.Declaration, Text.Whitespace),
+             "assignment"),
+            # Word operators
+            (words(OPERATORS_LIST["words"], prefix=r"\b", suffix=r"\b"),
+             Operator.Word),
+            # Statements
+            (words(STATEMENT_LIST, suffix=r"\b"), Keyword),
+            # Table names
+            (r"[a-z]\w*:", Keyword.Declaration),
+            # Constants
+            (words(CONSTANT_LIST, suffix=r"\b"), Keyword.Constant),
+            # Functions
+            (words(SCRIPT_FUNCTIONS, suffix=r"(?=\s*\()"), Name.Builtin,
+             "function"),
+            # interpolation - e.g. $(variableName)
+            include("interp"),
+            # Quotes denote a field/file name
+            (r'"', String.Symbol, "field_name_quote"),
+            # Square brackets denote a field/file name
+            (r"\[", String.Symbol, "field_name_bracket"),
+            # Strings
+            (r"'", String, "string"),
+            # Numbers
+            include("numerics"),
+            # Operator symbols
+            (words(OPERATORS_LIST["symbols"]), Operator),
+            # Strings denoted by single quotes
+            (r"'.+?'", String),
+            # Words as text
+            (r"\b\w+\b", Text),
+            # Basic punctuation
+            (r"[,;.()\\/]", Punctuation),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/qvt.py b/lib/python3.11/site-packages/pygments/lexers/qvt.py
new file mode 100644
index 0000000000000000000000000000000000000000..02d6fcf7d21003379377858820df83389a2b21c5
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/qvt.py
@@ -0,0 +1,153 @@
+"""
+    pygments.lexers.qvt
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexer for QVT Operational language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, include, combined, default, \
+    words
+from pygments.token import Text, Comment, Operator, Keyword, Punctuation, \
+    Name, String, Number
+
+__all__ = ['QVToLexer']
+
+
+class QVToLexer(RegexLexer):
+    """
+    For the QVT Operational Mapping language.
+
+    Reference for implementing this: «Meta Object Facility (MOF) 2.0
+    Query/View/Transformation Specification», Version 1.1 - January 2011
+    (https://www.omg.org/spec/QVT/1.1/), see §8.4, «Concrete Syntax» in
+    particular.
+
+    Notable tokens assignments:
+
+    - Name.Class is assigned to the identifier following any of the following
+      keywords: metamodel, class, exception, primitive, enum, transformation
+      or library
+
+    - Name.Function is assigned to the names of mappings and queries
+
+    - Name.Builtin.Pseudo is assigned to the pre-defined variables 'this',
+      'self' and 'result'.
+    """
+    # With obvious borrowings & inspiration from the Java, Python and C lexers
+
+    name = 'QVTO'
+    aliases = ['qvto', 'qvt']
+    filenames = ['*.qvto']
+    url = 'https://www.omg.org/spec/QVT/1.1'
+    version_added = ''
+
+    tokens = {
+        'root': [
+            (r'\n', Text),
+            (r'[^\S\n]+', Text),
+            (r'(--|//)(\s*)(directive:)?(.*)$',
+             bygroups(Comment, Comment, Comment.Preproc, Comment)),
+            # Uncomment the following if you want to distinguish between
+            # '/*' and '/**', à la javadoc
+            # (r'/[*]{2}(.|\n)*?[*]/', Comment.Multiline),
+            (r'/[*](.|\n)*?[*]/', Comment.Multiline),
+            (r'\\\n', Text),
+            (r'(and|not|or|xor|##?)\b', Operator.Word),
+            (r'(:{1,2}=|[-+]=)\b', Operator.Word),
+            (r'(@|<<|>>)\b', Keyword),  # stereotypes
+            (r'!=|<>|==|=|!->|->|>=|<=|[.]{3}|[+/*%=<>&|.~]', Operator),
+            (r'[]{}:(),;[]', Punctuation),
+            (r'(true|false|unlimited|null)\b', Keyword.Constant),
+            (r'(this|self|result)\b', Name.Builtin.Pseudo),
+            (r'(var)\b', Keyword.Declaration),
+            (r'(from|import)\b', Keyword.Namespace, 'fromimport'),
+            (r'(metamodel|class|exception|primitive|enum|transformation|'
+             r'library)(\s+)(\w+)',
+             bygroups(Keyword.Word, Text, Name.Class)),
+            (r'(exception)(\s+)(\w+)',
+             bygroups(Keyword.Word, Text, Name.Exception)),
+            (r'(main)\b', Name.Function),
+            (r'(mapping|helper|query)(\s+)',
+             bygroups(Keyword.Declaration, Text), 'operation'),
+            (r'(assert)(\s+)\b', bygroups(Keyword, Text), 'assert'),
+            (r'(Bag|Collection|Dict|OrderedSet|Sequence|Set|Tuple|List)\b',
+             Keyword.Type),
+            include('keywords'),
+            ('"', String, combined('stringescape', 'dqs')),
+            ("'", String, combined('stringescape', 'sqs')),
+            include('name'),
+            include('numbers'),
+            # (r'([a-zA-Z_]\w*)(::)([a-zA-Z_]\w*)',
+            # bygroups(Text, Text, Text)),
+        ],
+
+        'fromimport': [
+            (r'(?:[ \t]|\\\n)+', Text),
+            (r'[a-zA-Z_][\w.]*', Name.Namespace),
+            default('#pop'),
+        ],
+
+        'operation': [
+            (r'::', Text),
+            (r'(.*::)([a-zA-Z_]\w*)([ \t]*)(\()',
+             bygroups(Text, Name.Function, Text, Punctuation), '#pop')
+        ],
+
+        'assert': [
+            (r'(warning|error|fatal)\b', Keyword, '#pop'),
+            default('#pop'),  # all else: go back
+        ],
+
+        'keywords': [
+            (words((
+                'abstract', 'access', 'any', 'assert', 'blackbox', 'break',
+                'case', 'collect', 'collectNested', 'collectOne', 'collectselect',
+                'collectselectOne', 'composes', 'compute', 'configuration',
+                'constructor', 'continue', 'datatype', 'default', 'derived',
+                'disjuncts', 'do', 'elif', 'else', 'end', 'endif', 'except',
+                'exists', 'extends', 'forAll', 'forEach', 'forOne', 'from', 'if',
+                'implies', 'in', 'inherits', 'init', 'inout', 'intermediate',
+                'invresolve', 'invresolveIn', 'invresolveone', 'invresolveoneIn',
+                'isUnique', 'iterate', 'late', 'let', 'literal', 'log', 'map',
+                'merges', 'modeltype', 'new', 'object', 'one', 'ordered', 'out',
+                'package', 'population', 'property', 'raise', 'readonly',
+                'references', 'refines', 'reject', 'resolve', 'resolveIn',
+                'resolveone', 'resolveoneIn', 'return', 'select', 'selectOne',
+                'sortedBy', 'static', 'switch', 'tag', 'then', 'try', 'typedef',
+                'unlimited', 'uses', 'when', 'where', 'while', 'with', 'xcollect',
+                'xmap', 'xselect'), suffix=r'\b'), Keyword),
+        ],
+
+        # There is no need to distinguish between String.Single and
+        # String.Double: 'strings' is factorised for 'dqs' and 'sqs'
+        'strings': [
+            (r'[^\\\'"\n]+', String),
+            # quotes, percents and backslashes must be parsed one at a time
+            (r'[\'"\\]', String),
+        ],
+        'stringescape': [
+            (r'\\([\\btnfr"\']|u[0-3][0-7]{2}|u[0-7]{1,2})', String.Escape)
+        ],
+        'dqs': [  # double-quoted string
+            (r'"', String, '#pop'),
+            (r'\\\\|\\"', String.Escape),
+            include('strings')
+        ],
+        'sqs': [  # single-quoted string
+            (r"'", String, '#pop'),
+            (r"\\\\|\\'", String.Escape),
+            include('strings')
+        ],
+        'name': [
+            (r'[a-zA-Z_]\w*', Name),
+        ],
+        # numbers: excerpt taken from the python lexer
+        'numbers': [
+            (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
+            (r'\d+[eE][+-]?[0-9]+', Number.Float),
+            (r'\d+', Number.Integer)
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/r.py b/lib/python3.11/site-packages/pygments/lexers/r.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dcc148a9cb52683e928a307444dd5bfd311a45f
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/r.py
@@ -0,0 +1,196 @@
+"""
+    pygments.lexers.r
+    ~~~~~~~~~~~~~~~~~
+
+    Lexers for the R/S languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import Lexer, RegexLexer, include, do_insertions
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Generic, Whitespace
+
+__all__ = ['RConsoleLexer', 'SLexer', 'RdLexer']
+
+
+line_re  = re.compile('.*?\n')
+
+
+class RConsoleLexer(Lexer):
+    """
+    For R console transcripts or R CMD BATCH output files.
+    """
+
+    name = 'RConsole'
+    aliases = ['rconsole', 'rout']
+    filenames = ['*.Rout']
+    url = 'https://www.r-project.org'
+    version_added = ''
+    _example = "rconsole/r-console-transcript.Rout"
+
+    def get_tokens_unprocessed(self, text):
+        slexer = SLexer(**self.options)
+
+        current_code_block = ''
+        insertions = []
+
+        for match in line_re.finditer(text):
+            line = match.group()
+            if line.startswith('>') or line.startswith('+'):
+                # Colorize the prompt as such,
+                # then put rest of line into current_code_block
+                insertions.append((len(current_code_block),
+                                   [(0, Generic.Prompt, line[:2])]))
+                current_code_block += line[2:]
+            else:
+                # We have reached a non-prompt line!
+                # If we have stored prompt lines, need to process them first.
+                if current_code_block:
+                    # Weave together the prompts and highlight code.
+                    yield from do_insertions(
+                        insertions, slexer.get_tokens_unprocessed(current_code_block))
+                    # Reset vars for next code block.
+                    current_code_block = ''
+                    insertions = []
+                # Now process the actual line itself, this is output from R.
+                yield match.start(), Generic.Output, line
+
+        # If we happen to end on a code block with nothing after it, need to
+        # process the last code block. This is neither elegant nor DRY so
+        # should be changed.
+        if current_code_block:
+            yield from do_insertions(
+                insertions, slexer.get_tokens_unprocessed(current_code_block))
+
+
+class SLexer(RegexLexer):
+    """
+    For S, S-plus, and R source code.
+    """
+
+    name = 'S'
+    aliases = ['splus', 's', 'r']
+    filenames = ['*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron']
+    mimetypes = ['text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r',
+                 'text/x-R', 'text/x-r-history', 'text/x-r-profile']
+    url = 'https://www.r-project.org'
+    version_added = '0.10'
+
+    valid_name = r'`[^`\\]*(?:\\.[^`\\]*)*`|(?:[a-zA-Z]|\.[A-Za-z_.])[\w.]*|\.'
+    tokens = {
+        'comments': [
+            (r'#.*$', Comment.Single),
+        ],
+        'valid_name': [
+            (valid_name, Name),
+        ],
+        'function_name': [
+            (rf'({valid_name})\s*(?=\()', Name.Function),
+        ],
+        'punctuation': [
+            (r'\[{1,2}|\]{1,2}|\(|\)|;|,', Punctuation),
+        ],
+        'keywords': [
+            (r'(if|else|for|while|repeat|in|next|break|return|switch|function)'
+             r'(?![\w.])',
+             Keyword.Reserved),
+        ],
+        'operators': [
+            (r'<>?|-|==|<=|>=|\|>|<|>|&&?|!=|\|\|?|\?', Operator),
+            (r'\*|\+|\^|/|!|%[^%]*%|=|~|\$|@|:{1,3}', Operator),
+        ],
+        'builtin_symbols': [
+            (r'(NULL|NA(_(integer|real|complex|character)_)?|'
+             r'letters|LETTERS|Inf|TRUE|FALSE|NaN|pi|\.\.(\.|[0-9]+))'
+             r'(?![\w.])',
+             Keyword.Constant),
+            (r'(T|F)\b', Name.Builtin.Pseudo),
+        ],
+        'numbers': [
+            # hex number
+            (r'0[xX][a-fA-F0-9]+([pP][0-9]+)?[Li]?', Number.Hex),
+            # decimal number
+            (r'[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)([eE][+-]?[0-9]+)?[Li]?',
+             Number),
+        ],
+        'statements': [
+            include('comments'),
+            # whitespaces
+            (r'\s+', Whitespace),
+            (r'\'', String, 'string_squote'),
+            (r'\"', String, 'string_dquote'),
+            include('builtin_symbols'),
+            include('keywords'),
+            include('function_name'),
+            include('valid_name'),
+            include('numbers'),
+            include('punctuation'),
+            include('operators'),
+        ],
+        'root': [
+            # calls:
+            include('statements'),
+            # blocks:
+            (r'\{|\}', Punctuation),
+            # (r'\{', Punctuation, 'block'),
+            (r'.', Text),
+        ],
+        # 'block': [
+        #    include('statements'),
+        #    ('\{', Punctuation, '#push'),
+        #    ('\}', Punctuation, '#pop')
+        # ],
+        'string_squote': [
+            (r'([^\'\\]|\\.)*\'', String, '#pop'),
+        ],
+        'string_dquote': [
+            (r'([^"\\]|\\.)*"', String, '#pop'),
+        ],
+    }
+
+    def analyse_text(text):
+        if re.search(r'[a-z0-9_\])\s]<-(?!-)', text):
+            return 0.11
+
+
+class RdLexer(RegexLexer):
+    """
+    Pygments Lexer for R documentation (Rd) files
+
+    This is a very minimal implementation, highlighting little more
+    than the macros. A description of Rd syntax is found in `Writing R
+    Extensions `_
+    and `Parsing Rd files `_.
+    """
+    name = 'Rd'
+    aliases = ['rd']
+    filenames = ['*.Rd']
+    mimetypes = ['text/x-r-doc']
+    url = 'http://cran.r-project.org/doc/manuals/R-exts.html'
+    version_added = '1.6'
+
+    # To account for verbatim / LaTeX-like / and R-like areas
+    # would require parsing.
+    tokens = {
+        'root': [
+            # catch escaped brackets and percent sign
+            (r'\\[\\{}%]', String.Escape),
+            # comments
+            (r'%.*$', Comment),
+            # special macros with no arguments
+            (r'\\(?:cr|l?dots|R|tab)\b', Keyword.Constant),
+            # macros
+            (r'\\[a-zA-Z]+\b', Keyword),
+            # special preprocessor macros
+            (r'^\s*#(?:ifn?def|endif).*\b', Comment.Preproc),
+            # non-escaped brackets
+            (r'[{}]', Name.Builtin),
+            # everything else
+            (r'[^\\%\n{}]+', Text),
+            (r'.', Text),
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/rdf.py b/lib/python3.11/site-packages/pygments/lexers/rdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2ecf7a11f3072e3f009c22ebd0808905e2fbbcf
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rdf.py
@@ -0,0 +1,468 @@
+"""
+    pygments.lexers.rdf
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for semantic web and RDF query languages and markup.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, bygroups, default
+from pygments.token import Keyword, Punctuation, String, Number, Operator, \
+    Generic, Whitespace, Name, Literal, Comment, Text
+
+__all__ = ['SparqlLexer', 'TurtleLexer', 'ShExCLexer']
+
+
+class SparqlLexer(RegexLexer):
+    """
+    Lexer for SPARQL query language.
+    """
+    name = 'SPARQL'
+    aliases = ['sparql']
+    filenames = ['*.rq', '*.sparql']
+    mimetypes = ['application/sparql-query']
+    url = 'https://www.w3.org/TR/sparql11-query'
+    version_added = '2.0'
+
+    # character group definitions ::
+
+    PN_CHARS_BASE_GRP = ('a-zA-Z'
+                         '\u00c0-\u00d6'
+                         '\u00d8-\u00f6'
+                         '\u00f8-\u02ff'
+                         '\u0370-\u037d'
+                         '\u037f-\u1fff'
+                         '\u200c-\u200d'
+                         '\u2070-\u218f'
+                         '\u2c00-\u2fef'
+                         '\u3001-\ud7ff'
+                         '\uf900-\ufdcf'
+                         '\ufdf0-\ufffd')
+
+    PN_CHARS_U_GRP = (PN_CHARS_BASE_GRP + '_')
+
+    PN_CHARS_GRP = (PN_CHARS_U_GRP +
+                    r'\-' +
+                    r'0-9' +
+                    '\u00b7' +
+                    '\u0300-\u036f' +
+                    '\u203f-\u2040')
+
+    HEX_GRP = '0-9A-Fa-f'
+
+    PN_LOCAL_ESC_CHARS_GRP = r' _~.\-!$&"()*+,;=/?#@%'
+
+    # terminal productions ::
+
+    PN_CHARS_BASE = '[' + PN_CHARS_BASE_GRP + ']'
+
+    PN_CHARS_U = '[' + PN_CHARS_U_GRP + ']'
+
+    PN_CHARS = '[' + PN_CHARS_GRP + ']'
+
+    HEX = '[' + HEX_GRP + ']'
+
+    PN_LOCAL_ESC_CHARS = '[' + PN_LOCAL_ESC_CHARS_GRP + ']'
+
+    IRIREF = r'<(?:[^<>"{}|^`\\\x00-\x20])*>'
+
+    BLANK_NODE_LABEL = '_:[0-9' + PN_CHARS_U_GRP + '](?:[' + PN_CHARS_GRP + \
+                       '.]*' + PN_CHARS + ')?'
+
+    PN_PREFIX = PN_CHARS_BASE + '(?:[' + PN_CHARS_GRP + '.]*' + PN_CHARS + ')?'
+
+    VARNAME = '[0-9' + PN_CHARS_U_GRP + '][' + PN_CHARS_U_GRP + \
+              '0-9\u00b7\u0300-\u036f\u203f-\u2040]*'
+
+    PERCENT = '%' + HEX + HEX
+
+    PN_LOCAL_ESC = r'\\' + PN_LOCAL_ESC_CHARS
+
+    PLX = '(?:' + PERCENT + ')|(?:' + PN_LOCAL_ESC + ')'
+
+    PN_LOCAL = ('(?:[' + PN_CHARS_U_GRP + ':0-9' + ']|' + PLX + ')' +
+                '(?:(?:[' + PN_CHARS_GRP + '.:]|' + PLX + ')*(?:[' +
+                PN_CHARS_GRP + ':]|' + PLX + '))?')
+
+    EXPONENT = r'[eE][+-]?\d+'
+
+    # Lexer token definitions ::
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+            # keywords ::
+            (r'(?i)(select|construct|describe|ask|where|filter|group\s+by|minus|'
+             r'distinct|reduced|from\s+named|from|order\s+by|desc|asc|limit|'
+             r'offset|values|bindings|load|into|clear|drop|create|add|move|copy|'
+             r'insert\s+data|delete\s+data|delete\s+where|with|delete|insert|'
+             r'using\s+named|using|graph|default|named|all|optional|service|'
+             r'silent|bind|undef|union|not\s+in|in|as|having|to|prefix|base)\b', Keyword),
+            (r'(a)\b', Keyword),
+            # IRIs ::
+            ('(' + IRIREF + ')', Name.Label),
+            # blank nodes ::
+            ('(' + BLANK_NODE_LABEL + ')', Name.Label),
+            #  # variables ::
+            ('[?$]' + VARNAME, Name.Variable),
+            # prefixed names ::
+            (r'(' + PN_PREFIX + r')?(\:)(' + PN_LOCAL + r')?',
+             bygroups(Name.Namespace, Punctuation, Name.Tag)),
+            # function names ::
+            (r'(?i)(str|lang|langmatches|datatype|bound|iri|uri|bnode|rand|abs|'
+             r'ceil|floor|round|concat|strlen|ucase|lcase|encode_for_uri|'
+             r'contains|strstarts|strends|strbefore|strafter|year|month|day|'
+             r'hours|minutes|seconds|timezone|tz|now|uuid|struuid|md5|sha1|sha256|sha384|'
+             r'sha512|coalesce|if|strlang|strdt|sameterm|isiri|isuri|isblank|'
+             r'isliteral|isnumeric|regex|substr|replace|exists|not\s+exists|'
+             r'count|sum|min|max|avg|sample|group_concat|separator)\b',
+             Name.Function),
+            # boolean literals ::
+            (r'(true|false)', Keyword.Constant),
+            # double literals ::
+            (r'[+\-]?(\d+\.\d*' + EXPONENT + r'|\.?\d+' + EXPONENT + ')', Number.Float),
+            # decimal literals ::
+            (r'[+\-]?(\d+\.\d*|\.\d+)', Number.Float),
+            # integer literals ::
+            (r'[+\-]?\d+', Number.Integer),
+            # operators ::
+            (r'(\|\||&&|=|\*|\-|\+|/|!=|<=|>=|!|<|>)', Operator),
+            # punctuation characters ::
+            (r'[(){}.;,:^\[\]]', Punctuation),
+            # line comments ::
+            (r'#[^\n]*', Comment),
+            # strings ::
+            (r'"""', String, 'triple-double-quoted-string'),
+            (r'"', String, 'single-double-quoted-string'),
+            (r"'''", String, 'triple-single-quoted-string'),
+            (r"'", String, 'single-single-quoted-string'),
+        ],
+        'triple-double-quoted-string': [
+            (r'"""', String, 'end-of-string'),
+            (r'[^\\]+', String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'single-double-quoted-string': [
+            (r'"', String, 'end-of-string'),
+            (r'[^"\\\n]+', String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'triple-single-quoted-string': [
+            (r"'''", String, 'end-of-string'),
+            (r'[^\\]+', String),
+            (r'\\', String.Escape, 'string-escape'),
+        ],
+        'single-single-quoted-string': [
+            (r"'", String, 'end-of-string'),
+            (r"[^'\\\n]+", String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'string-escape': [
+            (r'u' + HEX + '{4}', String.Escape, '#pop'),
+            (r'U' + HEX + '{8}', String.Escape, '#pop'),
+            (r'.', String.Escape, '#pop'),
+        ],
+        'end-of-string': [
+            (r'(@)([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)',
+             bygroups(Operator, Name.Function), '#pop:2'),
+            (r'\^\^', Operator, '#pop:2'),
+            default('#pop:2'),
+        ],
+    }
+
+
+class TurtleLexer(RegexLexer):
+    """
+    Lexer for Turtle data language.
+    """
+    name = 'Turtle'
+    aliases = ['turtle']
+    filenames = ['*.ttl']
+    mimetypes = ['text/turtle', 'application/x-turtle']
+    url = 'https://www.w3.org/TR/turtle'
+    version_added = '2.1'
+
+    # character group definitions ::
+    PN_CHARS_BASE_GRP = ('a-zA-Z'
+                         '\u00c0-\u00d6'
+                         '\u00d8-\u00f6'
+                         '\u00f8-\u02ff'
+                         '\u0370-\u037d'
+                         '\u037f-\u1fff'
+                         '\u200c-\u200d'
+                         '\u2070-\u218f'
+                         '\u2c00-\u2fef'
+                         '\u3001-\ud7ff'
+                         '\uf900-\ufdcf'
+                         '\ufdf0-\ufffd')
+
+    PN_CHARS_U_GRP = (PN_CHARS_BASE_GRP + '_')
+
+    PN_CHARS_GRP = (PN_CHARS_U_GRP +
+                    r'\-' +
+                    r'0-9' +
+                    '\u00b7' +
+                    '\u0300-\u036f' +
+                    '\u203f-\u2040')
+
+    PN_CHARS = '[' + PN_CHARS_GRP + ']'
+
+    PN_CHARS_BASE = '[' + PN_CHARS_BASE_GRP + ']'
+
+    PN_PREFIX = PN_CHARS_BASE + '(?:[' + PN_CHARS_GRP + '.]*' + PN_CHARS + ')?'
+
+    HEX_GRP = '0-9A-Fa-f'
+
+    HEX = '[' + HEX_GRP + ']'
+
+    PERCENT = '%' + HEX + HEX
+
+    PN_LOCAL_ESC_CHARS_GRP = r' _~.\-!$&"()*+,;=/?#@%'
+
+    PN_LOCAL_ESC_CHARS = '[' + PN_LOCAL_ESC_CHARS_GRP + ']'
+
+    PN_LOCAL_ESC = r'\\' + PN_LOCAL_ESC_CHARS
+
+    PLX = '(?:' + PERCENT + ')|(?:' + PN_LOCAL_ESC + ')'
+
+    PN_LOCAL = ('(?:[' + PN_CHARS_U_GRP + ':0-9' + ']|' + PLX + ')' +
+                '(?:(?:[' + PN_CHARS_GRP + '.:]|' + PLX + ')*(?:[' +
+                PN_CHARS_GRP + ':]|' + PLX + '))?')
+
+    patterns = {
+        'PNAME_NS': r'((?:[a-zA-Z][\w-]*)?\:)',  # Simplified character range
+        'IRIREF': r'(<[^<>"{}|^`\\\x00-\x20]*>)'
+    }
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+
+            # Base / prefix
+            (r'(@base|BASE)(\s+){IRIREF}(\s*)(\.?)'.format(**patterns),
+             bygroups(Keyword, Whitespace, Name.Variable, Whitespace,
+                      Punctuation)),
+            (r'(@prefix|PREFIX)(\s+){PNAME_NS}(\s+){IRIREF}(\s*)(\.?)'.format(**patterns),
+             bygroups(Keyword, Whitespace, Name.Namespace, Whitespace,
+                      Name.Variable, Whitespace, Punctuation)),
+
+            # The shorthand predicate 'a'
+            (r'(?<=\s)a(?=\s)', Keyword.Type),
+
+            # IRIREF
+            (r'{IRIREF}'.format(**patterns), Name.Variable),
+
+            # PrefixedName
+            (r'(' + PN_PREFIX + r')?(\:)(' + PN_LOCAL + r')?',
+             bygroups(Name.Namespace, Punctuation, Name.Tag)),
+
+            # BlankNodeLabel
+            (r'(_)(:)([' + PN_CHARS_U_GRP + r'0-9]([' + PN_CHARS_GRP + r'.]*' + PN_CHARS + ')?)',
+             bygroups(Name.Namespace, Punctuation, Name.Tag)),
+
+            # Comment
+            (r'#([^\n]+|$)', Comment),
+
+            (r'\b(true|false)\b', Literal),
+            (r'[+\-]?\d*\.\d+', Number.Float),
+            (r'[+\-]?\d*(:?\.\d+)?E[+\-]?\d+', Number.Float),
+            (r'[+\-]?\d+', Number.Integer),
+            (r'[\[\](){}.;,:^]', Punctuation),
+
+            (r'"""', String, 'triple-double-quoted-string'),
+            (r'"', String, 'single-double-quoted-string'),
+            (r"'''", String, 'triple-single-quoted-string'),
+            (r"'", String, 'single-single-quoted-string'),
+        ],
+        'triple-double-quoted-string': [
+            (r'"""', String, 'end-of-string'),
+            (r'[^\\]+(?=""")', String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'single-double-quoted-string': [
+            (r'"', String, 'end-of-string'),
+            (r'[^"\\\n]+', String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'triple-single-quoted-string': [
+            (r"'''", String, 'end-of-string'),
+            (r"[^\\]+(?=''')", String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'single-single-quoted-string': [
+            (r"'", String, 'end-of-string'),
+            (r"[^'\\\n]+", String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'string-escape': [
+            (r'.', String, '#pop'),
+        ],
+        'end-of-string': [
+            (r'(@)([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)',
+             bygroups(Operator, Generic.Emph), '#pop:2'),
+
+            (r'(\^\^){IRIREF}'.format(**patterns), bygroups(Operator, Generic.Emph), '#pop:2'),
+
+            default('#pop:2'),
+
+        ],
+    }
+
+    # Turtle and Tera Term macro files share the same file extension
+    # but each has a recognizable and distinct syntax.
+    def analyse_text(text):
+        for t in ('@base ', 'BASE ', '@prefix ', 'PREFIX '):
+            if re.search(rf'^\s*{t}', text):
+                return 0.80
+
+
+class ShExCLexer(RegexLexer):
+    """
+    Lexer for ShExC shape expressions language syntax.
+    """
+    name = 'ShExC'
+    aliases = ['shexc', 'shex']
+    filenames = ['*.shex']
+    mimetypes = ['text/shex']
+    url = 'https://shex.io/shex-semantics/#shexc'
+    version_added = ''
+
+    # character group definitions ::
+
+    PN_CHARS_BASE_GRP = ('a-zA-Z'
+                         '\u00c0-\u00d6'
+                         '\u00d8-\u00f6'
+                         '\u00f8-\u02ff'
+                         '\u0370-\u037d'
+                         '\u037f-\u1fff'
+                         '\u200c-\u200d'
+                         '\u2070-\u218f'
+                         '\u2c00-\u2fef'
+                         '\u3001-\ud7ff'
+                         '\uf900-\ufdcf'
+                         '\ufdf0-\ufffd')
+
+    PN_CHARS_U_GRP = (PN_CHARS_BASE_GRP + '_')
+
+    PN_CHARS_GRP = (PN_CHARS_U_GRP +
+                    r'\-' +
+                    r'0-9' +
+                    '\u00b7' +
+                    '\u0300-\u036f' +
+                    '\u203f-\u2040')
+
+    HEX_GRP = '0-9A-Fa-f'
+
+    PN_LOCAL_ESC_CHARS_GRP = r"_~.\-!$&'()*+,;=/?#@%"
+
+    # terminal productions ::
+
+    PN_CHARS_BASE = '[' + PN_CHARS_BASE_GRP + ']'
+
+    PN_CHARS_U = '[' + PN_CHARS_U_GRP + ']'
+
+    PN_CHARS = '[' + PN_CHARS_GRP + ']'
+
+    HEX = '[' + HEX_GRP + ']'
+
+    PN_LOCAL_ESC_CHARS = '[' + PN_LOCAL_ESC_CHARS_GRP + ']'
+
+    UCHAR_NO_BACKSLASH = '(?:u' + HEX + '{4}|U' + HEX + '{8})'
+
+    UCHAR = r'\\' + UCHAR_NO_BACKSLASH
+
+    IRIREF = r'<(?:[^\x00-\x20<>"{}|^`\\]|' + UCHAR + ')*>'
+
+    BLANK_NODE_LABEL = '_:[0-9' + PN_CHARS_U_GRP + '](?:[' + PN_CHARS_GRP + \
+                       '.]*' + PN_CHARS + ')?'
+
+    PN_PREFIX = PN_CHARS_BASE + '(?:[' + PN_CHARS_GRP + '.]*' + PN_CHARS + ')?'
+
+    PERCENT = '%' + HEX + HEX
+
+    PN_LOCAL_ESC = r'\\' + PN_LOCAL_ESC_CHARS
+
+    PLX = '(?:' + PERCENT + ')|(?:' + PN_LOCAL_ESC + ')'
+
+    PN_LOCAL = ('(?:[' + PN_CHARS_U_GRP + ':0-9' + ']|' + PLX + ')' +
+                '(?:(?:[' + PN_CHARS_GRP + '.:]|' + PLX + ')*(?:[' +
+                PN_CHARS_GRP + ':]|' + PLX + '))?')
+
+    EXPONENT = r'[eE][+-]?\d+'
+
+    # Lexer token definitions ::
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+            # keywords ::
+            (r'(?i)(base|prefix|start|external|'
+             r'literal|iri|bnode|nonliteral|length|minlength|maxlength|'
+             r'mininclusive|minexclusive|maxinclusive|maxexclusive|'
+             r'totaldigits|fractiondigits|'
+             r'closed|extra)\b', Keyword),
+            (r'(a)\b', Keyword),
+            # IRIs ::
+            ('(' + IRIREF + ')', Name.Label),
+            # blank nodes ::
+            ('(' + BLANK_NODE_LABEL + ')', Name.Label),
+            # prefixed names ::
+            (r'(' + PN_PREFIX + r')?(\:)(' + PN_LOCAL + ')?',
+             bygroups(Name.Namespace, Punctuation, Name.Tag)),
+            # boolean literals ::
+            (r'(true|false)', Keyword.Constant),
+            # double literals ::
+            (r'[+\-]?(\d+\.\d*' + EXPONENT + r'|\.?\d+' + EXPONENT + ')', Number.Float),
+            # decimal literals ::
+            (r'[+\-]?(\d+\.\d*|\.\d+)', Number.Float),
+            # integer literals ::
+            (r'[+\-]?\d+', Number.Integer),
+            # operators ::
+            (r'[@|$&=*+?^\-~]', Operator),
+            # operator keywords ::
+            (r'(?i)(and|or|not)\b', Operator.Word),
+            # punctuation characters ::
+            (r'[(){}.;,:^\[\]]', Punctuation),
+            # line comments ::
+            (r'#[^\n]*', Comment),
+            # strings ::
+            (r'"""', String, 'triple-double-quoted-string'),
+            (r'"', String, 'single-double-quoted-string'),
+            (r"'''", String, 'triple-single-quoted-string'),
+            (r"'", String, 'single-single-quoted-string'),
+        ],
+        'triple-double-quoted-string': [
+            (r'"""', String, 'end-of-string'),
+            (r'[^\\]+', String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'single-double-quoted-string': [
+            (r'"', String, 'end-of-string'),
+            (r'[^"\\\n]+', String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'triple-single-quoted-string': [
+            (r"'''", String, 'end-of-string'),
+            (r'[^\\]+', String),
+            (r'\\', String.Escape, 'string-escape'),
+        ],
+        'single-single-quoted-string': [
+            (r"'", String, 'end-of-string'),
+            (r"[^'\\\n]+", String),
+            (r'\\', String, 'string-escape'),
+        ],
+        'string-escape': [
+            (UCHAR_NO_BACKSLASH, String.Escape, '#pop'),
+            (r'.', String.Escape, '#pop'),
+        ],
+        'end-of-string': [
+            (r'(@)([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)',
+             bygroups(Operator, Name.Function), '#pop:2'),
+            (r'\^\^', Operator, '#pop:2'),
+            default('#pop:2'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/rebol.py b/lib/python3.11/site-packages/pygments/lexers/rebol.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcff62be14de1f3d89c43600daa10f33e7acbc8a
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rebol.py
@@ -0,0 +1,419 @@
+"""
+    pygments.lexers.rebol
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the REBOL and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, bygroups
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Generic, Whitespace
+
+__all__ = ['RebolLexer', 'RedLexer']
+
+
+class RebolLexer(RegexLexer):
+    """
+    A REBOL lexer.
+    """
+    name = 'REBOL'
+    aliases = ['rebol']
+    filenames = ['*.r', '*.r3', '*.reb']
+    mimetypes = ['text/x-rebol']
+    url = 'http://www.rebol.com'
+    version_added = '1.1'
+
+    flags = re.IGNORECASE | re.MULTILINE
+
+    escape_re = r'(?:\^\([0-9a-f]{1,4}\)*)'
+
+    def word_callback(lexer, match):
+        word = match.group()
+
+        if re.match(".*:$", word):
+            yield match.start(), Generic.Subheading, word
+        elif re.match(
+            r'(native|alias|all|any|as-string|as-binary|bind|bound\?|case|'
+            r'catch|checksum|comment|debase|dehex|exclude|difference|disarm|'
+            r'either|else|enbase|foreach|remove-each|form|free|get|get-env|if|'
+            r'in|intersect|loop|minimum-of|maximum-of|mold|new-line|'
+            r'new-line\?|not|now|prin|print|reduce|compose|construct|repeat|'
+            r'reverse|save|script\?|set|shift|switch|throw|to-hex|trace|try|'
+            r'type\?|union|unique|unless|unprotect|unset|until|use|value\?|'
+            r'while|compress|decompress|secure|open|close|read|read-io|'
+            r'write-io|write|update|query|wait|input\?|exp|log-10|log-2|'
+            r'log-e|square-root|cosine|sine|tangent|arccosine|arcsine|'
+            r'arctangent|protect|lowercase|uppercase|entab|detab|connected\?|'
+            r'browse|launch|stats|get-modes|set-modes|to-local-file|'
+            r'to-rebol-file|encloak|decloak|create-link|do-browser|bind\?|'
+            r'hide|draw|show|size-text|textinfo|offset-to-caret|'
+            r'caret-to-offset|local-request-file|rgb-to-hsv|hsv-to-rgb|'
+            r'crypt-strength\?|dh-make-key|dh-generate-key|dh-compute-key|'
+            r'dsa-make-key|dsa-generate-key|dsa-make-signature|'
+            r'dsa-verify-signature|rsa-make-key|rsa-generate-key|'
+            r'rsa-encrypt)$', word):
+            yield match.start(), Name.Builtin, word
+        elif re.match(
+            r'(add|subtract|multiply|divide|remainder|power|and~|or~|xor~|'
+            r'minimum|maximum|negate|complement|absolute|random|head|tail|'
+            r'next|back|skip|at|pick|first|second|third|fourth|fifth|sixth|'
+            r'seventh|eighth|ninth|tenth|last|path|find|select|make|to|copy\*|'
+            r'insert|remove|change|poke|clear|trim|sort|min|max|abs|cp|'
+            r'copy)$', word):
+            yield match.start(), Name.Function, word
+        elif re.match(
+            r'(error|source|input|license|help|install|echo|Usage|with|func|'
+            r'throw-on-error|function|does|has|context|probe|\?\?|as-pair|'
+            r'mod|modulo|round|repend|about|set-net|append|join|rejoin|reform|'
+            r'remold|charset|array|replace|move|extract|forskip|forall|alter|'
+            r'first+|also|take|for|forever|dispatch|attempt|what-dir|'
+            r'change-dir|clean-path|list-dir|dirize|rename|split-path|delete|'
+            r'make-dir|delete-dir|in-dir|confirm|dump-obj|upgrade|what|'
+            r'build-tag|process-source|build-markup|decode-cgi|read-cgi|'
+            r'write-user|save-user|set-user-name|protect-system|parse-xml|'
+            r'cvs-date|cvs-version|do-boot|get-net-info|desktop|layout|'
+            r'scroll-para|get-face|alert|set-face|uninstall|unfocus|'
+            r'request-dir|center-face|do-events|net-error|decode-url|'
+            r'parse-header|parse-header-date|parse-email-addrs|import-email|'
+            r'send|build-attach-body|resend|show-popup|hide-popup|open-events|'
+            r'find-key-face|do-face|viewtop|confine|find-window|'
+            r'insert-event-func|remove-event-func|inform|dump-pane|dump-face|'
+            r'flag-face|deflag-face|clear-fields|read-net|vbug|path-thru|'
+            r'read-thru|load-thru|do-thru|launch-thru|load-image|'
+            r'request-download|do-face-alt|set-font|set-para|get-style|'
+            r'set-style|make-face|stylize|choose|hilight-text|hilight-all|'
+            r'unlight-text|focus|scroll-drag|clear-face|reset-face|scroll-face|'
+            r'resize-face|load-stock|load-stock-block|notify|request|flash|'
+            r'request-color|request-pass|request-text|request-list|'
+            r'request-date|request-file|dbug|editor|link-relative-path|'
+            r'emailer|parse-error)$', word):
+            yield match.start(), Keyword.Namespace, word
+        elif re.match(
+            r'(halt|quit|do|load|q|recycle|call|run|ask|parse|view|unview|'
+            r'return|exit|break)$', word):
+            yield match.start(), Name.Exception, word
+        elif re.match('REBOL$', word):
+            yield match.start(), Generic.Heading, word
+        elif re.match("to-.*", word):
+            yield match.start(), Keyword, word
+        elif re.match(r'(\+|-|\*|/|//|\*\*|and|or|xor|=\?|=|==|<>|<|>|<=|>=)$',
+                      word):
+            yield match.start(), Operator, word
+        elif re.match(r".*\?$", word):
+            yield match.start(), Keyword, word
+        elif re.match(r".*\!$", word):
+            yield match.start(), Keyword.Type, word
+        elif re.match("'.*", word):
+            yield match.start(), Name.Variable.Instance, word  # lit-word
+        elif re.match("#.*", word):
+            yield match.start(), Name.Label, word  # issue
+        elif re.match("%.*", word):
+            yield match.start(), Name.Decorator, word  # file
+        else:
+            yield match.start(), Name.Variable, word
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+            (r'#"', String.Char, 'char'),
+            (r'#\{[0-9a-f]*\}', Number.Hex),
+            (r'2#\{', Number.Hex, 'bin2'),
+            (r'64#\{[0-9a-z+/=\s]*\}', Number.Hex),
+            (r'"', String, 'string'),
+            (r'\{', String, 'string2'),
+            (r';#+.*\n', Comment.Special),
+            (r';\*+.*\n', Comment.Preproc),
+            (r';.*\n', Comment),
+            (r'%"', Name.Decorator, 'stringFile'),
+            (r'%[^(^{")\s\[\]]+', Name.Decorator),
+            (r'[+-]?([a-z]{1,3})?\$\d+(\.\d+)?', Number.Float),  # money
+            (r'[+-]?\d+\:\d+(\:\d+)?(\.\d+)?', String.Other),    # time
+            (r'\d+[\-/][0-9a-z]+[\-/]\d+(\/\d+\:\d+((\:\d+)?'
+             r'([.\d+]?([+-]?\d+:\d+)?)?)?)?', String.Other),   # date
+            (r'\d+(\.\d+)+\.\d+', Keyword.Constant),             # tuple
+            (r'\d+X\d+', Keyword.Constant),                   # pair
+            (r'[+-]?\d+(\'\d+)?([.,]\d*)?E[+-]?\d+', Number.Float),
+            (r'[+-]?\d+(\'\d+)?[.,]\d*', Number.Float),
+            (r'[+-]?\d+(\'\d+)?', Number),
+            (r'[\[\]()]', Generic.Strong),
+            (r'[a-z]+[^(^{"\s:)]*://[^(^{"\s)]*', Name.Decorator),  # url
+            (r'mailto:[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator),  # url
+            (r'[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator),         # email
+            (r'comment\s"', Comment, 'commentString1'),
+            (r'comment\s\{', Comment, 'commentString2'),
+            (r'comment\s\[', Comment, 'commentBlock'),
+            (r'comment\s[^(\s{"\[]+', Comment),
+            (r'/[^(^{")\s/[\]]*', Name.Attribute),
+            (r'([^(^{")\s/[\]]+)(?=[:({"\s/\[\]])', word_callback),
+            (r'<[\w:.-]*>', Name.Tag),
+            (r'<[^(<>\s")]+', Name.Tag, 'tag'),
+            (r'([^(^{")\s]+)', Text),
+        ],
+        'string': [
+            (r'[^(^")]+', String),
+            (escape_re, String.Escape),
+            (r'[(|)]+', String),
+            (r'\^.', String.Escape),
+            (r'"', String, '#pop'),
+        ],
+        'string2': [
+            (r'[^(^{})]+', String),
+            (escape_re, String.Escape),
+            (r'[(|)]+', String),
+            (r'\^.', String.Escape),
+            (r'\{', String, '#push'),
+            (r'\}', String, '#pop'),
+        ],
+        'stringFile': [
+            (r'[^(^")]+', Name.Decorator),
+            (escape_re, Name.Decorator),
+            (r'\^.', Name.Decorator),
+            (r'"', Name.Decorator, '#pop'),
+        ],
+        'char': [
+            (escape_re + '"', String.Char, '#pop'),
+            (r'\^."', String.Char, '#pop'),
+            (r'."', String.Char, '#pop'),
+        ],
+        'tag': [
+            (escape_re, Name.Tag),
+            (r'"', Name.Tag, 'tagString'),
+            (r'[^(<>\r\n")]+', Name.Tag),
+            (r'>', Name.Tag, '#pop'),
+        ],
+        'tagString': [
+            (r'[^(^")]+', Name.Tag),
+            (escape_re, Name.Tag),
+            (r'[(|)]+', Name.Tag),
+            (r'\^.', Name.Tag),
+            (r'"', Name.Tag, '#pop'),
+        ],
+        'tuple': [
+            (r'(\d+\.)+', Keyword.Constant),
+            (r'\d+', Keyword.Constant, '#pop'),
+        ],
+        'bin2': [
+            (r'\s+', Number.Hex),
+            (r'([01]\s*){8}', Number.Hex),
+            (r'\}', Number.Hex, '#pop'),
+        ],
+        'commentString1': [
+            (r'[^(^")]+', Comment),
+            (escape_re, Comment),
+            (r'[(|)]+', Comment),
+            (r'\^.', Comment),
+            (r'"', Comment, '#pop'),
+        ],
+        'commentString2': [
+            (r'[^(^{})]+', Comment),
+            (escape_re, Comment),
+            (r'[(|)]+', Comment),
+            (r'\^.', Comment),
+            (r'\{', Comment, '#push'),
+            (r'\}', Comment, '#pop'),
+        ],
+        'commentBlock': [
+            (r'\[', Comment, '#push'),
+            (r'\]', Comment, '#pop'),
+            (r'"', Comment, "commentString1"),
+            (r'\{', Comment, "commentString2"),
+            (r'[^(\[\]"{)]+', Comment),
+        ],
+    }
+
+    def analyse_text(text):
+        """
+        Check if code contains REBOL header and so it probably not R code
+        """
+        if re.match(r'^\s*REBOL\s*\[', text, re.IGNORECASE):
+            # The code starts with REBOL header
+            return 1.0
+        elif re.search(r'\s*REBOL\s*\[', text, re.IGNORECASE):
+            # The code contains REBOL header but also some text before it
+            return 0.5
+
+
+class RedLexer(RegexLexer):
+    """
+    A Red-language lexer.
+    """
+    name = 'Red'
+    aliases = ['red', 'red/system']
+    filenames = ['*.red', '*.reds']
+    mimetypes = ['text/x-red', 'text/x-red-system']
+    url = 'https://www.red-lang.org'
+    version_added = '2.0'
+
+    flags = re.IGNORECASE | re.MULTILINE
+
+    escape_re = r'(?:\^\([0-9a-f]{1,4}\)*)'
+
+    def word_callback(lexer, match):
+        word = match.group()
+
+        if re.match(".*:$", word):
+            yield match.start(), Generic.Subheading, word
+        elif re.match(r'(if|unless|either|any|all|while|until|loop|repeat|'
+                      r'foreach|forall|func|function|does|has|switch|'
+                      r'case|reduce|compose|get|set|print|prin|equal\?|'
+                      r'not-equal\?|strict-equal\?|lesser\?|greater\?|lesser-or-equal\?|'
+                      r'greater-or-equal\?|same\?|not|type\?|stats|'
+                      r'bind|union|replace|charset|routine)$', word):
+            yield match.start(), Name.Builtin, word
+        elif re.match(r'(make|random|reflect|to|form|mold|absolute|add|divide|multiply|negate|'
+                      r'power|remainder|round|subtract|even\?|odd\?|and~|complement|or~|xor~|'
+                      r'append|at|back|change|clear|copy|find|head|head\?|index\?|insert|'
+                      r'length\?|next|pick|poke|remove|reverse|select|sort|skip|swap|tail|tail\?|'
+                      r'take|trim|create|close|delete|modify|open|open\?|query|read|rename|'
+                      r'update|write)$', word):
+            yield match.start(), Name.Function, word
+        elif re.match(r'(yes|on|no|off|true|false|tab|cr|lf|newline|escape|slash|sp|space|null|'
+                      r'none|crlf|dot|null-byte)$', word):
+            yield match.start(), Name.Builtin.Pseudo, word
+        elif re.match(r'(#system-global|#include|#enum|#define|#either|#if|#import|#export|'
+                      r'#switch|#default|#get-definition)$', word):
+            yield match.start(), Keyword.Namespace, word
+        elif re.match(r'(system|halt|quit|quit-return|do|load|q|recycle|call|run|ask|parse|'
+                      r'raise-error|return|exit|break|alias|push|pop|probe|\?\?|spec-of|body-of|'
+                      r'quote|forever)$', word):
+            yield match.start(), Name.Exception, word
+        elif re.match(r'(action\?|block\?|char\?|datatype\?|file\?|function\?|get-path\?|zero\?|'
+                      r'get-word\?|integer\?|issue\?|lit-path\?|lit-word\?|logic\?|native\?|'
+                      r'op\?|paren\?|path\?|refinement\?|set-path\?|set-word\?|string\?|unset\?|'
+                      r'any-struct\?|none\?|word\?|any-series\?)$', word):
+            yield match.start(), Keyword, word
+        elif re.match(r'(JNICALL|stdcall|cdecl|infix)$', word):
+            yield match.start(), Keyword.Namespace, word
+        elif re.match("to-.*", word):
+            yield match.start(), Keyword, word
+        elif re.match(r'(\+|-\*\*|-|\*\*|//|/|\*|and|or|xor|=\?|===|==|=|<>|<=|>=|'
+                      r'<<<|>>>|<<|>>|<|>%)$', word):
+            yield match.start(), Operator, word
+        elif re.match(r".*\!$", word):
+            yield match.start(), Keyword.Type, word
+        elif re.match("'.*", word):
+            yield match.start(), Name.Variable.Instance, word  # lit-word
+        elif re.match("#.*", word):
+            yield match.start(), Name.Label, word  # issue
+        elif re.match("%.*", word):
+            yield match.start(), Name.Decorator, word  # file
+        elif re.match(":.*", word):
+            yield match.start(), Generic.Subheading, word  # get-word
+        else:
+            yield match.start(), Name.Variable, word
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+            (r'#"', String.Char, 'char'),
+            (r'#\{[0-9a-f\s]*\}', Number.Hex),
+            (r'2#\{', Number.Hex, 'bin2'),
+            (r'64#\{[0-9a-z+/=\s]*\}', Number.Hex),
+            (r'([0-9a-f]+)(h)((\s)|(?=[\[\]{}"()]))',
+             bygroups(Number.Hex, Name.Variable, Whitespace)),
+            (r'"', String, 'string'),
+            (r'\{', String, 'string2'),
+            (r';#+.*\n', Comment.Special),
+            (r';\*+.*\n', Comment.Preproc),
+            (r';.*\n', Comment),
+            (r'%"', Name.Decorator, 'stringFile'),
+            (r'%[^(^{")\s\[\]]+', Name.Decorator),
+            (r'[+-]?([a-z]{1,3})?\$\d+(\.\d+)?', Number.Float),  # money
+            (r'[+-]?\d+\:\d+(\:\d+)?(\.\d+)?', String.Other),    # time
+            (r'\d+[\-/][0-9a-z]+[\-/]\d+(/\d+:\d+((:\d+)?'
+             r'([\.\d+]?([+-]?\d+:\d+)?)?)?)?', String.Other),   # date
+            (r'\d+(\.\d+)+\.\d+', Keyword.Constant),             # tuple
+            (r'\d+X\d+', Keyword.Constant),                   # pair
+            (r'[+-]?\d+(\'\d+)?([.,]\d*)?E[+-]?\d+', Number.Float),
+            (r'[+-]?\d+(\'\d+)?[.,]\d*', Number.Float),
+            (r'[+-]?\d+(\'\d+)?', Number),
+            (r'[\[\]()]', Generic.Strong),
+            (r'[a-z]+[^(^{"\s:)]*://[^(^{"\s)]*', Name.Decorator),  # url
+            (r'mailto:[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator),  # url
+            (r'[^(^{"@\s)]+@[^(^{"@\s)]+', Name.Decorator),         # email
+            (r'comment\s"', Comment, 'commentString1'),
+            (r'comment\s\{', Comment, 'commentString2'),
+            (r'comment\s\[', Comment, 'commentBlock'),
+            (r'comment\s[^(\s{"\[]+', Comment),
+            (r'/[^(^{^")\s/[\]]*', Name.Attribute),
+            (r'([^(^{^")\s/[\]]+)(?=[:({"\s/\[\]])', word_callback),
+            (r'<[\w:.-]*>', Name.Tag),
+            (r'<[^(<>\s")]+', Name.Tag, 'tag'),
+            (r'([^(^{")\s]+)', Text),
+        ],
+        'string': [
+            (r'[^(^")]+', String),
+            (escape_re, String.Escape),
+            (r'[(|)]+', String),
+            (r'\^.', String.Escape),
+            (r'"', String, '#pop'),
+        ],
+        'string2': [
+            (r'[^(^{})]+', String),
+            (escape_re, String.Escape),
+            (r'[(|)]+', String),
+            (r'\^.', String.Escape),
+            (r'\{', String, '#push'),
+            (r'\}', String, '#pop'),
+        ],
+        'stringFile': [
+            (r'[^(^")]+', Name.Decorator),
+            (escape_re, Name.Decorator),
+            (r'\^.', Name.Decorator),
+            (r'"', Name.Decorator, '#pop'),
+        ],
+        'char': [
+            (escape_re + '"', String.Char, '#pop'),
+            (r'\^."', String.Char, '#pop'),
+            (r'."', String.Char, '#pop'),
+        ],
+        'tag': [
+            (escape_re, Name.Tag),
+            (r'"', Name.Tag, 'tagString'),
+            (r'[^(<>\r\n")]+', Name.Tag),
+            (r'>', Name.Tag, '#pop'),
+        ],
+        'tagString': [
+            (r'[^(^")]+', Name.Tag),
+            (escape_re, Name.Tag),
+            (r'[(|)]+', Name.Tag),
+            (r'\^.', Name.Tag),
+            (r'"', Name.Tag, '#pop'),
+        ],
+        'tuple': [
+            (r'(\d+\.)+', Keyword.Constant),
+            (r'\d+', Keyword.Constant, '#pop'),
+        ],
+        'bin2': [
+            (r'\s+', Number.Hex),
+            (r'([01]\s*){8}', Number.Hex),
+            (r'\}', Number.Hex, '#pop'),
+        ],
+        'commentString1': [
+            (r'[^(^")]+', Comment),
+            (escape_re, Comment),
+            (r'[(|)]+', Comment),
+            (r'\^.', Comment),
+            (r'"', Comment, '#pop'),
+        ],
+        'commentString2': [
+            (r'[^(^{})]+', Comment),
+            (escape_re, Comment),
+            (r'[(|)]+', Comment),
+            (r'\^.', Comment),
+            (r'\{', Comment, '#push'),
+            (r'\}', Comment, '#pop'),
+        ],
+        'commentBlock': [
+            (r'\[', Comment, '#push'),
+            (r'\]', Comment, '#pop'),
+            (r'"', Comment, "commentString1"),
+            (r'\{', Comment, "commentString2"),
+            (r'[^(\[\]"{)]+', Comment),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/rego.py b/lib/python3.11/site-packages/pygments/lexers/rego.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2e8b75473ce1f8b72a94f7de904d9f3b23c3a9f
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rego.py
@@ -0,0 +1,57 @@
+"""
+    pygments.lexers.rego
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Rego policy languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words
+from pygments.token import Comment, Operator, Keyword, Name, String, Number, Punctuation, Whitespace
+
+class RegoLexer(RegexLexer):
+    """
+    For Rego source.
+    """
+    name = 'Rego'
+    url = 'https://www.openpolicyagent.org/docs/latest/policy-language/'
+    filenames = ['*.rego']
+    aliases = ['rego']
+    mimetypes = ['text/x-rego']
+    version_added = '2.19'
+
+    reserved_words = (
+        'as', 'contains', 'data', 'default', 'else', 'every', 'false',
+        'if', 'in', 'import', 'package', 'not', 'null',
+        'some', 'true', 'with'
+    )
+
+    builtins = (
+        # https://www.openpolicyagent.org/docs/latest/philosophy/#the-opa-document-model
+        'data',  # Global variable for accessing base and virtual documents
+        'input', # Represents synchronously pushed base documents
+    )
+
+    tokens = {
+        'root': [
+            (r'\n', Whitespace),
+            (r'\s+', Whitespace),
+            (r'#.*?$', Comment.Single),
+            (words(reserved_words, suffix=r'\b'), Keyword),
+            (words(builtins, suffix=r'\b'), Name.Builtin),
+            (r'[a-zA-Z_][a-zA-Z0-9_]*', Name),
+            (r'"(\\\\|\\"|[^"])*"', String.Double),
+            (r'`[^`]*`', String.Backtick),
+            (r'-?\d+(\.\d+)?', Number),
+            (r'(==|!=|<=|>=|:=)', Operator),  # Compound operators
+            (r'[=<>+\-*/%&|]', Operator),     # Single-character operators
+            (r'[\[\]{}(),.:;]', Punctuation),
+        ]
+    }
+
+__all__ = ['RegoLexer']
+
+
+
diff --git a/lib/python3.11/site-packages/pygments/lexers/rell.py b/lib/python3.11/site-packages/pygments/lexers/rell.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d54ed2a5162448386aa30d1d2f2f99f9e836c20
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rell.py
@@ -0,0 +1,68 @@
+"""
+    pygments.lexers.rell
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Rell language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, default, words
+from pygments.token import Comment, Keyword, Name, String, Number, \
+        Punctuation, Whitespace
+
+__all__ = ['RellLexer']
+
+
+class RellLexer(RegexLexer):
+    """
+    A Lexer for Rell.
+    """
+    name = 'Rell'
+    url = 'https://docs.chromia.com/rell/rell-intro'
+    aliases = ['rell']
+    filenames = ['*.rell']
+    mimetypes = ['text/x-rell']
+    version_added = '2.20'
+
+    ident = r'[a-zA-Z_][a-zA-Z0-9_]*'
+
+    tokens = {
+        'root': [
+            (words((
+                'big_integer', 'boolean', 'byte_array', 'decimal', 'gtv',
+                'integer', 'json', 'list', 'map', 'mutable', 'set', 'text',
+                'virtual'), suffix=r'\b'),
+             Keyword.Type),
+            (r'(false|true|null)\b', Keyword.Constant),
+            (r'(entity|enum|namespace|object|struct)\b', Keyword.Declaration),
+            (r'(function|operation|query)\b', Keyword.Declaration, 'function'),
+            (words((
+                'abstract', 'and', 'break', 'continue', 'create', 'delete',
+                'else', 'for', 'if', 'import', 'in', 'index', 'key', 'limit',
+                'module', 'not', 'offset', 'or', 'override', 'return', 'update',
+                'val', 'var', 'when', 'while'), suffix=r'\b'),
+             Keyword.Reserved),
+            (r'//.*?$', Comment.Single),
+            (r'/\*(.|\n|\r)*?\*/', Comment.Multiline),
+            (r'"(\\\\|\\"|[^"])*"', String.Double),
+            (r'\'(\\\\|\\\'|[^\\\'])*\'', String.Single),
+            (r'-?[0-9]*\.[0-9]+([eE][+-][0-9]+)?', Number.Float),
+            (r'-?[0-9]+([eE][+-][0-9]+|[lL])?', Number.Integer),
+            (r'x(\'[a-fA-F0-9]*\'|"[a-fA-F0-9]*")', String.Binary),
+            (r'(\.)([ \n\t\r]*)(' + ident + ')',
+                bygroups(Punctuation, Whitespace, Name.Attribute)),
+            (r'[{}():;,]+', Punctuation),
+            (r'[ \n\t\r]+', Whitespace),
+            (r'@[a-zA-Z_][a-zA-Z0-9_]*', Name.Decorator),
+            (r'[~^*!%&\[\]<>|+=/?\-@\$]', Punctuation.Marker),
+            (ident, Name),
+            (r'(\.)+', Punctuation),
+        ],
+        'function': [
+            (r'[ \n\t\r]+', Whitespace),
+            (ident, Name.Function, '#pop'),
+            default('#pop'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/resource.py b/lib/python3.11/site-packages/pygments/lexers/resource.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb6cb4a2ee6b9a661613d68fcd8f1fc2d77e96a2
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/resource.py
@@ -0,0 +1,83 @@
+"""
+    pygments.lexers.resource
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for resource definition files.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, bygroups, words
+from pygments.token import Comment, String, Number, Operator, Text, \
+    Keyword, Name
+
+__all__ = ['ResourceLexer']
+
+
+class ResourceLexer(RegexLexer):
+    """Lexer for ICU Resource bundles.
+    """
+    name = 'ResourceBundle'
+    aliases = ['resourcebundle', 'resource']
+    filenames = []
+    url = 'https://unicode-org.github.io/icu/userguide/locale/resources.html'
+    version_added = '2.0'
+
+    _types = (':table', ':array', ':string', ':bin', ':import', ':intvector',
+              ':int', ':alias')
+
+    flags = re.MULTILINE | re.IGNORECASE
+    tokens = {
+        'root': [
+            (r'//.*?$', Comment),
+            (r'"', String, 'string'),
+            (r'-?\d+', Number.Integer),
+            (r'[,{}]', Operator),
+            (r'([^\s{{:]+)(\s*)({}?)'.format('|'.join(_types)),
+             bygroups(Name, Text, Keyword)),
+            (r'\s+', Text),
+            (words(_types), Keyword),
+        ],
+        'string': [
+            (r'(\\x[0-9a-f]{2}|\\u[0-9a-f]{4}|\\U00[0-9a-f]{6}|'
+             r'\\[0-7]{1,3}|\\c.|\\[abtnvfre\'"?\\]|\\\{|[^"{\\])+', String),
+            (r'\{', String.Escape, 'msgname'),
+            (r'"', String, '#pop')
+        ],
+        'msgname': [
+            (r'([^{},]+)(\s*)', bygroups(Name, String.Escape), ('#pop', 'message'))
+        ],
+        'message': [
+            (r'\{', String.Escape, 'msgname'),
+            (r'\}', String.Escape, '#pop'),
+            (r'(,)(\s*)([a-z]+)(\s*\})',
+             bygroups(Operator, String.Escape, Keyword, String.Escape), '#pop'),
+            (r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)(offset)(\s*)(:)(\s*)(-?\d+)(\s*)',
+             bygroups(Operator, String.Escape, Keyword, String.Escape, Operator,
+                      String.Escape, Operator.Word, String.Escape, Operator,
+                      String.Escape, Number.Integer, String.Escape), 'choice'),
+            (r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)',
+             bygroups(Operator, String.Escape, Keyword, String.Escape, Operator,
+                      String.Escape), 'choice'),
+            (r'\s+', String.Escape)
+        ],
+        'choice': [
+            (r'(=|<|>|<=|>=|!=)(-?\d+)(\s*\{)',
+             bygroups(Operator, Number.Integer, String.Escape), 'message'),
+            (r'([a-z]+)(\s*\{)', bygroups(Keyword.Type, String.Escape), 'str'),
+            (r'\}', String.Escape, ('#pop', '#pop')),
+            (r'\s+', String.Escape)
+        ],
+        'str': [
+            (r'\}', String.Escape, '#pop'),
+            (r'\{', String.Escape, 'msgname'),
+            (r'[^{}]+', String)
+        ]
+    }
+
+    def analyse_text(text):
+        if text.startswith('root:table'):
+            return 1.0
diff --git a/lib/python3.11/site-packages/pygments/lexers/ride.py b/lib/python3.11/site-packages/pygments/lexers/ride.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ed8f38412baa74fc0ed6b53709cdcb41afeb893
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/ride.py
@@ -0,0 +1,138 @@
+"""
+    pygments.lexers.ride
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for the Ride programming language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words, include
+from pygments.token import Comment, Keyword, Name, Number, Punctuation, \
+    String, Text
+
+__all__ = ['RideLexer']
+
+
+class RideLexer(RegexLexer):
+    """
+    For Ride source code.
+    """
+
+    name = 'Ride'
+    aliases = ['ride']
+    filenames = ['*.ride']
+    mimetypes = ['text/x-ride']
+    url = 'https://docs.waves.tech/en/ride'
+    version_added = '2.6'
+
+    validName = r'[a-zA-Z_][a-zA-Z0-9_\']*'
+
+    builtinOps = (
+        '||', '|', '>=', '>', '==', '!',
+        '=', '<=', '<', '::', ':+', ':', '!=', '/',
+        '.', '=>', '-', '+', '*', '&&', '%', '++',
+    )
+
+    globalVariablesName = (
+        'NOALG', 'MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512',
+        'SHA3224', 'SHA3256', 'SHA3384', 'SHA3512', 'nil', 'this', 'unit',
+        'height', 'lastBlock', 'Buy', 'Sell', 'CEILING', 'FLOOR', 'DOWN',
+        'HALFDOWN', 'HALFEVEN', 'HALFUP', 'UP',
+    )
+
+    typesName = (
+        'Unit', 'Int', 'Boolean', 'ByteVector', 'String', 'Address', 'Alias',
+        'Transfer', 'AssetPair', 'DataEntry', 'Order', 'Transaction',
+        'GenesisTransaction', 'PaymentTransaction', 'ReissueTransaction',
+        'BurnTransaction', 'MassTransferTransaction', 'ExchangeTransaction',
+        'TransferTransaction', 'SetAssetScriptTransaction',
+        'InvokeScriptTransaction', 'IssueTransaction', 'LeaseTransaction',
+        'LeaseCancelTransaction', 'CreateAliasTransaction',
+        'SetScriptTransaction', 'SponsorFeeTransaction', 'DataTransaction',
+        'WriteSet', 'AttachedPayment', 'ScriptTransfer', 'TransferSet',
+        'ScriptResult', 'Invocation', 'Asset', 'BlockInfo', 'Issue', 'Reissue',
+        'Burn', 'NoAlg', 'Md5', 'Sha1', 'Sha224', 'Sha256', 'Sha384', 'Sha512',
+        'Sha3224', 'Sha3256', 'Sha3384', 'Sha3512', 'BinaryEntry',
+        'BooleanEntry', 'IntegerEntry', 'StringEntry', 'List', 'Ceiling',
+        'Down', 'Floor', 'HalfDown', 'HalfEven', 'HalfUp', 'Up',
+    )
+
+    functionsName = (
+        'fraction', 'size', 'toBytes', 'take', 'drop', 'takeRight', 'dropRight',
+        'toString', 'isDefined', 'extract', 'throw', 'getElement', 'value',
+        'cons', 'toUtf8String', 'toInt', 'indexOf', 'lastIndexOf', 'split',
+        'parseInt', 'parseIntValue', 'keccak256', 'blake2b256', 'sha256',
+        'sigVerify', 'toBase58String', 'fromBase58String', 'toBase64String',
+        'fromBase64String', 'transactionById', 'transactionHeightById',
+        'getInteger', 'getBoolean', 'getBinary', 'getString',
+        'addressFromPublicKey', 'addressFromString', 'addressFromRecipient',
+        'assetBalance', 'wavesBalance', 'getIntegerValue', 'getBooleanValue',
+        'getBinaryValue', 'getStringValue', 'addressFromStringValue',
+        'assetInfo', 'rsaVerify', 'checkMerkleProof', 'median',
+        'valueOrElse', 'valueOrErrorMessage', 'contains', 'log', 'pow',
+        'toBase16String', 'fromBase16String', 'blockInfoByHeight',
+        'transferTransactionById',
+    )
+
+    reservedWords = words((
+        'match', 'case', 'else', 'func', 'if',
+        'let', 'then', '@Callable', '@Verifier',
+    ), suffix=r'\b')
+
+    tokens = {
+        'root': [
+            # Comments
+            (r'#.*', Comment.Single),
+            # Whitespace
+            (r'\s+', Text),
+            # Strings
+            (r'"', String, 'doublequote'),
+            (r'utf8\'', String, 'utf8quote'),
+            (r'base(58|64|16)\'', String, 'singlequote'),
+            # Keywords
+            (reservedWords, Keyword.Reserved),
+            (r'\{-#.*?#-\}', Keyword.Reserved),
+            (r'FOLD<\d+>', Keyword.Reserved),
+            # Types
+            (words(typesName), Keyword.Type),
+            # Main
+            # (specialName, Keyword.Reserved),
+            # Prefix Operators
+            (words(builtinOps, prefix=r'\(', suffix=r'\)'), Name.Function),
+            # Infix Operators
+            (words(builtinOps), Name.Function),
+            (words(globalVariablesName), Name.Function),
+            (words(functionsName), Name.Function),
+            # Numbers
+            include('numbers'),
+            # Variable Names
+            (validName, Name.Variable),
+            # Parens
+            (r'[,()\[\]{}]', Punctuation),
+        ],
+
+        'doublequote': [
+            (r'\\u[0-9a-fA-F]{4}', String.Escape),
+            (r'\\[nrfvb\\"]', String.Escape),
+            (r'[^"]', String),
+            (r'"', String, '#pop'),
+        ],
+
+        'utf8quote': [
+            (r'\\u[0-9a-fA-F]{4}', String.Escape),
+            (r'\\[nrfvb\\\']', String.Escape),
+            (r'[^\']', String),
+            (r'\'', String, '#pop'),
+        ],
+
+        'singlequote': [
+            (r'[^\']', String),
+            (r'\'', String, '#pop'),
+        ],
+
+        'numbers': [
+            (r'_?\d+', Number.Integer),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/rita.py b/lib/python3.11/site-packages/pygments/lexers/rita.py
new file mode 100644
index 0000000000000000000000000000000000000000..99a574c2a1a4d83050389f07dbb5052a3c39b180
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rita.py
@@ -0,0 +1,42 @@
+"""
+    pygments.lexers.rita
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for RITA language
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer
+from pygments.token import Comment, Operator, Keyword, Name, Literal, \
+    Punctuation, Whitespace
+
+__all__ = ['RitaLexer']
+
+
+class RitaLexer(RegexLexer):
+    """
+    Lexer for RITA.
+    """
+    name = 'Rita'
+    url = 'https://github.com/zaibacu/rita-dsl'
+    filenames = ['*.rita']
+    aliases = ['rita']
+    mimetypes = ['text/rita']
+    version_added = '2.11'
+
+    tokens = {
+        'root': [
+            (r'\n', Whitespace),
+            (r'\s+', Whitespace),
+            (r'#(.*?)\n', Comment.Single),
+            (r'@(.*?)\n', Operator),  # Yes, whole line as an operator
+            (r'"(\w|\d|\s|(\\")|[\'_\-./,\?\!])+?"', Literal),
+            (r'\'(\w|\d|\s|(\\\')|["_\-./,\?\!])+?\'', Literal),
+            (r'([A-Z_]+)', Keyword),
+            (r'([a-z0-9_]+)', Name),
+            (r'((->)|[!?+*|=])', Operator),
+            (r'[\(\),\{\}]', Punctuation)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/rnc.py b/lib/python3.11/site-packages/pygments/lexers/rnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ddd33e44474451c6f1cff5a9ac35eb40df3783a
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rnc.py
@@ -0,0 +1,66 @@
+"""
+    pygments.lexers.rnc
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Relax-NG Compact syntax
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Punctuation
+
+__all__ = ['RNCCompactLexer']
+
+
+class RNCCompactLexer(RegexLexer):
+    """
+    For RelaxNG-compact syntax.
+    """
+
+    name = 'Relax-NG Compact'
+    url = 'http://relaxng.org'
+    aliases = ['rng-compact', 'rnc']
+    filenames = ['*.rnc']
+    version_added = '2.2'
+
+    tokens = {
+        'root': [
+            (r'namespace\b', Keyword.Namespace),
+            (r'(?:default|datatypes)\b', Keyword.Declaration),
+            (r'##.*$', Comment.Preproc),
+            (r'#.*$', Comment.Single),
+            (r'"[^"]*"', String.Double),
+            # TODO single quoted strings and escape sequences outside of
+            # double-quoted strings
+            (r'(?:element|attribute|mixed)\b', Keyword.Declaration, 'variable'),
+            (r'(text\b|xsd:[^ ]+)', Keyword.Type, 'maybe_xsdattributes'),
+            (r'[,?&*=|~]|>>', Operator),
+            (r'[(){}]', Punctuation),
+            (r'.', Text),
+        ],
+
+        # a variable has been declared using `element` or `attribute`
+        'variable': [
+            (r'[^{]+', Name.Variable),
+            (r'\{', Punctuation, '#pop'),
+        ],
+
+        # after an xsd: declaration there may be attributes
+        'maybe_xsdattributes': [
+            (r'\{', Punctuation, 'xsdattributes'),
+            (r'\}', Punctuation, '#pop'),
+            (r'.', Text),
+        ],
+
+        # attributes take the form { key1 = value1 key2 = value2 ... }
+        'xsdattributes': [
+            (r'[^ =}]', Name.Attribute),
+            (r'=', Operator),
+            (r'"[^"]*"', String.Double),
+            (r'\}', Punctuation, '#pop'),
+            (r'.', Text),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/roboconf.py b/lib/python3.11/site-packages/pygments/lexers/roboconf.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf0570cc37161e82e34a31113731d723b662128f
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/roboconf.py
@@ -0,0 +1,81 @@
+"""
+    pygments.lexers.roboconf
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Roboconf DSL.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words, re
+from pygments.token import Text, Operator, Keyword, Name, Comment
+
+__all__ = ['RoboconfGraphLexer', 'RoboconfInstancesLexer']
+
+
+class RoboconfGraphLexer(RegexLexer):
+    """
+    Lexer for Roboconf graph files.
+    """
+    name = 'Roboconf Graph'
+    aliases = ['roboconf-graph']
+    filenames = ['*.graph']
+    url = 'https://roboconf.github.io/en/user-guide/graph-definition.html'
+    version_added = '2.1'
+
+    flags = re.IGNORECASE | re.MULTILINE
+    tokens = {
+        'root': [
+            # Skip white spaces
+            (r'\s+', Text),
+
+            # There is one operator
+            (r'=', Operator),
+
+            # Keywords
+            (words(('facet', 'import'), suffix=r'\s*\b', prefix=r'\b'), Keyword),
+            (words((
+                'installer', 'extends', 'exports', 'imports', 'facets',
+                'children'), suffix=r'\s*:?', prefix=r'\b'), Name),
+
+            # Comments
+            (r'#.*\n', Comment),
+
+            # Default
+            (r'[^#]', Text),
+            (r'.*\n', Text)
+        ]
+    }
+
+
+class RoboconfInstancesLexer(RegexLexer):
+    """
+    Lexer for Roboconf instances files.
+    """
+    name = 'Roboconf Instances'
+    aliases = ['roboconf-instances']
+    filenames = ['*.instances']
+    url = 'https://roboconf.github.io'
+    version_added = '2.1'
+
+    flags = re.IGNORECASE | re.MULTILINE
+    tokens = {
+        'root': [
+
+            # Skip white spaces
+            (r'\s+', Text),
+
+            # Keywords
+            (words(('instance of', 'import'), suffix=r'\s*\b', prefix=r'\b'), Keyword),
+            (words(('name', 'count'), suffix=r's*:?', prefix=r'\b'), Name),
+            (r'\s*[\w.-]+\s*:', Name),
+
+            # Comments
+            (r'#.*\n', Comment),
+
+            # Default
+            (r'[^#]', Text),
+            (r'.*\n', Text)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/robotframework.py b/lib/python3.11/site-packages/pygments/lexers/robotframework.py
new file mode 100644
index 0000000000000000000000000000000000000000..a481136cc7b8c08182e10fc5c57d9aa41ceedaf1
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/robotframework.py
@@ -0,0 +1,551 @@
+"""
+    pygments.lexers.robotframework
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Robot Framework.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+#  Copyright 2012 Nokia Siemens Networks Oyj
+#
+#  Licensed under the Apache License, Version 2.0 (the "License");
+#  you may not use this file except in compliance with the License.
+#  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+import re
+
+from pygments.lexer import Lexer
+from pygments.token import Token
+
+__all__ = ['RobotFrameworkLexer']
+
+
+HEADING = Token.Generic.Heading
+SETTING = Token.Keyword.Namespace
+IMPORT = Token.Name.Namespace
+TC_KW_NAME = Token.Generic.Subheading
+KEYWORD = Token.Name.Function
+ARGUMENT = Token.String
+VARIABLE = Token.Name.Variable
+COMMENT = Token.Comment
+SEPARATOR = Token.Punctuation
+SYNTAX = Token.Punctuation
+GHERKIN = Token.Generic.Emph
+ERROR = Token.Error
+
+
+def normalize(string, remove=''):
+    string = string.lower()
+    for char in remove + ' ':
+        if char in string:
+            string = string.replace(char, '')
+    return string
+
+
+class RobotFrameworkLexer(Lexer):
+    """
+    For Robot Framework test data.
+
+    Supports both space and pipe separated plain text formats.
+    """
+    name = 'RobotFramework'
+    url = 'http://robotframework.org'
+    aliases = ['robotframework']
+    filenames = ['*.robot', '*.resource']
+    mimetypes = ['text/x-robotframework']
+    version_added = '1.6'
+
+    def __init__(self, **options):
+        options['tabsize'] = 2
+        options['encoding'] = 'UTF-8'
+        Lexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        row_tokenizer = RowTokenizer()
+        var_tokenizer = VariableTokenizer()
+        index = 0
+        for row in text.splitlines():
+            for value, token in row_tokenizer.tokenize(row):
+                for value, token in var_tokenizer.tokenize(value, token):
+                    if value:
+                        yield index, token, str(value)
+                        index += len(value)
+
+
+class VariableTokenizer:
+
+    def tokenize(self, string, token):
+        var = VariableSplitter(string, identifiers='$@%&')
+        if var.start < 0 or token in (COMMENT, ERROR):
+            yield string, token
+            return
+        for value, token in self._tokenize(var, string, token):
+            if value:
+                yield value, token
+
+    def _tokenize(self, var, string, orig_token):
+        before = string[:var.start]
+        yield before, orig_token
+        yield var.identifier + '{', SYNTAX
+        yield from self.tokenize(var.base, VARIABLE)
+        yield '}', SYNTAX
+        if var.index is not None:
+            yield '[', SYNTAX
+            yield from self.tokenize(var.index, VARIABLE)
+            yield ']', SYNTAX
+        yield from self.tokenize(string[var.end:], orig_token)
+
+
+class RowTokenizer:
+
+    def __init__(self):
+        self._table = UnknownTable()
+        self._splitter = RowSplitter()
+        testcases = TestCaseTable()
+        settings = SettingTable(testcases.set_default_template)
+        variables = VariableTable()
+        keywords = KeywordTable()
+        self._tables = {'settings': settings, 'setting': settings,
+                        'metadata': settings,
+                        'variables': variables, 'variable': variables,
+                        'testcases': testcases, 'testcase': testcases,
+                        'tasks': testcases, 'task': testcases,
+                        'keywords': keywords, 'keyword': keywords,
+                        'userkeywords': keywords, 'userkeyword': keywords}
+
+    def tokenize(self, row):
+        commented = False
+        heading = False
+        for index, value in enumerate(self._splitter.split(row)):
+            # First value, and every second after that, is a separator.
+            index, separator = divmod(index-1, 2)
+            if value.startswith('#'):
+                commented = True
+            elif index == 0 and value.startswith('*'):
+                self._table = self._start_table(value)
+                heading = True
+            yield from self._tokenize(value, index, commented,
+                                      separator, heading)
+        self._table.end_row()
+
+    def _start_table(self, header):
+        name = normalize(header, remove='*')
+        return self._tables.get(name, UnknownTable())
+
+    def _tokenize(self, value, index, commented, separator, heading):
+        if commented:
+            yield value, COMMENT
+        elif separator:
+            yield value, SEPARATOR
+        elif heading:
+            yield value, HEADING
+        else:
+            yield from self._table.tokenize(value, index)
+
+
+class RowSplitter:
+    _space_splitter = re.compile('( {2,})')
+    _pipe_splitter = re.compile(r'((?:^| +)\|(?: +|$))')
+
+    def split(self, row):
+        splitter = (row.startswith('| ') and self._split_from_pipes
+                    or self._split_from_spaces)
+        yield from splitter(row)
+        yield '\n'
+
+    def _split_from_spaces(self, row):
+        yield ''  # Start with (pseudo)separator similarly as with pipes
+        yield from self._space_splitter.split(row)
+
+    def _split_from_pipes(self, row):
+        _, separator, rest = self._pipe_splitter.split(row, 1)
+        yield separator
+        while self._pipe_splitter.search(rest):
+            cell, separator, rest = self._pipe_splitter.split(rest, 1)
+            yield cell
+            yield separator
+        yield rest
+
+
+class Tokenizer:
+    _tokens = None
+
+    def __init__(self):
+        self._index = 0
+
+    def tokenize(self, value):
+        values_and_tokens = self._tokenize(value, self._index)
+        self._index += 1
+        if isinstance(values_and_tokens, type(Token)):
+            values_and_tokens = [(value, values_and_tokens)]
+        return values_and_tokens
+
+    def _tokenize(self, value, index):
+        index = min(index, len(self._tokens) - 1)
+        return self._tokens[index]
+
+    def _is_assign(self, value):
+        if value.endswith('='):
+            value = value[:-1].strip()
+        var = VariableSplitter(value, identifiers='$@&')
+        return var.start == 0 and var.end == len(value)
+
+
+class Comment(Tokenizer):
+    _tokens = (COMMENT,)
+
+
+class Setting(Tokenizer):
+    _tokens = (SETTING, ARGUMENT)
+    _keyword_settings = ('suitesetup', 'suiteprecondition', 'suiteteardown',
+                         'suitepostcondition', 'testsetup', 'tasksetup', 'testprecondition',
+                         'testteardown','taskteardown', 'testpostcondition', 'testtemplate', 'tasktemplate')
+    _import_settings = ('library', 'resource', 'variables')
+    _other_settings = ('documentation', 'metadata', 'forcetags', 'defaulttags',
+                       'testtimeout','tasktimeout')
+    _custom_tokenizer = None
+
+    def __init__(self, template_setter=None):
+        Tokenizer.__init__(self)
+        self._template_setter = template_setter
+
+    def _tokenize(self, value, index):
+        if index == 1 and self._template_setter:
+            self._template_setter(value)
+        if index == 0:
+            normalized = normalize(value)
+            if normalized in self._keyword_settings:
+                self._custom_tokenizer = KeywordCall(support_assign=False)
+            elif normalized in self._import_settings:
+                self._custom_tokenizer = ImportSetting()
+            elif normalized not in self._other_settings:
+                return ERROR
+        elif self._custom_tokenizer:
+            return self._custom_tokenizer.tokenize(value)
+        return Tokenizer._tokenize(self, value, index)
+
+
+class ImportSetting(Tokenizer):
+    _tokens = (IMPORT, ARGUMENT)
+
+
+class TestCaseSetting(Setting):
+    _keyword_settings = ('setup', 'precondition', 'teardown', 'postcondition',
+                         'template')
+    _import_settings = ()
+    _other_settings = ('documentation', 'tags', 'timeout')
+
+    def _tokenize(self, value, index):
+        if index == 0:
+            type = Setting._tokenize(self, value[1:-1], index)
+            return [('[', SYNTAX), (value[1:-1], type), (']', SYNTAX)]
+        return Setting._tokenize(self, value, index)
+
+
+class KeywordSetting(TestCaseSetting):
+    _keyword_settings = ('teardown',)
+    _other_settings = ('documentation', 'arguments', 'return', 'timeout', 'tags')
+
+
+class Variable(Tokenizer):
+    _tokens = (SYNTAX, ARGUMENT)
+
+    def _tokenize(self, value, index):
+        if index == 0 and not self._is_assign(value):
+            return ERROR
+        return Tokenizer._tokenize(self, value, index)
+
+
+class KeywordCall(Tokenizer):
+    _tokens = (KEYWORD, ARGUMENT)
+
+    def __init__(self, support_assign=True):
+        Tokenizer.__init__(self)
+        self._keyword_found = not support_assign
+        self._assigns = 0
+
+    def _tokenize(self, value, index):
+        if not self._keyword_found and self._is_assign(value):
+            self._assigns += 1
+            return SYNTAX  # VariableTokenizer tokenizes this later.
+        if self._keyword_found:
+            return Tokenizer._tokenize(self, value, index - self._assigns)
+        self._keyword_found = True
+        return GherkinTokenizer().tokenize(value, KEYWORD)
+
+
+class GherkinTokenizer:
+    _gherkin_prefix = re.compile('^(Given|When|Then|And|But) ', re.IGNORECASE)
+
+    def tokenize(self, value, token):
+        match = self._gherkin_prefix.match(value)
+        if not match:
+            return [(value, token)]
+        end = match.end()
+        return [(value[:end], GHERKIN), (value[end:], token)]
+
+
+class TemplatedKeywordCall(Tokenizer):
+    _tokens = (ARGUMENT,)
+
+
+class ForLoop(Tokenizer):
+
+    def __init__(self):
+        Tokenizer.__init__(self)
+        self._in_arguments = False
+
+    def _tokenize(self, value, index):
+        token = self._in_arguments and ARGUMENT or SYNTAX
+        if value.upper() in ('IN', 'IN RANGE'):
+            self._in_arguments = True
+        return token
+
+
+class _Table:
+    _tokenizer_class = None
+
+    def __init__(self, prev_tokenizer=None):
+        self._tokenizer = self._tokenizer_class()
+        self._prev_tokenizer = prev_tokenizer
+        self._prev_values_on_row = []
+
+    def tokenize(self, value, index):
+        if self._continues(value, index):
+            self._tokenizer = self._prev_tokenizer
+            yield value, SYNTAX
+        else:
+            yield from self._tokenize(value, index)
+        self._prev_values_on_row.append(value)
+
+    def _continues(self, value, index):
+        return value == '...' and all(self._is_empty(t)
+                                      for t in self._prev_values_on_row)
+
+    def _is_empty(self, value):
+        return value in ('', '\\')
+
+    def _tokenize(self, value, index):
+        return self._tokenizer.tokenize(value)
+
+    def end_row(self):
+        self.__init__(prev_tokenizer=self._tokenizer)
+
+
+class UnknownTable(_Table):
+    _tokenizer_class = Comment
+
+    def _continues(self, value, index):
+        return False
+
+
+class VariableTable(_Table):
+    _tokenizer_class = Variable
+
+
+class SettingTable(_Table):
+    _tokenizer_class = Setting
+
+    def __init__(self, template_setter, prev_tokenizer=None):
+        _Table.__init__(self, prev_tokenizer)
+        self._template_setter = template_setter
+
+    def _tokenize(self, value, index):
+        if index == 0 and normalize(value) == 'testtemplate':
+            self._tokenizer = Setting(self._template_setter)
+        return _Table._tokenize(self, value, index)
+
+    def end_row(self):
+        self.__init__(self._template_setter, prev_tokenizer=self._tokenizer)
+
+
+class TestCaseTable(_Table):
+    _setting_class = TestCaseSetting
+    _test_template = None
+    _default_template = None
+
+    @property
+    def _tokenizer_class(self):
+        if self._test_template or (self._default_template and
+                                   self._test_template is not False):
+            return TemplatedKeywordCall
+        return KeywordCall
+
+    def _continues(self, value, index):
+        return index > 0 and _Table._continues(self, value, index)
+
+    def _tokenize(self, value, index):
+        if index == 0:
+            if value:
+                self._test_template = None
+            return GherkinTokenizer().tokenize(value, TC_KW_NAME)
+        if index == 1 and self._is_setting(value):
+            if self._is_template(value):
+                self._test_template = False
+                self._tokenizer = self._setting_class(self.set_test_template)
+            else:
+                self._tokenizer = self._setting_class()
+        if index == 1 and self._is_for_loop(value):
+            self._tokenizer = ForLoop()
+        if index == 1 and self._is_empty(value):
+            return [(value, SYNTAX)]
+        return _Table._tokenize(self, value, index)
+
+    def _is_setting(self, value):
+        return value.startswith('[') and value.endswith(']')
+
+    def _is_template(self, value):
+        return normalize(value) == '[template]'
+
+    def _is_for_loop(self, value):
+        return value.startswith(':') and normalize(value, remove=':') == 'for'
+
+    def set_test_template(self, template):
+        self._test_template = self._is_template_set(template)
+
+    def set_default_template(self, template):
+        self._default_template = self._is_template_set(template)
+
+    def _is_template_set(self, template):
+        return normalize(template) not in ('', '\\', 'none', '${empty}')
+
+
+class KeywordTable(TestCaseTable):
+    _tokenizer_class = KeywordCall
+    _setting_class = KeywordSetting
+
+    def _is_template(self, value):
+        return False
+
+
+# Following code copied directly from Robot Framework 2.7.5.
+
+class VariableSplitter:
+
+    def __init__(self, string, identifiers):
+        self.identifier = None
+        self.base = None
+        self.index = None
+        self.start = -1
+        self.end = -1
+        self._identifiers = identifiers
+        self._may_have_internal_variables = False
+        try:
+            self._split(string)
+        except ValueError:
+            pass
+        else:
+            self._finalize()
+
+    def get_replaced_base(self, variables):
+        if self._may_have_internal_variables:
+            return variables.replace_string(self.base)
+        return self.base
+
+    def _finalize(self):
+        self.identifier = self._variable_chars[0]
+        self.base = ''.join(self._variable_chars[2:-1])
+        self.end = self.start + len(self._variable_chars)
+        if self._has_list_or_dict_variable_index():
+            self.index = ''.join(self._list_and_dict_variable_index_chars[1:-1])
+            self.end += len(self._list_and_dict_variable_index_chars)
+
+    def _has_list_or_dict_variable_index(self):
+        return self._list_and_dict_variable_index_chars\
+        and self._list_and_dict_variable_index_chars[-1] == ']'
+
+    def _split(self, string):
+        start_index, max_index = self._find_variable(string)
+        self.start = start_index
+        self._open_curly = 1
+        self._state = self._variable_state
+        self._variable_chars = [string[start_index], '{']
+        self._list_and_dict_variable_index_chars = []
+        self._string = string
+        start_index += 2
+        for index, char in enumerate(string[start_index:]):
+            index += start_index  # Giving start to enumerate only in Py 2.6+
+            try:
+                self._state(char, index)
+            except StopIteration:
+                return
+            if index  == max_index and not self._scanning_list_variable_index():
+                return
+
+    def _scanning_list_variable_index(self):
+        return self._state in [self._waiting_list_variable_index_state,
+                               self._list_variable_index_state]
+
+    def _find_variable(self, string):
+        max_end_index = string.rfind('}')
+        if max_end_index == -1:
+            raise ValueError('No variable end found')
+        if self._is_escaped(string, max_end_index):
+            return self._find_variable(string[:max_end_index])
+        start_index = self._find_start_index(string, 1, max_end_index)
+        if start_index == -1:
+            raise ValueError('No variable start found')
+        return start_index, max_end_index
+
+    def _find_start_index(self, string, start, end):
+        index = string.find('{', start, end) - 1
+        if index < 0:
+            return -1
+        if self._start_index_is_ok(string, index):
+            return index
+        return self._find_start_index(string, index+2, end)
+
+    def _start_index_is_ok(self, string, index):
+        return string[index] in self._identifiers\
+        and not self._is_escaped(string, index)
+
+    def _is_escaped(self, string, index):
+        escaped = False
+        while index > 0 and string[index-1] == '\\':
+            index -= 1
+            escaped = not escaped
+        return escaped
+
+    def _variable_state(self, char, index):
+        self._variable_chars.append(char)
+        if char == '}' and not self._is_escaped(self._string, index):
+            self._open_curly -= 1
+            if self._open_curly == 0:
+                if not self._is_list_or_dict_variable():
+                    raise StopIteration
+                self._state = self._waiting_list_variable_index_state
+        elif char in self._identifiers:
+            self._state = self._internal_variable_start_state
+
+    def _is_list_or_dict_variable(self):
+        return self._variable_chars[0] in ('@','&')
+
+    def _internal_variable_start_state(self, char, index):
+        self._state = self._variable_state
+        if char == '{':
+            self._variable_chars.append(char)
+            self._open_curly += 1
+            self._may_have_internal_variables = True
+        else:
+            self._variable_state(char, index)
+
+    def _waiting_list_variable_index_state(self, char, index):
+        if char != '[':
+            raise StopIteration
+        self._list_and_dict_variable_index_chars.append(char)
+        self._state = self._list_variable_index_state
+
+    def _list_variable_index_state(self, char, index):
+        self._list_and_dict_variable_index_chars.append(char)
+        if char == ']':
+            raise StopIteration
diff --git a/lib/python3.11/site-packages/pygments/lexers/ruby.py b/lib/python3.11/site-packages/pygments/lexers/ruby.py
new file mode 100644
index 0000000000000000000000000000000000000000..6832652a6cf52d22520a14a9adb78c8366b1f724
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/ruby.py
@@ -0,0 +1,518 @@
+"""
+    pygments.lexers.ruby
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Ruby and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import Lexer, RegexLexer, ExtendedRegexLexer, include, \
+    bygroups, default, LexerContext, do_insertions, words, line_re
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Error, Generic, Whitespace
+from pygments.util import shebang_matches
+
+__all__ = ['RubyLexer', 'RubyConsoleLexer', 'FancyLexer']
+
+
+RUBY_OPERATORS = (
+    '*', '**', '-', '+', '-@', '+@', '/', '%', '&', '|', '^', '`', '~',
+    '[]', '[]=', '<<', '>>', '<', '<>', '<=>', '>', '>=', '==', '==='
+)
+
+
+class RubyLexer(ExtendedRegexLexer):
+    """
+    For Ruby source code.
+    """
+
+    name = 'Ruby'
+    url = 'http://www.ruby-lang.org'
+    aliases = ['ruby', 'rb', 'duby']
+    filenames = ['*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec',
+                 '*.rbx', '*.duby', 'Gemfile', 'Vagrantfile']
+    mimetypes = ['text/x-ruby', 'application/x-ruby']
+    version_added = ''
+
+    flags = re.DOTALL | re.MULTILINE
+
+    def heredoc_callback(self, match, ctx):
+        # okay, this is the hardest part of parsing Ruby...
+        # match: 1 = <<[-~]?, 2 = quote? 3 = name 4 = quote? 5 = rest of line
+
+        start = match.start(1)
+        yield start, Operator, match.group(1)        # <<[-~]?
+        yield match.start(2), String.Heredoc, match.group(2)   # quote ", ', `
+        yield match.start(3), String.Delimiter, match.group(3) # heredoc name
+        yield match.start(4), String.Heredoc, match.group(4)   # quote again
+
+        heredocstack = ctx.__dict__.setdefault('heredocstack', [])
+        outermost = not bool(heredocstack)
+        heredocstack.append((match.group(1) in ('<<-', '<<~'), match.group(3)))
+
+        ctx.pos = match.start(5)
+        ctx.end = match.end(5)
+        # this may find other heredocs, so limit the recursion depth
+        if len(heredocstack) < 100:
+            yield from self.get_tokens_unprocessed(context=ctx)
+        else:
+            yield ctx.pos, String.Heredoc, match.group(5)
+        ctx.pos = match.end()
+
+        if outermost:
+            # this is the outer heredoc again, now we can process them all
+            for tolerant, hdname in heredocstack:
+                lines = []
+                for match in line_re.finditer(ctx.text, ctx.pos):
+                    if tolerant:
+                        check = match.group().strip()
+                    else:
+                        check = match.group().rstrip()
+                    if check == hdname:
+                        for amatch in lines:
+                            yield amatch.start(), String.Heredoc, amatch.group()
+                        yield match.start(), String.Delimiter, match.group()
+                        ctx.pos = match.end()
+                        break
+                    else:
+                        lines.append(match)
+                else:
+                    # end of heredoc not found -- error!
+                    for amatch in lines:
+                        yield amatch.start(), Error, amatch.group()
+            ctx.end = len(ctx.text)
+            del heredocstack[:]
+
+    def gen_rubystrings_rules():
+        def intp_regex_callback(self, match, ctx):
+            yield match.start(1), String.Regex, match.group(1)  # begin
+            nctx = LexerContext(match.group(3), 0, ['interpolated-regex'])
+            for i, t, v in self.get_tokens_unprocessed(context=nctx):
+                yield match.start(3)+i, t, v
+            yield match.start(4), String.Regex, match.group(4)  # end[mixounse]*
+            ctx.pos = match.end()
+
+        def intp_string_callback(self, match, ctx):
+            yield match.start(1), String.Other, match.group(1)
+            nctx = LexerContext(match.group(3), 0, ['interpolated-string'])
+            for i, t, v in self.get_tokens_unprocessed(context=nctx):
+                yield match.start(3)+i, t, v
+            yield match.start(4), String.Other, match.group(4)  # end
+            ctx.pos = match.end()
+
+        states = {}
+        states['strings'] = [
+            # easy ones
+            (r'\:@{0,2}[a-zA-Z_]\w*[!?]?', String.Symbol),
+            (words(RUBY_OPERATORS, prefix=r'\:@{0,2}'), String.Symbol),
+            (r":'(\\\\|\\[^\\]|[^'\\])*'", String.Symbol),
+            (r':"', String.Symbol, 'simple-sym'),
+            (r'([a-zA-Z_]\w*)(:)(?!:)',
+             bygroups(String.Symbol, Punctuation)),  # Since Ruby 1.9
+            (r'"', String.Double, 'simple-string-double'),
+            (r"'", String.Single, 'simple-string-single'),
+            (r'(?', '<>', 'ab'):
+            states[name+'-intp-string'] = [
+                (r'\\[\\' + bracecc + ']', String.Other),
+                (lbrace, String.Other, '#push'),
+                (rbrace, String.Other, '#pop'),
+                include('string-intp-escaped'),
+                (r'[\\#' + bracecc + ']', String.Other),
+                (r'[^\\#' + bracecc + ']+', String.Other),
+            ]
+            states['strings'].append((r'%[QWx]?' + lbrace, String.Other,
+                                      name+'-intp-string'))
+            states[name+'-string'] = [
+                (r'\\[\\' + bracecc + ']', String.Other),
+                (lbrace, String.Other, '#push'),
+                (rbrace, String.Other, '#pop'),
+                (r'[\\#' + bracecc + ']', String.Other),
+                (r'[^\\#' + bracecc + ']+', String.Other),
+            ]
+            states['strings'].append((r'%[qsw]' + lbrace, String.Other,
+                                      name+'-string'))
+            states[name+'-regex'] = [
+                (r'\\[\\' + bracecc + ']', String.Regex),
+                (lbrace, String.Regex, '#push'),
+                (rbrace + '[mixounse]*', String.Regex, '#pop'),
+                include('string-intp'),
+                (r'[\\#' + bracecc + ']', String.Regex),
+                (r'[^\\#' + bracecc + ']+', String.Regex),
+            ]
+            states['strings'].append((r'%r' + lbrace, String.Regex,
+                                      name+'-regex'))
+
+        # these must come after %!
+        states['strings'] += [
+            # %r regex
+            (r'(%r([\W_]))((?:\\\2|(?!\2).)*)(\2[mixounse]*)',
+             intp_regex_callback),
+            # regular fancy strings with qsw
+            (r'%[qsw]([\W_])((?:\\\1|(?!\1).)*)\1', String.Other),
+            (r'(%[QWx]([\W_]))((?:\\\2|(?!\2).)*)(\2)',
+             intp_string_callback),
+            # special forms of fancy strings after operators or
+            # in method calls with braces
+            (r'(?<=[-+/*%=<>&!^|~,(])(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)',
+             bygroups(Whitespace, String.Other, None)),
+            # and because of fixed width lookbehinds the whole thing a
+            # second time for line startings...
+            (r'^(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)',
+             bygroups(Whitespace, String.Other, None)),
+            # all regular fancy strings without qsw
+            (r'(%([^a-zA-Z0-9\s]))((?:\\\2|(?!\2).)*)(\2)',
+             intp_string_callback),
+        ]
+
+        return states
+
+    tokens = {
+        'root': [
+            (r'\A#!.+?$', Comment.Hashbang),
+            (r'#.*?$', Comment.Single),
+            (r'=begin\s.*?\n=end.*?$', Comment.Multiline),
+            # keywords
+            (words((
+                'BEGIN', 'END', 'alias', 'begin', 'break', 'case', 'defined?',
+                'do', 'else', 'elsif', 'end', 'ensure', 'for', 'if', 'in', 'next', 'redo',
+                'rescue', 'raise', 'retry', 'return', 'super', 'then', 'undef',
+                'unless', 'until', 'when', 'while', 'yield'), suffix=r'\b'),
+             Keyword),
+            # start of function, class and module names
+            (r'(module)(\s+)([a-zA-Z_]\w*'
+             r'(?:::[a-zA-Z_]\w*)*)',
+             bygroups(Keyword, Whitespace, Name.Namespace)),
+            (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'),
+            (r'def(?=[*%&^`~+-/\[<>=])', Keyword, 'funcname'),
+            (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
+            # special methods
+            (words((
+                'initialize', 'new', 'loop', 'include', 'extend', 'raise', 'attr_reader',
+                'attr_writer', 'attr_accessor', 'attr', 'catch', 'throw', 'private',
+                'module_function', 'public', 'protected', 'true', 'false', 'nil'),
+                suffix=r'\b'),
+             Keyword.Pseudo),
+            (r'(not|and|or)\b', Operator.Word),
+            (words((
+                'autoload', 'block_given', 'const_defined', 'eql', 'equal', 'frozen', 'include',
+                'instance_of', 'is_a', 'iterator', 'kind_of', 'method_defined', 'nil',
+                'private_method_defined', 'protected_method_defined',
+                'public_method_defined', 'respond_to', 'tainted'), suffix=r'\?'),
+             Name.Builtin),
+            (r'(chomp|chop|exit|gsub|sub)!', Name.Builtin),
+            (words((
+                'Array', 'Float', 'Integer', 'String', '__id__', '__send__', 'abort',
+                'ancestors', 'at_exit', 'autoload', 'binding', 'callcc', 'caller',
+                'catch', 'chomp', 'chop', 'class_eval', 'class_variables',
+                'clone', 'const_defined?', 'const_get', 'const_missing', 'const_set',
+                'constants', 'display', 'dup', 'eval', 'exec', 'exit', 'extend', 'fail', 'fork',
+                'format', 'freeze', 'getc', 'gets', 'global_variables', 'gsub',
+                'hash', 'id', 'included_modules', 'inspect', 'instance_eval',
+                'instance_method', 'instance_methods',
+                'instance_variable_get', 'instance_variable_set', 'instance_variables',
+                'lambda', 'load', 'local_variables', 'loop',
+                'method', 'method_missing', 'methods', 'module_eval', 'name',
+                'object_id', 'open', 'p', 'print', 'printf', 'private_class_method',
+                'private_instance_methods',
+                'private_methods', 'proc', 'protected_instance_methods',
+                'protected_methods', 'public_class_method',
+                'public_instance_methods', 'public_methods',
+                'putc', 'puts', 'raise', 'rand', 'readline', 'readlines', 'require',
+                'scan', 'select', 'self', 'send', 'set_trace_func', 'singleton_methods', 'sleep',
+                'split', 'sprintf', 'srand', 'sub', 'syscall', 'system', 'taint',
+                'test', 'throw', 'to_a', 'to_s', 'trace_var', 'trap', 'untaint',
+                'untrace_var', 'warn'), prefix=r'(?~!:])|'
+             r'(?<=(?:\s|;)when\s)|'
+             r'(?<=(?:\s|;)or\s)|'
+             r'(?<=(?:\s|;)and\s)|'
+             r'(?<=\.index\s)|'
+             r'(?<=\.scan\s)|'
+             r'(?<=\.sub\s)|'
+             r'(?<=\.sub!\s)|'
+             r'(?<=\.gsub\s)|'
+             r'(?<=\.gsub!\s)|'
+             r'(?<=\.match\s)|'
+             r'(?<=(?:\s|;)if\s)|'
+             r'(?<=(?:\s|;)elsif\s)|'
+             r'(?<=^when\s)|'
+             r'(?<=^index\s)|'
+             r'(?<=^scan\s)|'
+             r'(?<=^sub\s)|'
+             r'(?<=^gsub\s)|'
+             r'(?<=^sub!\s)|'
+             r'(?<=^gsub!\s)|'
+             r'(?<=^match\s)|'
+             r'(?<=^if\s)|'
+             r'(?<=^elsif\s)'
+             r')(\s*)(/)', bygroups(Text, String.Regex), 'multiline-regex'),
+            # multiline regex (in method calls or subscripts)
+            (r'(?<=\(|,|\[)/', String.Regex, 'multiline-regex'),
+            # multiline regex (this time the funny no whitespace rule)
+            (r'(\s+)(/)(?![\s=])', bygroups(Whitespace, String.Regex),
+             'multiline-regex'),
+            # lex numbers and ignore following regular expressions which
+            # are division operators in fact (grrrr. i hate that. any
+            # better ideas?)
+            # since pygments 0.7 we also eat a "?" operator after numbers
+            # so that the char operator does not work. Chars are not allowed
+            # there so that you can use the ternary operator.
+            # stupid example:
+            #   x>=0?n[x]:""
+            (r'(0_?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?',
+             bygroups(Number.Oct, Whitespace, Operator)),
+            (r'(0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?',
+             bygroups(Number.Hex, Whitespace, Operator)),
+            (r'(0b[01]+(?:_[01]+)*)(\s*)([/?])?',
+             bygroups(Number.Bin, Whitespace, Operator)),
+            (r'([\d]+(?:_\d+)*)(\s*)([/?])?',
+             bygroups(Number.Integer, Whitespace, Operator)),
+            # Names
+            (r'@@[a-zA-Z_]\w*', Name.Variable.Class),
+            (r'@[a-zA-Z_]\w*', Name.Variable.Instance),
+            (r'\$\w+', Name.Variable.Global),
+            (r'\$[!@&`\'+~=/\\,;.<>_*$?:"^-]', Name.Variable.Global),
+            (r'\$-[0adFiIlpvw]', Name.Variable.Global),
+            (r'::', Operator),
+            include('strings'),
+            # chars
+            (r'\?(\\[MC]-)*'  # modifiers
+             r'(\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})|\S)'
+             r'(?!\w)',
+             String.Char),
+            (r'[A-Z]\w+', Name.Constant),
+            # this is needed because ruby attributes can look
+            # like keywords (class) or like this: ` ?!?
+            (words(RUBY_OPERATORS, prefix=r'(\.|::)'),
+             bygroups(Operator, Name.Operator)),
+            (r'(\.|::)([a-zA-Z_]\w*[!?]?|[*%&^`~+\-/\[<>=])',
+             bygroups(Operator, Name)),
+            (r'[a-zA-Z_]\w*[!?]?', Name),
+            (r'(\[|\]|\*\*|<>?|>=|<=|<=>|=~|={3}|'
+             r'!~|&&?|\|\||\.{1,3})', Operator),
+            (r'[-+/*%=<>&!^|~]=?', Operator),
+            (r'[(){};,/?:\\]', Punctuation),
+            (r'\s+', Whitespace)
+        ],
+        'funcname': [
+            (r'\(', Punctuation, 'defexpr'),
+            (r'(?:([a-zA-Z_]\w*)(\.))?'  # optional scope name, like "self."
+             r'('
+                r'[a-zA-Z\u0080-\uffff][a-zA-Z0-9_\u0080-\uffff]*[!?=]?'  # method name
+                r'|!=|!~|=~|\*\*?|[-+!~]@?|[/%&|^]|<=>|<[<=]?|>[>=]?|===?'  # or operator override
+                r'|\[\]=?'  # or element reference/assignment override
+                r'|`'  # or the undocumented backtick override
+             r')',
+             bygroups(Name.Class, Operator, Name.Function), '#pop'),
+            default('#pop')
+        ],
+        'classname': [
+            (r'\(', Punctuation, 'defexpr'),
+            (r'<<', Operator, '#pop'),
+            (r'[A-Z_]\w*', Name.Class, '#pop'),
+            default('#pop')
+        ],
+        'defexpr': [
+            (r'(\))(\.|::)?', bygroups(Punctuation, Operator), '#pop'),
+            (r'\(', Operator, '#push'),
+            include('root')
+        ],
+        'in-intp': [
+            (r'\{', String.Interpol, '#push'),
+            (r'\}', String.Interpol, '#pop'),
+            include('root'),
+        ],
+        'string-intp': [
+            (r'#\{', String.Interpol, 'in-intp'),
+            (r'#@@?[a-zA-Z_]\w*', String.Interpol),
+            (r'#\$[a-zA-Z_]\w*', String.Interpol)
+        ],
+        'string-intp-escaped': [
+            include('string-intp'),
+            (r'\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})',
+             String.Escape)
+        ],
+        'interpolated-regex': [
+            include('string-intp'),
+            (r'[\\#]', String.Regex),
+            (r'[^\\#]+', String.Regex),
+        ],
+        'interpolated-string': [
+            include('string-intp'),
+            (r'[\\#]', String.Other),
+            (r'[^\\#]+', String.Other),
+        ],
+        'multiline-regex': [
+            include('string-intp'),
+            (r'\\\\', String.Regex),
+            (r'\\/', String.Regex),
+            (r'[\\#]', String.Regex),
+            (r'[^\\/#]+', String.Regex),
+            (r'/[mixounse]*', String.Regex, '#pop'),
+        ],
+        'end-part': [
+            (r'.+', Comment.Preproc, '#pop')
+        ]
+    }
+    tokens.update(gen_rubystrings_rules())
+
+    def analyse_text(text):
+        return shebang_matches(text, r'ruby(1\.\d)?')
+
+
+class RubyConsoleLexer(Lexer):
+    """
+    For Ruby interactive console (**irb**) output.
+    """
+    name = 'Ruby irb session'
+    aliases = ['rbcon', 'irb']
+    mimetypes = ['text/x-ruby-shellsession']
+    url = 'https://www.ruby-lang.org'
+    version_added = ''
+    _example = 'rbcon/console'
+
+    _prompt_re = re.compile(r'irb\([a-zA-Z_]\w*\):\d{3}:\d+[>*"\'] '
+                            r'|>> |\?> ')
+
+    def get_tokens_unprocessed(self, text):
+        rblexer = RubyLexer(**self.options)
+
+        curcode = ''
+        insertions = []
+        for match in line_re.finditer(text):
+            line = match.group()
+            m = self._prompt_re.match(line)
+            if m is not None:
+                end = m.end()
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, line[:end])]))
+                curcode += line[end:]
+            else:
+                if curcode:
+                    yield from do_insertions(
+                        insertions, rblexer.get_tokens_unprocessed(curcode))
+                    curcode = ''
+                    insertions = []
+                yield match.start(), Generic.Output, line
+        if curcode:
+            yield from do_insertions(
+                insertions, rblexer.get_tokens_unprocessed(curcode))
+
+
+class FancyLexer(RegexLexer):
+    """
+    Pygments Lexer For Fancy.
+
+    Fancy is a self-hosted, pure object-oriented, dynamic,
+    class-based, concurrent general-purpose programming language
+    running on Rubinius, the Ruby VM.
+    """
+    name = 'Fancy'
+    url = 'https://github.com/bakkdoor/fancy'
+    filenames = ['*.fy', '*.fancypack']
+    aliases = ['fancy', 'fy']
+    mimetypes = ['text/x-fancysrc']
+    version_added = '1.5'
+
+    tokens = {
+        # copied from PerlLexer:
+        'balanced-regex': [
+            (r'/(\\\\|\\[^\\]|[^/\\])*/[egimosx]*', String.Regex, '#pop'),
+            (r'!(\\\\|\\[^\\]|[^!\\])*![egimosx]*', String.Regex, '#pop'),
+            (r'\\(\\\\|[^\\])*\\[egimosx]*', String.Regex, '#pop'),
+            (r'\{(\\\\|\\[^\\]|[^}\\])*\}[egimosx]*', String.Regex, '#pop'),
+            (r'<(\\\\|\\[^\\]|[^>\\])*>[egimosx]*', String.Regex, '#pop'),
+            (r'\[(\\\\|\\[^\\]|[^\]\\])*\][egimosx]*', String.Regex, '#pop'),
+            (r'\((\\\\|\\[^\\]|[^)\\])*\)[egimosx]*', String.Regex, '#pop'),
+            (r'@(\\\\|\\[^\\]|[^@\\])*@[egimosx]*', String.Regex, '#pop'),
+            (r'%(\\\\|\\[^\\]|[^%\\])*%[egimosx]*', String.Regex, '#pop'),
+            (r'\$(\\\\|\\[^\\]|[^$\\])*\$[egimosx]*', String.Regex, '#pop'),
+        ],
+        'root': [
+            (r'\s+', Whitespace),
+
+            # balanced delimiters (copied from PerlLexer):
+            (r's\{(\\\\|\\[^\\]|[^}\\])*\}\s*', String.Regex, 'balanced-regex'),
+            (r's<(\\\\|\\[^\\]|[^>\\])*>\s*', String.Regex, 'balanced-regex'),
+            (r's\[(\\\\|\\[^\\]|[^\]\\])*\]\s*', String.Regex, 'balanced-regex'),
+            (r's\((\\\\|\\[^\\]|[^)\\])*\)\s*', String.Regex, 'balanced-regex'),
+            (r'm?/(\\\\|\\[^\\]|[^///\n])*/[gcimosx]*', String.Regex),
+            (r'm(?=[/!\\{<\[(@%$])', String.Regex, 'balanced-regex'),
+
+            # Comments
+            (r'#(.*?)\n', Comment.Single),
+            # Symbols
+            (r'\'([^\'\s\[\](){}]+|\[\])', String.Symbol),
+            # Multi-line DoubleQuotedString
+            (r'"""(\\\\|\\[^\\]|[^\\])*?"""', String),
+            # DoubleQuotedString
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
+            # keywords
+            (r'(def|class|try|catch|finally|retry|return|return_local|match|'
+             r'case|->|=>)\b', Keyword),
+            # constants
+            (r'(self|super|nil|false|true)\b', Name.Constant),
+            (r'[(){};,/?|:\\]', Punctuation),
+            # names
+            (words((
+                'Object', 'Array', 'Hash', 'Directory', 'File', 'Class', 'String',
+                'Number', 'Enumerable', 'FancyEnumerable', 'Block', 'TrueClass',
+                'NilClass', 'FalseClass', 'Tuple', 'Symbol', 'Stack', 'Set',
+                'FancySpec', 'Method', 'Package', 'Range'), suffix=r'\b'),
+             Name.Builtin),
+            # functions
+            (r'[a-zA-Z](\w|[-+?!=*/^><%])*:', Name.Function),
+            # operators, must be below functions
+            (r'[-+*/~,<>=&!?%^\[\].$]+', Operator),
+            (r'[A-Z]\w*', Name.Constant),
+            (r'@[a-zA-Z_]\w*', Name.Variable.Instance),
+            (r'@@[a-zA-Z_]\w*', Name.Variable.Class),
+            ('@@?', Operator),
+            (r'[a-zA-Z_]\w*', Name),
+            # numbers - / checks are necessary to avoid mismarking regexes,
+            # see comment in RubyLexer
+            (r'(0[oO]?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?',
+             bygroups(Number.Oct, Whitespace, Operator)),
+            (r'(0[xX][0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?',
+             bygroups(Number.Hex, Whitespace, Operator)),
+            (r'(0[bB][01]+(?:_[01]+)*)(\s*)([/?])?',
+             bygroups(Number.Bin, Whitespace, Operator)),
+            (r'([\d]+(?:_\d+)*)(\s*)([/?])?',
+             bygroups(Number.Integer, Whitespace, Operator)),
+            (r'\d+([eE][+-]?[0-9]+)|\d+\.\d+([eE][+-]?[0-9]+)?', Number.Float),
+            (r'\d+', Number.Integer)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/rust.py b/lib/python3.11/site-packages/pygments/lexers/rust.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c9e6217a4e88ca15012c5ea57181a8eaa37e0cf
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/rust.py
@@ -0,0 +1,222 @@
+"""
+    pygments.lexers.rust
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Rust language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, include, bygroups, words, default
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Whitespace
+
+__all__ = ['RustLexer']
+
+
+class RustLexer(RegexLexer):
+    """
+    Lexer for the Rust programming language (version 1.47).
+    """
+    name = 'Rust'
+    url = 'https://www.rust-lang.org/'
+    filenames = ['*.rs', '*.rs.in']
+    aliases = ['rust', 'rs']
+    mimetypes = ['text/rust', 'text/x-rust']
+    version_added = '1.6'
+
+    keyword_types = (words((
+        'u8', 'u16', 'u32', 'u64', 'u128', 'i8', 'i16', 'i32', 'i64', 'i128',
+        'usize', 'isize', 'f32', 'f64', 'char', 'str', 'bool',
+    ), suffix=r'\b'), Keyword.Type)
+
+    builtin_funcs_types = (words((
+        'Copy', 'Send', 'Sized', 'Sync', 'Unpin',
+        'Drop', 'Fn', 'FnMut', 'FnOnce', 'drop',
+        'Box', 'ToOwned', 'Clone',
+        'PartialEq', 'PartialOrd', 'Eq', 'Ord',
+        'AsRef', 'AsMut', 'Into', 'From', 'Default',
+        'Iterator', 'Extend', 'IntoIterator', 'DoubleEndedIterator',
+        'ExactSizeIterator',
+        'Option', 'Some', 'None',
+        'Result', 'Ok', 'Err',
+        'String', 'ToString', 'Vec',
+    ), suffix=r'\b'), Name.Builtin)
+
+    builtin_macros = (words((
+        'asm', 'assert', 'assert_eq', 'assert_ne', 'cfg', 'column',
+        'compile_error', 'concat', 'concat_idents', 'dbg', 'debug_assert',
+        'debug_assert_eq', 'debug_assert_ne', 'env', 'eprint', 'eprintln',
+        'file', 'format', 'format_args', 'format_args_nl', 'global_asm',
+        'include', 'include_bytes', 'include_str',
+        'is_aarch64_feature_detected',
+        'is_arm_feature_detected',
+        'is_mips64_feature_detected',
+        'is_mips_feature_detected',
+        'is_powerpc64_feature_detected',
+        'is_powerpc_feature_detected',
+        'is_x86_feature_detected',
+        'line', 'llvm_asm', 'log_syntax', 'macro_rules', 'matches',
+        'module_path', 'option_env', 'panic', 'print', 'println', 'stringify',
+        'thread_local', 'todo', 'trace_macros', 'unimplemented', 'unreachable',
+        'vec', 'write', 'writeln',
+    ), suffix=r'!'), Name.Function.Magic)
+
+    tokens = {
+        'root': [
+            # rust allows a file to start with a shebang, but if the first line
+            # starts with #![ then it's not a shebang but a crate attribute.
+            (r'#![^[\r\n].*$', Comment.Preproc),
+            default('base'),
+        ],
+        'base': [
+            # Whitespace and Comments
+            (r'\n', Whitespace),
+            (r'\s+', Whitespace),
+            (r'//!.*?\n', String.Doc),
+            (r'///(\n|[^/].*?\n)', String.Doc),
+            (r'//(.*?)\n', Comment.Single),
+            (r'/\*\*(\n|[^/*])', String.Doc, 'doccomment'),
+            (r'/\*!', String.Doc, 'doccomment'),
+            (r'/\*', Comment.Multiline, 'comment'),
+
+            # Macro parameters
+            (r"""\$([a-zA-Z_]\w*|\(,?|\),?|,?)""", Comment.Preproc),
+            # Keywords
+            (words(('as', 'async', 'await', 'box', 'const', 'crate', 'dyn',
+                    'else', 'extern', 'for', 'if', 'impl', 'in', 'loop',
+                    'match', 'move', 'mut', 'pub', 'ref', 'return', 'static',
+                    'super', 'trait', 'unsafe', 'use', 'where', 'while'),
+                   suffix=r'\b'), Keyword),
+            (words(('abstract', 'become', 'do', 'final', 'macro', 'override',
+                    'priv', 'typeof', 'try', 'unsized', 'virtual', 'yield'),
+                   suffix=r'\b'), Keyword.Reserved),
+            (r'(true|false)\b', Keyword.Constant),
+            (r'self\b', Name.Builtin.Pseudo),
+            (r'mod\b', Keyword, 'modname'),
+            (r'let\b', Keyword.Declaration),
+            (r'fn\b', Keyword, 'funcname'),
+            (r'(struct|enum|type|union)\b', Keyword, 'typename'),
+            (r'(default)(\s+)(type|fn)\b', bygroups(Keyword, Whitespace, Keyword)),
+            keyword_types,
+            (r'[sS]elf\b', Name.Builtin.Pseudo),
+            # Prelude (taken from Rust's src/libstd/prelude.rs)
+            builtin_funcs_types,
+            builtin_macros,
+            # Path separators, so types don't catch them.
+            (r'::\b', Punctuation),
+            # Types in positions.
+            (r'(?::|->)', Punctuation, 'typename'),
+            # Labels
+            (r'(break|continue)(\b\s*)(\'[A-Za-z_]\w*)?',
+             bygroups(Keyword, Text.Whitespace, Name.Label)),
+
+            # Character literals
+            (r"""'(\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
+             r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
+             String.Char),
+            (r"""b'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\0"""
+             r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
+             String.Char),
+
+            # Binary literals
+            (r'0b[01_]+', Number.Bin, 'number_lit'),
+            # Octal literals
+            (r'0o[0-7_]+', Number.Oct, 'number_lit'),
+            # Hexadecimal literals
+            (r'0[xX][0-9a-fA-F_]+', Number.Hex, 'number_lit'),
+            # Decimal literals
+            (r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
+             r'\.[0-9_]*(?!\.)|[eE][+\-]?[0-9_]+)', Number.Float,
+             'number_lit'),
+            (r'[0-9][0-9_]*', Number.Integer, 'number_lit'),
+
+            # String literals
+            (r'b"', String, 'bytestring'),
+            (r'"', String, 'string'),
+            (r'(?s)b?r(#*)".*?"\1', String),
+
+            # Lifetime names
+            (r"'", Operator, 'lifetime'),
+
+            # Operators and Punctuation
+            (r'\.\.=?', Operator),
+            (r'[{}()\[\],.;]', Punctuation),
+            (r'[+\-*/%&|<>^!~@=:?]', Operator),
+
+            # Identifiers
+            (r'[a-zA-Z_]\w*', Name),
+            # Raw identifiers
+            (r'r#[a-zA-Z_]\w*', Name),
+
+            # Attributes
+            (r'#!?\[', Comment.Preproc, 'attribute['),
+
+            # Misc
+            # Lone hashes: not used in Rust syntax, but allowed in macro
+            # arguments, most famously for quote::quote!()
+            (r'#', Punctuation),
+        ],
+        'comment': [
+            (r'[^*/]+', Comment.Multiline),
+            (r'/\*', Comment.Multiline, '#push'),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'[*/]', Comment.Multiline),
+        ],
+        'doccomment': [
+            (r'[^*/]+', String.Doc),
+            (r'/\*', String.Doc, '#push'),
+            (r'\*/', String.Doc, '#pop'),
+            (r'[*/]', String.Doc),
+        ],
+        'modname': [
+            (r'\s+', Whitespace),
+            (r'[a-zA-Z_]\w*', Name.Namespace, '#pop'),
+            default('#pop'),
+        ],
+        'funcname': [
+            (r'\s+', Whitespace),
+            (r'[a-zA-Z_]\w*', Name.Function, '#pop'),
+            default('#pop'),
+        ],
+        'typename': [
+            (r'\s+', Whitespace),
+            (r'&', Keyword.Pseudo),
+            (r"'", Operator, 'lifetime'),
+            builtin_funcs_types,
+            keyword_types,
+            (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
+            default('#pop'),
+        ],
+        'lifetime': [
+            (r"(static|_)", Name.Builtin),
+            (r"[a-zA-Z_]+\w*", Name.Attribute),
+            default('#pop'),
+        ],
+        'number_lit': [
+            (r'[ui](8|16|32|64|size)', Keyword, '#pop'),
+            (r'f(32|64)', Keyword, '#pop'),
+            default('#pop'),
+        ],
+        'string': [
+            (r'"', String, '#pop'),
+            (r"""\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
+             r"""|\\u\{[0-9a-fA-F]{1,6}\}""", String.Escape),
+            (r'[^\\"]+', String),
+            (r'\\', String),
+        ],
+        'bytestring': [
+            (r"""\\x[89a-fA-F][0-9a-fA-F]""", String.Escape),
+            include('string'),
+        ],
+        'attribute_common': [
+            (r'"', String, 'string'),
+            (r'\[', Comment.Preproc, 'attribute['),
+        ],
+        'attribute[': [
+            include('attribute_common'),
+            (r'\]', Comment.Preproc, '#pop'),
+            (r'[^"\]\[]+', Comment.Preproc),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/sas.py b/lib/python3.11/site-packages/pygments/lexers/sas.py
new file mode 100644
index 0000000000000000000000000000000000000000..35ee8541a9c8817f4050957bc62238a94f938e38
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/sas.py
@@ -0,0 +1,227 @@
+"""
+    pygments.lexers.sas
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexer for SAS.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+from pygments.lexer import RegexLexer, include, words
+from pygments.token import Comment, Keyword, Name, Number, String, Text, \
+    Other, Generic
+
+__all__ = ['SASLexer']
+
+
+class SASLexer(RegexLexer):
+    """
+    For SAS files.
+    """
+    # Syntax from syntax/sas.vim by James Kidd 
+
+    name      = 'SAS'
+    aliases   = ['sas']
+    filenames = ['*.SAS', '*.sas']
+    mimetypes = ['text/x-sas', 'text/sas', 'application/x-sas']
+    url = 'https://en.wikipedia.org/wiki/SAS_(software)'
+    version_added = '2.2'
+    flags     = re.IGNORECASE | re.MULTILINE
+
+    builtins_macros = (
+        "bquote", "nrbquote", "cmpres", "qcmpres", "compstor", "datatyp",
+        "display", "do", "else", "end", "eval", "global", "goto", "if",
+        "index", "input", "keydef", "label", "left", "length", "let",
+        "local", "lowcase", "macro", "mend", "nrquote",
+        "nrstr", "put", "qleft", "qlowcase", "qscan",
+        "qsubstr", "qsysfunc", "qtrim", "quote", "qupcase", "scan",
+        "str", "substr", "superq", "syscall", "sysevalf", "sysexec",
+        "sysfunc", "sysget", "syslput", "sysprod", "sysrc", "sysrput",
+        "then", "to", "trim", "unquote", "until", "upcase", "verify",
+        "while", "window"
+    )
+
+    builtins_conditionals = (
+        "do", "if", "then", "else", "end", "until", "while"
+    )
+
+    builtins_statements = (
+        "abort", "array", "attrib", "by", "call", "cards", "cards4",
+        "catname", "continue", "datalines", "datalines4", "delete", "delim",
+        "delimiter", "display", "dm", "drop", "endsas", "error", "file",
+        "filename", "footnote", "format", "goto", "in", "infile", "informat",
+        "input", "keep", "label", "leave", "length", "libname", "link",
+        "list", "lostcard", "merge", "missing", "modify", "options", "output",
+        "out", "page", "put", "redirect", "remove", "rename", "replace",
+        "retain", "return", "select", "set", "skip", "startsas", "stop",
+        "title", "update", "waitsas", "where", "window", "x", "systask"
+    )
+
+    builtins_sql = (
+        "add", "and", "alter", "as", "cascade", "check", "create",
+        "delete", "describe", "distinct", "drop", "foreign", "from",
+        "group", "having", "index", "insert", "into", "in", "key", "like",
+        "message", "modify", "msgtype", "not", "null", "on", "or",
+        "order", "primary", "references", "reset", "restrict", "select",
+        "set", "table", "unique", "update", "validate", "view", "where"
+    )
+
+    builtins_functions = (
+        "abs", "addr", "airy", "arcos", "arsin", "atan", "attrc",
+        "attrn", "band", "betainv", "blshift", "bnot", "bor",
+        "brshift", "bxor", "byte", "cdf", "ceil", "cexist", "cinv",
+        "close", "cnonct", "collate", "compbl", "compound",
+        "compress", "cos", "cosh", "css", "curobs", "cv", "daccdb",
+        "daccdbsl", "daccsl", "daccsyd", "dacctab", "dairy", "date",
+        "datejul", "datepart", "datetime", "day", "dclose", "depdb",
+        "depdbsl", "depsl", "depsyd",
+        "deptab", "dequote", "dhms", "dif", "digamma",
+        "dim", "dinfo", "dnum", "dopen", "doptname", "doptnum",
+        "dread", "dropnote", "dsname", "erf", "erfc", "exist", "exp",
+        "fappend", "fclose", "fcol", "fdelete", "fetch", "fetchobs",
+        "fexist", "fget", "fileexist", "filename", "fileref",
+        "finfo", "finv", "fipname", "fipnamel", "fipstate", "floor",
+        "fnonct", "fnote", "fopen", "foptname", "foptnum", "fpoint",
+        "fpos", "fput", "fread", "frewind", "frlen", "fsep", "fuzz",
+        "fwrite", "gaminv", "gamma", "getoption", "getvarc", "getvarn",
+        "hbound", "hms", "hosthelp", "hour", "ibessel", "index",
+        "indexc", "indexw", "input", "inputc", "inputn", "int",
+        "intck", "intnx", "intrr", "irr", "jbessel", "juldate",
+        "kurtosis", "lag", "lbound", "left", "length", "lgamma",
+        "libname", "libref", "log", "log10", "log2", "logpdf", "logpmf",
+        "logsdf", "lowcase", "max", "mdy", "mean", "min", "minute",
+        "mod", "month", "mopen", "mort", "n", "netpv", "nmiss",
+        "normal", "note", "npv", "open", "ordinal", "pathname",
+        "pdf", "peek", "peekc", "pmf", "point", "poisson", "poke",
+        "probbeta", "probbnml", "probchi", "probf", "probgam",
+        "probhypr", "probit", "probnegb", "probnorm", "probt",
+        "put", "putc", "putn", "qtr", "quote", "ranbin", "rancau",
+        "ranexp", "rangam", "range", "rank", "rannor", "ranpoi",
+        "rantbl", "rantri", "ranuni", "repeat", "resolve", "reverse",
+        "rewind", "right", "round", "saving", "scan", "sdf", "second",
+        "sign", "sin", "sinh", "skewness", "soundex", "spedis",
+        "sqrt", "std", "stderr", "stfips", "stname", "stnamel",
+        "substr", "sum", "symget", "sysget", "sysmsg", "sysprod",
+        "sysrc", "system", "tan", "tanh", "time", "timepart", "tinv",
+        "tnonct", "today", "translate", "tranwrd", "trigamma",
+        "trim", "trimn", "trunc", "uniform", "upcase", "uss", "var",
+        "varfmt", "varinfmt", "varlabel", "varlen", "varname",
+        "varnum", "varray", "varrayx", "vartype", "verify", "vformat",
+        "vformatd", "vformatdx", "vformatn", "vformatnx", "vformatw",
+        "vformatwx", "vformatx", "vinarray", "vinarrayx", "vinformat",
+        "vinformatd", "vinformatdx", "vinformatn", "vinformatnx",
+        "vinformatw", "vinformatwx", "vinformatx", "vlabel",
+        "vlabelx", "vlength", "vlengthx", "vname", "vnamex", "vtype",
+        "vtypex", "weekday", "year", "yyq", "zipfips", "zipname",
+        "zipnamel", "zipstate"
+    )
+
+    tokens = {
+        'root': [
+            include('comments'),
+            include('proc-data'),
+            include('cards-datalines'),
+            include('logs'),
+            include('general'),
+            (r'.', Text),
+        ],
+        # SAS is multi-line regardless, but * is ended by ;
+        'comments': [
+            (r'^\s*\*.*?;', Comment),
+            (r'/\*.*?\*/', Comment),
+            (r'^\s*\*(.|\n)*?;', Comment.Multiline),
+            (r'/[*](.|\n)*?[*]/', Comment.Multiline),
+        ],
+        # Special highlight for proc, data, quit, run
+        'proc-data': [
+            (r'(^|;)\s*(proc \w+|data|run|quit)[\s;]',
+             Keyword.Reserved),
+        ],
+        # Special highlight cards and datalines
+        'cards-datalines': [
+            (r'^\s*(datalines|cards)\s*;\s*$', Keyword, 'data'),
+        ],
+        'data': [
+            (r'(.|\n)*^\s*;\s*$', Other, '#pop'),
+        ],
+        # Special highlight for put NOTE|ERROR|WARNING (order matters)
+        'logs': [
+            (r'\n?^\s*%?put ', Keyword, 'log-messages'),
+        ],
+        'log-messages': [
+            (r'NOTE(:|-).*', Generic, '#pop'),
+            (r'WARNING(:|-).*', Generic.Emph, '#pop'),
+            (r'ERROR(:|-).*', Generic.Error, '#pop'),
+            include('general'),
+        ],
+        'general': [
+            include('keywords'),
+            include('vars-strings'),
+            include('special'),
+            include('numbers'),
+        ],
+        # Keywords, statements, functions, macros
+        'keywords': [
+            (words(builtins_statements,
+                   prefix = r'\b',
+                   suffix = r'\b'),
+             Keyword),
+            (words(builtins_sql,
+                   prefix = r'\b',
+                   suffix = r'\b'),
+             Keyword),
+            (words(builtins_conditionals,
+                   prefix = r'\b',
+                   suffix = r'\b'),
+             Keyword),
+            (words(builtins_macros,
+                   prefix = r'%',
+                   suffix = r'\b'),
+             Name.Builtin),
+            (words(builtins_functions,
+                   prefix = r'\b',
+                   suffix = r'\('),
+             Name.Builtin),
+        ],
+        # Strings and user-defined variables and macros (order matters)
+        'vars-strings': [
+            (r'&[a-z_]\w{0,31}\.?', Name.Variable),
+            (r'%[a-z_]\w{0,31}', Name.Function),
+            (r'\'', String, 'string_squote'),
+            (r'"', String, 'string_dquote'),
+        ],
+        'string_squote': [
+            ('\'', String, '#pop'),
+            (r'\\\\|\\"|\\\n', String.Escape),
+            # AFAIK, macro variables are not evaluated in single quotes
+            # (r'&', Name.Variable, 'validvar'),
+            (r'[^$\'\\]+', String),
+            (r'[$\'\\]', String),
+        ],
+        'string_dquote': [
+            (r'"', String, '#pop'),
+            (r'\\\\|\\"|\\\n', String.Escape),
+            (r'&', Name.Variable, 'validvar'),
+            (r'[^$&"\\]+', String),
+            (r'[$"\\]', String),
+        ],
+        'validvar': [
+            (r'[a-z_]\w{0,31}\.?', Name.Variable, '#pop'),
+        ],
+        # SAS numbers and special variables
+        'numbers': [
+            (r'\b[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)(E[+-]?[0-9]+)?i?\b',
+             Number),
+        ],
+        'special': [
+            (r'(null|missing|_all_|_automatic_|_character_|_n_|'
+             r'_infile_|_name_|_null_|_numeric_|_user_|_webout_)',
+             Keyword.Constant),
+        ],
+        # 'operators': [
+        #     (r'(-|=|<=|>=|<|>|<>|&|!=|'
+        #      r'\||\*|\+|\^|/|!|~|~=)', Operator)
+        # ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/savi.py b/lib/python3.11/site-packages/pygments/lexers/savi.py
new file mode 100644
index 0000000000000000000000000000000000000000..548a05665fb166f2e3bbd400a3a09630b709eb4e
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/savi.py
@@ -0,0 +1,171 @@
+"""
+    pygments.lexers.savi
+    ~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Savi.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, include
+from pygments.token import Whitespace, Keyword, Name, String, Number, \
+  Operator, Punctuation, Comment, Generic, Error
+
+__all__ = ['SaviLexer']
+
+
+# The canonical version of this file can be found in the following repository,
+# where it is kept in sync with any language changes, as well as the other
+# pygments-like lexers that are maintained for use with other tools:
+# - https://github.com/savi-lang/savi/blob/main/tooling/pygments/lexers/savi.py
+#
+# If you're changing this file in the pygments repository, please ensure that
+# any changes you make are also propagated to the official Savi repository,
+# in order to avoid accidental clobbering of your changes later when an update
+# from the Savi repository flows forward into the pygments repository.
+#
+# If you're changing this file in the Savi repository, please ensure that
+# any changes you make are also reflected in the other pygments-like lexers
+# (rouge, vscode, etc) so that all of the lexers can be kept cleanly in sync.
+
+class SaviLexer(RegexLexer):
+    """
+    For Savi source code.
+
+    .. versionadded: 2.10
+    """
+
+    name = 'Savi'
+    url = 'https://github.com/savi-lang/savi'
+    aliases = ['savi']
+    filenames = ['*.savi']
+    version_added = ''
+
+    tokens = {
+      "root": [
+        # Line Comment
+        (r'//.*?$', Comment.Single),
+
+        # Doc Comment
+        (r'::.*?$', Comment.Single),
+
+        # Capability Operator
+        (r'(\')(\w+)(?=[^\'])', bygroups(Operator, Name)),
+
+        # Double-Quote String
+        (r'\w?"', String.Double, "string.double"),
+
+        # Single-Char String
+        (r"'", String.Char, "string.char"),
+
+        # Type Name
+        (r'(_?[A-Z]\w*)', Name.Class),
+
+        # Nested Type Name
+        (r'(\.)(\s*)(_?[A-Z]\w*)', bygroups(Punctuation, Whitespace, Name.Class)),
+
+        # Declare
+        (r'^([ \t]*)(:\w+)',
+          bygroups(Whitespace, Name.Tag),
+          "decl"),
+
+        # Error-Raising Calls/Names
+        (r'((\w+|\+|\-|\*)\!)', Generic.Deleted),
+
+        # Numeric Values
+        (r'\b\d([\d_]*(\.[\d_]+)?)\b', Number),
+
+        # Hex Numeric Values
+        (r'\b0x([0-9a-fA-F_]+)\b', Number.Hex),
+
+        # Binary Numeric Values
+        (r'\b0b([01_]+)\b', Number.Bin),
+
+        # Function Call (with braces)
+        (r'\w+(?=\()', Name.Function),
+
+        # Function Call (with receiver)
+        (r'(\.)(\s*)(\w+)', bygroups(Punctuation, Whitespace, Name.Function)),
+
+        # Function Call (with self receiver)
+        (r'(@)(\w+)', bygroups(Punctuation, Name.Function)),
+
+        # Parenthesis
+        (r'\(', Punctuation, "root"),
+        (r'\)', Punctuation, "#pop"),
+
+        # Brace
+        (r'\{', Punctuation, "root"),
+        (r'\}', Punctuation, "#pop"),
+
+        # Bracket
+        (r'\[', Punctuation, "root"),
+        (r'(\])(\!)', bygroups(Punctuation, Generic.Deleted), "#pop"),
+        (r'\]', Punctuation, "#pop"),
+
+        # Punctuation
+        (r'[,;:\.@]', Punctuation),
+
+        # Piping Operators
+        (r'(\|\>)', Operator),
+
+        # Branching Operators
+        (r'(\&\&|\|\||\?\?|\&\?|\|\?|\.\?)', Operator),
+
+        # Comparison Operators
+        (r'(\<\=\>|\=\~|\=\=|\<\=|\>\=|\<|\>)', Operator),
+
+        # Arithmetic Operators
+        (r'(\+|\-|\/|\*|\%)', Operator),
+
+        # Assignment Operators
+        (r'(\=)', Operator),
+
+        # Other Operators
+        (r'(\!|\<\<|\<|\&|\|)', Operator),
+
+        # Identifiers
+        (r'\b\w+\b', Name),
+
+        # Whitespace
+        (r'[ \t\r]+\n*|\n+', Whitespace),
+      ],
+
+      # Declare (nested rules)
+      "decl": [
+        (r'\b[a-z_]\w*\b(?!\!)', Keyword.Declaration),
+        (r':', Punctuation, "#pop"),
+        (r'\n', Whitespace, "#pop"),
+        include("root"),
+      ],
+
+      # Double-Quote String (nested rules)
+      "string.double": [
+        (r'\\\(', String.Interpol, "string.interpolation"),
+        (r'\\u[0-9a-fA-F]{4}', String.Escape),
+        (r'\\x[0-9a-fA-F]{2}', String.Escape),
+        (r'\\[bfnrt\\\']', String.Escape),
+        (r'\\"', String.Escape),
+        (r'"', String.Double, "#pop"),
+        (r'[^\\"]+', String.Double),
+        (r'.', Error),
+      ],
+
+      # Single-Char String (nested rules)
+      "string.char": [
+        (r'\\u[0-9a-fA-F]{4}', String.Escape),
+        (r'\\x[0-9a-fA-F]{2}', String.Escape),
+        (r'\\[bfnrt\\\']', String.Escape),
+        (r"\\'", String.Escape),
+        (r"'", String.Char, "#pop"),
+        (r"[^\\']+", String.Char),
+        (r'.', Error),
+      ],
+
+      # Interpolation inside String (nested rules)
+      "string.interpolation": [
+        (r"\)", String.Interpol, "#pop"),
+        include("root"),
+      ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/scdoc.py b/lib/python3.11/site-packages/pygments/lexers/scdoc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b2e01da1f8443a0f7ddf8952531fb94f1e35e2e
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/scdoc.py
@@ -0,0 +1,85 @@
+"""
+    pygments.lexers.scdoc
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for scdoc, a simple man page generator.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, bygroups, using, this
+from pygments.token import Text, Comment, Keyword, String, Generic
+
+__all__ = ['ScdocLexer']
+
+
+class ScdocLexer(RegexLexer):
+    """
+    `scdoc` is a simple man page generator for POSIX systems written in C99.
+    """
+    name = 'scdoc'
+    url = 'https://git.sr.ht/~sircmpwn/scdoc'
+    aliases = ['scdoc', 'scd']
+    filenames = ['*.scd', '*.scdoc']
+    version_added = '2.5'
+    flags = re.MULTILINE
+
+    tokens = {
+        'root': [
+            # comment
+            (r'^(;.+\n)', bygroups(Comment)),
+
+            # heading with pound prefix
+            (r'^(#)([^#].+\n)', bygroups(Generic.Heading, Text)),
+            (r'^(#{2})(.+\n)', bygroups(Generic.Subheading, Text)),
+            # bulleted lists
+            (r'^(\s*)([*-])(\s)(.+\n)',
+            bygroups(Text, Keyword, Text, using(this, state='inline'))),
+            # numbered lists
+            (r'^(\s*)(\.+\.)( .+\n)',
+            bygroups(Text, Keyword, using(this, state='inline'))),
+            # quote
+            (r'^(\s*>\s)(.+\n)', bygroups(Keyword, Generic.Emph)),
+            # text block
+            (r'^(```\n)([\w\W]*?)(^```$)', bygroups(String, Text, String)),
+
+            include('inline'),
+        ],
+        'inline': [
+            # escape
+            (r'\\.', Text),
+            # underlines
+            (r'(\s)(_[^_]+_)(\W|\n)', bygroups(Text, Generic.Emph, Text)),
+            # bold
+            (r'(\s)(\*[^*]+\*)(\W|\n)', bygroups(Text, Generic.Strong, Text)),
+            # inline code
+            (r'`[^`]+`', String.Backtick),
+
+            # general text, must come last!
+            (r'[^\\\s]+', Text),
+            (r'.', Text),
+        ],
+    }
+
+    def analyse_text(text):
+        """We checks for bold and underline text with * and _. Also
+        every scdoc file must start with a strictly defined first line."""
+        result = 0
+
+        if '*' in text:
+            result += 0.01
+
+        if '_' in text:
+            result += 0.01
+
+        # name(section) ["left_footer" ["center_header"]]
+        first_line = text.partition('\n')[0]
+        scdoc_preamble_pattern = r'^.*\([1-7]\)( "[^"]+"){0,2}$'
+
+        if re.search(scdoc_preamble_pattern, first_line):
+            result += 0.5
+
+        return result
diff --git a/lib/python3.11/site-packages/pygments/lexers/scripting.py b/lib/python3.11/site-packages/pygments/lexers/scripting.py
new file mode 100644
index 0000000000000000000000000000000000000000..2adb7bbd0194cd2482a6c2d99d573a8486084bf8
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/scripting.py
@@ -0,0 +1,1638 @@
+"""
+    pygments.lexers.scripting
+    ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for scripting and embedded languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import RegexLexer, include, bygroups, default, combined, \
+    words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Error, Whitespace, Other
+from pygments.util import get_bool_opt, get_list_opt
+
+__all__ = ['LuaLexer', 'LuauLexer', 'MoonScriptLexer', 'ChaiscriptLexer', 'LSLLexer',
+           'AppleScriptLexer', 'RexxLexer', 'MOOCodeLexer', 'HybrisLexer',
+           'EasytrieveLexer', 'JclLexer', 'MiniScriptLexer']
+
+
+def all_lua_builtins():
+    from pygments.lexers._lua_builtins import MODULES
+    return [w for values in MODULES.values() for w in values]
+
+class LuaLexer(RegexLexer):
+    """
+    For Lua source code.
+
+    Additional options accepted:
+
+    `func_name_highlighting`
+        If given and ``True``, highlight builtin function names
+        (default: ``True``).
+    `disabled_modules`
+        If given, must be a list of module names whose function names
+        should not be highlighted. By default all modules are highlighted.
+
+        To get a list of allowed modules have a look into the
+        `_lua_builtins` module:
+
+        .. sourcecode:: pycon
+
+            >>> from pygments.lexers._lua_builtins import MODULES
+            >>> MODULES.keys()
+            ['string', 'coroutine', 'modules', 'io', 'basic', ...]
+    """
+
+    name = 'Lua'
+    url = 'https://www.lua.org/'
+    aliases = ['lua']
+    filenames = ['*.lua', '*.wlua']
+    mimetypes = ['text/x-lua', 'application/x-lua']
+    version_added = ''
+
+    _comment_multiline = r'(?:--\[(?P=*)\[[\w\W]*?\](?P=level)\])'
+    _comment_single = r'(?:--.*$)'
+    _space = r'(?:\s+(?!\s))'
+    _s = rf'(?:{_comment_multiline}|{_comment_single}|{_space})'
+    # A lookahead-safe version of _s that avoids catastrophic backtracking.
+    # The _comment_multiline pattern contains [\w\W]*? which, when used
+    # inside a lookahead with a * quantifier, causes exponential blowup.
+    # This version skips only whitespace; comments between an identifier
+    # and a following [.:] or ( are rare enough to sacrifice.
+    _s_la = r'\s'
+    _name = r'(?:[^\W\d]\w*)'
+
+    tokens = {
+        'root': [
+            # Lua allows a file to start with a shebang.
+            (r'#!.*', Comment.Preproc),
+            default('base'),
+        ],
+        'ws': [
+            (_comment_multiline, Comment.Multiline),
+            (_comment_single, Comment.Single),
+            (_space, Whitespace),
+        ],
+        'base': [
+            include('ws'),
+
+            (r'(?i)0x[\da-f]*(\.[\da-f]*)?(p[+-]?\d+)?', Number.Hex),
+            (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
+            (r'(?i)\d+e[+-]?\d+', Number.Float),
+            (r'\d+', Number.Integer),
+
+            # multiline strings
+            (r'(?s)\[(=*)\[.*?\]\1\]', String),
+
+            (r'::', Punctuation, 'label'),
+            (r'\.{3}', Punctuation),
+            (r'[=<>|~&+\-*/%#^]+|\.\.', Operator),
+            (r'[\[\]{}().,:;]+', Punctuation),
+            (r'(and|or|not)\b', Operator.Word),
+
+            (words([
+                'break', 'do', 'else', 'elseif', 'end', 'for', 'if', 'in',
+                'repeat', 'return', 'then', 'until', 'while'
+            ], suffix=r'\b'), Keyword.Reserved),
+            (r'goto\b', Keyword.Reserved, 'goto'),
+            (r'(local)\b', Keyword.Declaration),
+            (r'(true|false|nil)\b', Keyword.Constant),
+
+            (r'(function)\b', Keyword.Reserved, 'funcname'),
+
+            (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin),
+            (fr'[A-Za-z_]\w*(?={_s_la}*[.:])', Name.Variable, 'varname'),
+            (fr'[A-Za-z_]\w*(?={_s_la}*\()', Name.Function),
+            (r'[A-Za-z_]\w*', Name.Variable),
+
+            ("'", String.Single, combined('stringescape', 'sqs')),
+            ('"', String.Double, combined('stringescape', 'dqs'))
+        ],
+
+        'varname': [
+            include('ws'),
+            (r'\.\.', Operator, '#pop'),
+            (r'[.:]', Punctuation),
+            (rf'{_name}(?={_s_la}*[.:])', Name.Property),
+            (rf'{_name}(?={_s_la}*\()', Name.Function, '#pop'),
+            (_name, Name.Property, '#pop'),
+        ],
+
+        'funcname': [
+            include('ws'),
+            (r'[.:]', Punctuation),
+            (rf'{_name}(?={_s_la}*[.:])', Name.Class),
+            (_name, Name.Function, '#pop'),
+            # inline function
+            (r'\(', Punctuation, '#pop'),
+        ],
+
+        'goto': [
+            include('ws'),
+            (_name, Name.Label, '#pop'),
+        ],
+
+        'label': [
+            include('ws'),
+            (r'::', Punctuation, '#pop'),
+            (_name, Name.Label),
+        ],
+
+        'stringescape': [
+            (r'\\([abfnrtv\\"\']|[\r\n]{1,2}|z\s*|x[0-9a-fA-F]{2}|\d{1,3}|'
+             r'u\{[0-9a-fA-F]+\})', String.Escape),
+        ],
+
+        'sqs': [
+            (r"'", String.Single, '#pop'),
+            (r"[^\\']+", String.Single),
+        ],
+
+        'dqs': [
+            (r'"', String.Double, '#pop'),
+            (r'[^\\"]+', String.Double),
+        ]
+    }
+
+    def __init__(self, **options):
+        self.func_name_highlighting = get_bool_opt(
+            options, 'func_name_highlighting', True)
+        self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
+
+        self._functions = set()
+        if self.func_name_highlighting:
+            from pygments.lexers._lua_builtins import MODULES
+            for mod, func in MODULES.items():
+                if mod not in self.disabled_modules:
+                    self._functions.update(func)
+        RegexLexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        for index, token, value in \
+                RegexLexer.get_tokens_unprocessed(self, text):
+            if token is Name.Builtin and value not in self._functions:
+                if '.' in value:
+                    a, b = value.split('.')
+                    yield index, Name, a
+                    yield index + len(a), Punctuation, '.'
+                    yield index + len(a) + 1, Name, b
+                else:
+                    yield index, Name, value
+                continue
+            yield index, token, value
+
+def _luau_make_expression(should_pop, _s, _s_la):
+    temp_list = [
+        (r'0[xX][\da-fA-F_]*', Number.Hex, '#pop'),
+        (r'0[bB][\d_]*', Number.Bin, '#pop'),
+        (r'\.?\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?[\d_]+)?', Number.Float, '#pop'),
+
+        (words((
+            'true', 'false', 'nil'
+        ), suffix=r'\b'), Keyword.Constant, '#pop'),
+
+        (r'\[(=*)\[[.\n]*?\]\1\]', String, '#pop'),
+
+        (r'(\.)([a-zA-Z_]\w*)(?=%s*[({"\'])', bygroups(Punctuation, Name.Function), '#pop'),
+        (r'(\.)([a-zA-Z_]\w*)', bygroups(Punctuation, Name.Variable), '#pop'),
+
+        (rf'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*(?={_s_la}*[({{"\'])', Name.Other, '#pop'),
+        (r'[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*', Name, '#pop'),
+    ]
+    if should_pop:
+        return temp_list
+    return [entry[:2] for entry in temp_list]
+
+def _luau_make_expression_special(should_pop):
+    temp_list = [
+        (r'\{', Punctuation, ('#pop', 'closing_brace_base', 'expression')),
+        (r'\(', Punctuation, ('#pop', 'closing_parenthesis_base', 'expression')),
+
+        (r'::?', Punctuation, ('#pop', 'type_end', 'type_start')),
+
+        (r"'", String.Single, ('#pop', 'string_single')),
+        (r'"', String.Double, ('#pop', 'string_double')),
+        (r'`', String.Backtick, ('#pop', 'string_interpolated')),
+    ]
+    if should_pop:
+        return temp_list
+    return [(entry[0], entry[1], entry[2][1:]) for entry in temp_list]
+
+class LuauLexer(RegexLexer):
+    """
+    For Luau source code.
+
+    Additional options accepted:
+
+    `include_luau_builtins`
+        If given and ``True``, automatically highlight Luau builtins
+        (default: ``True``).
+    `include_roblox_builtins`
+        If given and ``True``, automatically highlight Roblox-specific builtins
+        (default: ``False``).
+    `additional_builtins`
+        If given, must be a list of additional builtins to highlight.
+    `disabled_builtins`
+        If given, must be a list of builtins that will not be highlighted.
+    """
+
+    name = 'Luau'
+    url = 'https://luau-lang.org/'
+    aliases = ['luau']
+    filenames = ['*.luau']
+    version_added = '2.18'
+
+    _comment_multiline = r'(?:--\[(?P=*)\[[\w\W]*?\](?P=level)\])'
+    _comment_single = r'(?:--.*$)'
+    _s = r'(?:{}|{}|{})'.format(_comment_multiline, _comment_single, r'\s+')
+    # Lookahead-safe version — avoids catastrophic backtracking from
+    # [\w\W]*? inside _comment_multiline when combined with * quantifier.
+    _s_la = r'\s'
+
+    tokens = {
+        'root': [
+            (r'#!.*', Comment.Hashbang, 'base'),
+            default('base'),
+        ],
+
+        'ws': [
+            (_comment_multiline, Comment.Multiline),
+            (_comment_single, Comment.Single),
+            (r'\s+', Whitespace),
+        ],
+
+        'base': [
+            include('ws'),
+
+            *_luau_make_expression_special(False),
+            (r'\.\.\.', Punctuation),
+
+            (rf'type\b(?={_s}+[a-zA-Z_])', Keyword.Reserved, 'type_declaration'),
+            (rf'export\b(?={_s}+[a-zA-Z_])', Keyword.Reserved),
+
+            (r'(?:\.\.|//|[+\-*\/%^<>=])=?', Operator, 'expression'),
+            (r'~=', Operator, 'expression'),
+
+            (words((
+                'and', 'or', 'not'
+            ), suffix=r'\b'), Operator.Word, 'expression'),
+
+            (words((
+                'elseif', 'for', 'if', 'in', 'repeat', 'return', 'until',
+                'while'), suffix=r'\b'), Keyword.Reserved, 'expression'),
+            (r'local\b', Keyword.Declaration, 'expression'),
+
+            (r'function\b', Keyword.Reserved, ('expression', 'func_name')),
+
+            (r'[\])};]+', Punctuation),
+
+            include('expression_static'),
+            *_luau_make_expression(False, _s, _s_la),
+
+            (r'[\[.,]', Punctuation, 'expression'),
+        ],
+        'expression_static': [
+            (words((
+                'break', 'continue', 'do', 'else', 'elseif', 'end', 'for',
+                'if', 'in', 'repeat', 'return', 'then', 'until', 'while'),
+                suffix=r'\b'), Keyword.Reserved),
+        ],
+        'expression': [
+            include('ws'),
+
+            (r'if\b', Keyword.Reserved, ('ternary', 'expression')),
+
+            (r'local\b', Keyword.Declaration),
+            *_luau_make_expression_special(True),
+            (r'\.\.\.', Punctuation, '#pop'),
+
+            (r'function\b', Keyword.Reserved, 'func_name'),
+
+            include('expression_static'),
+            *_luau_make_expression(True, _s, _s_la),
+
+            default('#pop'),
+        ],
+        'ternary': [
+            include('ws'),
+
+            (r'else\b', Keyword.Reserved, '#pop'),
+            (words((
+                'then', 'elseif',
+            ), suffix=r'\b'), Operator.Reserved, 'expression'),
+
+            default('#pop'),
+        ],
+
+        'closing_brace_pop': [
+            (r'\}', Punctuation, '#pop'),
+        ],
+        'closing_parenthesis_pop': [
+            (r'\)', Punctuation, '#pop'),
+        ],
+        'closing_gt_pop': [
+            (r'>', Punctuation, '#pop'),
+        ],
+
+        'closing_parenthesis_base': [
+            include('closing_parenthesis_pop'),
+            include('base'),
+        ],
+        'closing_parenthesis_type': [
+            include('closing_parenthesis_pop'),
+            include('type'),
+        ],
+        'closing_brace_base': [
+            include('closing_brace_pop'),
+            include('base'),
+        ],
+        'closing_brace_type': [
+            include('closing_brace_pop'),
+            include('type'),
+        ],
+        'closing_gt_type': [
+            include('closing_gt_pop'),
+            include('type'),
+        ],
+
+        'string_escape': [
+            (r'\\z\s*', String.Escape),
+            (r'\\(?:[abfnrtvz\\"\'`\{\n])|[\r\n]{1,2}|x[\da-fA-F]{2}|\d{1,3}|'
+             r'u\{\}[\da-fA-F]*\}', String.Escape),
+        ],
+        'string_single': [
+            include('string_escape'),
+
+            (r"'", String.Single, "#pop"),
+            (r"[^\\']+", String.Single),
+        ],
+        'string_double': [
+            include('string_escape'),
+
+            (r'"', String.Double, "#pop"),
+            (r'[^\\"]+', String.Double),
+        ],
+        'string_interpolated': [
+            include('string_escape'),
+
+            (r'\{', Punctuation, ('closing_brace_base', 'expression')),
+
+            (r'`', String.Backtick, "#pop"),
+            (r'[^\\`\{]+', String.Backtick),
+        ],
+
+        'func_name': [
+            include('ws'),
+
+            (r'[.:]', Punctuation),
+            (rf'[a-zA-Z_]\w*(?={_s_la}*[.:])', Name.Class),
+            (r'[a-zA-Z_]\w*', Name.Function),
+
+            (r'<', Punctuation, 'closing_gt_type'),
+
+            (r'\(', Punctuation, '#pop'),
+        ],
+
+        'type': [
+            include('ws'),
+
+            (r'\(', Punctuation, 'closing_parenthesis_type'),
+            (r'\{', Punctuation, 'closing_brace_type'),
+            (r'<', Punctuation, 'closing_gt_type'),
+
+            (r"'", String.Single, 'string_single'),
+            (r'"', String.Double, 'string_double'),
+
+            (r'[|&\.,\[\]:=]+', Punctuation),
+            (r'->', Punctuation),
+
+            (r'typeof\(', Name.Builtin, ('closing_parenthesis_base',
+                                         'expression')),
+            (r'[a-zA-Z_]\w*', Name.Class),
+        ],
+        'type_start': [
+            include('ws'),
+
+            (r'\(', Punctuation, ('#pop', 'closing_parenthesis_type')),
+            (r'\{', Punctuation, ('#pop', 'closing_brace_type')),
+            (r'<', Punctuation, ('#pop', 'closing_gt_type')),
+
+            (r"'", String.Single, ('#pop', 'string_single')),
+            (r'"', String.Double, ('#pop', 'string_double')),
+
+            (r'typeof\(', Name.Builtin, ('#pop', 'closing_parenthesis_base',
+                                         'expression')),
+            (r'[a-zA-Z_]\w*', Name.Class, '#pop'),
+        ],
+        'type_end': [
+            include('ws'),
+
+            (r'[|&\.]', Punctuation, 'type_start'),
+            (r'->', Punctuation, 'type_start'),
+
+            (r'<', Punctuation, 'closing_gt_type'),
+
+            default('#pop'),
+        ],
+        'type_declaration': [
+            include('ws'),
+
+            (r'[a-zA-Z_]\w*', Name.Class),
+            (r'<', Punctuation, 'closing_gt_type'),
+
+            (r'=', Punctuation, ('#pop', 'type_end', 'type_start')),
+        ],
+    }
+
+    def __init__(self, **options):
+        self.include_luau_builtins = get_bool_opt(
+            options, 'include_luau_builtins', True)
+        self.include_roblox_builtins = get_bool_opt(
+            options, 'include_roblox_builtins', False)
+        self.additional_builtins = get_list_opt(options, 'additional_builtins', [])
+        self.disabled_builtins = get_list_opt(options, 'disabled_builtins', [])
+
+        self._builtins = set(self.additional_builtins)
+        if self.include_luau_builtins:
+            from pygments.lexers._luau_builtins import LUAU_BUILTINS
+            self._builtins.update(LUAU_BUILTINS)
+        if self.include_roblox_builtins:
+            from pygments.lexers._luau_builtins import ROBLOX_BUILTINS
+            self._builtins.update(ROBLOX_BUILTINS)
+        if self.additional_builtins:
+            self._builtins.update(self.additional_builtins)
+        self._builtins.difference_update(self.disabled_builtins)
+
+        RegexLexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        for index, token, value in \
+                RegexLexer.get_tokens_unprocessed(self, text):
+            if token is Name or token is Name.Other:
+                split_value = value.split('.')
+                complete_value = []
+                new_index = index
+                for position in range(len(split_value), 0, -1):
+                    potential_string = '.'.join(split_value[:position])
+                    if potential_string in self._builtins:
+                        yield index, Name.Builtin, potential_string
+                        new_index += len(potential_string)
+
+                        if complete_value:
+                            yield new_index, Punctuation, '.'
+                            new_index += 1
+                        break
+                    complete_value.insert(0, split_value[position - 1])
+
+                for position, substring in enumerate(complete_value):
+                    if position + 1 == len(complete_value):
+                        if token is Name:
+                            yield new_index, Name.Variable, substring
+                            continue
+                        yield new_index, Name.Function, substring
+                        continue
+                    yield new_index, Name.Variable, substring
+                    new_index += len(substring)
+                    yield new_index, Punctuation, '.'
+                    new_index += 1
+
+                continue
+            yield index, token, value
+
+class MoonScriptLexer(LuaLexer):
+    """
+    For MoonScript source code.
+    """
+
+    name = 'MoonScript'
+    url = 'http://moonscript.org'
+    aliases = ['moonscript', 'moon']
+    filenames = ['*.moon']
+    mimetypes = ['text/x-moonscript', 'application/x-moonscript']
+    version_added = '1.5'
+
+    tokens = {
+        'root': [
+            (r'#!(.*?)$', Comment.Preproc),
+            default('base'),
+        ],
+        'base': [
+            ('--.*$', Comment.Single),
+            (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
+            (r'(?i)\d+e[+-]?\d+', Number.Float),
+            (r'(?i)0x[0-9a-f]*', Number.Hex),
+            (r'\d+', Number.Integer),
+            (r'\n', Whitespace),
+            (r'[^\S\n]+', Text),
+            (r'(?s)\[(=*)\[.*?\]\1\]', String),
+            (r'(->|=>)', Name.Function),
+            (r':[a-zA-Z_]\w*', Name.Variable),
+            (r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator),
+            (r'[;,]', Punctuation),
+            (r'[\[\]{}()]', Keyword.Type),
+            (r'[a-zA-Z_]\w*:', Name.Variable),
+            (words((
+                'class', 'extends', 'if', 'then', 'super', 'do', 'with',
+                'import', 'export', 'while', 'elseif', 'return', 'for', 'in',
+                'from', 'when', 'using', 'else', 'and', 'or', 'not', 'switch',
+                'break'), suffix=r'\b'),
+             Keyword),
+            (r'(true|false|nil)\b', Keyword.Constant),
+            (r'(and|or|not)\b', Operator.Word),
+            (r'(self)\b', Name.Builtin.Pseudo),
+            (r'@@?([a-zA-Z_]\w*)?', Name.Variable.Class),
+            (r'[A-Z]\w*', Name.Class),  # proper name
+            (words(all_lua_builtins(), suffix=r"\b"), Name.Builtin),
+            (r'[A-Za-z_]\w*', Name),
+            ("'", String.Single, combined('stringescape', 'sqs')),
+            ('"', String.Double, combined('stringescape', 'dqs'))
+        ],
+        'stringescape': [
+            (r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
+        ],
+        'strings': [
+            (r'[^#\\\'"]+', String),
+            # note that strings are multi-line.
+            # hashmarks, quotes and backslashes must be parsed one at a time
+        ],
+        'interpoling_string': [
+            (r'\}', String.Interpol, "#pop"),
+            include('base')
+        ],
+        'dqs': [
+            (r'"', String.Double, '#pop'),
+            (r'\\.|\'', String),  # double-quoted string don't need ' escapes
+            (r'#\{', String.Interpol, "interpoling_string"),
+            (r'#', String),
+            include('strings')
+        ],
+        'sqs': [
+            (r"'", String.Single, '#pop'),
+            (r'#|\\.|"', String),  # single quoted strings don't need " escapses
+            include('strings')
+        ]
+    }
+
+    def get_tokens_unprocessed(self, text):
+        # set . as Operator instead of Punctuation
+        for index, token, value in LuaLexer.get_tokens_unprocessed(self, text):
+            if token == Punctuation and value == ".":
+                token = Operator
+            yield index, token, value
+
+
+class ChaiscriptLexer(RegexLexer):
+    """
+    For ChaiScript source code.
+    """
+
+    name = 'ChaiScript'
+    url = 'http://chaiscript.com/'
+    aliases = ['chaiscript', 'chai']
+    filenames = ['*.chai']
+    mimetypes = ['text/x-chaiscript', 'application/x-chaiscript']
+    version_added = '2.0'
+
+    flags = re.DOTALL | re.MULTILINE
+
+    tokens = {
+        'commentsandwhitespace': [
+            (r'\s+', Text),
+            (r'//.*?\n', Comment.Single),
+            (r'/\*.*?\*/', Comment.Multiline),
+            (r'^\#.*?\n', Comment.Single)
+        ],
+        'slashstartsregex': [
+            include('commentsandwhitespace'),
+            (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
+             r'([gim]+\b|\B)', String.Regex, '#pop'),
+            (r'(?=/)', Text, ('#pop', 'badregex')),
+            default('#pop')
+        ],
+        'badregex': [
+            (r'\n', Text, '#pop')
+        ],
+        'root': [
+            include('commentsandwhitespace'),
+            (r'\n', Text),
+            (r'[^\S\n]+', Text),
+            (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|\.\.'
+             r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
+            (r'[{(\[;,]', Punctuation, 'slashstartsregex'),
+            (r'[})\].]', Punctuation),
+            (r'[=+\-*/]', Operator),
+            (r'(for|in|while|do|break|return|continue|if|else|'
+             r'throw|try|catch'
+             r')\b', Keyword, 'slashstartsregex'),
+            (r'(var)\b', Keyword.Declaration, 'slashstartsregex'),
+            (r'(attr|def|fun)\b', Keyword.Reserved),
+            (r'(true|false)\b', Keyword.Constant),
+            (r'(eval|throw)\b', Name.Builtin),
+            (r'`\S+`', Name.Builtin),
+            (r'[$a-zA-Z_]\w*', Name.Other),
+            (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'[0-9]+', Number.Integer),
+            (r'"', String.Double, 'dqstring'),
+            (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
+        ],
+        'dqstring': [
+            (r'\$\{[^"}]+?\}', String.Interpol),
+            (r'\$', String.Double),
+            (r'\\\\', String.Double),
+            (r'\\"', String.Double),
+            (r'[^\\"$]+', String.Double),
+            (r'"', String.Double, '#pop'),
+        ],
+    }
+
+
+class LSLLexer(RegexLexer):
+    """
+    For Second Life's Linden Scripting Language source code.
+    """
+
+    name = 'LSL'
+    aliases = ['lsl']
+    filenames = ['*.lsl']
+    mimetypes = ['text/x-lsl']
+    url = 'https://wiki.secondlife.com/wiki/Linden_Scripting_Language'
+    version_added = '2.0'
+
+    flags = re.MULTILINE
+
+    lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b'
+    lsl_types = r'\b(?:float|integer|key|list|quaternion|rotation|string|vector)\b'
+    lsl_states = r'\b(?:(?:state)\s+\w+|default)\b'
+    lsl_events = r'\b(?:state_(?:entry|exit)|touch(?:_(?:start|end))?|(?:land_)?collision(?:_(?:start|end))?|timer|listen|(?:no_)?sensor|control|(?:not_)?at_(?:rot_)?target|money|email|run_time_permissions|changed|attach|dataserver|moving_(?:start|end)|link_message|(?:on|object)_rez|remote_data|http_re(?:sponse|quest)|path_update|transaction_result)\b'
+    lsl_functions_builtin = r'\b(?:ll(?:ReturnObjectsBy(?:ID|Owner)|Json(?:2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(?:Mag|Norm|Dist)|Rot(?:Between|2(?:Euler|Fwd|Left|Up))|(?:Euler|Axes)2Rot|Whisper|(?:Region|Owner)?Say|Shout|Listen(?:Control|Remove)?|Sensor(?:Repeat|Remove)?|Detected(?:Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|(?:[GS]et)(?:AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(?:Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(?:Scale|Offset|Rotate)Texture|(?:Rot)?Target(?:Remove)?|(?:Stop)?MoveToTarget|Apply(?:Rotational)?Impulse|Set(?:KeyframedMotion|ContentType|RegionPos|(?:Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(?:Queueing|Radius)|Vehicle(?:Type|(?:Float|Vector|Rotation)Param)|(?:Touch|Sit)?Text|Camera(?:Eye|At)Offset|PrimitiveParams|ClickAction|Link(?:Alpha|Color|PrimitiveParams(?:Fast)?|Texture(?:Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get(?:(?:Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(?:PrimitiveParams|Number(?:OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(?:Details|PermMask|PrimCount)|Parcel(?:MaxPrims|Details|Prim(?:Count|Owners))|Attached|(?:SPMax|Free|Used)Memory|Region(?:Name|TimeDilation|FPS|Corner|AgentCount)|Root(?:Position|Rotation)|UnixTime|(?:Parcel|Region)Flags|(?:Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(?:Prims|NotecardLines|Sides)|Animation(?:List)?|(?:Camera|Local)(?:Pos|Rot)|Vel|Accel|Omega|Time(?:stamp|OfDay)|(?:Object|CenterOf)?Mass|MassMKS|Energy|Owner|(?:Owner)?Key|SunDirection|Texture(?:Offset|Scale|Rot)|Inventory(?:Number|Name|Key|Type|Creator|PermMask)|Permissions(?:Key)?|StartParameter|List(?:Length|EntryType)|Date|Agent(?:Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(?:Name|State))|(?:Get|Reset|GetAndReset)Time|PlaySound(?:Slave)?|LoopSound(?:Master|Slave)?|(?:Trigger|Stop|Preload)Sound|(?:(?:Get|Delete)Sub|Insert)String|To(?:Upper|Lower)|Give(?:InventoryList|Money)|RezObject|(?:Stop)?LookAt|Sleep|CollisionFilter|(?:Take|Release)Controls|DetachFromAvatar|AttachToAvatar(?:Temp)?|InstantMessage|(?:GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(?:Length|Trim)|(?:Start|Stop)Animation|TargetOmega|RequestPermissions|(?:Create|Break)Link|BreakAllLinks|(?:Give|Remove)Inventory|Water|PassTouches|Request(?:Agent|Inventory)Data|TeleportAgent(?:Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(?:Axis|Angle)|A(?:cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(?:CSV|Integer|Json|Float|String|Key|Vector|Rot|List(?:Strided)?)|DeleteSubList|List(?:Statistics|Sort|Randomize|(?:Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(?:CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(?:Slope|Normal|Contour)|GroundRepel|(?:Set|Remove)VehicleFlags|(?:AvatarOn)?(?:Link)?SitTarget|Script(?:Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(?:Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(?:Integer|String)ToBase64|XorBase64|Log(?:10)?|Base64To(?:String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(?:Load|Release|(?:E|Une)scape)URL|ParcelMedia(?:CommandList|Query)|ModPow|MapDestination|(?:RemoveFrom|AddTo|Reset)Land(?:Pass|Ban)List|(?:Set|Clear)CameraParams|HTTP(?:Request|Response)|TextBox|DetectedTouch(?:UV|Face|Pos|(?:N|Bin)ormal|ST)|(?:MD5|SHA1|DumpList2)String|Request(?:Secure)?URL|Clear(?:Prim|Link)Media|(?:Link)?ParticleSystem|(?:Get|Request)(?:Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(?:Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\b'
+    lsl_constants_float = r'\b(?:DEG_TO_RAD|PI(?:_BY_TWO)?|RAD_TO_DEG|SQRT2|TWO_PI)\b'
+    lsl_constants_integer = r'\b(?:JSON_APPEND|STATUS_(?:PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(?:_OBJECT)?|(?:DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(?:FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(?:_(?:BY_(?:LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(?:PARCEL(?:_OWNER)?|REGION)))?|CAMERA_(?:PITCH|DISTANCE|BEHINDNESS_(?:ANGLE|LAG)|(?:FOCUS|POSITION)(?:_(?:THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(?:ROOT|SET|ALL_(?:OTHERS|CHILDREN)|THIS)|ACTIVE|PASSIVE|SCRIPTED|CONTROL_(?:FWD|BACK|(?:ROT_)?(?:LEFT|RIGHT)|UP|DOWN|(?:ML_)?LBUTTON)|PERMISSION_(?:RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(?:CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(?:TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(?:INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(?:_START)?|TELEPORT|MEDIA)|OBJECT_(?:(?:PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_ON_REZ|NAME|DESC|POS|PRIM_EQUIVALENCE|RETURN_(?:PARCEL(?:_OWNER)?|REGION)|ROO?T|VELOCITY|OWNER|GROUP|CREATOR|ATTACHED_POINT|RENDER_WEIGHT|PATHFINDING_TYPE|(?:RUNNING|TOTAL)_SCRIPT_COUNT|SCRIPT_(?:MEMORY|TIME))|TYPE_(?:INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(?:DEBUG|PUBLIC)_CHANNEL|ATTACH_(?:AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](?:SHOULDER|HAND|FOOT|EAR|EYE|[UL](?:ARM|LEG)|HIP)|(?:LEFT|RIGHT)_PEC|HUD_(?:CENTER_[12]|TOP_(?:RIGHT|CENTER|LEFT)|BOTTOM(?:_(?:RIGHT|LEFT))?))|LAND_(?:LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(?:ONLINE|NAME|BORN|SIM_(?:POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(?:ON_FILE|USED)|REMOTE_DATA_(?:CHANNEL|REQUEST|REPLY)|PSYS_(?:PART_(?:BF_(?:ZERO|ONE(?:_MINUS_(?:DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(?:START|END)_(?:COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(?:RIBBON|WIND|INTERP_(?:COLOR|SCALE)|BOUNCE|FOLLOW_(?:SRC|VELOCITY)|TARGET_(?:POS|LINEAR)|EMISSIVE)_MASK)|SRC_(?:MAX_AGE|PATTERN|ANGLE_(?:BEGIN|END)|BURST_(?:RATE|PART_COUNT|RADIUS|SPEED_(?:MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(?:DROP|EXPLODE|ANGLE(?:_CONE(?:_EMPTY)?)?)))|VEHICLE_(?:REFERENCE_FRAME|TYPE_(?:NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(?:LINEAR|ANGULAR)_(?:FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(?:HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(?:LINEAR|ANGULAR)_(?:DEFLECTION_(?:EFFICIENCY|TIMESCALE)|MOTOR_(?:DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(?:EFFICIENCY|TIMESCALE)|BANKING_(?:EFFICIENCY|MIX|TIMESCALE)|FLAG_(?:NO_DEFLECTION_UP|LIMIT_(?:ROLL_ONLY|MOTOR_UP)|HOVER_(?:(?:WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(?:STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(?:TYPE(?:_(?:BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(?:DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(?:_(?:STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(?:NONE|LOW|MEDIUM|HIGH)|BUMP_(?:NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(?:DEFAULT|PLANAR)|SCULPT_(?:TYPE_(?:SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(?:MIRROR|INVERT))|PHYSICS(?:_(?:SHAPE_(?:CONVEX|NONE|PRIM|TYPE)))?|(?:POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(?:ALT_IMAGE_ENABLE|CONTROLS|(?:CURRENT|HOME)_URL|AUTO_(?:LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(?:WIDTH|HEIGHT)_PIXELS|WHITELIST(?:_ENABLE)?|PERMS_(?:INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(?:STANDARD|MINI)|PERM_(?:NONE|OWNER|GROUP|ANYONE)|MAX_(?:URL_LENGTH|WHITELIST_(?:SIZE|COUNT)|(?:WIDTH|HEIGHT)_PIXELS)))|MASK_(?:BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(?:TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(?:MEDIA_COMMAND_(?:STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(?:ALLOW_(?:FLY|(?:GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(?:GROUP_)?OBJECTS)|USE_(?:ACCESS_(?:GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(?:GROUP|ALL)_OBJECT_ENTRY)|COUNT_(?:TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(?:NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(?:MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(?:_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(?:HIDE|DEFAULT)|REGION_FLAG_(?:ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(?:COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(?:METHOD|MIMETYPE|BODY_(?:MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|STRING_(?:TRIM(?:_(?:HEAD|TAIL))?)|CLICK_ACTION_(?:NONE|TOUCH|SIT|BUY|PAY|OPEN(?:_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(?:NONE|SCRIPT_MEMORY)|RC_(?:DATA_FLAGS|DETECT_PHANTOM|GET_(?:LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(?:TYPES|AGENTS|(?:NON)?PHYSICAL|LAND))|RCERR_(?:CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(?:ALLOWED_(?:AGENT|GROUP)_(?:ADD|REMOVE)|BANNED_AGENT_(?:ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(?:COMMAND|CMD_(?:PLAY|STOP|PAUSE|SET_MODE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(?:GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(?:CMD_(?:(?:SMOOTH_)?STOP|JUMP)|DESIRED_(?:TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(?:_(?:[A-D]|NONE))?|MAX_(?:DECEL|TURN_RADIUS|(?:ACCEL|SPEED)))|PURSUIT_(?:OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(?:CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(?:EVADE_(?:HIDDEN|SPOTTED)|FAILURE_(?:DYNAMIC_PATHFINDING_DISABLED|INVALID_(?:GOAL|START)|NO_(?:NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(?:PARCEL_)?UNREACHABLE)|(?:GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(?:_(?:FAST|NONE|SLOW))?|CONTENT_TYPE_(?:ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(?:RADIUS|STATIC)|(?:PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(?:AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\b'
+    lsl_constants_integer_boolean = r'\b(?:FALSE|TRUE)\b'
+    lsl_constants_rotation = r'\b(?:ZERO_ROTATION)\b'
+    lsl_constants_string = r'\b(?:EOF|JSON_(?:ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(?:BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(?:GRANTED|DENIED))\b'
+    lsl_constants_vector = r'\b(?:TOUCH_INVALID_(?:TEXCOORD|VECTOR)|ZERO_VECTOR)\b'
+    lsl_invalid_broken = r'\b(?:LAND_(?:LARGE|MEDIUM|SMALL)_BRUSH)\b'
+    lsl_invalid_deprecated = r'\b(?:ATTACH_[LR]PEC|DATA_RATING|OBJECT_ATTACHMENT_(?:GEOMETRY_BYTES|SURFACE_AREA)|PRIM_(?:CAST_SHADOWS|MATERIAL_LIGHT|TYPE_LEGACY)|PSYS_SRC_(?:INNER|OUTER)ANGLE|VEHICLE_FLAG_NO_FLY_UP|ll(?:Cloud|Make(?:Explosion|Fountain|Smoke|Fire)|RemoteDataSetRegion|Sound(?:Preload)?|XorBase64Strings(?:Correct)?))\b'
+    lsl_invalid_illegal = r'\b(?:event)\b'
+    lsl_invalid_unimplemented = r'\b(?:CHARACTER_(?:MAX_ANGULAR_(?:ACCEL|SPEED)|TURN_SPEED_MULTIPLIER)|PERMISSION_(?:CHANGE_(?:JOINTS|PERMISSIONS)|RELEASE_OWNERSHIP|REMAP_CONTROLS)|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|ll(?:CollisionSprite|(?:Stop)?PointAt|(?:(?:Refresh|Set)Prim)URL|(?:Take|Release)Camera|RemoteLoadScript))\b'
+    lsl_reserved_godmode = r'\b(?:ll(?:GodLikeRezObject|Set(?:Inventory|Object)PermMask))\b'
+    lsl_reserved_log = r'\b(?:print)\b'
+    lsl_operators = r'\+\+|\-\-|<<|>>|&&?|\|\|?|\^|~|[!%<>=*+\-/]=?'
+
+    tokens = {
+        'root':
+        [
+            (r'//.*?\n',                          Comment.Single),
+            (r'/\*',                              Comment.Multiline, 'comment'),
+            (r'"',                                String.Double, 'string'),
+            (lsl_keywords,                        Keyword),
+            (lsl_types,                           Keyword.Type),
+            (lsl_states,                          Name.Class),
+            (lsl_events,                          Name.Builtin),
+            (lsl_functions_builtin,               Name.Function),
+            (lsl_constants_float,                 Keyword.Constant),
+            (lsl_constants_integer,               Keyword.Constant),
+            (lsl_constants_integer_boolean,       Keyword.Constant),
+            (lsl_constants_rotation,              Keyword.Constant),
+            (lsl_constants_string,                Keyword.Constant),
+            (lsl_constants_vector,                Keyword.Constant),
+            (lsl_invalid_broken,                  Error),
+            (lsl_invalid_deprecated,              Error),
+            (lsl_invalid_illegal,                 Error),
+            (lsl_invalid_unimplemented,           Error),
+            (lsl_reserved_godmode,                Keyword.Reserved),
+            (lsl_reserved_log,                    Keyword.Reserved),
+            (r'\b([a-zA-Z_]\w*)\b',     Name.Variable),
+            (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d*', Number.Float),
+            (r'(\d+\.\d*|\.\d+)',                 Number.Float),
+            (r'0[xX][0-9a-fA-F]+',                Number.Hex),
+            (r'\d+',                              Number.Integer),
+            (lsl_operators,                       Operator),
+            (r':=?',                              Error),
+            (r'[,;{}()\[\]]',                     Punctuation),
+            (r'\n+',                              Whitespace),
+            (r'\s+',                              Whitespace)
+        ],
+        'comment':
+        [
+            (r'[^*/]+',                           Comment.Multiline),
+            (r'/\*',                              Comment.Multiline, '#push'),
+            (r'\*/',                              Comment.Multiline, '#pop'),
+            (r'[*/]',                             Comment.Multiline)
+        ],
+        'string':
+        [
+            (r'\\([nt"\\])',                      String.Escape),
+            (r'"',                                String.Double, '#pop'),
+            (r'\\.',                              Error),
+            (r'[^"\\]+',                          String.Double),
+        ]
+    }
+
+
+class AppleScriptLexer(RegexLexer):
+    """
+    For AppleScript source code,
+    including `AppleScript Studio
+    `_.
+    Contributed by Andreas Amann .
+    """
+
+    name = 'AppleScript'
+    url = 'https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html'
+    aliases = ['applescript']
+    filenames = ['*.applescript']
+    version_added = '1.0'
+
+    flags = re.MULTILINE | re.DOTALL
+
+    Identifiers = r'[a-zA-Z]\w*'
+
+    # XXX: use words() for all of these
+    Literals = ('AppleScript', 'current application', 'false', 'linefeed',
+                'missing value', 'pi', 'quote', 'result', 'return', 'space',
+                'tab', 'text item delimiters', 'true', 'version')
+    Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ',
+               'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ',
+               'real ', 'record ', 'reference ', 'RGB color ', 'script ',
+               'text ', 'unit types', '(?:Unicode )?text', 'string')
+    BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month',
+               'paragraph', 'word', 'year')
+    HandlerParams = ('about', 'above', 'against', 'apart from', 'around',
+                     'aside from', 'at', 'below', 'beneath', 'beside',
+                     'between', 'for', 'given', 'instead of', 'on', 'onto',
+                     'out of', 'over', 'since')
+    Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL',
+                'choose application', 'choose color', 'choose file( name)?',
+                'choose folder', 'choose from list',
+                'choose remote application', 'clipboard info',
+                'close( access)?', 'copy', 'count', 'current date', 'delay',
+                'delete', 'display (alert|dialog)', 'do shell script',
+                'duplicate', 'exists', 'get eof', 'get volume settings',
+                'info for', 'launch', 'list (disks|folder)', 'load script',
+                'log', 'make', 'mount volume', 'new', 'offset',
+                'open( (for access|location))?', 'path to', 'print', 'quit',
+                'random number', 'read', 'round', 'run( script)?',
+                'say', 'scripting components',
+                'set (eof|the clipboard to|volume)', 'store script',
+                'summarize', 'system attribute', 'system info',
+                'the clipboard', 'time to GMT', 'write', 'quoted form')
+    References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)',
+                  'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
+                  'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back',
+                  'before', 'behind', 'every', 'front', 'index', 'last',
+                  'middle', 'some', 'that', 'through', 'thru', 'where', 'whose')
+    Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not",
+                 "isn't", "isn't equal( to)?", "is not equal( to)?",
+                 "doesn't equal", "does not equal", "(is )?greater than",
+                 "comes after", "is not less than or equal( to)?",
+                 "isn't less than or equal( to)?", "(is )?less than",
+                 "comes before", "is not greater than or equal( to)?",
+                 "isn't greater than or equal( to)?",
+                 "(is  )?greater than or equal( to)?", "is not less than",
+                 "isn't less than", "does not come before",
+                 "doesn't come before", "(is )?less than or equal( to)?",
+                 "is not greater than", "isn't greater than",
+                 "does not come after", "doesn't come after", "starts? with",
+                 "begins? with", "ends? with", "contains?", "does not contain",
+                 "doesn't contain", "is in", "is contained by", "is not in",
+                 "is not contained by", "isn't contained by", "div", "mod",
+                 "not", "(a  )?(ref( to)?|reference to)", "is", "does")
+    Control = ('considering', 'else', 'error', 'exit', 'from', 'if',
+               'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to',
+               'try', 'until', 'using terms from', 'while', 'whith',
+               'with timeout( of)?', 'with transaction', 'by', 'continue',
+               'end', 'its?', 'me', 'my', 'return', 'of', 'as')
+    Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get')
+    Reserved = ('but', 'put', 'returning', 'the')
+    StudioClasses = ('action cell', 'alert reply', 'application', 'box',
+                     'browser( cell)?', 'bundle', 'button( cell)?', 'cell',
+                     'clip view', 'color well', 'color-panel',
+                     'combo box( item)?', 'control',
+                     'data( (cell|column|item|row|source))?', 'default entry',
+                     'dialog reply', 'document', 'drag info', 'drawer',
+                     'event', 'font(-panel)?', 'formatter',
+                     'image( (cell|view))?', 'matrix', 'menu( item)?', 'item',
+                     'movie( view)?', 'open-panel', 'outline view', 'panel',
+                     'pasteboard', 'plugin', 'popup button',
+                     'progress indicator', 'responder', 'save-panel',
+                     'scroll view', 'secure text field( cell)?', 'slider',
+                     'sound', 'split view', 'stepper', 'tab view( item)?',
+                     'table( (column|header cell|header view|view))',
+                     'text( (field( cell)?|view))?', 'toolbar( item)?',
+                     'user-defaults', 'view', 'window')
+    StudioEvents = ('accept outline drop', 'accept table drop', 'action',
+                    'activated', 'alert ended', 'awake from nib', 'became key',
+                    'became main', 'begin editing', 'bounds changed',
+                    'cell value', 'cell value changed', 'change cell value',
+                    'change item value', 'changed', 'child of item',
+                    'choose menu item', 'clicked', 'clicked toolbar item',
+                    'closed', 'column clicked', 'column moved',
+                    'column resized', 'conclude drop', 'data representation',
+                    'deminiaturized', 'dialog ended', 'document nib name',
+                    'double clicked', 'drag( (entered|exited|updated))?',
+                    'drop', 'end editing', 'exposed', 'idle', 'item expandable',
+                    'item value', 'item value changed', 'items changed',
+                    'keyboard down', 'keyboard up', 'launched',
+                    'load data representation', 'miniaturized', 'mouse down',
+                    'mouse dragged', 'mouse entered', 'mouse exited',
+                    'mouse moved', 'mouse up', 'moved',
+                    'number of browser rows', 'number of items',
+                    'number of rows', 'open untitled', 'opened', 'panel ended',
+                    'parameters updated', 'plugin loaded', 'prepare drop',
+                    'prepare outline drag', 'prepare outline drop',
+                    'prepare table drag', 'prepare table drop',
+                    'read from file', 'resigned active', 'resigned key',
+                    'resigned main', 'resized( sub views)?',
+                    'right mouse down', 'right mouse dragged',
+                    'right mouse up', 'rows changed', 'scroll wheel',
+                    'selected tab view item', 'selection changed',
+                    'selection changing', 'should begin editing',
+                    'should close', 'should collapse item',
+                    'should end editing', 'should expand item',
+                    'should open( untitled)?',
+                    'should quit( after last window closed)?',
+                    'should select column', 'should select item',
+                    'should select row', 'should select tab view item',
+                    'should selection change', 'should zoom', 'shown',
+                    'update menu item', 'update parameters',
+                    'update toolbar item', 'was hidden', 'was miniaturized',
+                    'will become active', 'will close', 'will dismiss',
+                    'will display browser cell', 'will display cell',
+                    'will display item cell', 'will display outline cell',
+                    'will finish launching', 'will hide', 'will miniaturize',
+                    'will move', 'will open', 'will pop up', 'will quit',
+                    'will resign active', 'will resize( sub views)?',
+                    'will select tab view item', 'will show', 'will zoom',
+                    'write to file', 'zoomed')
+    StudioCommands = ('animate', 'append', 'call method', 'center',
+                      'close drawer', 'close panel', 'display',
+                      'display alert', 'display dialog', 'display panel', 'go',
+                      'hide', 'highlight', 'increment', 'item for',
+                      'load image', 'load movie', 'load nib', 'load panel',
+                      'load sound', 'localized string', 'lock focus', 'log',
+                      'open drawer', 'path for', 'pause', 'perform action',
+                      'play', 'register', 'resume', 'scroll', 'select( all)?',
+                      'show', 'size to fit', 'start', 'step back',
+                      'step forward', 'stop', 'synchronize', 'unlock focus',
+                      'update')
+    StudioProperties = ('accepts arrow key', 'action method', 'active',
+                        'alignment', 'allowed identifiers',
+                        'allows branch selection', 'allows column reordering',
+                        'allows column resizing', 'allows column selection',
+                        'allows customization',
+                        'allows editing text attributes',
+                        'allows empty selection', 'allows mixed state',
+                        'allows multiple selection', 'allows reordering',
+                        'allows undo', 'alpha( value)?', 'alternate image',
+                        'alternate increment value', 'alternate title',
+                        'animation delay', 'associated file name',
+                        'associated object', 'auto completes', 'auto display',
+                        'auto enables items', 'auto repeat',
+                        'auto resizes( outline column)?',
+                        'auto save expanded items', 'auto save name',
+                        'auto save table columns', 'auto saves configuration',
+                        'auto scroll', 'auto sizes all columns to fit',
+                        'auto sizes cells', 'background color', 'bezel state',
+                        'bezel style', 'bezeled', 'border rect', 'border type',
+                        'bordered', 'bounds( rotation)?', 'box type',
+                        'button returned', 'button type',
+                        'can choose directories', 'can choose files',
+                        'can draw', 'can hide',
+                        'cell( (background color|size|type))?', 'characters',
+                        'class', 'click count', 'clicked( data)? column',
+                        'clicked data item', 'clicked( data)? row',
+                        'closeable', 'collating', 'color( (mode|panel))',
+                        'command key down', 'configuration',
+                        'content(s| (size|view( margins)?))?', 'context',
+                        'continuous', 'control key down', 'control size',
+                        'control tint', 'control view',
+                        'controller visible', 'coordinate system',
+                        'copies( on scroll)?', 'corner view', 'current cell',
+                        'current column', 'current( field)?  editor',
+                        'current( menu)? item', 'current row',
+                        'current tab view item', 'data source',
+                        'default identifiers', 'delta (x|y|z)',
+                        'destination window', 'directory', 'display mode',
+                        'displayed cell', 'document( (edited|rect|view))?',
+                        'double value', 'dragged column', 'dragged distance',
+                        'dragged items', 'draws( cell)? background',
+                        'draws grid', 'dynamically scrolls', 'echos bullets',
+                        'edge', 'editable', 'edited( data)? column',
+                        'edited data item', 'edited( data)? row', 'enabled',
+                        'enclosing scroll view', 'ending page',
+                        'error handling', 'event number', 'event type',
+                        'excluded from windows menu', 'executable path',
+                        'expanded', 'fax number', 'field editor', 'file kind',
+                        'file name', 'file type', 'first responder',
+                        'first visible column', 'flipped', 'floating',
+                        'font( panel)?', 'formatter', 'frameworks path',
+                        'frontmost', 'gave up', 'grid color', 'has data items',
+                        'has horizontal ruler', 'has horizontal scroller',
+                        'has parent data item', 'has resize indicator',
+                        'has shadow', 'has sub menu', 'has vertical ruler',
+                        'has vertical scroller', 'header cell', 'header view',
+                        'hidden', 'hides when deactivated', 'highlights by',
+                        'horizontal line scroll', 'horizontal page scroll',
+                        'horizontal ruler view', 'horizontally resizable',
+                        'icon image', 'id', 'identifier',
+                        'ignores multiple clicks',
+                        'image( (alignment|dims when disabled|frame style|scaling))?',
+                        'imports graphics', 'increment value',
+                        'indentation per level', 'indeterminate', 'index',
+                        'integer value', 'intercell spacing', 'item height',
+                        'key( (code|equivalent( modifier)?|window))?',
+                        'knob thickness', 'label', 'last( visible)? column',
+                        'leading offset', 'leaf', 'level', 'line scroll',
+                        'loaded', 'localized sort', 'location', 'loop mode',
+                        'main( (bunde|menu|window))?', 'marker follows cell',
+                        'matrix mode', 'maximum( content)? size',
+                        'maximum visible columns',
+                        'menu( form representation)?', 'miniaturizable',
+                        'miniaturized', 'minimized image', 'minimized title',
+                        'minimum column width', 'minimum( content)? size',
+                        'modal', 'modified', 'mouse down state',
+                        'movie( (controller|file|rect))?', 'muted', 'name',
+                        'needs display', 'next state', 'next text',
+                        'number of tick marks', 'only tick mark values',
+                        'opaque', 'open panel', 'option key down',
+                        'outline table column', 'page scroll', 'pages across',
+                        'pages down', 'palette label', 'pane splitter',
+                        'parent data item', 'parent window', 'pasteboard',
+                        'path( (names|separator))?', 'playing',
+                        'plays every frame', 'plays selection only', 'position',
+                        'preferred edge', 'preferred type', 'pressure',
+                        'previous text', 'prompt', 'properties',
+                        'prototype cell', 'pulls down', 'rate',
+                        'released when closed', 'repeated',
+                        'requested print time', 'required file type',
+                        'resizable', 'resized column', 'resource path',
+                        'returns records', 'reuses columns', 'rich text',
+                        'roll over', 'row height', 'rulers visible',
+                        'save panel', 'scripts path', 'scrollable',
+                        'selectable( identifiers)?', 'selected cell',
+                        'selected( data)? columns?', 'selected data items?',
+                        'selected( data)? rows?', 'selected item identifier',
+                        'selection by rect', 'send action on arrow key',
+                        'sends action when done editing', 'separates columns',
+                        'separator item', 'sequence number', 'services menu',
+                        'shared frameworks path', 'shared support path',
+                        'sheet', 'shift key down', 'shows alpha',
+                        'shows state by', 'size( mode)?',
+                        'smart insert delete enabled', 'sort case sensitivity',
+                        'sort column', 'sort order', 'sort type',
+                        'sorted( data rows)?', 'sound', 'source( mask)?',
+                        'spell checking enabled', 'starting page', 'state',
+                        'string value', 'sub menu', 'super menu', 'super view',
+                        'tab key traverses cells', 'tab state', 'tab type',
+                        'tab view', 'table view', 'tag', 'target( printer)?',
+                        'text color', 'text container insert',
+                        'text container origin', 'text returned',
+                        'tick mark position', 'time stamp',
+                        'title(d| (cell|font|height|position|rect))?',
+                        'tool tip', 'toolbar', 'trailing offset', 'transparent',
+                        'treat packages as directories', 'truncated labels',
+                        'types', 'unmodified characters', 'update views',
+                        'use sort indicator', 'user defaults',
+                        'uses data source', 'uses ruler',
+                        'uses threaded animation',
+                        'uses title from previous column', 'value wraps',
+                        'version',
+                        'vertical( (line scroll|page scroll|ruler view))?',
+                        'vertically resizable', 'view',
+                        'visible( document rect)?', 'volume', 'width', 'window',
+                        'windows menu', 'wraps', 'zoomable', 'zoomed')
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+            (r'¬\n', String.Escape),
+            (r"'s\s+", Text),  # This is a possessive, consider moving
+            (r'(--|#).*?$', Comment),
+            (r'\(\*', Comment.Multiline, 'comment'),
+            (r'[(){}!,.:]', Punctuation),
+            (r'(«)([^»]+)(»)',
+             bygroups(Text, Name.Builtin, Text)),
+            (r'\b((?:considering|ignoring)\s*)'
+             r'(application responses|case|diacriticals|hyphens|'
+             r'numeric strings|punctuation|white space)',
+             bygroups(Keyword, Name.Builtin)),
+            (r'(-|\*|\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\^)', Operator),
+            (r"\b({})\b".format('|'.join(Operators)), Operator.Word),
+            (r'^(\s*(?:on|end)\s+)'
+             r'({})'.format('|'.join(StudioEvents[::-1])),
+             bygroups(Keyword, Name.Function)),
+            (r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)),
+            (r'\b(as )({})\b'.format('|'.join(Classes)),
+             bygroups(Keyword, Name.Class)),
+            (r'\b({})\b'.format('|'.join(Literals)), Name.Constant),
+            (r'\b({})\b'.format('|'.join(Commands)), Name.Builtin),
+            (r'\b({})\b'.format('|'.join(Control)), Keyword),
+            (r'\b({})\b'.format('|'.join(Declarations)), Keyword),
+            (r'\b({})\b'.format('|'.join(Reserved)), Name.Builtin),
+            (r'\b({})s?\b'.format('|'.join(BuiltIn)), Name.Builtin),
+            (r'\b({})\b'.format('|'.join(HandlerParams)), Name.Builtin),
+            (r'\b({})\b'.format('|'.join(StudioProperties)), Name.Attribute),
+            (r'\b({})s?\b'.format('|'.join(StudioClasses)), Name.Builtin),
+            (r'\b({})\b'.format('|'.join(StudioCommands)), Name.Builtin),
+            (r'\b({})\b'.format('|'.join(References)), Name.Builtin),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
+            (rf'\b({Identifiers})\b', Name.Variable),
+            (r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float),
+            (r'[-+]?\d+', Number.Integer),
+        ],
+        'comment': [
+            (r'\(\*', Comment.Multiline, '#push'),
+            (r'\*\)', Comment.Multiline, '#pop'),
+            ('[^*(]+', Comment.Multiline),
+            ('[*(]', Comment.Multiline),
+        ],
+    }
+
+
+class RexxLexer(RegexLexer):
+    """
+    Rexx is a scripting language available for
+    a wide range of different platforms with its roots found on mainframe
+    systems. It is popular for I/O- and data based tasks and can act as glue
+    language to bind different applications together.
+    """
+    name = 'Rexx'
+    url = 'http://www.rexxinfo.org/'
+    aliases = ['rexx', 'arexx']
+    filenames = ['*.rexx', '*.rex', '*.rx', '*.arexx']
+    mimetypes = ['text/x-rexx']
+    version_added = '2.0'
+    flags = re.IGNORECASE
+
+    tokens = {
+        'root': [
+            (r'\s+', Whitespace),
+            (r'/\*', Comment.Multiline, 'comment'),
+            (r'"', String, 'string_double'),
+            (r"'", String, 'string_single'),
+            (r'[0-9]+(\.[0-9]+)?(e[+-]?[0-9])?', Number),
+            (r'([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b',
+             bygroups(Name.Function, Whitespace, Operator, Whitespace,
+                      Keyword.Declaration)),
+            (r'([a-z_]\w*)(\s*)(:)',
+             bygroups(Name.Label, Whitespace, Operator)),
+            include('function'),
+            include('keyword'),
+            include('operator'),
+            (r'[a-z_]\w*', Text),
+        ],
+        'function': [
+            (words((
+                'abbrev', 'abs', 'address', 'arg', 'b2x', 'bitand', 'bitor', 'bitxor',
+                'c2d', 'c2x', 'center', 'charin', 'charout', 'chars', 'compare',
+                'condition', 'copies', 'd2c', 'd2x', 'datatype', 'date', 'delstr',
+                'delword', 'digits', 'errortext', 'form', 'format', 'fuzz', 'insert',
+                'lastpos', 'left', 'length', 'linein', 'lineout', 'lines', 'max',
+                'min', 'overlay', 'pos', 'queued', 'random', 'reverse', 'right', 'sign',
+                'sourceline', 'space', 'stream', 'strip', 'substr', 'subword', 'symbol',
+                'time', 'trace', 'translate', 'trunc', 'value', 'verify', 'word',
+                'wordindex', 'wordlength', 'wordpos', 'words', 'x2b', 'x2c', 'x2d',
+                'xrange'), suffix=r'(\s*)(\()'),
+             bygroups(Name.Builtin, Whitespace, Operator)),
+        ],
+        'keyword': [
+            (r'(address|arg|by|call|do|drop|else|end|exit|for|forever|if|'
+             r'interpret|iterate|leave|nop|numeric|off|on|options|parse|'
+             r'pull|push|queue|return|say|select|signal|to|then|trace|until|'
+             r'while)\b', Keyword.Reserved),
+        ],
+        'operator': [
+            (r'(-|//|/|\(|\)|\*\*|\*|\\<<|\\<|\\==|\\=|\\>>|\\>|\\|\|\||\||'
+             r'&&|&|%|\+|<<=|<<|<=|<>|<|==|=|><|>=|>>=|>>|>|¬<<|¬<|¬==|¬=|'
+             r'¬>>|¬>|¬|\.|,)', Operator),
+        ],
+        'string_double': [
+            (r'[^"\n]+', String),
+            (r'""', String),
+            (r'"', String, '#pop'),
+            (r'\n', Text, '#pop'),  # Stray linefeed also terminates strings.
+        ],
+        'string_single': [
+            (r'[^\'\n]+', String),
+            (r'\'\'', String),
+            (r'\'', String, '#pop'),
+            (r'\n', Text, '#pop'),  # Stray linefeed also terminates strings.
+        ],
+        'comment': [
+            (r'[^*]+', Comment.Multiline),
+            (r'\*/', Comment.Multiline, '#pop'),
+            (r'\*', Comment.Multiline),
+        ]
+    }
+
+    def _c(s):
+        return re.compile(s, re.MULTILINE)
+    _ADDRESS_COMMAND_PATTERN = _c(r'^\s*address\s+command\b')
+    _ADDRESS_PATTERN = _c(r'^\s*address\s+')
+    _DO_WHILE_PATTERN = _c(r'^\s*do\s+while\b')
+    _IF_THEN_DO_PATTERN = _c(r'^\s*if\b.+\bthen\s+do\s*$')
+    _PROCEDURE_PATTERN = _c(r'^\s*([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b')
+    _ELSE_DO_PATTERN = _c(r'\belse\s+do\s*$')
+    _PARSE_ARG_PATTERN = _c(r'^\s*parse\s+(upper\s+)?(arg|value)\b')
+    PATTERNS_AND_WEIGHTS = (
+        (_ADDRESS_COMMAND_PATTERN, 0.2),
+        (_ADDRESS_PATTERN, 0.05),
+        (_DO_WHILE_PATTERN, 0.1),
+        (_ELSE_DO_PATTERN, 0.1),
+        (_IF_THEN_DO_PATTERN, 0.1),
+        (_PROCEDURE_PATTERN, 0.5),
+        (_PARSE_ARG_PATTERN, 0.2),
+    )
+
+    def analyse_text(text):
+        """
+        Check for initial comment and patterns that distinguish Rexx from other
+        C-like languages.
+        """
+        if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE):
+            # Header matches MVS Rexx requirements, this is certainly a Rexx
+            # script.
+            return 1.0
+        elif text.startswith('/*'):
+            # Header matches general Rexx requirements; the source code might
+            # still be any language using C comments such as C++, C# or Java.
+            lowerText = text.lower()
+            result = sum(weight
+                         for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS
+                         if pattern.search(lowerText)) + 0.01
+            return min(result, 1.0)
+
+
+class MOOCodeLexer(RegexLexer):
+    """
+    For MOOCode (the MOO scripting language).
+    """
+    name = 'MOOCode'
+    url = 'http://www.moo.mud.org/'
+    filenames = ['*.moo']
+    aliases = ['moocode', 'moo']
+    mimetypes = ['text/x-moocode']
+    version_added = '0.9'
+
+    tokens = {
+        'root': [
+            # Numbers
+            (r'(0|[1-9][0-9_]*)', Number.Integer),
+            # Strings
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
+            # exceptions
+            (r'(E_PERM|E_DIV)', Name.Exception),
+            # db-refs
+            (r'((#[-0-9]+)|(\$\w+))', Name.Entity),
+            # Keywords
+            (r'\b(if|else|elseif|endif|for|endfor|fork|endfork|while'
+             r'|endwhile|break|continue|return|try'
+             r'|except|endtry|finally|in)\b', Keyword),
+            # builtins
+            (r'(random|length)', Name.Builtin),
+            # special variables
+            (r'(player|caller|this|args)', Name.Variable.Instance),
+            # skip whitespace
+            (r'\s+', Text),
+            (r'\n', Text),
+            # other operators
+            (r'([!;=,{}&|:.\[\]@()<>?]+)', Operator),
+            # function call
+            (r'(\w+)(\()', bygroups(Name.Function, Operator)),
+            # variables
+            (r'(\w+)', Text),
+        ]
+    }
+
+
+class HybrisLexer(RegexLexer):
+    """
+    For Hybris source code.
+    """
+
+    name = 'Hybris'
+    aliases = ['hybris']
+    filenames = ['*.hyb']
+    mimetypes = ['text/x-hybris', 'application/x-hybris']
+    url = 'https://github.com/evilsocket/hybris'
+    version_added = '1.4'
+
+    flags = re.MULTILINE | re.DOTALL
+
+    tokens = {
+        'root': [
+            # method names
+            (r'^(\s*(?:function|method|operator\s+)+?)'
+             r'([a-zA-Z_]\w*)'
+             r'(\s*)(\()', bygroups(Keyword, Name.Function, Text, Operator)),
+            (r'[^\S\n]+', Text),
+            (r'//.*?\n', Comment.Single),
+            (r'/\*.*?\*/', Comment.Multiline),
+            (r'@[a-zA-Z_][\w.]*', Name.Decorator),
+            (r'(break|case|catch|next|default|do|else|finally|for|foreach|of|'
+             r'unless|if|new|return|switch|me|throw|try|while)\b', Keyword),
+            (r'(extends|private|protected|public|static|throws|function|method|'
+             r'operator)\b', Keyword.Declaration),
+            (r'(true|false|null|__FILE__|__LINE__|__VERSION__|__LIB_PATH__|'
+             r'__INC_PATH__)\b', Keyword.Constant),
+            (r'(class|struct)(\s+)',
+             bygroups(Keyword.Declaration, Text), 'class'),
+            (r'(import|include)(\s+)',
+             bygroups(Keyword.Namespace, Text), 'import'),
+            (words((
+                'gc_collect', 'gc_mm_items', 'gc_mm_usage', 'gc_collect_threshold',
+                'urlencode', 'urldecode', 'base64encode', 'base64decode', 'sha1', 'crc32',
+                'sha2', 'md5', 'md5_file', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
+                'cosh', 'exp', 'fabs', 'floor', 'fmod', 'log', 'log10', 'pow', 'sin',
+                'sinh', 'sqrt', 'tan', 'tanh', 'isint', 'isfloat', 'ischar', 'isstring',
+                'isarray', 'ismap', 'isalias', 'typeof', 'sizeof', 'toint', 'tostring',
+                'fromxml', 'toxml', 'binary', 'pack', 'load', 'eval', 'var_names',
+                'var_values', 'user_functions', 'dyn_functions', 'methods', 'call',
+                'call_method', 'mknod', 'mkfifo', 'mount', 'umount2', 'umount', 'ticks',
+                'usleep', 'sleep', 'time', 'strtime', 'strdate', 'dllopen', 'dlllink',
+                'dllcall', 'dllcall_argv', 'dllclose', 'env', 'exec', 'fork', 'getpid',
+                'wait', 'popen', 'pclose', 'exit', 'kill', 'pthread_create',
+                'pthread_create_argv', 'pthread_exit', 'pthread_join', 'pthread_kill',
+                'smtp_send', 'http_get', 'http_post', 'http_download', 'socket', 'bind',
+                'listen', 'accept', 'getsockname', 'getpeername', 'settimeout', 'connect',
+                'server', 'recv', 'send', 'close', 'print', 'println', 'printf', 'input',
+                'readline', 'serial_open', 'serial_fcntl', 'serial_get_attr',
+                'serial_get_ispeed', 'serial_get_ospeed', 'serial_set_attr',
+                'serial_set_ispeed', 'serial_set_ospeed', 'serial_write', 'serial_read',
+                'serial_close', 'xml_load', 'xml_parse', 'fopen', 'fseek', 'ftell',
+                'fsize', 'fread', 'fwrite', 'fgets', 'fclose', 'file', 'readdir',
+                'pcre_replace', 'size', 'pop', 'unmap', 'has', 'keys', 'values',
+                'length', 'find', 'substr', 'replace', 'split', 'trim', 'remove',
+                'contains', 'join'), suffix=r'\b'),
+             Name.Builtin),
+            (words((
+                'MethodReference', 'Runner', 'Dll', 'Thread', 'Pipe', 'Process',
+                'Runnable', 'CGI', 'ClientSocket', 'Socket', 'ServerSocket',
+                'File', 'Console', 'Directory', 'Exception'), suffix=r'\b'),
+             Keyword.Type),
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
+            (r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char),
+            (r'(\.)([a-zA-Z_]\w*)',
+             bygroups(Operator, Name.Attribute)),
+            (r'[a-zA-Z_]\w*:', Name.Label),
+            (r'[a-zA-Z_$]\w*', Name),
+            (r'[~^*!%&\[\](){}<>|+=:;,./?\-@]+', Operator),
+            (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
+            (r'0x[0-9a-f]+', Number.Hex),
+            (r'[0-9]+L?', Number.Integer),
+            (r'\n', Text),
+        ],
+        'class': [
+            (r'[a-zA-Z_]\w*', Name.Class, '#pop')
+        ],
+        'import': [
+            (r'[\w.]+\*?', Name.Namespace, '#pop')
+        ],
+    }
+
+    def analyse_text(text):
+        """public method and private method don't seem to be quite common
+        elsewhere."""
+        result = 0
+        if re.search(r'\b(?:public|private)\s+method\b', text):
+            result += 0.01
+        return result
+
+
+
+class EasytrieveLexer(RegexLexer):
+    """
+    Easytrieve Plus is a programming language for extracting, filtering and
+    converting sequential data. Furthermore it can layout data for reports.
+    It is mainly used on mainframe platforms and can access several of the
+    mainframe's native file formats. It is somewhat comparable to awk.
+    """
+    name = 'Easytrieve'
+    aliases = ['easytrieve']
+    filenames = ['*.ezt', '*.mac']
+    mimetypes = ['text/x-easytrieve']
+    url = 'https://www.broadcom.com/products/mainframe/application-development/easytrieve-report-generator'
+    version_added = '2.1'
+    flags = 0
+
+    # Note: We cannot use r'\b' at the start and end of keywords because
+    # Easytrieve Plus delimiter characters are:
+    #
+    #   * space ( )
+    #   * apostrophe (')
+    #   * period (.)
+    #   * comma (,)
+    #   * parenthesis ( and )
+    #   * colon (:)
+    #
+    # Additionally words end once a '*' appears, indicatins a comment.
+    _DELIMITERS = r' \'.,():\n'
+    _DELIMITERS_OR_COMENT = _DELIMITERS + '*'
+    _DELIMITER_PATTERN = '[' + _DELIMITERS + ']'
+    _DELIMITER_PATTERN_CAPTURE = '(' + _DELIMITER_PATTERN + ')'
+    _NON_DELIMITER_OR_COMMENT_PATTERN = '[^' + _DELIMITERS_OR_COMENT + ']'
+    _OPERATORS_PATTERN = '[.+\\-/=\\[\\](){}<>;,&%¬]'
+    _KEYWORDS = [
+        'AFTER-BREAK', 'AFTER-LINE', 'AFTER-SCREEN', 'AIM', 'AND', 'ATTR',
+        'BEFORE', 'BEFORE-BREAK', 'BEFORE-LINE', 'BEFORE-SCREEN', 'BUSHU',
+        'BY', 'CALL', 'CASE', 'CHECKPOINT', 'CHKP', 'CHKP-STATUS', 'CLEAR',
+        'CLOSE', 'COL', 'COLOR', 'COMMIT', 'CONTROL', 'COPY', 'CURSOR', 'D',
+        'DECLARE', 'DEFAULT', 'DEFINE', 'DELETE', 'DENWA', 'DISPLAY', 'DLI',
+        'DO', 'DUPLICATE', 'E', 'ELSE', 'ELSE-IF', 'END', 'END-CASE',
+        'END-DO', 'END-IF', 'END-PROC', 'ENDPAGE', 'ENDTABLE', 'ENTER', 'EOF',
+        'EQ', 'ERROR', 'EXIT', 'EXTERNAL', 'EZLIB', 'F1', 'F10', 'F11', 'F12',
+        'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F2', 'F20', 'F21',
+        'F22', 'F23', 'F24', 'F25', 'F26', 'F27', 'F28', 'F29', 'F3', 'F30',
+        'F31', 'F32', 'F33', 'F34', 'F35', 'F36', 'F4', 'F5', 'F6', 'F7',
+        'F8', 'F9', 'FETCH', 'FILE-STATUS', 'FILL', 'FINAL', 'FIRST',
+        'FIRST-DUP', 'FOR', 'GE', 'GET', 'GO', 'GOTO', 'GQ', 'GR', 'GT',
+        'HEADING', 'HEX', 'HIGH-VALUES', 'IDD', 'IDMS', 'IF', 'IN', 'INSERT',
+        'JUSTIFY', 'KANJI-DATE', 'KANJI-DATE-LONG', 'KANJI-TIME', 'KEY',
+        'KEY-PRESSED', 'KOKUGO', 'KUN', 'LAST-DUP', 'LE', 'LEVEL', 'LIKE',
+        'LINE', 'LINE-COUNT', 'LINE-NUMBER', 'LINK', 'LIST', 'LOW-VALUES',
+        'LQ', 'LS', 'LT', 'MACRO', 'MASK', 'MATCHED', 'MEND', 'MESSAGE',
+        'MOVE', 'MSTART', 'NE', 'NEWPAGE', 'NOMASK', 'NOPRINT', 'NOT',
+        'NOTE', 'NOVERIFY', 'NQ', 'NULL', 'OF', 'OR', 'OTHERWISE', 'PA1',
+        'PA2', 'PA3', 'PAGE-COUNT', 'PAGE-NUMBER', 'PARM-REGISTER',
+        'PATH-ID', 'PATTERN', 'PERFORM', 'POINT', 'POS', 'PRIMARY', 'PRINT',
+        'PROCEDURE', 'PROGRAM', 'PUT', 'READ', 'RECORD', 'RECORD-COUNT',
+        'RECORD-LENGTH', 'REFRESH', 'RELEASE', 'RENUM', 'REPEAT', 'REPORT',
+        'REPORT-INPUT', 'RESHOW', 'RESTART', 'RETRIEVE', 'RETURN-CODE',
+        'ROLLBACK', 'ROW', 'S', 'SCREEN', 'SEARCH', 'SECONDARY', 'SELECT',
+        'SEQUENCE', 'SIZE', 'SKIP', 'SOKAKU', 'SORT', 'SQL', 'STOP', 'SUM',
+        'SYSDATE', 'SYSDATE-LONG', 'SYSIN', 'SYSIPT', 'SYSLST', 'SYSPRINT',
+        'SYSSNAP', 'SYSTIME', 'TALLY', 'TERM-COLUMNS', 'TERM-NAME',
+        'TERM-ROWS', 'TERMINATION', 'TITLE', 'TO', 'TRANSFER', 'TRC',
+        'UNIQUE', 'UNTIL', 'UPDATE', 'UPPERCASE', 'USER', 'USERID', 'VALUE',
+        'VERIFY', 'W', 'WHEN', 'WHILE', 'WORK', 'WRITE', 'X', 'XDM', 'XRST'
+    ]
+
+    tokens = {
+        'root': [
+            (r'\*.*\n', Comment.Single),
+            (r'\n+', Whitespace),
+            # Macro argument
+            (r'&' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+\.', Name.Variable,
+             'after_macro_argument'),
+            # Macro call
+            (r'%' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Variable),
+            (r'(FILE|MACRO|REPORT)(\s+)',
+             bygroups(Keyword.Declaration, Whitespace), 'after_declaration'),
+            (r'(JOB|PARM)' + r'(' + _DELIMITER_PATTERN + r')',
+             bygroups(Keyword.Declaration, Operator)),
+            (words(_KEYWORDS, suffix=_DELIMITER_PATTERN_CAPTURE),
+             bygroups(Keyword.Reserved, Operator)),
+            (_OPERATORS_PATTERN, Operator),
+            # Procedure declaration
+            (r'(' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+)(\s*)(\.?)(\s*)(PROC)(\s*\n)',
+             bygroups(Name.Function, Whitespace, Operator, Whitespace,
+                      Keyword.Declaration, Whitespace)),
+            (r'[0-9]+\.[0-9]*', Number.Float),
+            (r'[0-9]+', Number.Integer),
+            (r"'(''|[^'])*'", String),
+            (r'\s+', Whitespace),
+            # Everything else just belongs to a name
+            (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
+         ],
+        'after_declaration': [
+            (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Function),
+            default('#pop'),
+        ],
+        'after_macro_argument': [
+            (r'\*.*\n', Comment.Single, '#pop'),
+            (r'\s+', Whitespace, '#pop'),
+            (_OPERATORS_PATTERN, Operator, '#pop'),
+            (r"'(''|[^'])*'", String, '#pop'),
+            # Everything else just belongs to a name
+            (_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
+        ],
+    }
+    _COMMENT_LINE_REGEX = re.compile(r'^\s*\*')
+    _MACRO_HEADER_REGEX = re.compile(r'^\s*MACRO')
+
+    def analyse_text(text):
+        """
+        Perform a structural analysis for basic Easytrieve constructs.
+        """
+        result = 0.0
+        lines = text.split('\n')
+        hasEndProc = False
+        hasHeaderComment = False
+        hasFile = False
+        hasJob = False
+        hasProc = False
+        hasParm = False
+        hasReport = False
+
+        def isCommentLine(line):
+            return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None
+
+        def isEmptyLine(line):
+            return not bool(line.strip())
+
+        # Remove possible empty lines and header comments.
+        while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])):
+            if not isEmptyLine(lines[0]):
+                hasHeaderComment = True
+            del lines[0]
+
+        if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]):
+            # Looks like an Easytrieve macro.
+            result = 0.4
+            if hasHeaderComment:
+                result += 0.4
+        else:
+            # Scan the source for lines starting with indicators.
+            for line in lines:
+                words = line.split()
+                if (len(words) >= 2):
+                    firstWord = words[0]
+                    if not hasReport:
+                        if not hasJob:
+                            if not hasFile:
+                                if not hasParm:
+                                    if firstWord == 'PARM':
+                                        hasParm = True
+                                if firstWord == 'FILE':
+                                    hasFile = True
+                            if firstWord == 'JOB':
+                                hasJob = True
+                        elif firstWord == 'PROC':
+                            hasProc = True
+                        elif firstWord == 'END-PROC':
+                            hasEndProc = True
+                        elif firstWord == 'REPORT':
+                            hasReport = True
+
+            # Weight the findings.
+            if hasJob and (hasProc == hasEndProc):
+                if hasHeaderComment:
+                    result += 0.1
+                if hasParm:
+                    if hasProc:
+                        # Found PARM, JOB and PROC/END-PROC:
+                        # pretty sure this is Easytrieve.
+                        result += 0.8
+                    else:
+                        # Found PARAM and  JOB: probably this is Easytrieve
+                        result += 0.5
+                else:
+                    # Found JOB and possibly other keywords: might be Easytrieve
+                    result += 0.11
+                    if hasParm:
+                        # Note: PARAM is not a proper English word, so this is
+                        # regarded a much better indicator for Easytrieve than
+                        # the other words.
+                        result += 0.2
+                    if hasFile:
+                        result += 0.01
+                    if hasReport:
+                        result += 0.01
+        assert 0.0 <= result <= 1.0
+        return result
+
+
+class JclLexer(RegexLexer):
+    """
+    Job Control Language (JCL)
+    is a scripting language used on mainframe platforms to instruct the system
+    on how to run a batch job or start a subsystem. It is somewhat
+    comparable to MS DOS batch and Unix shell scripts.
+    """
+    name = 'JCL'
+    aliases = ['jcl']
+    filenames = ['*.jcl']
+    mimetypes = ['text/x-jcl']
+    url = 'https://en.wikipedia.org/wiki/Job_Control_Language'
+    version_added = '2.1'
+
+    flags = re.IGNORECASE
+
+    tokens = {
+        'root': [
+            (r'//\*.*\n', Comment.Single),
+            (r'//', Keyword.Pseudo, 'statement'),
+            (r'/\*', Keyword.Pseudo, 'jes2_statement'),
+            # TODO: JES3 statement
+            (r'.*\n', Other)  # Input text or inline code in any language.
+        ],
+        'statement': [
+            (r'\s*\n', Whitespace, '#pop'),
+            (r'([a-z]\w*)(\s+)(exec|job)(\s*)',
+             bygroups(Name.Label, Whitespace, Keyword.Reserved, Whitespace),
+             'option'),
+            (r'[a-z]\w*', Name.Variable, 'statement_command'),
+            (r'\s+', Whitespace, 'statement_command'),
+        ],
+        'statement_command': [
+            (r'\s+(command|cntl|dd|endctl|endif|else|include|jcllib|'
+             r'output|pend|proc|set|then|xmit)\s+', Keyword.Reserved, 'option'),
+            include('option')
+        ],
+        'jes2_statement': [
+            (r'\s*\n', Whitespace, '#pop'),
+            (r'\$', Keyword, 'option'),
+            (r'\b(jobparam|message|netacct|notify|output|priority|route|'
+             r'setup|signoff|xeq|xmit)\b', Keyword, 'option'),
+        ],
+        'option': [
+            # (r'\n', Text, 'root'),
+            (r'\*', Name.Builtin),
+            (r'[\[\](){}<>;,]', Punctuation),
+            (r'[-+*/=&%]', Operator),
+            (r'[a-z_]\w*', Name),
+            (r'\d+\.\d*', Number.Float),
+            (r'\.\d+', Number.Float),
+            (r'\d+', Number.Integer),
+            (r"'", String, 'option_string'),
+            (r'[ \t]+', Whitespace, 'option_comment'),
+            (r'\.', Punctuation),
+        ],
+        'option_string': [
+            (r"(\n)(//)", bygroups(Text, Keyword.Pseudo)),
+            (r"''", String),
+            (r"[^']", String),
+            (r"'", String, '#pop'),
+        ],
+        'option_comment': [
+            # (r'\n', Text, 'root'),
+            (r'.+', Comment.Single),
+        ]
+    }
+
+    _JOB_HEADER_PATTERN = re.compile(r'^//[a-z#$@][a-z0-9#$@]{0,7}\s+job(\s+.*)?$',
+                                     re.IGNORECASE)
+
+    def analyse_text(text):
+        """
+        Recognize JCL job by header.
+        """
+        result = 0.0
+        lines = text.split('\n')
+        if len(lines) > 0:
+            if JclLexer._JOB_HEADER_PATTERN.match(lines[0]):
+                result = 1.0
+        assert 0.0 <= result <= 1.0
+        return result
+
+
+class MiniScriptLexer(RegexLexer):
+    """
+    For MiniScript source code.
+    """
+
+    name = 'MiniScript'
+    url = 'https://miniscript.org'
+    aliases = ['miniscript', 'ms']
+    filenames = ['*.ms']
+    mimetypes = ['text/x-minicript', 'application/x-miniscript']
+    version_added = '2.6'
+
+    tokens = {
+        'root': [
+            (r'#!(.*?)$', Comment.Preproc),
+            default('base'),
+        ],
+        'base': [
+            ('//.*$', Comment.Single),
+            (r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number),
+            (r'(?i)\d+e[+-]?\d+', Number),
+            (r'\d+', Number),
+            (r'\n', Text),
+            (r'[^\S\n]+', Text),
+            (r'"', String, 'string_double'),
+            (r'(==|!=|<=|>=|[=+\-*/%^<>.:])', Operator),
+            (r'[;,\[\]{}()]', Punctuation),
+            (words((
+                'break', 'continue', 'else', 'end', 'for', 'function', 'if',
+                'in', 'isa', 'then', 'repeat', 'return', 'while'), suffix=r'\b'),
+             Keyword),
+            (words((
+                'abs', 'acos', 'asin', 'atan', 'ceil', 'char', 'cos', 'floor',
+                'log', 'round', 'rnd', 'pi', 'sign', 'sin', 'sqrt', 'str', 'tan',
+                'hasIndex', 'indexOf', 'len', 'val', 'code', 'remove', 'lower',
+                'upper', 'replace', 'split', 'indexes', 'values', 'join', 'sum',
+                'sort', 'shuffle', 'push', 'pop', 'pull', 'range',
+                'print', 'input', 'time', 'wait', 'locals', 'globals', 'outer',
+                'yield'), suffix=r'\b'),
+             Name.Builtin),
+            (r'(true|false|null)\b', Keyword.Constant),
+            (r'(and|or|not|new)\b', Operator.Word),
+            (r'(self|super|__isa)\b', Name.Builtin.Pseudo),
+            (r'[a-zA-Z_]\w*', Name.Variable)
+        ],
+        'string_double': [
+            (r'[^"\n]+', String),
+            (r'""', String),
+            (r'"', String, '#pop'),
+            (r'\n', Text, '#pop'),  # Stray linefeed also terminates strings.
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/sgf.py b/lib/python3.11/site-packages/pygments/lexers/sgf.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d7c30432cc39e99f3cacebde19db1550c814ac8
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/sgf.py
@@ -0,0 +1,59 @@
+"""
+    pygments.lexers.sgf
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Smart Game Format (sgf) file format.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups
+from pygments.token import Name, Literal, String, Punctuation, Whitespace
+
+__all__ = ["SmartGameFormatLexer"]
+
+
+class SmartGameFormatLexer(RegexLexer):
+    """
+    Lexer for Smart Game Format (sgf) file format.
+
+    The format is used to store game records of board games for two players
+    (mainly Go game).
+    """
+    name = 'SmartGameFormat'
+    url = 'https://www.red-bean.com/sgf/'
+    aliases = ['sgf']
+    filenames = ['*.sgf']
+    version_added = '2.4'
+
+    tokens = {
+        'root': [
+            (r'[():;]+', Punctuation),
+            # tokens:
+            (r'(A[BW]|AE|AN|AP|AR|AS|[BW]L|BM|[BW]R|[BW]S|[BW]T|CA|CH|CP|CR|'
+             r'DD|DM|DO|DT|EL|EV|EX|FF|FG|G[BW]|GC|GM|GN|HA|HO|ID|IP|IT|IY|KM|'
+             r'KO|LB|LN|LT|L|MA|MN|M|N|OB|OM|ON|OP|OT|OV|P[BW]|PC|PL|PM|RE|RG|'
+             r'RO|RU|SO|SC|SE|SI|SL|SO|SQ|ST|SU|SZ|T[BW]|TC|TE|TM|TR|UC|US|VW|'
+             r'V|[BW]|C)',
+             Name.Builtin),
+            # number:
+            (r'(\[)([0-9.]+)(\])',
+             bygroups(Punctuation, Literal.Number, Punctuation)),
+            # date:
+            (r'(\[)([0-9]{4}-[0-9]{2}-[0-9]{2})(\])',
+             bygroups(Punctuation, Literal.Date, Punctuation)),
+            # point:
+            (r'(\[)([a-z]{2})(\])',
+             bygroups(Punctuation, String, Punctuation)),
+            # double points:
+            (r'(\[)([a-z]{2})(:)([a-z]{2})(\])',
+             bygroups(Punctuation, String, Punctuation, String, Punctuation)),
+
+            (r'(\[)([\w\s#()+,\-.:?]+)(\])',
+             bygroups(Punctuation, String, Punctuation)),
+            (r'(\[)(\s.*)(\])',
+             bygroups(Punctuation, Whitespace, Punctuation)),
+            (r'\s+', Whitespace)
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/shell.py b/lib/python3.11/site-packages/pygments/lexers/shell.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1ce07fcc8aa5ac7aab453df30af21f94d859f3e
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/shell.py
@@ -0,0 +1,902 @@
+"""
+    pygments.lexers.shell
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for various shells.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, \
+    include, default, this, using, words, line_re
+from pygments.token import Punctuation, Whitespace, \
+    Text, Comment, Operator, Keyword, Name, String, Number, Generic
+from pygments.util import shebang_matches
+
+__all__ = ['BashLexer', 'BashSessionLexer', 'TcshLexer', 'BatchLexer',
+           'SlurmBashLexer', 'MSDOSSessionLexer', 'PowerShellLexer',
+           'PowerShellSessionLexer', 'TcshSessionLexer', 'FishShellLexer',
+           'ExeclineLexer']
+
+
+class BashLexer(RegexLexer):
+    """
+    Lexer for (ba|k|z|)sh shell scripts.
+    """
+
+    name = 'Bash'
+    aliases = ['bash', 'sh', 'ksh', 'zsh', 'shell', 'openrc']
+    filenames = ['*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass',
+                 '*.exheres-0', '*.exlib', '*.zsh',
+                 '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc',
+                 '.kshrc', 'kshrc',
+                 'PKGBUILD']
+    mimetypes = ['application/x-sh', 'application/x-shellscript', 'text/x-shellscript']
+    url = 'https://en.wikipedia.org/wiki/Unix_shell'
+    version_added = '0.6'
+
+    tokens = {
+        'root': [
+            include('basic'),
+            (r'`', String.Backtick, 'backticks'),
+            include('data'),
+            include('interp'),
+        ],
+        'interp': [
+            (r'\$\(\(', Keyword, 'math'),
+            (r'\$\(', Keyword, 'paren'),
+            (r'\$\{#?', String.Interpol, 'curly'),
+            (r'\$[a-zA-Z_]\w*', Name.Variable),  # user variable
+            (r'\$(?:\d+|[#$?!_*@-])', Name.Variable),      # builtin
+            (r'\$', Text),
+        ],
+        'basic': [
+            (r'\b(if|fi|else|while|in|do|done|for|then|return|function|case|'
+             r'select|break|continue|until|esac|elif)(\s*)\b',
+             bygroups(Keyword, Whitespace)),
+            (r'\b(alias|bg|bind|builtin|caller|cd|command|compgen|'
+             r'complete|declare|dirs|disown|echo|enable|eval|exec|exit|'
+             r'export|false|fc|fg|getopts|hash|help|history|jobs|kill|let|'
+             r'local|logout|popd|printf|pushd|pwd|read|readonly|set|shift|'
+             r'shopt|source|suspend|test|time|times|trap|true|type|typeset|'
+             r'ulimit|umask|unalias|unset|wait)(?=[\s)`])',
+             Name.Builtin),
+            (r'\A#!.+\n', Comment.Hashbang),
+            (r'#.*\n', Comment.Single),
+            (r'\\[\w\W]', String.Escape),
+            (r'(\b\w+)(\s*)(\+?=)', bygroups(Name.Variable, Whitespace, Operator)),
+            (r'[\[\]{}()=]', Operator),
+            (r'<<<', Operator),  # here-string
+            (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
+            (r'&&|\|\|', Operator),
+        ],
+        'data': [
+            (r'(?s)\$?"(\\.|[^"\\$])*"', String.Double),
+            (r'"', String.Double, 'string'),
+            (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
+            (r"(?s)'.*?'", String.Single),
+            (r';', Punctuation),
+            (r'&', Punctuation),
+            (r'\|', Punctuation),
+            (r'\s+', Whitespace),
+            (r'\d+\b', Number),
+            (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text),
+            (r'<', Text),
+        ],
+        'string': [
+            (r'"', String.Double, '#pop'),
+            (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double),
+            include('interp'),
+        ],
+        'curly': [
+            (r'\}', String.Interpol, '#pop'),
+            (r':-', Keyword),
+            (r'\w+', Name.Variable),
+            (r'[^}:"\'`$\\]+', Punctuation),
+            (r':', Punctuation),
+            include('root'),
+        ],
+        'paren': [
+            (r'\)', Keyword, '#pop'),
+            include('root'),
+        ],
+        'math': [
+            (r'\)\)', Keyword, '#pop'),
+            (r'\*\*|\|\||<<|>>|[-+*/%^|&<>]', Operator),
+            (r'\d+#[\da-zA-Z]+', Number),
+            (r'\d+#(?! )', Number),
+            (r'0[xX][\da-fA-F]+', Number),
+            (r'\d+', Number),
+            (r'[a-zA-Z_]\w*', Name.Variable),  # user variable
+            include('root'),
+        ],
+        'backticks': [
+            (r'`', String.Backtick, '#pop'),
+            include('root'),
+        ],
+    }
+
+    def analyse_text(text):
+        if shebang_matches(text, r'(ba|z|)sh'):
+            return 1
+        if text.startswith('$ '):
+            return 0.2
+
+
+class SlurmBashLexer(BashLexer):
+    """
+    Lexer for (ba|k|z|)sh Slurm scripts.
+    """
+
+    name = 'Slurm'
+    aliases = ['slurm', 'sbatch']
+    filenames = ['*.sl']
+    mimetypes = []
+    version_added = '2.4'
+    EXTRA_KEYWORDS = {'srun'}
+
+    def get_tokens_unprocessed(self, text):
+        for index, token, value in BashLexer.get_tokens_unprocessed(self, text):
+            if token is Text and value in self.EXTRA_KEYWORDS:
+                yield index, Name.Builtin, value
+            elif token is Comment.Single and 'SBATCH' in value:
+                yield index, Keyword.Pseudo, value
+            else:
+                yield index, token, value
+
+
+class ShellSessionBaseLexer(Lexer):
+    """
+    Base lexer for shell sessions.
+
+    .. versionadded:: 2.1
+    """
+
+    _bare_continuation = False
+    _venv = re.compile(r'^(\([^)]*\))(\s*)')
+
+    def get_tokens_unprocessed(self, text):
+        innerlexer = self._innerLexerCls(**self.options)
+
+        pos = 0
+        curcode = ''
+        insertions = []
+        backslash_continuation = False
+
+        for match in line_re.finditer(text):
+            line = match.group()
+
+            venv_match = self._venv.match(line)
+            if venv_match:
+                venv = venv_match.group(1)
+                venv_whitespace = venv_match.group(2)
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt.VirtualEnv, venv)]))
+                if venv_whitespace:
+                    insertions.append((len(curcode),
+                                       [(0, Text, venv_whitespace)]))
+                line = line[venv_match.end():]
+
+            m = self._ps1rgx.match(line)
+            if m:
+                # To support output lexers (say diff output), the output
+                # needs to be broken by prompts whenever the output lexer
+                # changes.
+                if not insertions:
+                    pos = match.start()
+
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, m.group(1))]))
+                curcode += m.group(2)
+                backslash_continuation = curcode.endswith('\\\n')
+            elif backslash_continuation:
+                if line.startswith(self._ps2):
+                    insertions.append((len(curcode),
+                                       [(0, Generic.Prompt,
+                                         line[:len(self._ps2)])]))
+                    curcode += line[len(self._ps2):]
+                else:
+                    curcode += line
+                backslash_continuation = curcode.endswith('\\\n')
+            elif self._bare_continuation and line.startswith(self._ps2):
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt,
+                                     line[:len(self._ps2)])]))
+                curcode += line[len(self._ps2):]
+            else:
+                if insertions:
+                    toks = innerlexer.get_tokens_unprocessed(curcode)
+                    for i, t, v in do_insertions(insertions, toks):
+                        yield pos+i, t, v
+                yield match.start(), Generic.Output, line
+                insertions = []
+                curcode = ''
+        if insertions:
+            for i, t, v in do_insertions(insertions,
+                                         innerlexer.get_tokens_unprocessed(curcode)):
+                yield pos+i, t, v
+
+
+class BashSessionLexer(ShellSessionBaseLexer):
+    """
+    Lexer for Bash shell sessions, i.e. command lines, including a
+    prompt, interspersed with output.
+    """
+
+    name = 'Bash Session'
+    aliases = ['console', 'shell-session']
+    filenames = ['*.sh-session', '*.shell-session']
+    mimetypes = ['application/x-shell-session', 'application/x-sh-session']
+    url = 'https://en.wikipedia.org/wiki/Unix_shell'
+    version_added = '1.1'
+    _example = "console/example.sh-session"
+
+    _innerLexerCls = BashLexer
+    _ps1rgx = re.compile(
+        r'^((?:(?:\[.*?\])|(?:\(\S+\))?(?:| |sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)' \
+        r'?|\[\S+[@:][^\n]+\].+))\s*[$#%]\s*)(.*\n?)')
+    _ps2 = '> '
+
+
+class BatchLexer(RegexLexer):
+    """
+    Lexer for the DOS/Windows Batch file format.
+    """
+    name = 'Batchfile'
+    aliases = ['batch', 'bat', 'dosbatch', 'winbatch']
+    filenames = ['*.bat', '*.cmd']
+    mimetypes = ['application/x-dos-batch']
+    url = 'https://en.wikipedia.org/wiki/Batch_file'
+    version_added = '0.7'
+
+    flags = re.MULTILINE | re.IGNORECASE
+
+    _nl = r'\n\x1a'
+    _punct = r'&<>|'
+    _ws = r'\t\v\f\r ,;=\xa0'
+    _nlws = r'\s\x1a\xa0,;='
+    _space = rf'(?:(?:(?:\^[{_nl}])?[{_ws}])+)'
+    _keyword_terminator = (rf'(?=(?:\^[{_nl}]?)?[{_ws}+./:[\\\]]|[{_nl}{_punct}(])')
+    _token_terminator = rf'(?=\^?[{_ws}]|[{_punct}{_nl}])'
+    _start_label = rf'((?:(?<=^[^:])|^[^:]?)[{_ws}]*)(:)'
+    _label = rf'(?:(?:[^{_nlws}{_punct}+:^]|\^[{_nl}]?[\w\W])*)'
+    _label_compound = rf'(?:(?:[^{_nlws}{_punct}+:^)]|\^[{_nl}]?[^)])*)'
+    _number = rf'(?:-?(?:0[0-7]+|0x[\da-f]+|\d+){_token_terminator})'
+    _opword = r'(?:equ|geq|gtr|leq|lss|neq)'
+    _string = rf'(?:"[^{_nl}"]*(?:"|(?=[{_nl}])))'
+    _variable = (r'(?:(?:%(?:\*|(?:~[a-z]*(?:\$[^:]+:)?)?\d|'
+                 rf'[^%:{_nl}]+(?::(?:~(?:-?\d+)?(?:,(?:-?\d+)?)?|(?:[^%{_nl}^]|'
+                 rf'\^[^%{_nl}])[^={_nl}]*=(?:[^%{_nl}^]|\^[^%{_nl}])*)?)?%))|'
+                 rf'(?:\^?![^!:{_nl}]+(?::(?:~(?:-?\d+)?(?:,(?:-?\d+)?)?|(?:'
+                 rf'[^!{_nl}^]|\^[^!{_nl}])[^={_nl}]*=(?:[^!{_nl}^]|\^[^!{_nl}])*)?)?\^?!))')
+    _core_token = rf'(?:(?:(?:\^[{_nl}]?)?[^"{_nlws}{_punct}])+)'
+    _core_token_compound = rf'(?:(?:(?:\^[{_nl}]?)?[^"{_nlws}{_punct})])+)'
+    _token = rf'(?:[{_punct}]+|{_core_token})'
+    _token_compound = rf'(?:[{_punct}]+|{_core_token_compound})'
+    _stoken = (rf'(?:[{_punct}]+|(?:{_string}|{_variable}|{_core_token})+)')
+
+    def _make_begin_state(compound, _core_token=_core_token,
+                          _core_token_compound=_core_token_compound,
+                          _keyword_terminator=_keyword_terminator,
+                          _nl=_nl, _punct=_punct, _string=_string,
+                          _space=_space, _start_label=_start_label,
+                          _stoken=_stoken, _token_terminator=_token_terminator,
+                          _variable=_variable, _ws=_ws):
+        rest = '(?:{}|{}|[^"%{}{}{}])*'.format(_string, _variable, _nl, _punct,
+                                            ')' if compound else '')
+        rest_of_line = rf'(?:(?:[^{_nl}^]|\^[{_nl}]?[\w\W])*)'
+        rest_of_line_compound = rf'(?:(?:[^{_nl}^)]|\^[{_nl}]?[^)])*)'
+        set_space = rf'((?:(?:\^[{_nl}]?)?[^\S\n])*)'
+        suffix = ''
+        if compound:
+            _keyword_terminator = rf'(?:(?=\))|{_keyword_terminator})'
+            _token_terminator = rf'(?:(?=\))|{_token_terminator})'
+            suffix = '/compound'
+        return [
+            ((r'\)', Punctuation, '#pop') if compound else
+             (rf'\)((?=\()|{_token_terminator}){rest_of_line}',
+              Comment.Single)),
+            (rf'(?={_start_label})', Text, f'follow{suffix}'),
+            (_space, using(this, state='text')),
+            include(f'redirect{suffix}'),
+            (rf'[{_nl}]+', Text),
+            (r'\(', Punctuation, 'root/compound'),
+            (r'@+', Punctuation),
+            (rf'((?:for|if|rem)(?:(?=(?:\^[{_nl}]?)?/)|(?:(?!\^)|'
+             rf'(?<=m))(?:(?=\()|{_token_terminator})))({_space}?{_core_token_compound if compound else _core_token}?(?:\^[{_nl}]?)?/(?:\^[{_nl}]?)?\?)',
+             bygroups(Keyword, using(this, state='text')),
+             f'follow{suffix}'),
+            (rf'(goto{_keyword_terminator})({rest}(?:\^[{_nl}]?)?/(?:\^[{_nl}]?)?\?{rest})',
+             bygroups(Keyword, using(this, state='text')),
+             f'follow{suffix}'),
+            (words(('assoc', 'break', 'cd', 'chdir', 'cls', 'color', 'copy',
+                    'date', 'del', 'dir', 'dpath', 'echo', 'endlocal', 'erase',
+                    'exit', 'ftype', 'keys', 'md', 'mkdir', 'mklink', 'move',
+                    'path', 'pause', 'popd', 'prompt', 'pushd', 'rd', 'ren',
+                    'rename', 'rmdir', 'setlocal', 'shift', 'start', 'time',
+                    'title', 'type', 'ver', 'verify', 'vol'),
+                   suffix=_keyword_terminator), Keyword, f'follow{suffix}'),
+            (rf'(call)({_space}?)(:)',
+             bygroups(Keyword, using(this, state='text'), Punctuation),
+             f'call{suffix}'),
+            (rf'call{_keyword_terminator}', Keyword),
+            (rf'(for{_token_terminator}(?!\^))({_space})(/f{_token_terminator})',
+             bygroups(Keyword, using(this, state='text'), Keyword),
+             ('for/f', 'for')),
+            (rf'(for{_token_terminator}(?!\^))({_space})(/l{_token_terminator})',
+             bygroups(Keyword, using(this, state='text'), Keyword),
+             ('for/l', 'for')),
+            (rf'for{_token_terminator}(?!\^)', Keyword, ('for2', 'for')),
+            (rf'(goto{_keyword_terminator})({_space}?)(:?)',
+             bygroups(Keyword, using(this, state='text'), Punctuation),
+             f'label{suffix}'),
+            (rf'(if(?:(?=\()|{_token_terminator})(?!\^))({_space}?)((?:/i{_token_terminator})?)({_space}?)((?:not{_token_terminator})?)({_space}?)',
+             bygroups(Keyword, using(this, state='text'), Keyword,
+                      using(this, state='text'), Keyword,
+                      using(this, state='text')), ('(?', 'if')),
+            (rf'rem(((?=\()|{_token_terminator}){_space}?{_stoken}?.*|{_keyword_terminator}{rest_of_line_compound if compound else rest_of_line})',
+             Comment.Single, f'follow{suffix}'),
+            (rf'(set{_keyword_terminator}){set_space}(/a)',
+             bygroups(Keyword, using(this, state='text'), Keyword),
+             f'arithmetic{suffix}'),
+            (r'(set{}){}((?:/p)?){}((?:(?:(?:\^[{}]?)?[^"{}{}^={}]|'
+             r'\^[{}]?[^"=])+)?)((?:(?:\^[{}]?)?=)?)'.format(_keyword_terminator, set_space, set_space, _nl, _nl, _punct,
+              ')' if compound else '', _nl, _nl),
+             bygroups(Keyword, using(this, state='text'), Keyword,
+                      using(this, state='text'), using(this, state='variable'),
+                      Punctuation),
+             f'follow{suffix}'),
+            default(f'follow{suffix}')
+        ]
+
+    def _make_follow_state(compound, _label=_label,
+                           _label_compound=_label_compound, _nl=_nl,
+                           _space=_space, _start_label=_start_label,
+                           _token=_token, _token_compound=_token_compound,
+                           _ws=_ws):
+        suffix = '/compound' if compound else ''
+        state = []
+        if compound:
+            state.append((r'(?=\))', Text, '#pop'))
+        state += [
+            (rf'{_start_label}([{_ws}]*)({_label_compound if compound else _label})(.*)',
+             bygroups(Text, Punctuation, Text, Name.Label, Comment.Single)),
+            include(f'redirect{suffix}'),
+            (rf'(?=[{_nl}])', Text, '#pop'),
+            (r'\|\|?|&&?', Punctuation, '#pop'),
+            include('text')
+        ]
+        return state
+
+    def _make_arithmetic_state(compound, _nl=_nl, _punct=_punct,
+                               _string=_string, _variable=_variable,
+                               _ws=_ws, _nlws=_nlws):
+        op = r'=+\-*/!~'
+        state = []
+        if compound:
+            state.append((r'(?=\))', Text, '#pop'))
+        state += [
+            (r'0[0-7]+', Number.Oct),
+            (r'0x[\da-f]+', Number.Hex),
+            (r'\d+', Number.Integer),
+            (r'[(),]+', Punctuation),
+            (rf'([{op}]|%|\^\^)+', Operator),
+            (r'({}|{}|(\^[{}]?)?[^(){}%\^"{}{}]|\^[{}]?{})+'.format(_string, _variable, _nl, op, _nlws, _punct, _nlws,
+              r'[^)]' if compound else r'[\w\W]'),
+             using(this, state='variable')),
+            (r'(?=[\x00|&])', Text, '#pop'),
+            include('follow')
+        ]
+        return state
+
+    def _make_call_state(compound, _label=_label,
+                         _label_compound=_label_compound):
+        state = []
+        if compound:
+            state.append((r'(?=\))', Text, '#pop'))
+        state.append((r'(:?)(%s)' % (_label_compound if compound else _label),
+                      bygroups(Punctuation, Name.Label), '#pop'))
+        return state
+
+    def _make_label_state(compound, _label=_label,
+                          _label_compound=_label_compound, _nl=_nl,
+                          _punct=_punct, _string=_string, _variable=_variable):
+        state = []
+        if compound:
+            state.append((r'(?=\))', Text, '#pop'))
+        state.append((r'({}?)((?:{}|{}|\^[{}]?{}|[^"%^{}{}{}])*)'.format(_label_compound if compound else _label, _string,
+                       _variable, _nl, r'[^)]' if compound else r'[\w\W]', _nl,
+                       _punct, r')' if compound else ''),
+                      bygroups(Name.Label, Comment.Single), '#pop'))
+        return state
+
+    def _make_redirect_state(compound,
+                             _core_token_compound=_core_token_compound,
+                             _nl=_nl, _punct=_punct, _stoken=_stoken,
+                             _string=_string, _space=_space,
+                             _variable=_variable, _nlws=_nlws):
+        stoken_compound = (rf'(?:[{_punct}]+|(?:{_string}|{_variable}|{_core_token_compound})+)')
+        return [
+            (rf'((?:(?<=[{_nlws}])\d)?)(>>?&|<&)([{_nlws}]*)(\d)',
+             bygroups(Number.Integer, Punctuation, Text, Number.Integer)),
+            (rf'((?:(?<=[{_nlws}])(?>?|<)({_space}?{stoken_compound if compound else _stoken})',
+             bygroups(Number.Integer, Punctuation, using(this, state='text')))
+        ]
+
+    tokens = {
+        'root': _make_begin_state(False),
+        'follow': _make_follow_state(False),
+        'arithmetic': _make_arithmetic_state(False),
+        'call': _make_call_state(False),
+        'label': _make_label_state(False),
+        'redirect': _make_redirect_state(False),
+        'root/compound': _make_begin_state(True),
+        'follow/compound': _make_follow_state(True),
+        'arithmetic/compound': _make_arithmetic_state(True),
+        'call/compound': _make_call_state(True),
+        'label/compound': _make_label_state(True),
+        'redirect/compound': _make_redirect_state(True),
+        'variable-or-escape': [
+            (_variable, Name.Variable),
+            (rf'%%|\^[{_nl}]?(\^!|[\w\W])', String.Escape)
+        ],
+        'string': [
+            (r'"', String.Double, '#pop'),
+            (_variable, Name.Variable),
+            (r'\^!|%%', String.Escape),
+            (rf'[^"%^{_nl}]+|[%^]', String.Double),
+            default('#pop')
+        ],
+        'sqstring': [
+            include('variable-or-escape'),
+            (r'[^%]+|%', String.Single)
+        ],
+        'bqstring': [
+            include('variable-or-escape'),
+            (r'[^%]+|%', String.Backtick)
+        ],
+        'text': [
+            (r'"', String.Double, 'string'),
+            include('variable-or-escape'),
+            (rf'[^"%^{_nlws}{_punct}\d)]+|.', Text)
+        ],
+        'variable': [
+            (r'"', String.Double, 'string'),
+            include('variable-or-escape'),
+            (rf'[^"%^{_nl}]+|.', Name.Variable)
+        ],
+        'for': [
+            (rf'({_space})(in)({_space})(\()',
+             bygroups(using(this, state='text'), Keyword,
+                      using(this, state='text'), Punctuation), '#pop'),
+            include('follow')
+        ],
+        'for2': [
+            (r'\)', Punctuation),
+            (rf'({_space})(do{_token_terminator})',
+             bygroups(using(this, state='text'), Keyword), '#pop'),
+            (rf'[{_nl}]+', Text),
+            include('follow')
+        ],
+        'for/f': [
+            (rf'(")((?:{_variable}|[^"])*?")([{_nlws}]*)(\))',
+             bygroups(String.Double, using(this, state='string'), Text,
+                      Punctuation)),
+            (r'"', String.Double, ('#pop', 'for2', 'string')),
+            (rf"('(?:%%|{_variable}|[\w\W])*?')([{_nlws}]*)(\))",
+             bygroups(using(this, state='sqstring'), Text, Punctuation)),
+            (rf'(`(?:%%|{_variable}|[\w\W])*?`)([{_nlws}]*)(\))',
+             bygroups(using(this, state='bqstring'), Text, Punctuation)),
+            include('for2')
+        ],
+        'for/l': [
+            (r'-?\d+', Number.Integer),
+            include('for2')
+        ],
+        'if': [
+            (rf'((?:cmdextversion|errorlevel){_token_terminator})({_space})(\d+)',
+             bygroups(Keyword, using(this, state='text'),
+                      Number.Integer), '#pop'),
+            (rf'(defined{_token_terminator})({_space})({_stoken})',
+             bygroups(Keyword, using(this, state='text'),
+                      using(this, state='variable')), '#pop'),
+            (rf'(exist{_token_terminator})({_space}{_stoken})',
+             bygroups(Keyword, using(this, state='text')), '#pop'),
+            (rf'({_number}{_space})({_opword})({_space}{_number})',
+             bygroups(using(this, state='arithmetic'), Operator.Word,
+                      using(this, state='arithmetic')), '#pop'),
+            (_stoken, using(this, state='text'), ('#pop', 'if2')),
+        ],
+        'if2': [
+            (rf'({_space}?)(==)({_space}?{_stoken})',
+             bygroups(using(this, state='text'), Operator,
+                      using(this, state='text')), '#pop'),
+            (rf'({_space})({_opword})({_space}{_stoken})',
+             bygroups(using(this, state='text'), Operator.Word,
+                      using(this, state='text')), '#pop')
+        ],
+        '(?': [
+            (_space, using(this, state='text')),
+            (r'\(', Punctuation, ('#pop', 'else?', 'root/compound')),
+            default('#pop')
+        ],
+        'else?': [
+            (_space, using(this, state='text')),
+            (rf'else{_token_terminator}', Keyword, '#pop'),
+            default('#pop')
+        ]
+    }
+
+
+class MSDOSSessionLexer(ShellSessionBaseLexer):
+    """
+    Lexer for MS DOS shell sessions, i.e. command lines, including a
+    prompt, interspersed with output.
+    """
+
+    name = 'MSDOS Session'
+    aliases = ['doscon']
+    filenames = []
+    mimetypes = []
+    url = 'https://en.wikipedia.org/wiki/MS-DOS'
+    version_added = '2.1'
+    _example = "doscon/session"
+
+    _innerLexerCls = BatchLexer
+    _ps1rgx = re.compile(r'^([^>]*>)(.*\n?)')
+    _ps2 = 'More? '
+
+
+class TcshLexer(RegexLexer):
+    """
+    Lexer for tcsh scripts.
+    """
+
+    name = 'Tcsh'
+    aliases = ['tcsh', 'csh']
+    filenames = ['*.tcsh', '*.csh']
+    mimetypes = ['application/x-csh']
+    url = 'https://www.tcsh.org'
+    version_added = '0.10'
+
+    tokens = {
+        'root': [
+            include('basic'),
+            (r'\$\(', Keyword, 'paren'),
+            (r'\$\{#?', Keyword, 'curly'),
+            (r'`', String.Backtick, 'backticks'),
+            include('data'),
+        ],
+        'basic': [
+            (r'\b(if|endif|else|while|then|foreach|case|default|'
+             r'break|continue|goto|breaksw|end|switch|endsw)\s*\b',
+             Keyword),
+            (r'\b(alias|alloc|bg|bindkey|builtins|bye|caller|cd|chdir|'
+             r'complete|dirs|echo|echotc|eval|exec|exit|fg|filetest|getxvers|'
+             r'glob|getspath|hashstat|history|hup|inlib|jobs|kill|'
+             r'limit|log|login|logout|ls-F|migrate|newgrp|nice|nohup|notify|'
+             r'onintr|popd|printenv|pushd|rehash|repeat|rootnode|popd|pushd|'
+             r'set|shift|sched|setenv|setpath|settc|setty|setxvers|shift|'
+             r'source|stop|suspend|source|suspend|telltc|time|'
+             r'umask|unalias|uncomplete|unhash|universe|unlimit|unset|unsetenv|'
+             r'ver|wait|warp|watchlog|where|which)\s*\b',
+             Name.Builtin),
+            (r'#.*', Comment),
+            (r'\\[\w\W]', String.Escape),
+            (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)),
+            (r'[\[\]{}()=]+', Operator),
+            (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
+            (r';', Punctuation),
+        ],
+        'data': [
+            (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
+            (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
+            (r'\s+', Text),
+            (r'[^=\s\[\]{}()$"\'`\\;#]+', Text),
+            (r'\d+(?= |\Z)', Number),
+            (r'\$#?(\w+|.)', Name.Variable),
+        ],
+        'curly': [
+            (r'\}', Keyword, '#pop'),
+            (r':-', Keyword),
+            (r'\w+', Name.Variable),
+            (r'[^}:"\'`$]+', Punctuation),
+            (r':', Punctuation),
+            include('root'),
+        ],
+        'paren': [
+            (r'\)', Keyword, '#pop'),
+            include('root'),
+        ],
+        'backticks': [
+            (r'`', String.Backtick, '#pop'),
+            include('root'),
+        ],
+    }
+
+
+class TcshSessionLexer(ShellSessionBaseLexer):
+    """
+    Lexer for Tcsh sessions, i.e. command lines, including a
+    prompt, interspersed with output.
+    """
+
+    name = 'Tcsh Session'
+    aliases = ['tcshcon']
+    filenames = []
+    mimetypes = []
+    url = 'https://www.tcsh.org'
+    version_added = '2.1'
+    _example = "tcshcon/session"
+
+    _innerLexerCls = TcshLexer
+    _ps1rgx = re.compile(r'^([^>]+>)(.*\n?)')
+    _ps2 = '? '
+
+
+class PowerShellLexer(RegexLexer):
+    """
+    For Windows PowerShell code.
+    """
+    name = 'PowerShell'
+    aliases = ['powershell', 'pwsh', 'posh', 'ps1', 'psm1']
+    filenames = ['*.ps1', '*.psm1']
+    mimetypes = ['text/x-powershell']
+    url = 'https://learn.microsoft.com/en-us/powershell'
+    version_added = '1.5'
+
+    flags = re.DOTALL | re.IGNORECASE | re.MULTILINE
+
+    keywords = (
+        'while validateset validaterange validatepattern validatelength '
+        'validatecount until trap switch return ref process param parameter in '
+        'if global: local: function foreach for finally filter end elseif else '
+        'dynamicparam do default continue cmdletbinding break begin alias \\? '
+        '% #script #private #local #global mandatory parametersetname position '
+        'valuefrompipeline valuefrompipelinebypropertyname '
+        'valuefromremainingarguments helpmessage try catch throw').split()
+
+    operators = (
+        'and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle '
+        'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains '
+        'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt '
+        'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like '
+        'lt match ne not notcontains notlike notmatch or regex replace '
+        'wildcard').split()
+
+    verbs = (
+        'write where watch wait use update unregister unpublish unprotect '
+        'unlock uninstall undo unblock trace test tee take sync switch '
+        'suspend submit stop step start split sort skip show set send select '
+        'search scroll save revoke resume restore restart resolve resize '
+        'reset request repair rename remove register redo receive read push '
+        'publish protect pop ping out optimize open new move mount merge '
+        'measure lock limit join invoke install initialize import hide group '
+        'grant get format foreach find export expand exit enter enable edit '
+        'dismount disconnect disable deny debug cxnew copy convertto '
+        'convertfrom convert connect confirm compress complete compare close '
+        'clear checkpoint block backup assert approve aggregate add').split()
+
+    aliases_ = (
+        'ac asnp cat cd cfs chdir clc clear clhy cli clp cls clv cnsn '
+        'compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo epal '
+        'epcsv epsn erase etsn exsn fc fhx fl foreach ft fw gal gbp gc gci gcm '
+        'gcs gdr ghy gi gjb gl gm gmo gp gps gpv group gsn gsnp gsv gu gv gwmi '
+        'h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp '
+        'ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv '
+        'oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo '
+        'rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc select '
+        'set shcm si sl sleep sls sort sp spjb spps spsv start sujb sv swmi tee '
+        'trcm type wget where wjb write').split()
+
+    commenthelp = (
+        'component description example externalhelp forwardhelpcategory '
+        'forwardhelptargetname functionality inputs link '
+        'notes outputs parameter remotehelprunspace role synopsis').split()
+
+    tokens = {
+        'root': [
+            # we need to count pairs of parentheses for correct highlight
+            # of '$(...)' blocks in strings
+            (r'\(', Punctuation, 'child'),
+            (r'\s+', Text),
+            (r'^(\s*#[#\s]*)(\.(?:{}))([^\n]*$)'.format('|'.join(commenthelp)),
+             bygroups(Comment, String.Doc, Comment)),
+            (r'#[^\n]*?$', Comment),
+            (r'(<|<)#', Comment.Multiline, 'multline'),
+            (r'@"\n', String.Heredoc, 'heredoc-double'),
+            (r"@'\n.*?\n'@", String.Heredoc),
+            # escaped syntax
+            (r'`[\'"$@-]', Punctuation),
+            (r'"', String.Double, 'string'),
+            (r"'([^']|'')*'", String.Single),
+            (r'(\$|@@|@)((global|script|private|env):)?\w+',
+             Name.Variable),
+            (r'({})\b'.format('|'.join(keywords)), Keyword),
+            (r'-({})\b'.format('|'.join(operators)), Operator),
+            (r'({})-[a-z_]\w*\b'.format('|'.join(verbs)), Name.Builtin),
+            (r'({})\s'.format('|'.join(aliases_)), Name.Builtin),
+            (r'\[[a-z_\[][\w. `,\[\]]*\]', Name.Constant),  # .net [type]s
+            (r'-[a-z_]\w*', Name),
+            (r'\w+', Name),
+            (r'[.,;:@{}\[\]$()=+*/\\&%!~?^`|<>-]', Punctuation),
+        ],
+        'child': [
+            (r'\)', Punctuation, '#pop'),
+            include('root'),
+        ],
+        'multline': [
+            (r'[^#&.]+', Comment.Multiline),
+            (r'#(>|>)', Comment.Multiline, '#pop'),
+            (r'\.({})'.format('|'.join(commenthelp)), String.Doc),
+            (r'[#&.]', Comment.Multiline),
+        ],
+        'string': [
+            (r"`[0abfnrtv'\"$`]", String.Escape),
+            (r'[^$`"]+', String.Double),
+            (r'\$\(', Punctuation, 'child'),
+            (r'""', String.Double),
+            (r'[`$]', String.Double),
+            (r'"', String.Double, '#pop'),
+        ],
+        'heredoc-double': [
+            (r'\n"@', String.Heredoc, '#pop'),
+            (r'\$\(', Punctuation, 'child'),
+            (r'[^@\n]+"]', String.Heredoc),
+            (r".", String.Heredoc),
+        ]
+    }
+
+
+class PowerShellSessionLexer(ShellSessionBaseLexer):
+    """
+    Lexer for PowerShell sessions, i.e. command lines, including a
+    prompt, interspersed with output.
+    """
+
+    name = 'PowerShell Session'
+    aliases = ['pwsh-session', 'ps1con']
+    filenames = []
+    mimetypes = []
+    url = 'https://learn.microsoft.com/en-us/powershell'
+    version_added = '2.1'
+    _example = "pwsh-session/session"
+
+    _innerLexerCls = PowerShellLexer
+    _bare_continuation = True
+    _ps1rgx = re.compile(r'^((?:\[[^]]+\]: )?PS[^>]*> ?)(.*\n?)')
+    _ps2 = '> '
+
+
+class FishShellLexer(RegexLexer):
+    """
+    Lexer for Fish shell scripts.
+    """
+
+    name = 'Fish'
+    aliases = ['fish', 'fishshell']
+    filenames = ['*.fish', '*.load']
+    mimetypes = ['application/x-fish']
+    url = 'https://fishshell.com'
+    version_added = '2.1'
+
+    tokens = {
+        'root': [
+            include('basic'),
+            include('data'),
+            include('interp'),
+        ],
+        'interp': [
+            (r'\$\(\(', Keyword, 'math'),
+            (r'\(', Keyword, 'paren'),
+            (r'\$#?(\w+|.)', Name.Variable),
+        ],
+        'basic': [
+            (r'\b(begin|end|if|else|while|break|for|in|return|function|block|'
+             r'case|continue|switch|not|and|or|set|echo|exit|pwd|true|false|'
+             r'cd|count|test)(\s*)\b',
+             bygroups(Keyword, Text)),
+            (r'\b(alias|bg|bind|breakpoint|builtin|command|commandline|'
+             r'complete|contains|dirh|dirs|emit|eval|exec|fg|fish|fish_config|'
+             r'fish_indent|fish_pager|fish_prompt|fish_right_prompt|'
+             r'fish_update_completions|fishd|funced|funcsave|functions|help|'
+             r'history|isatty|jobs|math|mimedb|nextd|open|popd|prevd|psub|'
+             r'pushd|random|read|set_color|source|status|trap|type|ulimit|'
+             r'umask|vared|fc|getopts|hash|kill|printf|time|wait)\s*\b(?!\.)',
+             Name.Builtin),
+            (r'#.*\n', Comment),
+            (r'\\[\w\W]', String.Escape),
+            (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Whitespace, Operator)),
+            (r'[\[\]()=]', Operator),
+            (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String),
+        ],
+        'data': [
+            (r'(?s)\$?"(\\\\|\\[0-7]+|\\.|[^"\\$])*"', String.Double),
+            (r'"', String.Double, 'string'),
+            (r"(?s)\$'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
+            (r"(?s)'.*?'", String.Single),
+            (r';', Punctuation),
+            (r'&|\||\^|<|>', Operator),
+            (r'\s+', Text),
+            (r'\d+(?= |\Z)', Number),
+            (r'[^=\s\[\]{}()$"\'`\\<&|;]+', Text),
+        ],
+        'string': [
+            (r'"', String.Double, '#pop'),
+            (r'(?s)(\\\\|\\[0-7]+|\\.|[^"\\$])+', String.Double),
+            include('interp'),
+        ],
+        'paren': [
+            (r'\)', Keyword, '#pop'),
+            include('root'),
+        ],
+        'math': [
+            (r'\)\)', Keyword, '#pop'),
+            (r'[-+*/%^|&]|\*\*|\|\|', Operator),
+            (r'\d+#\d+', Number),
+            (r'\d+#(?! )', Number),
+            (r'\d+', Number),
+            include('root'),
+        ],
+    }
+
+class ExeclineLexer(RegexLexer):
+    """
+    Lexer for Laurent Bercot's execline language.
+    """
+
+    name = 'execline'
+    aliases = ['execline']
+    filenames = ['*.exec']
+    url = 'https://skarnet.org/software/execline'
+    version_added = '2.7'
+
+    tokens = {
+        'root': [
+            include('basic'),
+            include('data'),
+            include('interp')
+        ],
+        'interp': [
+            (r'\$\{', String.Interpol, 'curly'),
+            (r'\$[\w@#]+', Name.Variable),  # user variable
+            (r'\$', Text),
+        ],
+        'basic': [
+            (r'\b(background|backtick|cd|define|dollarat|elgetopt|'
+             r'elgetpositionals|elglob|emptyenv|envfile|exec|execlineb|'
+             r'exit|export|fdblock|fdclose|fdmove|fdreserve|fdswap|'
+             r'forbacktickx|foreground|forstdin|forx|getcwd|getpid|heredoc|'
+             r'homeof|if|ifelse|ifte|ifthenelse|importas|loopwhilex|'
+             r'multidefine|multisubstitute|pipeline|piperw|posix-cd|'
+             r'redirfd|runblock|shift|trap|tryexec|umask|unexport|wait|'
+             r'withstdinas)\b', Name.Builtin),
+            (r'\A#!.+\n', Comment.Hashbang),
+            (r'#.*\n', Comment.Single),
+            (r'[{}]', Operator)
+        ],
+        'data': [
+            (r'(?s)"(\\.|[^"\\$])*"', String.Double),
+            (r'"', String.Double, 'string'),
+            (r'\s+', Text),
+            (r'[^\s{}$"\\]+', Text)
+        ],
+        'string': [
+            (r'"', String.Double, '#pop'),
+            (r'(?s)(\\\\|\\.|[^"\\$])+', String.Double),
+            include('interp'),
+        ],
+        'curly': [
+            (r'\}', String.Interpol, '#pop'),
+            (r'[\w#@]+', Name.Variable),
+            include('root')
+        ]
+
+    }
+
+    def analyse_text(text):
+        if shebang_matches(text, r'execlineb'):
+            return 1
diff --git a/lib/python3.11/site-packages/pygments/lexers/sieve.py b/lib/python3.11/site-packages/pygments/lexers/sieve.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bda3517e83e2ba20c57b165b237f845796d6727
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/sieve.py
@@ -0,0 +1,78 @@
+"""
+    pygments.lexers.sieve
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Sieve file format.
+
+    https://tools.ietf.org/html/rfc5228
+    https://tools.ietf.org/html/rfc5173
+    https://tools.ietf.org/html/rfc5229
+    https://tools.ietf.org/html/rfc5230
+    https://tools.ietf.org/html/rfc5232
+    https://tools.ietf.org/html/rfc5235
+    https://tools.ietf.org/html/rfc5429
+    https://tools.ietf.org/html/rfc8580
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups
+from pygments.token import Comment, Name, Literal, String, Text, Punctuation, \
+    Keyword
+
+__all__ = ["SieveLexer"]
+
+
+class SieveLexer(RegexLexer):
+    """
+    Lexer for sieve format.
+    """
+    name = 'Sieve'
+    filenames = ['*.siv', '*.sieve']
+    aliases = ['sieve']
+    url = 'https://en.wikipedia.org/wiki/Sieve_(mail_filtering_language)'
+    version_added = '2.6'
+
+    tokens = {
+        'root': [
+            (r'\s+', Text),
+            (r'[();,{}\[\]]', Punctuation),
+            # import:
+            (r'(?i)require',
+             Keyword.Namespace),
+            # tags:
+            (r'(?i)(:)(addresses|all|contains|content|create|copy|comparator|'
+             r'count|days|detail|domain|fcc|flags|from|handle|importance|is|'
+             r'localpart|length|lowerfirst|lower|matches|message|mime|options|'
+             r'over|percent|quotewildcard|raw|regex|specialuse|subject|text|'
+             r'under|upperfirst|upper|value)',
+             bygroups(Name.Tag, Name.Tag)),
+            # tokens:
+            (r'(?i)(address|addflag|allof|anyof|body|discard|elsif|else|envelope|'
+             r'ereject|exists|false|fileinto|if|hasflag|header|keep|'
+             r'notify_method_capability|notify|not|redirect|reject|removeflag|'
+             r'setflag|size|spamtest|stop|string|true|vacation|virustest)',
+             Name.Builtin),
+            (r'(?i)set',
+             Keyword.Declaration),
+            # number:
+            (r'([0-9.]+)([kmgKMG])?',
+             bygroups(Literal.Number, Literal.Number)),
+            # comment:
+            (r'#.*$',
+             Comment.Single),
+            (r'/\*.*\*/',
+             Comment.Multiline),
+            # string:
+            (r'"[^"]*?"',
+             String),
+            # text block:
+            (r'text:',
+             Name.Tag, 'text'),
+        ],
+        'text': [
+            (r'[^.].*?\n', String),
+            (r'^\.', Punctuation, "#pop"),
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/slash.py b/lib/python3.11/site-packages/pygments/lexers/slash.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bcbdf877548eb9d670ee2384aed01d2d631dc16
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/slash.py
@@ -0,0 +1,183 @@
+"""
+    pygments.lexers.slash
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for the Slash programming language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import ExtendedRegexLexer, bygroups, DelegatingLexer
+from pygments.token import Name, Number, String, Comment, Punctuation, \
+    Other, Keyword, Operator, Whitespace
+
+__all__ = ['SlashLexer']
+
+
+class SlashLanguageLexer(ExtendedRegexLexer):
+    _nkw = r'(?=[^a-zA-Z_0-9])'
+
+    def move_state(new_state):
+        return ("#pop", new_state)
+
+    def right_angle_bracket(lexer, match, ctx):
+        if len(ctx.stack) > 1 and ctx.stack[-2] == "string":
+            ctx.stack.pop()
+        yield match.start(), String.Interpol, '}'
+        ctx.pos = match.end()
+        pass
+
+    tokens = {
+        "root": [
+            (r"<%=",        Comment.Preproc,    move_state("slash")),
+            (r"<%!!",       Comment.Preproc,    move_state("slash")),
+            (r"<%#.*?%>",   Comment.Multiline),
+            (r"<%",         Comment.Preproc,    move_state("slash")),
+            (r".|\n",       Other),
+        ],
+        "string": [
+            (r"\\",         String.Escape,      move_state("string_e")),
+            (r"\"",         String,             move_state("slash")),
+            (r"#\{",        String.Interpol,    "slash"),
+            (r'.|\n',       String),
+        ],
+        "string_e": [
+            (r'n',                  String.Escape,      move_state("string")),
+            (r't',                  String.Escape,      move_state("string")),
+            (r'r',                  String.Escape,      move_state("string")),
+            (r'e',                  String.Escape,      move_state("string")),
+            (r'x[a-fA-F0-9]{2}',    String.Escape,      move_state("string")),
+            (r'.',                  String.Escape,      move_state("string")),
+        ],
+        "regexp": [
+            (r'}[a-z]*',            String.Regex,       move_state("slash")),
+            (r'\\(.|\n)',           String.Regex),
+            (r'{',                  String.Regex,       "regexp_r"),
+            (r'.|\n',               String.Regex),
+        ],
+        "regexp_r": [
+            (r'}[a-z]*',            String.Regex,       "#pop"),
+            (r'\\(.|\n)',           String.Regex),
+            (r'{',                  String.Regex,       "regexp_r"),
+        ],
+        "slash": [
+            (r"%>",                     Comment.Preproc,    move_state("root")),
+            (r"\"",                     String,             move_state("string")),
+            (r"'[a-zA-Z0-9_]+",         String),
+            (r'%r{',                    String.Regex,       move_state("regexp")),
+            (r'/\*.*?\*/',              Comment.Multiline),
+            (r"(#|//).*?\n",            Comment.Single),
+            (r'-?[0-9]+e[+-]?[0-9]+',   Number.Float),
+            (r'-?[0-9]+\.[0-9]+(e[+-]?[0-9]+)?', Number.Float),
+            (r'-?[0-9]+',               Number.Integer),
+            (r'nil'+_nkw,               Name.Builtin),
+            (r'true'+_nkw,              Name.Builtin),
+            (r'false'+_nkw,             Name.Builtin),
+            (r'self'+_nkw,              Name.Builtin),
+            (r'(class)(\s+)([A-Z][a-zA-Z0-9_\']*)',
+                bygroups(Keyword, Whitespace, Name.Class)),
+            (r'class'+_nkw,             Keyword),
+            (r'extends'+_nkw,           Keyword),
+            (r'(def)(\s+)(self)(\s*)(\.)(\s*)([a-z_][a-zA-Z0-9_\']*=?|<<|>>|==|<=>|<=|<|>=|>|\+|-(self)?|~(self)?|\*|/|%|^|&&|&|\||\[\]=?)',
+                bygroups(Keyword, Whitespace, Name.Builtin, Whitespace, Punctuation, Whitespace, Name.Function)),
+            (r'(def)(\s+)([a-z_][a-zA-Z0-9_\']*=?|<<|>>|==|<=>|<=|<|>=|>|\+|-(self)?|~(self)?|\*|/|%|^|&&|&|\||\[\]=?)',
+                bygroups(Keyword, Whitespace, Name.Function)),
+            (r'def'+_nkw,               Keyword),
+            (r'if'+_nkw,                Keyword),
+            (r'elsif'+_nkw,             Keyword),
+            (r'else'+_nkw,              Keyword),
+            (r'unless'+_nkw,            Keyword),
+            (r'for'+_nkw,               Keyword),
+            (r'in'+_nkw,                Keyword),
+            (r'while'+_nkw,             Keyword),
+            (r'until'+_nkw,             Keyword),
+            (r'and'+_nkw,               Keyword),
+            (r'or'+_nkw,                Keyword),
+            (r'not'+_nkw,               Keyword),
+            (r'lambda'+_nkw,            Keyword),
+            (r'try'+_nkw,               Keyword),
+            (r'catch'+_nkw,             Keyword),
+            (r'return'+_nkw,            Keyword),
+            (r'next'+_nkw,              Keyword),
+            (r'last'+_nkw,              Keyword),
+            (r'throw'+_nkw,             Keyword),
+            (r'use'+_nkw,               Keyword),
+            (r'switch'+_nkw,            Keyword),
+            (r'\\',                     Keyword),
+            (r'λ',                      Keyword),
+            (r'__FILE__'+_nkw,          Name.Builtin.Pseudo),
+            (r'__LINE__'+_nkw,          Name.Builtin.Pseudo),
+            (r'[A-Z][a-zA-Z0-9_\']*'+_nkw, Name.Constant),
+            (r'[a-z_][a-zA-Z0-9_\']*'+_nkw, Name),
+            (r'@[a-z_][a-zA-Z0-9_\']*'+_nkw, Name.Variable.Instance),
+            (r'@@[a-z_][a-zA-Z0-9_\']*'+_nkw, Name.Variable.Class),
+            (r'\(',                     Punctuation),
+            (r'\)',                     Punctuation),
+            (r'\[',                     Punctuation),
+            (r'\]',                     Punctuation),
+            (r'\{',                     Punctuation),
+            (r'\}',                     right_angle_bracket),
+            (r';',                      Punctuation),
+            (r',',                      Punctuation),
+            (r'<<=',                    Operator),
+            (r'>>=',                    Operator),
+            (r'<<',                     Operator),
+            (r'>>',                     Operator),
+            (r'==',                     Operator),
+            (r'!=',                     Operator),
+            (r'=>',                     Operator),
+            (r'=',                      Operator),
+            (r'<=>',                    Operator),
+            (r'<=',                     Operator),
+            (r'>=',                     Operator),
+            (r'<',                      Operator),
+            (r'>',                      Operator),
+            (r'\+\+',                   Operator),
+            (r'\+=',                    Operator),
+            (r'-=',                     Operator),
+            (r'\*\*=',                  Operator),
+            (r'\*=',                    Operator),
+            (r'\*\*',                   Operator),
+            (r'\*',                     Operator),
+            (r'/=',                     Operator),
+            (r'\+',                     Operator),
+            (r'-',                      Operator),
+            (r'/',                      Operator),
+            (r'%=',                     Operator),
+            (r'%',                      Operator),
+            (r'^=',                     Operator),
+            (r'&&=',                    Operator),
+            (r'&=',                     Operator),
+            (r'&&',                     Operator),
+            (r'&',                      Operator),
+            (r'\|\|=',                  Operator),
+            (r'\|=',                    Operator),
+            (r'\|\|',                   Operator),
+            (r'\|',                     Operator),
+            (r'!',                      Operator),
+            (r'\.\.\.',                 Operator),
+            (r'\.\.',                   Operator),
+            (r'\.',                     Operator),
+            (r'::',                     Operator),
+            (r':',                      Operator),
+            (r'(\s|\n)+',               Whitespace),
+            (r'[a-z_][a-zA-Z0-9_\']*',  Name.Variable),
+        ],
+    }
+
+
+class SlashLexer(DelegatingLexer):
+    """
+    Lexer for the Slash programming language.
+    """
+
+    name = 'Slash'
+    aliases = ['slash']
+    filenames = ['*.sla']
+    url = 'https://github.com/arturadib/Slash-A'
+    version_added = '2.4'
+
+    def __init__(self, **options):
+        from pygments.lexers.web import HtmlLexer
+        super().__init__(HtmlLexer, SlashLanguageLexer, **options)
diff --git a/lib/python3.11/site-packages/pygments/lexers/smalltalk.py b/lib/python3.11/site-packages/pygments/lexers/smalltalk.py
new file mode 100644
index 0000000000000000000000000000000000000000..69e0519b77f612145f5ac56f3260bfe4ad863d97
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/smalltalk.py
@@ -0,0 +1,194 @@
+"""
+    pygments.lexers.smalltalk
+    ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Smalltalk and related languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, include, bygroups, default
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['SmalltalkLexer', 'NewspeakLexer']
+
+
+class SmalltalkLexer(RegexLexer):
+    """
+    For Smalltalk syntax.
+    Contributed by Stefan Matthias Aust.
+    Rewritten by Nils Winter.
+    """
+    name = 'Smalltalk'
+    url = 'http://www.smalltalk.org/'
+    filenames = ['*.st']
+    aliases = ['smalltalk', 'squeak', 'st']
+    mimetypes = ['text/x-smalltalk']
+    version_added = '0.10'
+
+    tokens = {
+        'root': [
+            (r'(<)(\w+:)(.*?)(>)', bygroups(Text, Keyword, Text, Text)),
+            include('squeak fileout'),
+            include('whitespaces'),
+            include('method definition'),
+            (r'(\|)([\w\s]*)(\|)', bygroups(Operator, Name.Variable, Operator)),
+            include('objects'),
+            (r'\^|\:=|\_', Operator),
+            # temporaries
+            (r'[\]({}.;!]', Text),
+        ],
+        'method definition': [
+            # Not perfect can't allow whitespaces at the beginning and the
+            # without breaking everything
+            (r'([a-zA-Z]+\w*:)(\s*)(\w+)',
+             bygroups(Name.Function, Text, Name.Variable)),
+            (r'^(\b[a-zA-Z]+\w*\b)(\s*)$', bygroups(Name.Function, Text)),
+            (r'^([-+*/\\~<>=|&!?,@%]+)(\s*)(\w+)(\s*)$',
+             bygroups(Name.Function, Text, Name.Variable, Text)),
+        ],
+        'blockvariables': [
+            include('whitespaces'),
+            (r'(:)(\s*)(\w+)',
+             bygroups(Operator, Text, Name.Variable)),
+            (r'\|', Operator, '#pop'),
+            default('#pop'),  # else pop
+        ],
+        'literals': [
+            (r"'(''|[^'])*'", String, 'afterobject'),
+            (r'\$.', String.Char, 'afterobject'),
+            (r'#\(', String.Symbol, 'parenth'),
+            (r'\)', Text, 'afterobject'),
+            (r'(\d+r)?-?\d+(\.\d+)?(e-?\d+)?', Number, 'afterobject'),
+        ],
+        '_parenth_helper': [
+            include('whitespaces'),
+            (r'(\d+r)?-?\d+(\.\d+)?(e-?\d+)?', Number),
+            (r'[-+*/\\~<>=|&#!?,@%\w:]+', String.Symbol),
+            # literals
+            (r"'(''|[^'])*'", String),
+            (r'\$.', String.Char),
+            (r'#*\(', String.Symbol, 'inner_parenth'),
+        ],
+        'parenth': [
+            # This state is a bit tricky since
+            # we can't just pop this state
+            (r'\)', String.Symbol, ('root', 'afterobject')),
+            include('_parenth_helper'),
+        ],
+        'inner_parenth': [
+            (r'\)', String.Symbol, '#pop'),
+            include('_parenth_helper'),
+        ],
+        'whitespaces': [
+            # skip whitespace and comments
+            (r'\s+', Text),
+            (r'"(""|[^"])*"', Comment),
+        ],
+        'objects': [
+            (r'\[', Text, 'blockvariables'),
+            (r'\]', Text, 'afterobject'),
+            (r'\b(self|super|true|false|nil|thisContext)\b',
+             Name.Builtin.Pseudo, 'afterobject'),
+            (r'\b[A-Z]\w*(?!:)\b', Name.Class, 'afterobject'),
+            (r'\b[a-z]\w*(?!:)\b', Name.Variable, 'afterobject'),
+            (r'#("(""|[^"])*"|[-+*/\\~<>=|&!?,@%]+|[\w:]+)',
+             String.Symbol, 'afterobject'),
+            include('literals'),
+        ],
+        'afterobject': [
+            (r'! !$', Keyword, '#pop'),  # squeak chunk delimiter
+            include('whitespaces'),
+            (r'\b(ifTrue:|ifFalse:|whileTrue:|whileFalse:|timesRepeat:)',
+             Name.Builtin, '#pop'),
+            (r'\b(new\b(?!:))', Name.Builtin),
+            (r'\:=|\_', Operator, '#pop'),
+            (r'\b[a-zA-Z]+\w*:', Name.Function, '#pop'),
+            (r'\b[a-zA-Z]+\w*', Name.Function),
+            (r'\w+:?|[-+*/\\~<>=|&!?,@%]+', Name.Function, '#pop'),
+            (r'\.', Punctuation, '#pop'),
+            (r';', Punctuation),
+            (r'[\])}]', Text),
+            (r'[\[({]', Text, '#pop'),
+        ],
+        'squeak fileout': [
+            # Squeak fileout format (optional)
+            (r'^"(""|[^"])*"!', Keyword),
+            (r"^'(''|[^'])*'!", Keyword),
+            (r'^(!)(\w+)( commentStamp: )(.*?)( prior: .*?!\n)(.*?)(!)',
+                bygroups(Keyword, Name.Class, Keyword, String, Keyword, Text, Keyword)),
+            (r"^(!)(\w+(?: class)?)( methodsFor: )('(?:''|[^'])*')(.*?!)",
+                bygroups(Keyword, Name.Class, Keyword, String, Keyword)),
+            (r'^(\w+)( subclass: )(#\w+)'
+             r'(\s+instanceVariableNames: )(.*?)'
+             r'(\s+classVariableNames: )(.*?)'
+             r'(\s+poolDictionaries: )(.*?)'
+             r'(\s+category: )(.*?)(!)',
+                bygroups(Name.Class, Keyword, String.Symbol, Keyword, String, Keyword,
+                         String, Keyword, String, Keyword, String, Keyword)),
+            (r'^(\w+(?: class)?)(\s+instanceVariableNames: )(.*?)(!)',
+                bygroups(Name.Class, Keyword, String, Keyword)),
+            (r'(!\n)(\].*)(! !)$', bygroups(Keyword, Text, Keyword)),
+            (r'! !$', Keyword),
+        ],
+    }
+
+
+class NewspeakLexer(RegexLexer):
+    """
+    For Newspeak syntax.
+    """
+    name = 'Newspeak'
+    url = 'http://newspeaklanguage.org/'
+    filenames = ['*.ns2']
+    aliases = ['newspeak', ]
+    mimetypes = ['text/x-newspeak']
+    version_added = '1.1'
+
+    tokens = {
+        'root': [
+            (r'\b(Newsqueak2)\b', Keyword.Declaration),
+            (r"'[^']*'", String),
+            (r'\b(class)(\s+)(\w+)(\s*)',
+             bygroups(Keyword.Declaration, Text, Name.Class, Text)),
+            (r'\b(mixin|self|super|private|public|protected|nil|true|false)\b',
+             Keyword),
+            (r'(\w+\:)(\s*)([a-zA-Z_]\w+)',
+             bygroups(Name.Function, Text, Name.Variable)),
+            (r'(\w+)(\s*)(=)',
+             bygroups(Name.Attribute, Text, Operator)),
+            (r'<\w+>', Comment.Special),
+            include('expressionstat'),
+            include('whitespace')
+        ],
+
+        'expressionstat': [
+            (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float),
+            (r'\d+', Number.Integer),
+            (r':\w+', Name.Variable),
+            (r'(\w+)(::)', bygroups(Name.Variable, Operator)),
+            (r'\w+:', Name.Function),
+            (r'\w+', Name.Variable),
+            (r'\(|\)', Punctuation),
+            (r'\[|\]', Punctuation),
+            (r'\{|\}', Punctuation),
+
+            (r'(\^|\+|\/|~|\*|<|>|=|@|%|\||&|\?|!|,|-|:)', Operator),
+            (r'\.|;', Punctuation),
+            include('whitespace'),
+            include('literals'),
+        ],
+        'literals': [
+            (r'\$.', String),
+            (r"'[^']*'", String),
+            (r"#'[^']*'", String.Symbol),
+            (r"#\w+:?", String.Symbol),
+            (r"#(\+|\/|~|\*|<|>|=|@|%|\||&|\?|!|,|-)+", String.Symbol)
+        ],
+        'whitespace': [
+            (r'\s+', Text),
+            (r'"[^"]*"', Comment)
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/smithy.py b/lib/python3.11/site-packages/pygments/lexers/smithy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2642bb879901595f88e605364703db92de9707bd
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/smithy.py
@@ -0,0 +1,77 @@
+"""
+    pygments.lexers.smithy
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Smithy IDL.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, words
+from pygments.token import Text, Comment, Keyword, Name, String, \
+    Number, Whitespace, Punctuation
+
+__all__ = ['SmithyLexer']
+
+
+class SmithyLexer(RegexLexer):
+    """
+    For Smithy IDL
+    """
+    name = 'Smithy'
+    url = 'https://awslabs.github.io/smithy/'
+    filenames = ['*.smithy']
+    aliases = ['smithy']
+    version_added = '2.10'
+
+    unquoted = r'[A-Za-z0-9_\.#$-]+'
+    identifier = r"[A-Za-z0-9_\.#$-]+"
+
+    simple_shapes = (
+        'use', 'byte', 'short', 'integer', 'long', 'float', 'document',
+        'double', 'bigInteger', 'bigDecimal', 'boolean', 'blob', 'string',
+        'timestamp',
+    )
+
+    aggregate_shapes = (
+       'apply', 'list', 'map', 'set', 'structure', 'union', 'resource',
+       'operation', 'service', 'trait'
+    )
+
+    tokens = {
+        'root': [
+            (r'///.*$', Comment.Multiline),
+            (r'//.*$', Comment),
+            (r'@[0-9a-zA-Z\.#-]*', Name.Decorator),
+            (r'(=)', Name.Decorator),
+            (r'^(\$version)(:)(.+)',
+                bygroups(Keyword.Declaration, Name.Decorator, Name.Class)),
+            (r'^(namespace)(\s+' + identifier + r')\b',
+                bygroups(Keyword.Declaration, Name.Class)),
+            (words(simple_shapes,
+                   prefix=r'^', suffix=r'(\s+' + identifier + r')\b'),
+                bygroups(Keyword.Declaration, Name.Class)),
+            (words(aggregate_shapes,
+                   prefix=r'^', suffix=r'(\s+' + identifier + r')'),
+                bygroups(Keyword.Declaration, Name.Class)),
+            (r'^(metadata)(\s+)((?:\S+)|(?:\"[^"]+\"))(\s*)(=)',
+                bygroups(Keyword.Declaration, Whitespace, Name.Class,
+                         Whitespace, Name.Decorator)),
+            (r"(true|false|null)", Keyword.Constant),
+            (r"(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)", Number),
+            (identifier + ":", Name.Label),
+            (identifier, Name.Variable.Class),
+            (r'\[', Text, "#push"),
+            (r'\]', Text, "#pop"),
+            (r'\(', Text, "#push"),
+            (r'\)', Text, "#pop"),
+            (r'\{', Text, "#push"),
+            (r'\}', Text, "#pop"),
+            (r'"{3}(\\\\|\n|\\")*"{3}', String.Doc),
+            (r'"(\\\\|\n|\\"|[^"])*"', String.Double),
+            (r"'(\\\\|\n|\\'|[^'])*'", String.Single),
+            (r'[:,]+', Punctuation),
+            (r'\s+', Whitespace),
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/smv.py b/lib/python3.11/site-packages/pygments/lexers/smv.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d06f99f60b3af912d889faba24993a9b69ea5ca
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/smv.py
@@ -0,0 +1,78 @@
+"""
+    pygments.lexers.smv
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the SMV languages.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, words
+from pygments.token import Comment, Keyword, Name, Number, Operator, \
+    Punctuation, Text
+
+__all__ = ['NuSMVLexer']
+
+
+class NuSMVLexer(RegexLexer):
+    """
+    Lexer for the NuSMV language.
+    """
+
+    name = 'NuSMV'
+    aliases = ['nusmv']
+    filenames = ['*.smv']
+    mimetypes = []
+    url = 'https://nusmv.fbk.eu'
+    version_added = '2.2'
+
+    tokens = {
+        'root': [
+            # Comments
+            (r'(?s)\/\-\-.*?\-\-/', Comment),
+            (r'--.*\n', Comment),
+
+            # Reserved
+            (words(('MODULE', 'DEFINE', 'MDEFINE', 'CONSTANTS', 'VAR', 'IVAR',
+                    'FROZENVAR', 'INIT', 'TRANS', 'INVAR', 'SPEC', 'CTLSPEC',
+                    'LTLSPEC', 'PSLSPEC', 'COMPUTE', 'NAME', 'INVARSPEC',
+                    'FAIRNESS', 'JUSTICE', 'COMPASSION', 'ISA', 'ASSIGN',
+                    'CONSTRAINT', 'SIMPWFF', 'CTLWFF', 'LTLWFF', 'PSLWFF',
+                    'COMPWFF', 'IN', 'MIN', 'MAX', 'MIRROR', 'PRED',
+                    'PREDICATES'), suffix=r'(?![\w$#-])'),
+             Keyword.Declaration),
+            (r'process(?![\w$#-])', Keyword),
+            (words(('array', 'of', 'boolean', 'integer', 'real', 'word'),
+                   suffix=r'(?![\w$#-])'), Keyword.Type),
+            (words(('case', 'esac'), suffix=r'(?![\w$#-])'), Keyword),
+            (words(('word1', 'bool', 'signed', 'unsigned', 'extend', 'resize',
+                    'sizeof', 'uwconst', 'swconst', 'init', 'self', 'count',
+                    'abs', 'max', 'min'), suffix=r'(?![\w$#-])'),
+             Name.Builtin),
+            (words(('EX', 'AX', 'EF', 'AF', 'EG', 'AG', 'E', 'F', 'O', 'G',
+                    'H', 'X', 'Y', 'Z', 'A', 'U', 'S', 'V', 'T', 'BU', 'EBF',
+                    'ABF', 'EBG', 'ABG', 'next', 'mod', 'union', 'in', 'xor',
+                    'xnor'), suffix=r'(?![\w$#-])'),
+                Operator.Word),
+            (words(('TRUE', 'FALSE'), suffix=r'(?![\w$#-])'), Keyword.Constant),
+
+            # Names
+            (r'[a-zA-Z_][\w$#-]*', Name.Variable),
+
+            # Operators
+            (r':=', Operator),
+            (r'[-&|+*/<>!=]', Operator),
+
+            # Literals
+            (r'\-?\d+\b', Number.Integer),
+            (r'0[su][bB]\d*_[01_]+', Number.Bin),
+            (r'0[su][oO]\d*_[0-7_]+', Number.Oct),
+            (r'0[su][dD]\d*_[\d_]+', Number.Decimal),
+            (r'0[su][hH]\d*_[\da-fA-F_]+', Number.Hex),
+
+            # Whitespace, punctuation and the rest
+            (r'\s+', Text.Whitespace),
+            (r'[()\[\]{};?:.,]', Punctuation),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/snobol.py b/lib/python3.11/site-packages/pygments/lexers/snobol.py
new file mode 100644
index 0000000000000000000000000000000000000000..7016c96a5fdbaa7ed5e531a78584faf903d99841
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/snobol.py
@@ -0,0 +1,82 @@
+"""
+    pygments.lexers.snobol
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the SNOBOL language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation
+
+__all__ = ['SnobolLexer']
+
+
+class SnobolLexer(RegexLexer):
+    """
+    Lexer for the SNOBOL4 programming language.
+
+    Recognizes the common ASCII equivalents of the original SNOBOL4 operators.
+    Does not require spaces around binary operators.
+    """
+
+    name = "Snobol"
+    aliases = ["snobol"]
+    filenames = ['*.snobol']
+    mimetypes = ['text/x-snobol']
+    url = 'https://www.regressive.org/snobol4'
+    version_added = '1.5'
+
+    tokens = {
+        # root state, start of line
+        # comments, continuation lines, and directives start in column 1
+        # as do labels
+        'root': [
+            (r'\*.*\n', Comment),
+            (r'[+.] ', Punctuation, 'statement'),
+            (r'-.*\n', Comment),
+            (r'END\s*\n', Name.Label, 'heredoc'),
+            (r'[A-Za-z$][\w$]*', Name.Label, 'statement'),
+            (r'\s+', Text, 'statement'),
+        ],
+        # statement state, line after continuation or label
+        'statement': [
+            (r'\s*\n', Text, '#pop'),
+            (r'\s+', Text),
+            (r'(?<=[^\w.])(LT|LE|EQ|NE|GE|GT|INTEGER|IDENT|DIFFER|LGT|SIZE|'
+             r'REPLACE|TRIM|DUPL|REMDR|DATE|TIME|EVAL|APPLY|OPSYN|LOAD|UNLOAD|'
+             r'LEN|SPAN|BREAK|ANY|NOTANY|TAB|RTAB|REM|POS|RPOS|FAIL|FENCE|'
+             r'ABORT|ARB|ARBNO|BAL|SUCCEED|INPUT|OUTPUT|TERMINAL)(?=[^\w.])',
+             Name.Builtin),
+            (r'[A-Za-z][\w.]*', Name),
+            # ASCII equivalents of original operators
+            # | for the EBCDIC equivalent, ! likewise
+            # \ for EBCDIC negation
+            (r'\*\*|[?$.!%*/#+\-@|&\\=]', Operator),
+            (r'"[^"]*"', String),
+            (r"'[^']*'", String),
+            # Accept SPITBOL syntax for real numbers
+            # as well as Macro SNOBOL4
+            (r'[0-9]+(?=[^.EeDd])', Number.Integer),
+            (r'[0-9]+(\.[0-9]*)?([EDed][-+]?[0-9]+)?', Number.Float),
+            # Goto
+            (r':', Punctuation, 'goto'),
+            (r'[()<>,;]', Punctuation),
+        ],
+        # Goto block
+        'goto': [
+            (r'\s*\n', Text, "#pop:2"),
+            (r'\s+', Text),
+            (r'F|S', Keyword),
+            (r'(\()([A-Za-z][\w.]*)(\))',
+             bygroups(Punctuation, Name.Label, Punctuation))
+        ],
+        # everything after the END statement is basically one
+        # big heredoc.
+        'heredoc': [
+            (r'.*\n', String.Heredoc)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/solidity.py b/lib/python3.11/site-packages/pygments/lexers/solidity.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f2d1dd0ac19bd5d9eb90939da249d4505286803
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/solidity.py
@@ -0,0 +1,87 @@
+"""
+    pygments.lexers.solidity
+    ~~~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Solidity.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, include, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Whitespace
+
+__all__ = ['SolidityLexer']
+
+
+class SolidityLexer(RegexLexer):
+    """
+    For Solidity source code.
+    """
+
+    name = 'Solidity'
+    aliases = ['solidity']
+    filenames = ['*.sol']
+    mimetypes = []
+    url = 'https://soliditylang.org'
+    version_added = '2.5'
+
+    datatype = (
+        r'\b(address|bool|(?:(?:bytes|hash|int|string|uint)(?:8|16|24|32|40|48|56|64'
+        r'|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208'
+        r'|216|224|232|240|248|256)?))\b'
+    )
+
+    tokens = {
+        'root': [
+            include('whitespace'),
+            include('comments'),
+            (r'\bpragma\s+solidity\b', Keyword, 'pragma'),
+            (r'\b(contract)(\s+)([a-zA-Z_]\w*)',
+             bygroups(Keyword, Whitespace, Name.Entity)),
+            (datatype + r'(\s+)((?:external|public|internal|private)\s+)?' +
+             r'([a-zA-Z_]\w*)',
+             bygroups(Keyword.Type, Whitespace, Keyword, Name.Variable)),
+            (r'\b(enum|event|function|struct)(\s+)([a-zA-Z_]\w*)',
+             bygroups(Keyword.Type, Whitespace, Name.Variable)),
+            (r'\b(msg|block|tx)\.([A-Za-z_][a-zA-Z0-9_]*)\b', Keyword),
+            (words((
+                'block', 'break', 'constant', 'constructor', 'continue',
+                'contract', 'do', 'else', 'external', 'false', 'for',
+                'function', 'if', 'import', 'inherited', 'internal', 'is',
+                'library', 'mapping', 'memory', 'modifier', 'msg', 'new',
+                'payable', 'private', 'public', 'require', 'return',
+                'returns', 'struct', 'suicide', 'throw', 'this', 'true',
+                'tx', 'var', 'while'), prefix=r'\b', suffix=r'\b'),
+             Keyword.Type),
+            (words(('keccak256',), prefix=r'\b', suffix=r'\b'), Name.Builtin),
+            (datatype, Keyword.Type),
+            include('constants'),
+            (r'[a-zA-Z_]\w*', Text),
+            (r'[~!%^&*+=|?:<>/-]', Operator),
+            (r'[.;{}(),\[\]]', Punctuation)
+        ],
+        'comments': [
+            (r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single),
+            (r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline),
+            (r'/(\\\n)?[*][\w\W]*', Comment.Multiline)
+        ],
+        'constants': [
+            (r'("(\\"|.)*?")', String.Double),
+            (r"('(\\'|.)*?')", String.Single),
+            (r'\b0[xX][0-9a-fA-F]+\b', Number.Hex),
+            (r'\b\d+\b', Number.Decimal),
+        ],
+        'pragma': [
+            include('whitespace'),
+            include('comments'),
+            (r'(\^|>=|<)(\s*)(\d+\.\d+\.\d+)',
+             bygroups(Operator, Whitespace, Keyword)),
+            (r';', Punctuation, '#pop')
+        ],
+        'whitespace': [
+            (r'\s+', Whitespace),
+            (r'\n', Whitespace)
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/soong.py b/lib/python3.11/site-packages/pygments/lexers/soong.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d7f12ccd592e71b6a866089a35fd2582c82f3d6
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/soong.py
@@ -0,0 +1,78 @@
+"""
+    pygments.lexers.soong
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for Soong (Android.bp Blueprint) files.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, include
+from pygments.token import Comment, Name, Number, Operator, Punctuation, \
+        String, Whitespace
+
+__all__ = ['SoongLexer']
+
+class SoongLexer(RegexLexer):
+    name = 'Soong'
+    version_added = '2.18'
+    url = 'https://source.android.com/docs/setup/reference/androidbp'
+    aliases = ['androidbp', 'bp', 'soong']
+    filenames = ['Android.bp']
+
+    tokens = {
+        'root': [
+            # A variable assignment
+            (r'(\w*)(\s*)(\+?=)(\s*)',
+             bygroups(Name.Variable, Whitespace, Operator, Whitespace),
+             'assign-rhs'),
+
+            # A top-level module
+            (r'(\w*)(\s*)(\{)',
+             bygroups(Name.Function, Whitespace, Punctuation),
+             'in-rule'),
+
+            # Everything else
+            include('comments'),
+            (r'\s+', Whitespace),  # newlines okay
+        ],
+        'assign-rhs': [
+            include('expr'),
+            (r'\n', Whitespace, '#pop'),
+        ],
+        'in-list': [
+            include('expr'),
+            include('comments'),
+            (r'\s+', Whitespace),  # newlines okay in a list
+            (r',', Punctuation),
+            (r'\]', Punctuation, '#pop'),
+        ],
+        'in-map': [
+            # A map key
+            (r'(\w+)(:)(\s*)', bygroups(Name, Punctuation, Whitespace)),
+
+            include('expr'),
+            include('comments'),
+            (r'\s+', Whitespace),  # newlines okay in a map
+            (r',', Punctuation),
+            (r'\}', Punctuation, '#pop'),
+        ],
+        'in-rule': [
+            # Just re-use map syntax
+            include('in-map'),
+        ],
+        'comments': [
+            (r'//.*', Comment.Single),
+            (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
+        ],
+        'expr': [
+            (r'(true|false)\b', Name.Builtin),
+            (r'0x[0-9a-fA-F]+', Number.Hex),
+            (r'\d+', Number.Integer),
+            (r'".*?"', String),
+            (r'\{', Punctuation, 'in-map'),
+            (r'\[', Punctuation, 'in-list'),
+            (r'\w+', Name),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/sophia.py b/lib/python3.11/site-packages/pygments/lexers/sophia.py
new file mode 100644
index 0000000000000000000000000000000000000000..86435f3fe7e482cd069f2cdae33fe32a69f08434
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/sophia.py
@@ -0,0 +1,102 @@
+"""
+    pygments.lexers.sophia
+    ~~~~~~~~~~~~~~~~~~~~~~
+
+    Lexer for Sophia.
+
+    Derived from pygments/lexers/reason.py.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, include, default, words
+from pygments.token import Comment, Keyword, Name, Number, Operator, \
+    Punctuation, String, Text
+
+__all__ = ['SophiaLexer']
+
+class SophiaLexer(RegexLexer):
+    """
+    A Sophia lexer.
+    """
+
+    name = 'Sophia'
+    aliases = ['sophia']
+    filenames = ['*.aes']
+    mimetypes = []
+    url = 'https://docs.aeternity.com/aesophia'
+    version_added = '2.11'
+
+    keywords = (
+        'contract', 'include', 'let', 'switch', 'type', 'record', 'datatype',
+        'if', 'elif', 'else', 'function', 'stateful', 'payable', 'public',
+        'entrypoint', 'private', 'indexed', 'namespace', 'interface', 'main',
+        'using', 'as', 'for', 'hiding',
+    )
+
+    builtins = ('state', 'put', 'abort', 'require')
+
+    word_operators = ('mod', 'band', 'bor', 'bxor', 'bnot')
+
+    primitive_types = ('int', 'address', 'bool', 'bits', 'bytes', 'string',
+                       'list', 'option', 'char', 'unit', 'map', 'event',
+                       'hash', 'signature', 'oracle', 'oracle_query')
+
+    tokens = {
+        'escape-sequence': [
+            (r'\\[\\"\'ntbr]', String.Escape),
+            (r'\\[0-9]{3}', String.Escape),
+            (r'\\x[0-9a-fA-F]{2}', String.Escape),
+        ],
+        'root': [
+            (r'\s+', Text.Whitespace),
+            (r'(true|false)\b', Keyword.Constant),
+            (r'\b([A-Z][\w\']*)(?=\s*\.)', Name.Class, 'dotted'),
+            (r'\b([A-Z][\w\']*)', Name.Function),
+            (r'//.*?\n', Comment.Single),
+            (r'\/\*(?!/)', Comment.Multiline, 'comment'),
+
+            (r'0[xX][\da-fA-F][\da-fA-F_]*', Number.Hex),
+            (r'#[\da-fA-F][\da-fA-F_]*', Name.Label),
+            (r'\d[\d_]*', Number.Integer),
+
+            (words(keywords, suffix=r'\b'), Keyword),
+            (words(builtins, suffix=r'\b'), Name.Builtin),
+            (words(word_operators, prefix=r'\b', suffix=r'\b'), Operator.Word),
+            (words(primitive_types, prefix=r'\b', suffix=r'\b'), Keyword.Type),
+
+            (r'[=!<>+\\*/:&|?~@^-]', Operator.Word),
+            (r'[.;:{}(),\[\]]', Punctuation),
+
+            (r"(ak_|ok_|oq_|ct_)[\w']*", Name.Label),
+            (r"[^\W\d][\w']*", Name),
+
+            (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'",
+             String.Char),
+            (r"'.'", String.Char),
+            (r"'[a-z][\w]*", Name.Variable),
+
+            (r'"', String.Double, 'string')
+        ],
+        'comment': [
+            (r'[^/*]+', Comment.Multiline),
+            (r'\/\*', Comment.Multiline, '#push'),
+            (r'\*\/', Comment.Multiline, '#pop'),
+            (r'\*', Comment.Multiline),
+        ],
+        'string': [
+            (r'[^\\"]+', String.Double),
+            include('escape-sequence'),
+            (r'\\\n', String.Double),
+            (r'"', String.Double, '#pop'),
+        ],
+        'dotted': [
+            (r'\s+', Text),
+            (r'\.', Punctuation),
+            (r'[A-Z][\w\']*(?=\s*\.)', Name.Function),
+            (r'[A-Z][\w\']*', Name.Function, '#pop'),
+            (r'[a-z_][\w\']*', Name, '#pop'),
+            default('#pop'),
+        ],
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/special.py b/lib/python3.11/site-packages/pygments/lexers/special.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea345226fc7beca9290514d90dfef58bc8512a3a
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/special.py
@@ -0,0 +1,122 @@
+"""
+    pygments.lexers.special
+    ~~~~~~~~~~~~~~~~~~~~~~~
+
+    Special lexers.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import ast
+
+from pygments.lexer import Lexer, line_re
+from pygments.token import Token, Error, Text, Generic
+from pygments.util import get_choice_opt
+
+
+__all__ = ['TextLexer', 'OutputLexer', 'RawTokenLexer']
+
+
+class TextLexer(Lexer):
+    """
+    "Null" lexer, doesn't highlight anything.
+    """
+    name = 'Text only'
+    aliases = ['text']
+    filenames = ['*.txt']
+    mimetypes = ['text/plain']
+    url = ""
+    version_added = ''
+
+    priority = 0.01
+
+    def get_tokens_unprocessed(self, text):
+        yield 0, Text, text
+
+    def analyse_text(text):
+        return TextLexer.priority
+
+
+class OutputLexer(Lexer):
+    """
+    Simple lexer that highlights everything as ``Token.Generic.Output``.
+    """
+    name = 'Text output'
+    aliases = ['output']
+    url = ""
+    version_added = '2.10'
+    _example = "output/output"
+
+    def get_tokens_unprocessed(self, text):
+        yield 0, Generic.Output, text
+
+
+_ttype_cache = {}
+
+
+class RawTokenLexer(Lexer):
+    """
+    Recreate a token stream formatted with the `RawTokenFormatter`.
+
+    Additional options accepted:
+
+    `compress`
+        If set to ``"gz"`` or ``"bz2"``, decompress the token stream with
+        the given compression algorithm before lexing (default: ``""``).
+    """
+    name = 'Raw token data'
+    aliases = []
+    filenames = []
+    mimetypes = ['application/x-pygments-tokens']
+    url = 'https://pygments.org/docs/formatters/#RawTokenFormatter'
+    version_added = ''
+
+    def __init__(self, **options):
+        self.compress = get_choice_opt(options, 'compress',
+                                       ['', 'none', 'gz', 'bz2'], '')
+        Lexer.__init__(self, **options)
+
+    def get_tokens(self, text):
+        if self.compress:
+            if isinstance(text, str):
+                text = text.encode('latin1')
+            try:
+                if self.compress == 'gz':
+                    import gzip
+                    text = gzip.decompress(text)
+                elif self.compress == 'bz2':
+                    import bz2
+                    text = bz2.decompress(text)
+            except OSError:
+                yield Error, text.decode('latin1')
+        if isinstance(text, bytes):
+            text = text.decode('latin1')
+
+        # do not call Lexer.get_tokens() because stripping is not optional.
+        text = text.strip('\n') + '\n'
+        for i, t, v in self.get_tokens_unprocessed(text):
+            yield t, v
+
+    def get_tokens_unprocessed(self, text):
+        length = 0
+        for match in line_re.finditer(text):
+            try:
+                ttypestr, val = match.group().rstrip().split('\t', 1)
+                ttype = _ttype_cache.get(ttypestr)
+                if not ttype:
+                    ttype = Token
+                    ttypes = ttypestr.split('.')[1:]
+                    for ttype_ in ttypes:
+                        if not ttype_ or not ttype_[0].isupper():
+                            raise ValueError('malformed token name')
+                        ttype = getattr(ttype, ttype_)
+                    _ttype_cache[ttypestr] = ttype
+                val = ast.literal_eval(val)
+                if not isinstance(val, str):
+                    raise ValueError('expected str')
+            except (SyntaxError, ValueError):
+                val = match.group()
+                ttype = Error
+            yield length, ttype, val
+            length += len(val)
diff --git a/lib/python3.11/site-packages/pygments/lexers/spice.py b/lib/python3.11/site-packages/pygments/lexers/spice.py
new file mode 100644
index 0000000000000000000000000000000000000000..978f0a71fd2957c88060b51bb3bef863cff5769d
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/spice.py
@@ -0,0 +1,70 @@
+"""
+    pygments.lexers.spice
+    ~~~~~~~~~~~~~~~~~~~~~
+
+    Lexers for the Spice programming language.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.lexer import RegexLexer, bygroups, words
+from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
+    Number, Punctuation, Whitespace
+
+__all__ = ['SpiceLexer']
+
+
+class SpiceLexer(RegexLexer):
+    """
+    For Spice source.
+    """
+    name = 'Spice'
+    url = 'https://www.spicelang.com'
+    filenames = ['*.spice']
+    aliases = ['spice', 'spicelang']
+    mimetypes = ['text/x-spice']
+    version_added = '2.11'
+
+    tokens = {
+        'root': [
+            (r'\n', Whitespace),
+            (r'\s+', Whitespace),
+            (r'\\\n', Text),
+            # comments
+            (r'//(.*?)\n', Comment.Single),
+            (r'/(\\\n)?[*]{2}(.|\n)*?[*](\\\n)?/', String.Doc),
+            (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
+            # keywords
+            (r'(import|as)\b', Keyword.Namespace),
+            (r'(f|p|type|struct|interface|enum|alias|operator)\b', Keyword.Declaration),
+            (words(('if', 'else', 'switch', 'case', 'default', 'for', 'foreach', 'do',
+                    'while', 'break', 'continue', 'fallthrough', 'return', 'assert',
+                    'unsafe', 'ext', 'cast'), suffix=r'\b'), Keyword),
+            (words(('const', 'signed', 'unsigned', 'inline', 'public', 'heap', 'compose'),
+                   suffix=r'\b'), Keyword.Pseudo),
+            (words(('new', 'yield', 'stash', 'pick', 'sync', 'class'), suffix=r'\b'),
+                   Keyword.Reserved),
+            (r'(true|false|nil)\b', Keyword.Constant),
+            (words(('double', 'int', 'short', 'long', 'byte', 'char', 'string',
+                    'bool', 'dyn'), suffix=r'\b'), Keyword.Type),
+            (words(('printf', 'sizeof', 'alignof', 'len', 'panic'), suffix=r'\b(\()'),
+             bygroups(Name.Builtin, Punctuation)),
+            # numeric literals
+            (r'[-]?[0-9]*[.][0-9]+([eE][+-]?[0-9]+)?', Number.Double),
+            (r'0[bB][01]+[slu]?', Number.Bin),
+            (r'0[oO][0-7]+[slu]?', Number.Oct),
+            (r'0[xXhH][0-9a-fA-F]+[slu]?', Number.Hex),
+            (r'(0[dD])?[0-9]+[slu]?', Number.Integer),
+            # string literal
+            (r'"(\\\\|\\[^\\]|[^"\\])*"', String),
+            # char literal
+            (r'\'(\\\\|\\[^\\]|[^\'\\])\'', String.Char),
+            # tokens
+            (r'<<=|>>=|<<|>>|<=|>=|\+=|-=|\*=|/=|\%=|\|=|&=|\^=|&&|\|\||&|\||'
+             r'\+\+|--|\%|\^|\~|==|!=|->|::|[.]{3}|#!|#|[+\-*/&]', Operator),
+            (r'[|<>=!()\[\]{}.,;:\?]', Punctuation),
+            # identifiers
+            (r'[^\W\d]\w*', Name.Other),
+        ]
+    }
diff --git a/lib/python3.11/site-packages/pygments/lexers/sql.py b/lib/python3.11/site-packages/pygments/lexers/sql.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d3458e9aefd10bb0ef89ea81f6c006e3f690ec3
--- /dev/null
+++ b/lib/python3.11/site-packages/pygments/lexers/sql.py
@@ -0,0 +1,1111 @@
+"""
+    pygments.lexers.sql
+    ~~~~~~~~~~~~~~~~~~~
+
+    Lexers for various SQL dialects and related interactive sessions.
+
+    Postgres specific lexers:
+
+    `PostgresLexer`
+        A SQL lexer for the PostgreSQL dialect. Differences w.r.t. the SQL
+        lexer are:
+
+        - keywords and data types list parsed from the PG docs (run the
+          `_postgres_builtins` module to update them);
+        - Content of $-strings parsed using a specific lexer, e.g. the content
+          of a PL/Python function is parsed using the Python lexer;
+        - parse PG specific constructs: E-strings, $-strings, U&-strings,
+          different operators and punctuation.
+
+    `PlPgsqlLexer`
+        A lexer for the PL/pgSQL language. Adds a few specific construct on
+        top of the PG SQL lexer (such as <y)', r'\g', 'xx'), '')
+        self.assertEqual(regex.sub('(?Px)|(?Py)', r'\2', 'xx'), '')
+
+        # The old behaviour was to raise it as an IndexError.
+        self.assertRaisesRegex(regex.error, self.BAD_GROUP_NAME, lambda:
+          regex.sub('(?Px)', r'\g<-1>', 'xx'))
+
+    def test_re_subn(self):
+        self.assertEqual(regex.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2))
+        self.assertEqual(regex.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
+        self.assertEqual(regex.subn("b+", "x", "xyz"), ('xyz', 0))
+        self.assertEqual(regex.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
+        self.assertEqual(regex.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
+
+    def test_re_split(self):
+        self.assertEqual(regex.split(":", ":a:b::c"), ['', 'a', 'b', '', 'c'])
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.split(":*", ":a:b::c"), ['', '', 'a', '',
+              'b', '', 'c', ''])
+            self.assertEqual(regex.split("(:*)", ":a:b::c"), ['', ':', '', '',
+              'a', ':', '', '', 'b', '::', '', '', 'c', '', ''])
+            self.assertEqual(regex.split("(?::*)", ":a:b::c"), ['', '', 'a',
+              '', 'b', '', 'c', ''])
+            self.assertEqual(regex.split("(:)*", ":a:b::c"), ['', ':', '',
+              None, 'a', ':', '', None, 'b', ':', '', None, 'c', None, ''])
+        else:
+            self.assertEqual(regex.split(":*", ":a:b::c"), ['', 'a', 'b', 'c'])
+            self.assertEqual(regex.split("(:*)", ":a:b::c"), ['', ':', 'a',
+              ':', 'b', '::', 'c'])
+            self.assertEqual(regex.split("(?::*)", ":a:b::c"), ['', 'a', 'b',
+              'c'])
+            self.assertEqual(regex.split("(:)*", ":a:b::c"), ['', ':', 'a',
+              ':', 'b', ':', 'c'])
+        self.assertEqual(regex.split("([b:]+)", ":a:b::c"), ['', ':', 'a',
+          ':b::', 'c'])
+        self.assertEqual(regex.split("(b)|(:+)", ":a:b::c"), ['', None, ':',
+          'a', None, ':', '', 'b', None, '', None, '::', 'c'])
+        self.assertEqual(regex.split("(?:b)|(?::+)", ":a:b::c"), ['', 'a', '',
+          '', 'c'])
+
+        self.assertEqual(regex.split("x", "xaxbxc"), ['', 'a', 'b', 'c'])
+        self.assertEqual([m for m in regex.splititer("x", "xaxbxc")], ['', 'a',
+          'b', 'c'])
+
+        self.assertEqual(regex.split("(?r)x", "xaxbxc"), ['c', 'b', 'a', ''])
+        self.assertEqual([m for m in regex.splititer("(?r)x", "xaxbxc")], ['c',
+          'b', 'a', ''])
+
+        self.assertEqual(regex.split("(x)|(y)", "xaxbxc"), ['', 'x', None, 'a',
+          'x', None, 'b', 'x', None, 'c'])
+        self.assertEqual([m for m in regex.splititer("(x)|(y)", "xaxbxc")],
+          ['', 'x', None, 'a', 'x', None, 'b', 'x', None, 'c'])
+
+        self.assertEqual(regex.split("(?r)(x)|(y)", "xaxbxc"), ['c', 'x', None,
+          'b', 'x', None, 'a', 'x', None, ''])
+        self.assertEqual([m for m in regex.splititer("(?r)(x)|(y)", "xaxbxc")],
+          ['c', 'x', None, 'b', 'x', None, 'a', 'x', None, ''])
+
+        self.assertEqual(regex.split(r"(?V1)\b", "a b c"), ['', 'a', ' ', 'b',
+          ' ', 'c', ''])
+        self.assertEqual(regex.split(r"(?V1)\m", "a b c"), ['', 'a ', 'b ',
+          'c'])
+        self.assertEqual(regex.split(r"(?V1)\M", "a b c"), ['a', ' b', ' c',
+          ''])
+
+    def test_qualified_re_split(self):
+        self.assertEqual(regex.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
+        self.assertEqual(regex.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d'])
+        self.assertEqual(regex.split("(:)", ":a:b::c", 2), ['', ':', 'a', ':',
+          'b::c'])
+
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.split("(:*)", ":a:b::c", 2), ['', ':', '',
+              '', 'a:b::c'])
+        else:
+            self.assertEqual(regex.split("(:*)", ":a:b::c", 2), ['', ':', 'a',
+              ':', 'b::c'])
+
+    def test_re_findall(self):
+        self.assertEqual(regex.findall(":+", "abc"), [])
+        self.assertEqual(regex.findall(":+", "a:b::c:::d"), [':', '::', ':::'])
+        self.assertEqual(regex.findall("(:+)", "a:b::c:::d"), [':', '::',
+          ':::'])
+        self.assertEqual(regex.findall("(:)(:*)", "a:b::c:::d"), [(':', ''),
+          (':', ':'), (':', '::')])
+
+        self.assertEqual(regex.findall(r"\((?P.{0,5}?TEST)\)",
+          "(MY TEST)"), ["MY TEST"])
+        self.assertEqual(regex.findall(r"\((?P.{0,3}?TEST)\)",
+          "(MY TEST)"), ["MY TEST"])
+        self.assertEqual(regex.findall(r"\((?P.{0,3}?T)\)", "(MY T)"),
+          ["MY T"])
+
+        self.assertEqual(regex.findall(r"[^a]{2}[A-Z]", "\n  S"), ['  S'])
+        self.assertEqual(regex.findall(r"[^a]{2,3}[A-Z]", "\n  S"), ['\n  S'])
+        self.assertEqual(regex.findall(r"[^a]{2,3}[A-Z]", "\n   S"), ['   S'])
+
+        self.assertEqual(regex.findall(r"X(Y[^Y]+?){1,2}( |Q)+DEF",
+          "XYABCYPPQ\nQ DEF"), [('YPPQ\n', ' ')])
+
+        self.assertEqual(regex.findall(r"(\nTest(\n+.+?){0,2}?)?\n+End",
+          "\nTest\nxyz\nxyz\nEnd"), [('\nTest\nxyz\nxyz', '\nxyz')])
+
+    def test_bug_117612(self):
+        self.assertEqual(regex.findall(r"(a|(b))", "aba"), [('a', ''), ('b',
+          'b'), ('a', '')])
+
+    def test_re_match(self):
+        self.assertEqual(regex.match('a', 'a')[:], ('a',))
+        self.assertEqual(regex.match('(a)', 'a')[:], ('a', 'a'))
+        self.assertEqual(regex.match(r'(a)', 'a')[0], 'a')
+        self.assertEqual(regex.match(r'(a)', 'a')[1], 'a')
+        self.assertEqual(regex.match(r'(a)', 'a').group(1, 1), ('a', 'a'))
+
+        pat = regex.compile('((a)|(b))(c)?')
+        self.assertEqual(pat.match('a')[:], ('a', 'a', 'a', None, None))
+        self.assertEqual(pat.match('b')[:], ('b', 'b', None, 'b', None))
+        self.assertEqual(pat.match('ac')[:], ('ac', 'a', 'a', None, 'c'))
+        self.assertEqual(pat.match('bc')[:], ('bc', 'b', None, 'b', 'c'))
+        self.assertEqual(pat.match('bc')[:], ('bc', 'b', None, 'b', 'c'))
+
+        # A single group.
+        m = regex.match('(a)', 'a')
+        self.assertEqual(m.group(), 'a')
+        self.assertEqual(m.group(0), 'a')
+        self.assertEqual(m.group(1), 'a')
+        self.assertEqual(m.group(1, 1), ('a', 'a'))
+
+        pat = regex.compile('(?:(?Pa)|(?Pb))(?Pc)?')
+        self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None))
+        self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'), (None, 'b',
+          None))
+        self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c'))
+
+    def test_re_groupref_exists(self):
+        self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', '(a)')[:],
+          ('(a)', '(', 'a'))
+        self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', 'a')[:], ('a',
+          None, 'a'))
+        self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', 'a)'), None)
+        self.assertEqual(regex.match(r'^(\()?([^()]+)(?(1)\))$', '(a'), None)
+        self.assertEqual(regex.match('^(?:(a)|c)((?(1)b|d))$', 'ab')[:], ('ab',
+          'a', 'b'))
+        self.assertEqual(regex.match('^(?:(a)|c)((?(1)b|d))$', 'cd')[:], ('cd',
+          None, 'd'))
+        self.assertEqual(regex.match('^(?:(a)|c)((?(1)|d))$', 'cd')[:], ('cd',
+          None, 'd'))
+        self.assertEqual(regex.match('^(?:(a)|c)((?(1)|d))$', 'a')[:], ('a',
+          'a', ''))
+
+        # Tests for bug #1177831: exercise groups other than the first group.
+        p = regex.compile('(?Pa)(?Pb)?((?(g2)c|d))')
+        self.assertEqual(p.match('abc')[:], ('abc', 'a', 'b', 'c'))
+        self.assertEqual(p.match('ad')[:], ('ad', 'a', None, 'd'))
+        self.assertEqual(p.match('abd'), None)
+        self.assertEqual(p.match('ac'), None)
+
+    def test_re_groupref(self):
+        self.assertEqual(regex.match(r'^(\|)?([^()]+)\1$', '|a|')[:], ('|a|',
+          '|', 'a'))
+        self.assertEqual(regex.match(r'^(\|)?([^()]+)\1?$', 'a')[:], ('a',
+          None, 'a'))
+        self.assertEqual(regex.match(r'^(\|)?([^()]+)\1$', 'a|'), None)
+        self.assertEqual(regex.match(r'^(\|)?([^()]+)\1$', '|a'), None)
+        self.assertEqual(regex.match(r'^(?:(a)|c)(\1)$', 'aa')[:], ('aa', 'a',
+          'a'))
+        self.assertEqual(regex.match(r'^(?:(a)|c)(\1)?$', 'c')[:], ('c', None,
+          None))
+
+        self.assertEqual(regex.findall(r"(?i)(.{1,40}?),(.{1,40}?)(?:;)+(.{1,80}).{1,40}?\3(\ |;)+(.{1,80}?)\1",
+          "TEST, BEST; LEST ; Lest 123 Test, Best"), [('TEST', ' BEST',
+          ' LEST', ' ', '123 ')])
+
+    def test_groupdict(self):
+        self.assertEqual(regex.match('(?Pfirst) (?Psecond)',
+          'first second').groupdict(), {'first': 'first', 'second': 'second'})
+
+    def test_expand(self):
+        self.assertEqual(regex.match("(?Pfirst) (?Psecond)",
+          "first second").expand(r"\2 \1 \g \g"),
+          'second first second first')
+
+    def test_repeat_minmax(self):
+        self.assertEqual(regex.match(r"^(\w){1}$", "abc"), None)
+        self.assertEqual(regex.match(r"^(\w){1}?$", "abc"), None)
+        self.assertEqual(regex.match(r"^(\w){1,2}$", "abc"), None)
+        self.assertEqual(regex.match(r"^(\w){1,2}?$", "abc"), None)
+
+        self.assertEqual(regex.match(r"^(\w){3}$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){1,3}$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){1,4}$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){3,4}?$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){3}?$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){1,3}?$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){1,4}?$", "abc")[1], 'c')
+        self.assertEqual(regex.match(r"^(\w){3,4}?$", "abc")[1], 'c')
+
+        self.assertEqual(regex.match("^x{1}$", "xxx"), None)
+        self.assertEqual(regex.match("^x{1}?$", "xxx"), None)
+        self.assertEqual(regex.match("^x{1,2}$", "xxx"), None)
+        self.assertEqual(regex.match("^x{1,2}?$", "xxx"), None)
+
+        self.assertEqual(regex.match("^x{1}", "xxx")[0], 'x')
+        self.assertEqual(regex.match("^x{1}?", "xxx")[0], 'x')
+        self.assertEqual(regex.match("^x{0,1}", "xxx")[0], 'x')
+        self.assertEqual(regex.match("^x{0,1}?", "xxx")[0], '')
+
+        self.assertEqual(bool(regex.match("^x{3}$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{1,3}$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{1,4}$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{3,4}?$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{3}?$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{1,3}?$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{1,4}?$", "xxx")), True)
+        self.assertEqual(bool(regex.match("^x{3,4}?$", "xxx")), True)
+
+        self.assertEqual(regex.match("^x{}$", "xxx"), None)
+        self.assertEqual(bool(regex.match("^x{}$", "x{}")), True)
+
+    def test_getattr(self):
+        self.assertEqual(regex.compile("(?i)(a)(b)").pattern, '(?i)(a)(b)')
+        self.assertEqual(regex.compile("(?i)(a)(b)").flags, regex.I | regex.U |
+          regex.DEFAULT_VERSION)
+        self.assertEqual(regex.compile(b"(?i)(a)(b)").flags, regex.A | regex.I
+          | regex.DEFAULT_VERSION)
+        self.assertEqual(regex.compile("(?i)(a)(b)").groups, 2)
+        self.assertEqual(regex.compile("(?i)(a)(b)").groupindex, {})
+
+        self.assertEqual(regex.compile("(?i)(?Pa)(?Pb)").groupindex,
+          {'first': 1, 'other': 2})
+
+        self.assertEqual(regex.match("(a)", "a").pos, 0)
+        self.assertEqual(regex.match("(a)", "a").endpos, 1)
+
+        self.assertEqual(regex.search("b(c)", "abcdef").pos, 0)
+        self.assertEqual(regex.search("b(c)", "abcdef").endpos, 6)
+        self.assertEqual(regex.search("b(c)", "abcdef").span(), (1, 3))
+        self.assertEqual(regex.search("b(c)", "abcdef").span(1), (2, 3))
+
+        self.assertEqual(regex.match("(a)", "a").string, 'a')
+        self.assertEqual(regex.match("(a)", "a").regs, ((0, 1), (0, 1)))
+        self.assertEqual(repr(type(regex.match("(a)", "a").re)),
+          self.PATTERN_CLASS)
+
+        # Issue 14260.
+        p = regex.compile(r'abc(?Pdef)')
+        p.groupindex["n"] = 0
+        self.assertEqual(p.groupindex["n"], 1)
+
+    def test_special_escapes(self):
+        self.assertEqual(regex.search(r"\b(b.)\b", "abcd abc bcd bx")[1], 'bx')
+        self.assertEqual(regex.search(r"\B(b.)\B", "abc bcd bc abxd")[1], 'bx')
+        self.assertEqual(regex.search(br"\b(b.)\b", b"abcd abc bcd bx",
+          regex.LOCALE)[1], b'bx')
+        self.assertEqual(regex.search(br"\B(b.)\B", b"abc bcd bc abxd",
+          regex.LOCALE)[1], b'bx')
+        self.assertEqual(regex.search(r"\b(b.)\b", "abcd abc bcd bx",
+          regex.UNICODE)[1], 'bx')
+        self.assertEqual(regex.search(r"\B(b.)\B", "abc bcd bc abxd",
+          regex.UNICODE)[1], 'bx')
+
+        self.assertEqual(regex.search(r"^abc$", "\nabc\n", regex.M)[0], 'abc')
+        self.assertEqual(regex.search(r"^\Aabc\Z$", "abc", regex.M)[0], 'abc')
+        self.assertEqual(regex.search(r"^\Aabc\Z$", "\nabc\n", regex.M), None)
+
+        self.assertEqual(regex.search(br"\b(b.)\b", b"abcd abc bcd bx")[1],
+          b'bx')
+        self.assertEqual(regex.search(br"\B(b.)\B", b"abc bcd bc abxd")[1],
+          b'bx')
+        self.assertEqual(regex.search(br"^abc$", b"\nabc\n", regex.M)[0],
+          b'abc')
+        self.assertEqual(regex.search(br"^\Aabc\Z$", b"abc", regex.M)[0],
+          b'abc')
+        self.assertEqual(regex.search(br"^\Aabc\Z$", b"\nabc\n", regex.M),
+          None)
+
+        self.assertEqual(regex.search(r"\d\D\w\W\s\S", "1aa! a")[0], '1aa! a')
+        self.assertEqual(regex.search(br"\d\D\w\W\s\S", b"1aa! a",
+          regex.LOCALE)[0], b'1aa! a')
+        self.assertEqual(regex.search(r"\d\D\w\W\s\S", "1aa! a",
+          regex.UNICODE)[0], '1aa! a')
+
+    def test_bigcharset(self):
+        self.assertEqual(regex.match(r"([\u2222\u2223])", "\u2222")[1],
+          '\u2222')
+        self.assertEqual(regex.match(r"([\u2222\u2223])", "\u2222",
+          regex.UNICODE)[1], '\u2222')
+        self.assertEqual("".join(regex.findall(".",
+          "e\xe8\xe9\xea\xeb\u0113\u011b\u0117", flags=regex.UNICODE)),
+          'e\xe8\xe9\xea\xeb\u0113\u011b\u0117')
+        self.assertEqual("".join(regex.findall(r"[e\xe8\xe9\xea\xeb\u0113\u011b\u0117]",
+          "e\xe8\xe9\xea\xeb\u0113\u011b\u0117", flags=regex.UNICODE)),
+          'e\xe8\xe9\xea\xeb\u0113\u011b\u0117')
+        self.assertEqual("".join(regex.findall(r"e|\xe8|\xe9|\xea|\xeb|\u0113|\u011b|\u0117",
+          "e\xe8\xe9\xea\xeb\u0113\u011b\u0117", flags=regex.UNICODE)),
+          'e\xe8\xe9\xea\xeb\u0113\u011b\u0117')
+
+    def test_anyall(self):
+        self.assertEqual(regex.match("a.b", "a\nb", regex.DOTALL)[0], "a\nb")
+        self.assertEqual(regex.match("a.*b", "a\n\nb", regex.DOTALL)[0],
+          "a\n\nb")
+
+    def test_non_consuming(self):
+        self.assertEqual(regex.match(r"(a(?=\s[^a]))", "a b")[1], 'a')
+        self.assertEqual(regex.match(r"(a(?=\s[^a]*))", "a b")[1], 'a')
+        self.assertEqual(regex.match(r"(a(?=\s[abc]))", "a b")[1], 'a')
+        self.assertEqual(regex.match(r"(a(?=\s[abc]*))", "a bc")[1], 'a')
+        self.assertEqual(regex.match(r"(a)(?=\s\1)", "a a")[1], 'a')
+        self.assertEqual(regex.match(r"(a)(?=\s\1*)", "a aa")[1], 'a')
+        self.assertEqual(regex.match(r"(a)(?=\s(abc|a))", "a a")[1], 'a')
+
+        self.assertEqual(regex.match(r"(a(?!\s[^a]))", "a a")[1], 'a')
+        self.assertEqual(regex.match(r"(a(?!\s[abc]))", "a d")[1], 'a')
+        self.assertEqual(regex.match(r"(a)(?!\s\1)", "a b")[1], 'a')
+        self.assertEqual(regex.match(r"(a)(?!\s(abc|a))", "a b")[1], 'a')
+
+    def test_ignore_case(self):
+        self.assertEqual(regex.match("abc", "ABC", regex.I)[0], 'ABC')
+        self.assertEqual(regex.match(b"abc", b"ABC", regex.I)[0], b'ABC')
+
+        self.assertEqual(regex.match(r"(a\s[^a]*)", "a bb", regex.I)[1],
+          'a bb')
+        self.assertEqual(regex.match(r"(a\s[abc])", "a b", regex.I)[1], 'a b')
+        self.assertEqual(regex.match(r"(a\s[abc]*)", "a bb", regex.I)[1],
+          'a bb')
+        self.assertEqual(regex.match(r"((a)\s\2)", "a a", regex.I)[1], 'a a')
+        self.assertEqual(regex.match(r"((a)\s\2*)", "a aa", regex.I)[1],
+          'a aa')
+        self.assertEqual(regex.match(r"((a)\s(abc|a))", "a a", regex.I)[1],
+          'a a')
+        self.assertEqual(regex.match(r"((a)\s(abc|a)*)", "a aa", regex.I)[1],
+          'a aa')
+
+        # Issue 3511.
+        self.assertEqual(regex.match(r"[Z-a]", "_").span(), (0, 1))
+        self.assertEqual(regex.match(r"(?i)[Z-a]", "_").span(), (0, 1))
+
+        self.assertEqual(bool(regex.match(r"(?i)nao", "nAo")), True)
+        self.assertEqual(bool(regex.match(r"(?i)n\xE3o", "n\xC3o")), True)
+        self.assertEqual(bool(regex.match(r"(?i)n\xE3o", "N\xC3O")), True)
+        self.assertEqual(bool(regex.match(r"(?i)s", "\u017F")), True)
+
+    def test_case_folding(self):
+        self.assertEqual(regex.search(r"(?fi)ss", "SS").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)SS", "ss").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)SS",
+          "\N{LATIN SMALL LETTER SHARP S}").span(), (0, 1))
+        self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LETTER SHARP S}",
+          "SS").span(), (0, 2))
+
+        self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE ST}",
+          "ST").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)ST",
+          "\N{LATIN SMALL LIGATURE ST}").span(), (0, 1))
+        self.assertEqual(regex.search(r"(?fi)ST",
+          "\N{LATIN SMALL LIGATURE LONG S T}").span(), (0, 1))
+
+        self.assertEqual(regex.search(r"(?fi)SST",
+          "\N{LATIN SMALL LETTER SHARP S}t").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)SST",
+          "s\N{LATIN SMALL LIGATURE LONG S T}").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)SST",
+          "s\N{LATIN SMALL LIGATURE ST}").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE ST}",
+          "SST").span(), (1, 3))
+        self.assertEqual(regex.search(r"(?fi)SST",
+          "s\N{LATIN SMALL LIGATURE ST}").span(), (0, 2))
+
+        self.assertEqual(regex.search(r"(?fi)FFI",
+          "\N{LATIN SMALL LIGATURE FFI}").span(), (0, 1))
+        self.assertEqual(regex.search(r"(?fi)FFI",
+          "\N{LATIN SMALL LIGATURE FF}i").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)FFI",
+          "f\N{LATIN SMALL LIGATURE FI}").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE FFI}",
+          "FFI").span(), (0, 3))
+        self.assertEqual(regex.search(r"(?fi)\N{LATIN SMALL LIGATURE FF}i",
+          "FFI").span(), (0, 3))
+        self.assertEqual(regex.search(r"(?fi)f\N{LATIN SMALL LIGATURE FI}",
+          "FFI").span(), (0, 3))
+
+        sigma = "\u03A3\u03C3\u03C2"
+        for ch1 in sigma:
+            for ch2 in sigma:
+                if not regex.match(r"(?fi)" + ch1, ch2):
+                    self.fail()
+
+        self.assertEqual(bool(regex.search(r"(?iV1)ff", "\uFB00\uFB01")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)ff", "\uFB01\uFB00")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)fi", "\uFB00\uFB01")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)fi", "\uFB01\uFB00")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)fffi", "\uFB00\uFB01")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)f\uFB03",
+          "\uFB00\uFB01")), True)
+        self.assertEqual(bool(regex.search(r"(?iV1)ff", "\uFB00\uFB01")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)fi", "\uFB00\uFB01")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)fffi", "\uFB00\uFB01")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)f\uFB03",
+          "\uFB00\uFB01")), True)
+        self.assertEqual(bool(regex.search(r"(?iV1)f\uFB01", "\uFB00i")),
+          True)
+        self.assertEqual(bool(regex.search(r"(?iV1)f\uFB01", "\uFB00i")),
+          True)
+
+        self.assertEqual(regex.findall(r"(?iV0)\m(?:word){e<=3}\M(?ne", "affine",
+          options=["\N{LATIN SMALL LIGATURE FFI}"]).span(), (0, 6))
+        self.assertEqual(regex.search(r"(?fi)a\Lne",
+          "a\N{LATIN SMALL LIGATURE FFI}ne", options=["ffi"]).span(), (0, 4))
+
+    def test_category(self):
+        self.assertEqual(regex.match(r"(\s)", " ")[1], ' ')
+
+    def test_not_literal(self):
+        self.assertEqual(regex.search(r"\s([^a])", " b")[1], 'b')
+        self.assertEqual(regex.search(r"\s([^a]*)", " bb")[1], 'bb')
+
+    def test_search_coverage(self):
+        self.assertEqual(regex.search(r"\s(b)", " b")[1], 'b')
+        self.assertEqual(regex.search(r"a\s", "a ")[0], 'a ')
+
+    def test_re_escape(self):
+        p = ""
+        self.assertEqual(regex.escape(p), p)
+        for i in range(0, 256):
+            p += chr(i)
+            self.assertEqual(bool(regex.match(regex.escape(chr(i)), chr(i))),
+              True)
+            self.assertEqual(regex.match(regex.escape(chr(i)), chr(i)).span(),
+              (0, 1))
+
+        pat = regex.compile(regex.escape(p))
+        self.assertEqual(pat.match(p).span(), (0, 256))
+
+    def test_re_escape_byte(self):
+        p = b""
+        self.assertEqual(regex.escape(p), p)
+        for i in range(0, 256):
+            b = bytes([i])
+            p += b
+            self.assertEqual(bool(regex.match(regex.escape(b), b)), True)
+            self.assertEqual(regex.match(regex.escape(b), b).span(), (0, 1))
+
+        pat = regex.compile(regex.escape(p))
+        self.assertEqual(pat.match(p).span(), (0, 256))
+
+    def test_constants(self):
+        if regex.I != regex.IGNORECASE:
+            self.fail()
+        if regex.L != regex.LOCALE:
+            self.fail()
+        if regex.M != regex.MULTILINE:
+            self.fail()
+        if regex.S != regex.DOTALL:
+            self.fail()
+        if regex.X != regex.VERBOSE:
+            self.fail()
+
+    def test_flags(self):
+        for flag in [regex.I, regex.M, regex.X, regex.S, regex.L]:
+            self.assertEqual(repr(type(regex.compile('^pattern$', flag))),
+              self.PATTERN_CLASS)
+
+    def test_sre_character_literals(self):
+        for i in [0, 8, 16, 32, 64, 127, 128, 255]:
+            self.assertEqual(bool(regex.match(r"\%03o" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"\%03o0" % i, chr(i) + "0")),
+              True)
+            self.assertEqual(bool(regex.match(r"\%03o8" % i, chr(i) + "8")),
+              True)
+            self.assertEqual(bool(regex.match(r"\x%02x" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"\x%02x0" % i, chr(i) + "0")),
+              True)
+            self.assertEqual(bool(regex.match(r"\x%02xz" % i, chr(i) + "z")),
+              True)
+
+        self.assertRaisesRegex(regex.error, self.INVALID_GROUP_REF, lambda:
+          regex.match(r"\911", ""))
+
+    def test_sre_character_class_literals(self):
+        for i in [0, 8, 16, 32, 64, 127, 128, 255]:
+            self.assertEqual(bool(regex.match(r"[\%03o]" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"[\%03o0]" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"[\%03o8]" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"[\x%02x]" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"[\x%02x0]" % i, chr(i))), True)
+            self.assertEqual(bool(regex.match(r"[\x%02xz]" % i, chr(i))), True)
+
+        self.assertRaisesRegex(regex.error, self.BAD_OCTAL_ESCAPE, lambda:
+          regex.match(r"[\911]", ""))
+
+    def test_bug_113254(self):
+        self.assertEqual(regex.match(r'(a)|(b)', 'b').start(1), -1)
+        self.assertEqual(regex.match(r'(a)|(b)', 'b').end(1), -1)
+        self.assertEqual(regex.match(r'(a)|(b)', 'b').span(1), (-1, -1))
+
+    def test_bug_527371(self):
+        # Bug described in patches 527371/672491.
+        self.assertEqual(regex.match(r'(a)?a','a').lastindex, None)
+        self.assertEqual(regex.match(r'(a)(b)?b','ab').lastindex, 1)
+        self.assertEqual(regex.match(r'(?Pa)(?Pb)?b','ab').lastgroup,
+          'a')
+        self.assertEqual(regex.match("(?Pa(b))", "ab").lastgroup, 'a')
+        self.assertEqual(regex.match("((a))", "a").lastindex, 1)
+
+    def test_bug_545855(self):
+        # Bug 545855 -- This pattern failed to cause a compile error as it
+        # should, instead provoking a TypeError.
+        self.assertRaisesRegex(regex.error, self.BAD_SET, lambda:
+          regex.compile('foo[a-'))
+
+    def test_bug_418626(self):
+        # Bugs 418626 at al. -- Testing Greg Chapman's addition of op code
+        # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of
+        # pattern '*?' on a long string.
+        self.assertEqual(regex.match('.*?c', 10000 * 'ab' + 'cd').end(0),
+          20001)
+        self.assertEqual(regex.match('.*?cd', 5000 * 'ab' + 'c' + 5000 * 'ab' +
+          'cde').end(0), 20003)
+        self.assertEqual(regex.match('.*?cd', 20000 * 'abc' + 'de').end(0),
+          60001)
+        # Non-simple '*?' still used to hit the recursion limit, before the
+        # non-recursive scheme was implemented.
+        self.assertEqual(regex.search('(a|b)*?c', 10000 * 'ab' + 'cd').end(0),
+          20001)
+
+    def test_bug_612074(self):
+        pat = "[" + regex.escape("\u2039") + "]"
+        self.assertEqual(regex.compile(pat) and 1, 1)
+
+    def test_stack_overflow(self):
+        # Nasty cases that used to overflow the straightforward recursive
+        # implementation of repeated groups.
+        self.assertEqual(regex.match('(x)*', 50000 * 'x')[1], 'x')
+        self.assertEqual(regex.match('(x)*y', 50000 * 'x' + 'y')[1], 'x')
+        self.assertEqual(regex.match('(x)*?y', 50000 * 'x' + 'y')[1], 'x')
+
+    def test_scanner(self):
+        def s_ident(scanner, token): return token
+        def s_operator(scanner, token): return "op%s" % token
+        def s_float(scanner, token): return float(token)
+        def s_int(scanner, token): return int(token)
+
+        scanner = regex.Scanner([(r"[a-zA-Z_]\w*", s_ident), (r"\d+\.\d*",
+          s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+",
+            None), ])
+
+        self.assertEqual(repr(type(scanner.scanner.scanner("").pattern)),
+          self.PATTERN_CLASS)
+
+        self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"), (['sum',
+          'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], ''))
+
+    def test_bug_448951(self):
+        # Bug 448951 (similar to 429357, but with single char match).
+        # (Also test greedy matches.)
+        for op in '', '?', '*':
+            self.assertEqual(regex.match(r'((.%s):)?z' % op, 'z')[:], ('z',
+              None, None))
+            self.assertEqual(regex.match(r'((.%s):)?z' % op, 'a:z')[:], ('a:z',
+              'a:', 'a'))
+
+    def test_bug_725106(self):
+        # Capturing groups in alternatives in repeats.
+        self.assertEqual(regex.match('^((a)|b)*', 'abc')[:], ('ab', 'b', 'a'))
+        self.assertEqual(regex.match('^(([ab])|c)*', 'abc')[:], ('abc', 'c',
+          'b'))
+        self.assertEqual(regex.match('^((d)|[ab])*', 'abc')[:], ('ab', 'b',
+          None))
+        self.assertEqual(regex.match('^((a)c|[ab])*', 'abc')[:], ('ab', 'b',
+          None))
+        self.assertEqual(regex.match('^((a)|b)*?c', 'abc')[:], ('abc', 'b',
+          'a'))
+        self.assertEqual(regex.match('^(([ab])|c)*?d', 'abcd')[:], ('abcd',
+          'c', 'b'))
+        self.assertEqual(regex.match('^((d)|[ab])*?c', 'abc')[:], ('abc', 'b',
+          None))
+        self.assertEqual(regex.match('^((a)c|[ab])*?c', 'abc')[:], ('abc', 'b',
+          None))
+
+    def test_bug_725149(self):
+        # Mark_stack_base restoring before restoring marks.
+        self.assertEqual(regex.match('(a)(?:(?=(b)*)c)*', 'abb')[:], ('a', 'a',
+          None))
+        self.assertEqual(regex.match('(a)((?!(b)*))*', 'abb')[:], ('a', 'a',
+          None, None))
+
+    def test_bug_764548(self):
+        # Bug 764548, regex.compile() barfs on str/unicode subclasses.
+        class my_unicode(str): pass
+        pat = regex.compile(my_unicode("abc"))
+        self.assertEqual(pat.match("xyz"), None)
+
+    def test_finditer(self):
+        it = regex.finditer(r":+", "a:b::c:::d")
+        self.assertEqual([item[0] for item in it], [':', '::', ':::'])
+
+    def test_bug_926075(self):
+        if regex.compile('bug_926075') is regex.compile(b'bug_926075'):
+            self.fail()
+
+    def test_bug_931848(self):
+        pattern = "[\u002E\u3002\uFF0E\uFF61]"
+        self.assertEqual(regex.compile(pattern).split("a.b.c"), ['a', 'b',
+          'c'])
+
+    def test_bug_581080(self):
+        it = regex.finditer(r"\s", "a b")
+        self.assertEqual(next(it).span(), (1, 2))
+        self.assertRaises(StopIteration, lambda: next(it))
+
+        scanner = regex.compile(r"\s").scanner("a b")
+        self.assertEqual(scanner.search().span(), (1, 2))
+        self.assertEqual(scanner.search(), None)
+
+    def test_bug_817234(self):
+        it = regex.finditer(r".*", "asdf")
+        self.assertEqual(next(it).span(), (0, 4))
+        self.assertEqual(next(it).span(), (4, 4))
+        self.assertRaises(StopIteration, lambda: next(it))
+
+    def test_empty_array(self):
+        # SF buf 1647541.
+        import array
+        for typecode in 'bBhHiIlLfd':
+            a = array.array(typecode)
+            self.assertEqual(regex.compile(b"bla").match(a), None)
+            self.assertEqual(regex.compile(b"").match(a)[1 : ], ())
+
+    def test_inline_flags(self):
+        # Bug #1700.
+        upper_char = chr(0x1ea0) # Latin Capital Letter A with Dot Below
+        lower_char = chr(0x1ea1) # Latin Small Letter A with Dot Below
+
+        p = regex.compile(upper_char, regex.I | regex.U)
+        self.assertEqual(bool(p.match(lower_char)), True)
+
+        p = regex.compile(lower_char, regex.I | regex.U)
+        self.assertEqual(bool(p.match(upper_char)), True)
+
+        p = regex.compile('(?i)' + upper_char, regex.U)
+        self.assertEqual(bool(p.match(lower_char)), True)
+
+        p = regex.compile('(?i)' + lower_char, regex.U)
+        self.assertEqual(bool(p.match(upper_char)), True)
+
+        p = regex.compile('(?iu)' + upper_char)
+        self.assertEqual(bool(p.match(lower_char)), True)
+
+        p = regex.compile('(?iu)' + lower_char)
+        self.assertEqual(bool(p.match(upper_char)), True)
+
+        # Changed to positional flags in regex 2023.12.23.
+        self.assertEqual(bool(regex.match(r"(?i)a", "A")), True)
+        self.assertEqual(regex.match(r"a(?i)", "A"), None)
+
+    def test_dollar_matches_twice(self):
+        # $ matches the end of string, and just before the terminating \n.
+        pattern = regex.compile('$')
+        self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#')
+        self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#')
+        self.assertEqual(pattern.sub('#', '\n'), '#\n#')
+
+        pattern = regex.compile('$', regex.MULTILINE)
+        self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#')
+        self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#')
+        self.assertEqual(pattern.sub('#', '\n'), '#\n#')
+
+    def test_bytes_str_mixing(self):
+        # Mixing str and bytes is disallowed.
+        pat = regex.compile('.')
+        bpat = regex.compile(b'.')
+        self.assertRaisesRegex(TypeError, self.STR_PAT_ON_BYTES, lambda:
+          pat.match(b'b'))
+        self.assertRaisesRegex(TypeError, self.BYTES_PAT_ON_STR, lambda:
+          bpat.match('b'))
+        self.assertRaisesRegex(TypeError, self.STR_PAT_BYTES_TEMPL, lambda:
+          pat.sub(b'b', 'c'))
+        self.assertRaisesRegex(TypeError, self.STR_PAT_ON_BYTES, lambda:
+          pat.sub('b', b'c'))
+        self.assertRaisesRegex(TypeError, self.STR_PAT_ON_BYTES, lambda:
+          pat.sub(b'b', b'c'))
+        self.assertRaisesRegex(TypeError, self.BYTES_PAT_ON_STR, lambda:
+          bpat.sub(b'b', 'c'))
+        self.assertRaisesRegex(TypeError, self.BYTES_PAT_STR_TEMPL, lambda:
+          bpat.sub('b', b'c'))
+        self.assertRaisesRegex(TypeError, self.BYTES_PAT_ON_STR, lambda:
+          bpat.sub('b', 'c'))
+
+        self.assertRaisesRegex(ValueError, self.BYTES_PAT_UNI_FLAG, lambda:
+          regex.compile(br'\w', regex.UNICODE))
+        self.assertRaisesRegex(ValueError, self.BYTES_PAT_UNI_FLAG, lambda:
+          regex.compile(br'(?u)\w'))
+        self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda:
+          regex.compile(r'\w', regex.UNICODE | regex.ASCII))
+        self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda:
+          regex.compile(r'(?u)\w', regex.ASCII))
+        self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda:
+          regex.compile(r'(?a)\w', regex.UNICODE))
+        self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda:
+          regex.compile(r'(?au)\w'))
+
+    def test_ascii_and_unicode_flag(self):
+        # String patterns.
+        for flags in (0, regex.UNICODE):
+            pat = regex.compile('\xc0', flags | regex.IGNORECASE)
+            self.assertEqual(bool(pat.match('\xe0')), True)
+            pat = regex.compile(r'\w', flags)
+            self.assertEqual(bool(pat.match('\xe0')), True)
+
+        pat = regex.compile('\xc0', regex.ASCII | regex.IGNORECASE)
+        self.assertEqual(pat.match('\xe0'), None)
+        pat = regex.compile('(?a)\xc0', regex.IGNORECASE)
+        self.assertEqual(pat.match('\xe0'), None)
+        pat = regex.compile(r'\w', regex.ASCII)
+        self.assertEqual(pat.match('\xe0'), None)
+        pat = regex.compile(r'(?a)\w')
+        self.assertEqual(pat.match('\xe0'), None)
+
+        # Bytes patterns.
+        for flags in (0, regex.ASCII):
+            pat = regex.compile(b'\xc0', flags | regex.IGNORECASE)
+            self.assertEqual(pat.match(b'\xe0'), None)
+            pat = regex.compile(br'\w')
+            self.assertEqual(pat.match(b'\xe0'), None)
+
+        self.assertRaisesRegex(ValueError, self.MIXED_FLAGS, lambda:
+          regex.compile(r'(?au)\w'))
+
+    def test_subscripting_match(self):
+        m = regex.match(r'(?\w)', 'xy')
+        if not m:
+            self.fail("Failed: expected match but returned None")
+        elif not m or m[0] != m.group(0) or m[1] != m.group(1):
+            self.fail("Failed")
+        if not m:
+            self.fail("Failed: expected match but returned None")
+        elif m[:] != ('x', 'x'):
+            self.fail("Failed: expected \"('x', 'x')\" but got {} instead".format(ascii(m[:])))
+
+    def test_new_named_groups(self):
+        m0 = regex.match(r'(?P\w)', 'x')
+        m1 = regex.match(r'(?\w)', 'x')
+        if not (m0 and m1 and m0[:] == m1[:]):
+            self.fail("Failed")
+
+    def test_properties(self):
+        self.assertEqual(regex.match(b'(?ai)\xC0', b'\xE0'), None)
+        self.assertEqual(regex.match(br'(?ai)\xC0', b'\xE0'), None)
+        self.assertEqual(regex.match(br'(?a)\w', b'\xE0'), None)
+        self.assertEqual(bool(regex.match(r'\w', '\xE0')), True)
+
+        # Dropped the following test. It's not possible to determine what the
+        # correct result should be in the general case.
+#        self.assertEqual(bool(regex.match(br'(?L)\w', b'\xE0')),
+#          b'\xE0'.isalnum())
+
+        self.assertEqual(bool(regex.match(br'(?L)\d', b'0')), True)
+        self.assertEqual(bool(regex.match(br'(?L)\s', b' ')), True)
+        self.assertEqual(bool(regex.match(br'(?L)\w', b'a')), True)
+        self.assertEqual(regex.match(br'(?L)\d', b'?'), None)
+        self.assertEqual(regex.match(br'(?L)\s', b'?'), None)
+        self.assertEqual(regex.match(br'(?L)\w', b'?'), None)
+
+        self.assertEqual(regex.match(br'(?L)\D', b'0'), None)
+        self.assertEqual(regex.match(br'(?L)\S', b' '), None)
+        self.assertEqual(regex.match(br'(?L)\W', b'a'), None)
+        self.assertEqual(bool(regex.match(br'(?L)\D', b'?')), True)
+        self.assertEqual(bool(regex.match(br'(?L)\S', b'?')), True)
+        self.assertEqual(bool(regex.match(br'(?L)\W', b'?')), True)
+
+        self.assertEqual(bool(regex.match(r'\p{Cyrillic}',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'(?i)\p{Cyrillic}',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{IsCyrillic}',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{Script=Cyrillic}',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{InCyrillic}',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{Block=Cyrillic}',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:Cyrillic:]]',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:IsCyrillic:]]',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:Script=Cyrillic:]]',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:InCyrillic:]]',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:Block=Cyrillic:]]',
+          '\N{CYRILLIC CAPITAL LETTER A}')), True)
+
+        self.assertEqual(bool(regex.match(r'\P{Cyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\P{IsCyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\P{Script=Cyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\P{InCyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\P{Block=Cyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{^Cyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{^IsCyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{^Script=Cyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{^InCyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'\p{^Block=Cyrillic}',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:^Cyrillic:]]',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:^IsCyrillic:]]',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:^Script=Cyrillic:]]',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:^InCyrillic:]]',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+        self.assertEqual(bool(regex.match(r'[[:^Block=Cyrillic:]]',
+          '\N{LATIN CAPITAL LETTER A}')), True)
+
+        self.assertEqual(bool(regex.match(r'\d', '0')), True)
+        self.assertEqual(bool(regex.match(r'\s', ' ')), True)
+        self.assertEqual(bool(regex.match(r'\w', 'A')), True)
+        self.assertEqual(regex.match(r"\d", "?"), None)
+        self.assertEqual(regex.match(r"\s", "?"), None)
+        self.assertEqual(regex.match(r"\w", "?"), None)
+        self.assertEqual(regex.match(r"\D", "0"), None)
+        self.assertEqual(regex.match(r"\S", " "), None)
+        self.assertEqual(regex.match(r"\W", "A"), None)
+        self.assertEqual(bool(regex.match(r'\D', '?')), True)
+        self.assertEqual(bool(regex.match(r'\S', '?')), True)
+        self.assertEqual(bool(regex.match(r'\W', '?')), True)
+
+        self.assertEqual(bool(regex.match(r'\p{L}', 'A')), True)
+        self.assertEqual(bool(regex.match(r'\p{L}', 'a')), True)
+        self.assertEqual(bool(regex.match(r'\p{Lu}', 'A')), True)
+        self.assertEqual(bool(regex.match(r'\p{Ll}', 'a')), True)
+
+        self.assertEqual(bool(regex.match(r'(?i)a', 'a')), True)
+        self.assertEqual(bool(regex.match(r'(?i)a', 'A')), True)
+
+        self.assertEqual(bool(regex.match(r'\w', '0')), True)
+        self.assertEqual(bool(regex.match(r'\w', 'a')), True)
+        self.assertEqual(bool(regex.match(r'\w', '_')), True)
+
+        self.assertEqual(regex.match(r"\X", "\xE0").span(), (0, 1))
+        self.assertEqual(regex.match(r"\X", "a\u0300").span(), (0, 2))
+        self.assertEqual(regex.findall(r"\X",
+          "a\xE0a\u0300e\xE9e\u0301"), ['a', '\xe0', 'a\u0300', 'e',
+          '\xe9', 'e\u0301'])
+        self.assertEqual(regex.findall(r"\X{3}",
+          "a\xE0a\u0300e\xE9e\u0301"), ['a\xe0a\u0300', 'e\xe9e\u0301'])
+        self.assertEqual(regex.findall(r"\X", "\r\r\n\u0301A\u0301"),
+          ['\r', '\r\n', '\u0301', 'A\u0301'])
+
+        self.assertEqual(bool(regex.match(r'\p{Ll}', 'a')), True)
+
+        chars_u = "-09AZaz_\u0393\u03b3"
+        chars_b = b"-09AZaz_"
+        word_set = set("Ll Lm Lo Lt Lu Mc Me Mn Nd Nl No Pc".split())
+
+        tests = [
+            (r"\w", chars_u, "09AZaz_\u0393\u03b3"),
+            (r"[[:word:]]", chars_u, "09AZaz_\u0393\u03b3"),
+            (r"\W", chars_u, "-"),
+            (r"[[:^word:]]", chars_u, "-"),
+            (r"\d", chars_u, "09"),
+            (r"[[:digit:]]", chars_u, "09"),
+            (r"\D", chars_u, "-AZaz_\u0393\u03b3"),
+            (r"[[:^digit:]]", chars_u, "-AZaz_\u0393\u03b3"),
+            (r"[[:alpha:]]", chars_u, "AZaz\u0393\u03b3"),
+            (r"[[:^alpha:]]", chars_u, "-09_"),
+            (r"[[:alnum:]]", chars_u, "09AZaz\u0393\u03b3"),
+            (r"[[:^alnum:]]", chars_u, "-_"),
+            (r"[[:xdigit:]]", chars_u, "09Aa"),
+            (r"[[:^xdigit:]]", chars_u, "-Zz_\u0393\u03b3"),
+            (r"\p{InBasicLatin}", "a\xE1", "a"),
+            (r"\P{InBasicLatin}", "a\xE1", "\xE1"),
+            (r"(?i)\p{InBasicLatin}", "a\xE1", "a"),
+            (r"(?i)\P{InBasicLatin}", "a\xE1", "\xE1"),
+
+            (br"(?L)\w", chars_b, b"09AZaz_"),
+            (br"(?L)[[:word:]]", chars_b, b"09AZaz_"),
+            (br"(?L)\W", chars_b, b"-"),
+            (br"(?L)[[:^word:]]", chars_b, b"-"),
+            (br"(?L)\d", chars_b, b"09"),
+            (br"(?L)[[:digit:]]", chars_b, b"09"),
+            (br"(?L)\D", chars_b, b"-AZaz_"),
+            (br"(?L)[[:^digit:]]", chars_b, b"-AZaz_"),
+            (br"(?L)[[:alpha:]]", chars_b, b"AZaz"),
+            (br"(?L)[[:^alpha:]]", chars_b, b"-09_"),
+            (br"(?L)[[:alnum:]]", chars_b, b"09AZaz"),
+            (br"(?L)[[:^alnum:]]", chars_b, b"-_"),
+            (br"(?L)[[:xdigit:]]", chars_b, b"09Aa"),
+            (br"(?L)[[:^xdigit:]]", chars_b, b"-Zz_"),
+
+            (br"(?a)\w", chars_b, b"09AZaz_"),
+            (br"(?a)[[:word:]]", chars_b, b"09AZaz_"),
+            (br"(?a)\W", chars_b, b"-"),
+            (br"(?a)[[:^word:]]", chars_b, b"-"),
+            (br"(?a)\d", chars_b, b"09"),
+            (br"(?a)[[:digit:]]", chars_b, b"09"),
+            (br"(?a)\D", chars_b, b"-AZaz_"),
+            (br"(?a)[[:^digit:]]", chars_b, b"-AZaz_"),
+            (br"(?a)[[:alpha:]]", chars_b, b"AZaz"),
+            (br"(?a)[[:^alpha:]]", chars_b, b"-09_"),
+            (br"(?a)[[:alnum:]]", chars_b, b"09AZaz"),
+            (br"(?a)[[:^alnum:]]", chars_b, b"-_"),
+            (br"(?a)[[:xdigit:]]", chars_b, b"09Aa"),
+            (br"(?a)[[:^xdigit:]]", chars_b, b"-Zz_"),
+        ]
+        for pattern, chars, expected in tests:
+            try:
+                if chars[ : 0].join(regex.findall(pattern, chars)) != expected:
+                    self.fail("Failed: {}".format(pattern))
+            except Exception as e:
+                self.fail("Failed: {} raised {}".format(pattern, ascii(e)))
+
+        self.assertEqual(bool(regex.match(r"\p{NumericValue=0}", "0")),
+          True)
+        self.assertEqual(bool(regex.match(r"\p{NumericValue=1/2}",
+          "\N{VULGAR FRACTION ONE HALF}")), True)
+        self.assertEqual(bool(regex.match(r"\p{NumericValue=0.5}",
+          "\N{VULGAR FRACTION ONE HALF}")), True)
+
+    def test_word_class(self):
+        self.assertEqual(regex.findall(r"\w+",
+          " \u0939\u093f\u0928\u094d\u0926\u0940,"),
+          ['\u0939\u093f\u0928\u094d\u0926\u0940'])
+        self.assertEqual(regex.findall(r"\W+",
+          " \u0939\u093f\u0928\u094d\u0926\u0940,"), [' ', ','])
+        self.assertEqual(regex.split(r"(?V1)\b",
+          " \u0939\u093f\u0928\u094d\u0926\u0940,"), [' ',
+          '\u0939\u093f\u0928\u094d\u0926\u0940', ','])
+        self.assertEqual(regex.split(r"(?V1)\B",
+          " \u0939\u093f\u0928\u094d\u0926\u0940,"), ['', ' \u0939',
+          '\u093f', '\u0928', '\u094d', '\u0926', '\u0940,', ''])
+
+    def test_search_anchor(self):
+        self.assertEqual(regex.findall(r"\G\w{2}", "abcd ef"), ['ab', 'cd'])
+
+    def test_search_reverse(self):
+        self.assertEqual(regex.findall(r"(?r).", "abc"), ['c', 'b', 'a'])
+        self.assertEqual(regex.findall(r"(?r).", "abc", overlapped=True), ['c',
+          'b', 'a'])
+        self.assertEqual(regex.findall(r"(?r)..", "abcde"), ['de', 'bc'])
+        self.assertEqual(regex.findall(r"(?r)..", "abcde", overlapped=True),
+          ['de', 'cd', 'bc', 'ab'])
+        self.assertEqual(regex.findall(r"(?r)(.)(-)(.)", "a-b-c",
+          overlapped=True), [("b", "-", "c"), ("a", "-", "b")])
+
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r).", "abc")], ['c',
+          'b', 'a'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde",
+          overlapped=True)], ['de', 'cd', 'bc', 'ab'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r).", "abc")], ['c',
+          'b', 'a'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde",
+          overlapped=True)], ['de', 'cd', 'bc', 'ab'])
+
+        self.assertEqual(regex.findall(r"^|\w+", "foo bar"), ['', 'foo',
+          'bar'])
+        self.assertEqual(regex.findall(r"(?V1)^|\w+", "foo bar"), ['', 'foo',
+          'bar'])
+        self.assertEqual(regex.findall(r"(?r)^|\w+", "foo bar"), ['bar', 'foo',
+          ''])
+        self.assertEqual(regex.findall(r"(?rV1)^|\w+", "foo bar"), ['bar',
+          'foo', ''])
+
+        self.assertEqual([m[0] for m in regex.finditer(r"^|\w+", "foo bar")],
+          ['', 'foo', 'bar'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?V1)^|\w+",
+          "foo bar")], ['', 'foo', 'bar'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)^|\w+",
+          "foo bar")], ['bar', 'foo', ''])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?rV1)^|\w+",
+          "foo bar")], ['bar', 'foo', ''])
+
+        self.assertEqual(regex.findall(r"\G\w{2}", "abcd ef"), ['ab', 'cd'])
+        self.assertEqual(regex.findall(r".{2}(?<=\G.*)", "abcd"), ['ab', 'cd'])
+        self.assertEqual(regex.findall(r"(?r)\G\w{2}", "abcd ef"), [])
+        self.assertEqual(regex.findall(r"(?r)\w{2}\G", "abcd ef"), ['ef'])
+
+        self.assertEqual(regex.findall(r"q*", "qqwe"), ['qq', '', '', ''])
+        self.assertEqual(regex.findall(r"(?V1)q*", "qqwe"), ['qq', '', '', ''])
+        self.assertEqual(regex.findall(r"(?r)q*", "qqwe"), ['', '', 'qq', ''])
+        self.assertEqual(regex.findall(r"(?rV1)q*", "qqwe"), ['', '', 'qq',
+          ''])
+
+        self.assertEqual(regex.findall(".", "abcd", pos=1, endpos=3), ['b',
+          'c'])
+        self.assertEqual(regex.findall(".", "abcd", pos=1, endpos=-1), ['b',
+          'c'])
+        self.assertEqual([m[0] for m in regex.finditer(".", "abcd", pos=1,
+          endpos=3)], ['b', 'c'])
+        self.assertEqual([m[0] for m in regex.finditer(".", "abcd", pos=1,
+          endpos=-1)], ['b', 'c'])
+
+        self.assertEqual([m[0] for m in regex.finditer("(?r).", "abcd", pos=1,
+          endpos=3)], ['c', 'b'])
+        self.assertEqual([m[0] for m in regex.finditer("(?r).", "abcd", pos=1,
+          endpos=-1)], ['c', 'b'])
+        self.assertEqual(regex.findall("(?r).", "abcd", pos=1, endpos=3), ['c',
+          'b'])
+        self.assertEqual(regex.findall("(?r).", "abcd", pos=1, endpos=-1),
+          ['c', 'b'])
+
+        self.assertEqual(regex.findall(r"[ab]", "aB", regex.I), ['a', 'B'])
+        self.assertEqual(regex.findall(r"(?r)[ab]", "aB", regex.I), ['B', 'a'])
+
+        self.assertEqual(regex.findall(r"(?r).{2}", "abc"), ['bc'])
+        self.assertEqual(regex.findall(r"(?r).{2}", "abc", overlapped=True),
+          ['bc', 'ab'])
+        self.assertEqual(regex.findall(r"(\w+) (\w+)",
+          "first second third fourth fifth"), [('first', 'second'), ('third',
+          'fourth')])
+        self.assertEqual(regex.findall(r"(?r)(\w+) (\w+)",
+          "first second third fourth fifth"), [('fourth', 'fifth'), ('second',
+          'third')])
+
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r).{2}", "abc")],
+          ['bc'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r).{2}", "abc",
+          overlapped=True)], ['bc', 'ab'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(\w+) (\w+)",
+          "first second third fourth fifth")], ['first second',
+          'third fourth'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)(\w+) (\w+)",
+          "first second third fourth fifth")], ['fourth fifth',
+          'second third'])
+
+        self.assertEqual(regex.search("abcdef", "abcdef").span(), (0, 6))
+        self.assertEqual(regex.search("(?r)abcdef", "abcdef").span(), (0, 6))
+        self.assertEqual(regex.search("(?i)abcdef", "ABCDEF").span(), (0, 6))
+        self.assertEqual(regex.search("(?ir)abcdef", "ABCDEF").span(), (0, 6))
+
+        self.assertEqual(regex.sub(r"(.)", r"\1", "abc"), 'abc')
+        self.assertEqual(regex.sub(r"(?r)(.)", r"\1", "abc"), 'abc')
+
+    def test_atomic(self):
+        # Issue 433030.
+        self.assertEqual(regex.search(r"(?>a*)a", "aa"), None)
+
+    def test_possessive(self):
+        # Single-character non-possessive.
+        self.assertEqual(regex.search(r"a?a", "a").span(), (0, 1))
+        self.assertEqual(regex.search(r"a*a", "aaa").span(), (0, 3))
+        self.assertEqual(regex.search(r"a+a", "aaa").span(), (0, 3))
+        self.assertEqual(regex.search(r"a{1,3}a", "aaa").span(), (0, 3))
+
+        # Multiple-character non-possessive.
+        self.assertEqual(regex.search(r"(?:ab)?ab", "ab").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?:ab)*ab", "ababab").span(), (0, 6))
+        self.assertEqual(regex.search(r"(?:ab)+ab", "ababab").span(), (0, 6))
+        self.assertEqual(regex.search(r"(?:ab){1,3}ab", "ababab").span(), (0,
+          6))
+
+        # Single-character possessive.
+        self.assertEqual(regex.search(r"a?+a", "a"), None)
+        self.assertEqual(regex.search(r"a*+a", "aaa"), None)
+        self.assertEqual(regex.search(r"a++a", "aaa"), None)
+        self.assertEqual(regex.search(r"a{1,3}+a", "aaa"), None)
+
+        # Multiple-character possessive.
+        self.assertEqual(regex.search(r"(?:ab)?+ab", "ab"), None)
+        self.assertEqual(regex.search(r"(?:ab)*+ab", "ababab"), None)
+        self.assertEqual(regex.search(r"(?:ab)++ab", "ababab"), None)
+        self.assertEqual(regex.search(r"(?:ab){1,3}+ab", "ababab"), None)
+
+    def test_zerowidth(self):
+        # Issue 3262.
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.split(r"\b", "a b"), ['', 'a', ' ', 'b',
+              ''])
+        else:
+            self.assertEqual(regex.split(r"\b", "a b"), ['a b'])
+        self.assertEqual(regex.split(r"(?V1)\b", "a b"), ['', 'a', ' ', 'b',
+          ''])
+
+        # Issue 1647489.
+        self.assertEqual(regex.findall(r"^|\w+", "foo bar"), ['', 'foo',
+          'bar'])
+        self.assertEqual([m[0] for m in regex.finditer(r"^|\w+", "foo bar")],
+          ['', 'foo', 'bar'])
+        self.assertEqual(regex.findall(r"(?r)^|\w+", "foo bar"), ['bar',
+          'foo', ''])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)^|\w+",
+          "foo bar")], ['bar', 'foo', ''])
+        self.assertEqual(regex.findall(r"(?V1)^|\w+", "foo bar"), ['', 'foo',
+          'bar'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?V1)^|\w+",
+          "foo bar")], ['', 'foo', 'bar'])
+        self.assertEqual(regex.findall(r"(?rV1)^|\w+", "foo bar"), ['bar',
+          'foo', ''])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?rV1)^|\w+",
+          "foo bar")], ['bar', 'foo', ''])
+
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.split("", "xaxbxc"), ['', 'x', 'a', 'x',
+              'b', 'x', 'c', ''])
+            self.assertEqual([m for m in regex.splititer("", "xaxbxc")], ['',
+              'x', 'a', 'x', 'b', 'x', 'c', ''])
+        else:
+            self.assertEqual(regex.split("", "xaxbxc"), ['xaxbxc'])
+            self.assertEqual([m for m in regex.splititer("", "xaxbxc")],
+              ['xaxbxc'])
+
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.split("(?r)", "xaxbxc"), ['', 'c', 'x', 'b',
+              'x', 'a', 'x', ''])
+            self.assertEqual([m for m in regex.splititer("(?r)", "xaxbxc")],
+              ['', 'c', 'x', 'b', 'x', 'a', 'x', ''])
+        else:
+            self.assertEqual(regex.split("(?r)", "xaxbxc"), ['xaxbxc'])
+            self.assertEqual([m for m in regex.splititer("(?r)", "xaxbxc")],
+              ['xaxbxc'])
+
+        self.assertEqual(regex.split("(?V1)", "xaxbxc"), ['', 'x', 'a', 'x',
+          'b', 'x', 'c', ''])
+        self.assertEqual([m for m in regex.splititer("(?V1)", "xaxbxc")], ['',
+          'x', 'a', 'x', 'b', 'x', 'c', ''])
+
+        self.assertEqual(regex.split("(?rV1)", "xaxbxc"), ['', 'c', 'x', 'b',
+          'x', 'a', 'x', ''])
+        self.assertEqual([m for m in regex.splititer("(?rV1)", "xaxbxc")], ['',
+          'c', 'x', 'b', 'x', 'a', 'x', ''])
+
+    def test_scoped_and_inline_flags(self):
+        # Issues 433028, 433024, 433027.
+        self.assertEqual(regex.search(r"(?i)Ab", "ab").span(), (0, 2))
+        self.assertEqual(regex.search(r"(?i:A)b", "ab").span(), (0, 2))
+        # Changed to positional flags in regex 2023.12.23.
+        self.assertEqual(regex.search(r"A(?i)b", "ab"), None)
+
+        self.assertEqual(regex.search(r"(?V0)Ab", "ab"), None)
+        self.assertEqual(regex.search(r"(?V1)Ab", "ab"), None)
+        self.assertEqual(regex.search(r"(?-i)Ab", "ab", flags=regex.I), None)
+        self.assertEqual(regex.search(r"(?-i:A)b", "ab", flags=regex.I), None)
+        self.assertEqual(regex.search(r"A(?-i)b", "ab", flags=regex.I).span(),
+          (0, 2))
+
+    def test_repeated_repeats(self):
+        # Issue 2537.
+        self.assertEqual(regex.search(r"(?:a+)+", "aaa").span(), (0, 3))
+        self.assertEqual(regex.search(r"(?:(?:ab)+c)+", "abcabc").span(), (0,
+          6))
+
+        # Hg issue 286.
+        self.assertEqual(regex.search(r"(?:a+){2,}", "aaa").span(), (0, 3))
+
+    def test_lookbehind(self):
+        self.assertEqual(regex.search(r"123(?<=a\d+)", "a123").span(), (1, 4))
+        self.assertEqual(regex.search(r"123(?<=a\d+)", "b123"), None)
+        self.assertEqual(regex.search(r"123(?= (3, 7, 0):
+            self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "xy"),
+              'y-x-')
+        else:
+            self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "xy"),
+              'y-x')
+        self.assertEqual(regex.sub(r"(?V1)(x)?(y)?", r"\2-\1", "xy"), 'y-x-')
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "x"), '-x-')
+        else:
+            self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "x"), '-x')
+        self.assertEqual(regex.sub(r"(?V1)(x)?(y)?", r"\2-\1", "x"), '-x-')
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "y"), 'y--')
+        else:
+            self.assertEqual(regex.sub(r"(?V0)(x)?(y)?", r"\2-\1", "y"), 'y-')
+        self.assertEqual(regex.sub(r"(?V1)(x)?(y)?", r"\2-\1", "y"), 'y--')
+
+    def test_bug_10328 (self):
+        # Issue 10328.
+        pat = regex.compile(r'(?mV0)(?P[ \t]+\r*$)|(?P(?<=[^\n])\Z)')
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(pat.subn(lambda m: '<' + m.lastgroup + '>',
+              'foobar '), ('foobar', 2))
+        else:
+            self.assertEqual(pat.subn(lambda m: '<' + m.lastgroup + '>',
+              'foobar '), ('foobar', 1))
+        self.assertEqual([m.group() for m in pat.finditer('foobar ')], [' ',
+          ''])
+        pat = regex.compile(r'(?mV1)(?P[ \t]+\r*$)|(?P(?<=[^\n])\Z)')
+        self.assertEqual(pat.subn(lambda m: '<' + m.lastgroup + '>',
+          'foobar '), ('foobar', 2))
+        self.assertEqual([m.group() for m in pat.finditer('foobar ')], [' ',
+          ''])
+
+    def test_overlapped(self):
+        self.assertEqual(regex.findall(r"..", "abcde"), ['ab', 'cd'])
+        self.assertEqual(regex.findall(r"..", "abcde", overlapped=True), ['ab',
+          'bc', 'cd', 'de'])
+        self.assertEqual(regex.findall(r"(?r)..", "abcde"), ['de', 'bc'])
+        self.assertEqual(regex.findall(r"(?r)..", "abcde", overlapped=True),
+          ['de', 'cd', 'bc', 'ab'])
+        self.assertEqual(regex.findall(r"(.)(-)(.)", "a-b-c", overlapped=True),
+          [("a", "-", "b"), ("b", "-", "c")])
+
+        self.assertEqual([m[0] for m in regex.finditer(r"..", "abcde")], ['ab',
+          'cd'])
+        self.assertEqual([m[0] for m in regex.finditer(r"..", "abcde",
+          overlapped=True)], ['ab', 'bc', 'cd', 'de'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde")],
+          ['de', 'bc'])
+        self.assertEqual([m[0] for m in regex.finditer(r"(?r)..", "abcde",
+          overlapped=True)], ['de', 'cd', 'bc', 'ab'])
+
+        self.assertEqual([m.groups() for m in regex.finditer(r"(.)(-)(.)",
+          "a-b-c", overlapped=True)], [("a", "-", "b"), ("b", "-", "c")])
+        self.assertEqual([m.groups() for m in regex.finditer(r"(?r)(.)(-)(.)",
+          "a-b-c", overlapped=True)], [("b", "-", "c"), ("a", "-", "b")])
+
+    def test_splititer(self):
+        self.assertEqual(regex.split(r",", "a,b,,c,"), ['a', 'b', '', 'c', ''])
+        self.assertEqual([m for m in regex.splititer(r",", "a,b,,c,")], ['a',
+          'b', '', 'c', ''])
+
+    def test_grapheme(self):
+        self.assertEqual(regex.match(r"\X", "\xE0").span(), (0, 1))
+        self.assertEqual(regex.match(r"\X", "a\u0300").span(), (0, 2))
+
+        self.assertEqual(regex.findall(r"\X",
+          "a\xE0a\u0300e\xE9e\u0301"), ['a', '\xe0', 'a\u0300', 'e',
+          '\xe9', 'e\u0301'])
+        self.assertEqual(regex.findall(r"\X{3}",
+          "a\xE0a\u0300e\xE9e\u0301"), ['a\xe0a\u0300', 'e\xe9e\u0301'])
+        self.assertEqual(regex.findall(r"\X", "\r\r\n\u0301A\u0301"),
+          ['\r', '\r\n', '\u0301', 'A\u0301'])
+
+    def test_word_boundary(self):
+        text = 'The quick ("brown") fox can\'t jump 32.3 feet, right?'
+        self.assertEqual(regex.split(r'(?V1)\b', text), ['', 'The', ' ',
+          'quick', ' ("', 'brown', '") ', 'fox', ' ', 'can', "'", 't',
+          ' ', 'jump', ' ', '32', '.', '3', ' ', 'feet', ', ',
+          'right', '?'])
+        self.assertEqual(regex.split(r'(?V1w)\b', text), ['', 'The', ' ',
+          'quick', ' ', '(', '"', 'brown', '"', ')', ' ', 'fox', ' ',
+          "can't", ' ', 'jump', ' ', '32.3', ' ', 'feet', ',', ' ',
+          'right', '?', ''])
+
+        text = "The  fox"
+        self.assertEqual(regex.split(r'(?V1)\b', text), ['', 'The', '  ',
+          'fox', ''])
+        self.assertEqual(regex.split(r'(?V1w)\b', text), ['', 'The', '  ',
+          'fox', ''])
+
+        text = "can't aujourd'hui l'objectif"
+        self.assertEqual(regex.split(r'(?V1)\b', text), ['', 'can', "'",
+          't', ' ', 'aujourd', "'", 'hui', ' ', 'l', "'", 'objectif',
+          ''])
+        self.assertEqual(regex.split(r'(?V1w)\b', text), ['', "can't", ' ',
+          "aujourd'hui", ' ', "l'objectif", ''])
+
+    def test_line_boundary(self):
+        self.assertEqual(regex.findall(r".+", "Line 1\nLine 2\n"), ["Line 1",
+          "Line 2"])
+        self.assertEqual(regex.findall(r".+", "Line 1\rLine 2\r"),
+          ["Line 1\rLine 2\r"])
+        self.assertEqual(regex.findall(r".+", "Line 1\r\nLine 2\r\n"),
+          ["Line 1\r", "Line 2\r"])
+        self.assertEqual(regex.findall(r"(?w).+", "Line 1\nLine 2\n"),
+          ["Line 1", "Line 2"])
+        self.assertEqual(regex.findall(r"(?w).+", "Line 1\rLine 2\r"),
+          ["Line 1", "Line 2"])
+        self.assertEqual(regex.findall(r"(?w).+", "Line 1\r\nLine 2\r\n"),
+          ["Line 1", "Line 2"])
+
+        self.assertEqual(regex.search(r"^abc", "abc").start(), 0)
+        self.assertEqual(regex.search(r"^abc", "\nabc"), None)
+        self.assertEqual(regex.search(r"^abc", "\rabc"), None)
+        self.assertEqual(regex.search(r"(?w)^abc", "abc").start(), 0)
+        self.assertEqual(regex.search(r"(?w)^abc", "\nabc"), None)
+        self.assertEqual(regex.search(r"(?w)^abc", "\rabc"), None)
+
+        self.assertEqual(regex.search(r"abc$", "abc").start(), 0)
+        self.assertEqual(regex.search(r"abc$", "abc\n").start(), 0)
+        self.assertEqual(regex.search(r"abc$", "abc\r"), None)
+        self.assertEqual(regex.search(r"(?w)abc$", "abc").start(), 0)
+        self.assertEqual(regex.search(r"(?w)abc$", "abc\n").start(), 0)
+        self.assertEqual(regex.search(r"(?w)abc$", "abc\r").start(), 0)
+
+        self.assertEqual(regex.search(r"(?m)^abc", "abc").start(), 0)
+        self.assertEqual(regex.search(r"(?m)^abc", "\nabc").start(), 1)
+        self.assertEqual(regex.search(r"(?m)^abc", "\rabc"), None)
+        self.assertEqual(regex.search(r"(?mw)^abc", "abc").start(), 0)
+        self.assertEqual(regex.search(r"(?mw)^abc", "\nabc").start(), 1)
+        self.assertEqual(regex.search(r"(?mw)^abc", "\rabc").start(), 1)
+
+        self.assertEqual(regex.search(r"(?m)abc$", "abc").start(), 0)
+        self.assertEqual(regex.search(r"(?m)abc$", "abc\n").start(), 0)
+        self.assertEqual(regex.search(r"(?m)abc$", "abc\r"), None)
+        self.assertEqual(regex.search(r"(?mw)abc$", "abc").start(), 0)
+        self.assertEqual(regex.search(r"(?mw)abc$", "abc\n").start(), 0)
+        self.assertEqual(regex.search(r"(?mw)abc$", "abc\r").start(), 0)
+
+    def test_branch_reset(self):
+        self.assertEqual(regex.match(r"(?:(a)|(b))(c)", "ac").groups(), ('a',
+          None, 'c'))
+        self.assertEqual(regex.match(r"(?:(a)|(b))(c)", "bc").groups(), (None,
+          'b', 'c'))
+        self.assertEqual(regex.match(r"(?:(?a)|(?b))(?c)",
+          "ac").groups(), ('a', None, 'c'))
+        self.assertEqual(regex.match(r"(?:(?a)|(?b))(?c)",
+          "bc").groups(), (None, 'b', 'c'))
+
+        self.assertEqual(regex.match(r"(?a)(?:(?b)|(?c))(?d)",
+          "abd").groups(), ('a', 'b', None, 'd'))
+        self.assertEqual(regex.match(r"(?a)(?:(?b)|(?c))(?d)",
+          "acd").groups(), ('a', None, 'c', 'd'))
+        self.assertEqual(regex.match(r"(a)(?:(b)|(c))(d)", "abd").groups(),
+          ('a', 'b', None, 'd'))
+
+        self.assertEqual(regex.match(r"(a)(?:(b)|(c))(d)", "acd").groups(),
+          ('a', None, 'c', 'd'))
+        self.assertEqual(regex.match(r"(a)(?|(b)|(b))(d)", "abd").groups(),
+          ('a', 'b', 'd'))
+        self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "ac").groups(),
+          ('a', None, 'c'))
+        self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "bc").groups(),
+          (None, 'b', 'c'))
+        self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "ac").groups(),
+          ('a', 'c'))
+
+        self.assertEqual(regex.match(r"(?|(?a)|(?b))(c)", "bc").groups(),
+          ('b', 'c'))
+
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(?d))(e)",
+          "abe").groups(), ('a', 'b', 'e'))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(?d))(e)",
+          "cde").groups(), ('d', 'c', 'e'))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(d))(e)",
+          "abe").groups(), ('a', 'b', 'e'))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(?c)(d))(e)",
+          "cde").groups(), ('d', 'c', 'e'))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(d))(e)",
+          "abe").groups(), ('a', 'b', 'e'))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(d))(e)",
+          "cde").groups(), ('c', 'd', 'e'))
+
+        # Hg issue 87: Allow duplicate names of groups
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)",
+          "abe").groups(), ("a", "b", "e"))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)",
+          "abe").capturesdict(), {"a": ["a"], "b": ["b"]})
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)",
+          "cde").groups(), ("d", None, "e"))
+        self.assertEqual(regex.match(r"(?|(?a)(?b)|(c)(?d))(e)",
+          "cde").capturesdict(), {"a": ["c", "d"], "b": []})
+
+    def test_set(self):
+        self.assertEqual(regex.match(r"[a]", "a").span(), (0, 1))
+        self.assertEqual(regex.match(r"(?i)[a]", "A").span(), (0, 1))
+        self.assertEqual(regex.match(r"[a-b]", r"a").span(), (0, 1))
+        self.assertEqual(regex.match(r"(?i)[a-b]", r"A").span(), (0, 1))
+
+        self.assertEqual(regex.sub(r"(?V0)([][])", r"-", "a[b]c"), "a-b-c")
+
+        self.assertEqual(regex.findall(r"[\p{Alpha}]", "a0"), ["a"])
+        self.assertEqual(regex.findall(r"(?i)[\p{Alpha}]", "A0"), ["A"])
+
+        self.assertEqual(regex.findall(r"[a\p{Alpha}]", "ab0"), ["a", "b"])
+        self.assertEqual(regex.findall(r"[a\P{Alpha}]", "ab0"), ["a", "0"])
+        self.assertEqual(regex.findall(r"(?i)[a\p{Alpha}]", "ab0"), ["a",
+          "b"])
+        self.assertEqual(regex.findall(r"(?i)[a\P{Alpha}]", "ab0"), ["a",
+          "0"])
+
+        self.assertEqual(regex.findall(r"[a-b\p{Alpha}]", "abC0"), ["a",
+          "b", "C"])
+        self.assertEqual(regex.findall(r"(?i)[a-b\p{Alpha}]", "AbC0"), ["A",
+          "b", "C"])
+
+        self.assertEqual(regex.findall(r"[\p{Alpha}]", "a0"), ["a"])
+        self.assertEqual(regex.findall(r"[\P{Alpha}]", "a0"), ["0"])
+        self.assertEqual(regex.findall(r"[^\p{Alpha}]", "a0"), ["0"])
+        self.assertEqual(regex.findall(r"[^\P{Alpha}]", "a0"), ["a"])
+
+        self.assertEqual("".join(regex.findall(r"[^\d-h]", "a^b12c-h")),
+          'a^bc')
+        self.assertEqual("".join(regex.findall(r"[^\dh]", "a^b12c-h")),
+          'a^bc-')
+        self.assertEqual("".join(regex.findall(r"[^h\s\db]", "a^b 12c-h")),
+          'a^c-')
+        self.assertEqual("".join(regex.findall(r"[^b\w]", "a b")), ' ')
+        self.assertEqual("".join(regex.findall(r"[^b\S]", "a b")), ' ')
+        self.assertEqual("".join(regex.findall(r"[^8\d]", "a 1b2")), 'a b')
+
+        all_chars = "".join(chr(c) for c in range(0x100))
+        self.assertEqual(len(regex.findall(r"\p{ASCII}", all_chars)), 128)
+        self.assertEqual(len(regex.findall(r"\p{Letter}", all_chars)),
+          117)
+        self.assertEqual(len(regex.findall(r"\p{Digit}", all_chars)), 10)
+
+        # Set operators
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Letter}]",
+          all_chars)), 52)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Alnum}&&\p{Letter}]",
+          all_chars)), 52)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Alnum}&&\p{Digit}]",
+          all_chars)), 10)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Cc}]",
+          all_chars)), 33)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}&&\p{Graph}]",
+          all_chars)), 94)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{ASCII}--\p{Cc}]",
+          all_chars)), 95)
+        self.assertEqual(len(regex.findall(r"[\p{Letter}\p{Digit}]",
+          all_chars)), 127)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{Letter}||\p{Digit}]",
+          all_chars)), 127)
+        self.assertEqual(len(regex.findall(r"\p{HexDigit}", all_chars)),
+          22)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{HexDigit}~~\p{Digit}]",
+          all_chars)), 12)
+        self.assertEqual(len(regex.findall(r"(?V1)[\p{Digit}~~\p{HexDigit}]",
+          all_chars)), 12)
+
+        self.assertEqual(repr(type(regex.compile(r"(?V0)([][-])"))),
+          self.PATTERN_CLASS)
+        self.assertEqual(regex.findall(r"(?V1)[[a-z]--[aei]]", "abc"), ["b",
+          "c"])
+        self.assertEqual(regex.findall(r"(?iV1)[[a-z]--[aei]]", "abc"), ["b",
+          "c"])
+        self.assertEqual(regex.findall(r"(?V1)[\w--a]","abc"), ["b", "c"])
+        self.assertEqual(regex.findall(r"(?iV1)[\w--a]","abc"), ["b", "c"])
+
+    def test_various(self):
+        tests = [
+            # Test ?P< and ?P= extensions.
+            ('(?Pa)', '', '', regex.error, self.BAD_GROUP_NAME),     # Begins with a digit.
+            ('(?Pa)', '', '', regex.error, self.BAD_GROUP_NAME),     # Begins with an illegal char.
+            ('(?Pa)', '', '', regex.error, self.BAD_GROUP_NAME),  # Begins with an illegal char.
+
+            # Same tests, for the ?P= form.
+            ('(?Pa)(?P=foo_123', 'aa', '', regex.error,
+              self.MISSING_RPAREN),
+            ('(?Pa)(?P=1)', 'aa', '1', ascii('a')),
+            ('(?Pa)(?P=0)', 'aa', '', regex.error,
+              self.BAD_GROUP_NAME),
+            ('(?Pa)(?P=-1)', 'aa', '', regex.error,
+              self.BAD_GROUP_NAME),
+            ('(?Pa)(?P=!)', 'aa', '', regex.error,
+              self.BAD_GROUP_NAME),
+            ('(?Pa)(?P=foo_124)', 'aa', '', regex.error,
+              self.UNKNOWN_GROUP),  # Backref to undefined group.
+
+            ('(?Pa)', 'a', '1', ascii('a')),
+            ('(?Pa)(?P=foo_123)', 'aa', '1', ascii('a')),
+
+            # Mal-formed \g in pattern treated as literal for compatibility.
+            (r'(?a)\ga)\g<1>', 'aa', '1', ascii('a')),
+            (r'(?a)\g', 'aa', '', ascii(None)),
+            (r'(?a)\g', 'aa', '', regex.error,
+              self.UNKNOWN_GROUP),  # Backref to undefined group.
+
+            ('(?a)', 'a', '1', ascii('a')),
+            (r'(?a)\g', 'aa', '1', ascii('a')),
+
+            # Test octal escapes.
+            ('\\1', 'a', '', regex.error, self.INVALID_GROUP_REF),    # Backreference.
+            ('[\\1]', '\1', '0', "'\\x01'"),  # Character.
+            ('\\09', chr(0) + '9', '0', ascii(chr(0) + '9')),
+            ('\\141', 'a', '0', ascii('a')),
+            ('(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)\\119', 'abcdefghijklk9',
+              '0,11', ascii(('abcdefghijklk9', 'k'))),
+
+            # Test \0 is handled everywhere.
+            (r'\0', '\0', '0', ascii('\0')),
+            (r'[\0a]', '\0', '0', ascii('\0')),
+            (r'[a\0]', '\0', '0', ascii('\0')),
+            (r'[^a\0]', '\0', '', ascii(None)),
+
+            # Test various letter escapes.
+            (r'\a[\b]\f\n\r\t\v', '\a\b\f\n\r\t\v', '0',
+              ascii('\a\b\f\n\r\t\v')),
+            (r'[\a][\b][\f][\n][\r][\t][\v]', '\a\b\f\n\r\t\v', '0',
+              ascii('\a\b\f\n\r\t\v')),
+            (r'\xff', '\377', '0', ascii(chr(255))),
+
+            # New \x semantics.
+            (r'\x00ffffffffffffff', '\377', '', ascii(None)),
+            (r'\x00f', '\017', '', ascii(None)),
+            (r'\x00fe', '\376', '', ascii(None)),
+
+            (r'\x00ff', '\377', '', ascii(None)),
+            (r'\t\n\v\r\f\a\g', '\t\n\v\r\f\ag', '0', ascii('\t\n\v\r\f\ag')),
+            ('\t\n\v\r\f\a\\g', '\t\n\v\r\f\ag', '0', ascii('\t\n\v\r\f\ag')),
+            (r'\t\n\v\r\f\a', '\t\n\v\r\f\a', '0', ascii(chr(9) + chr(10) +
+              chr(11) + chr(13) + chr(12) + chr(7))),
+            (r'[\t][\n][\v][\r][\f][\b]', '\t\n\v\r\f\b', '0',
+              ascii('\t\n\v\r\f\b')),
+
+            (r"^\w+=(\\[\000-\277]|[^\n\\])*",
+              "SRC=eval.c g.c blah blah blah \\\\\n\tapes.c", '0',
+              ascii("SRC=eval.c g.c blah blah blah \\\\")),
+
+            # Test that . only matches \n in DOTALL mode.
+            ('a.b', 'acb', '0', ascii('acb')),
+            ('a.b', 'a\nb', '', ascii(None)),
+            ('a.*b', 'acc\nccb', '', ascii(None)),
+            ('a.{4,5}b', 'acc\nccb', '', ascii(None)),
+            ('a.b', 'a\rb', '0', ascii('a\rb')),
+            # Changed to positional flags in regex 2023.12.23.
+            ('a.b(?s)', 'a\nb', '', ascii(None)),
+            ('(?s)a.b', 'a\nb', '0', ascii('a\nb')),
+            ('a.*(?s)b', 'acc\nccb', '', ascii(None)),
+            ('(?s)a.*b', 'acc\nccb', '0', ascii('acc\nccb')),
+            ('(?s)a.{4,5}b', 'acc\nccb', '0', ascii('acc\nccb')),
+
+            (')', '', '', regex.error, self.TRAILING_CHARS),           # Unmatched right bracket.
+            ('', '', '0', "''"),    # Empty pattern.
+            ('abc', 'abc', '0', ascii('abc')),
+            ('abc', 'xbc', '', ascii(None)),
+            ('abc', 'axc', '', ascii(None)),
+            ('abc', 'abx', '', ascii(None)),
+            ('abc', 'xabcy', '0', ascii('abc')),
+            ('abc', 'ababc', '0', ascii('abc')),
+            ('ab*c', 'abc', '0', ascii('abc')),
+            ('ab*bc', 'abc', '0', ascii('abc')),
+
+            ('ab*bc', 'abbc', '0', ascii('abbc')),
+            ('ab*bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab+bc', 'abbc', '0', ascii('abbc')),
+            ('ab+bc', 'abc', '', ascii(None)),
+            ('ab+bc', 'abq', '', ascii(None)),
+            ('ab+bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab?bc', 'abbc', '0', ascii('abbc')),
+            ('ab?bc', 'abc', '0', ascii('abc')),
+            ('ab?bc', 'abbbbc', '', ascii(None)),
+            ('ab?c', 'abc', '0', ascii('abc')),
+
+            ('^abc$', 'abc', '0', ascii('abc')),
+            ('^abc$', 'abcc', '', ascii(None)),
+            ('^abc', 'abcc', '0', ascii('abc')),
+            ('^abc$', 'aabc', '', ascii(None)),
+            ('abc$', 'aabc', '0', ascii('abc')),
+            ('^', 'abc', '0', ascii('')),
+            ('$', 'abc', '0', ascii('')),
+            ('a.c', 'abc', '0', ascii('abc')),
+            ('a.c', 'axc', '0', ascii('axc')),
+            ('a.*c', 'axyzc', '0', ascii('axyzc')),
+
+            ('a.*c', 'axyzd', '', ascii(None)),
+            ('a[bc]d', 'abc', '', ascii(None)),
+            ('a[bc]d', 'abd', '0', ascii('abd')),
+            ('a[b-d]e', 'abd', '', ascii(None)),
+            ('a[b-d]e', 'ace', '0', ascii('ace')),
+            ('a[b-d]', 'aac', '0', ascii('ac')),
+            ('a[-b]', 'a-', '0', ascii('a-')),
+            ('a[\\-b]', 'a-', '0', ascii('a-')),
+            ('a[b-]', 'a-', '0', ascii('a-')),
+            ('a[]b', '-', '', regex.error, self.BAD_SET),
+
+            ('a[', '-', '', regex.error, self.BAD_SET),
+            ('a\\', '-', '', regex.error, self.BAD_ESCAPE),
+            ('abc)', '-', '', regex.error, self.TRAILING_CHARS),
+            ('(abc', '-', '', regex.error, self.MISSING_RPAREN),
+            ('a]', 'a]', '0', ascii('a]')),
+            ('a[]]b', 'a]b', '0', ascii('a]b')),
+            ('a[]]b', 'a]b', '0', ascii('a]b')),
+            ('a[^bc]d', 'aed', '0', ascii('aed')),
+            ('a[^bc]d', 'abd', '', ascii(None)),
+            ('a[^-b]c', 'adc', '0', ascii('adc')),
+
+            ('a[^-b]c', 'a-c', '', ascii(None)),
+            ('a[^]b]c', 'a]c', '', ascii(None)),
+            ('a[^]b]c', 'adc', '0', ascii('adc')),
+            ('\\ba\\b', 'a-', '0', ascii('a')),
+            ('\\ba\\b', '-a', '0', ascii('a')),
+            ('\\ba\\b', '-a-', '0', ascii('a')),
+            ('\\by\\b', 'xy', '', ascii(None)),
+            ('\\by\\b', 'yz', '', ascii(None)),
+            ('\\by\\b', 'xyz', '', ascii(None)),
+            ('x\\b', 'xyz', '', ascii(None)),
+
+            ('x\\B', 'xyz', '0', ascii('x')),
+            ('\\Bz', 'xyz', '0', ascii('z')),
+            ('z\\B', 'xyz', '', ascii(None)),
+            ('\\Bx', 'xyz', '', ascii(None)),
+            ('\\Ba\\B', 'a-', '', ascii(None)),
+            ('\\Ba\\B', '-a', '', ascii(None)),
+            ('\\Ba\\B', '-a-', '', ascii(None)),
+            ('\\By\\B', 'xy', '', ascii(None)),
+            ('\\By\\B', 'yz', '', ascii(None)),
+            ('\\By\\b', 'xy', '0', ascii('y')),
+
+            ('\\by\\B', 'yz', '0', ascii('y')),
+            ('\\By\\B', 'xyz', '0', ascii('y')),
+            ('ab|cd', 'abc', '0', ascii('ab')),
+            ('ab|cd', 'abcd', '0', ascii('ab')),
+            ('()ef', 'def', '0,1', ascii(('ef', ''))),
+            ('$b', 'b', '', ascii(None)),
+            ('a\\(b', 'a(b', '', ascii(('a(b',))),
+            ('a\\(*b', 'ab', '0', ascii('ab')),
+            ('a\\(*b', 'a((b', '0', ascii('a((b')),
+            ('a\\\\b', 'a\\b', '0', ascii('a\\b')),
+
+            ('((a))', 'abc', '0,1,2', ascii(('a', 'a', 'a'))),
+            ('(a)b(c)', 'abc', '0,1,2', ascii(('abc', 'a', 'c'))),
+            ('a+b+c', 'aabbabc', '0', ascii('abc')),
+            ('(a+|b)*', 'ab', '0,1', ascii(('ab', 'b'))),
+            ('(a+|b)+', 'ab', '0,1', ascii(('ab', 'b'))),
+            ('(a+|b)?', 'ab', '0,1', ascii(('a', 'a'))),
+            (')(', '-', '', regex.error, self.TRAILING_CHARS),
+            ('[^ab]*', 'cde', '0', ascii('cde')),
+            ('abc', '', '', ascii(None)),
+            ('a*', '', '0', ascii('')),
+
+            ('a|b|c|d|e', 'e', '0', ascii('e')),
+            ('(a|b|c|d|e)f', 'ef', '0,1', ascii(('ef', 'e'))),
+            ('abcd*efg', 'abcdefg', '0', ascii('abcdefg')),
+            ('ab*', 'xabyabbbz', '0', ascii('ab')),
+            ('ab*', 'xayabbbz', '0', ascii('a')),
+            ('(ab|cd)e', 'abcde', '0,1', ascii(('cde', 'cd'))),
+            ('[abhgefdc]ij', 'hij', '0', ascii('hij')),
+            ('^(ab|cd)e', 'abcde', '', ascii(None)),
+            ('(abc|)ef', 'abcdef', '0,1', ascii(('ef', ''))),
+            ('(a|b)c*d', 'abcd', '0,1', ascii(('bcd', 'b'))),
+
+            ('(ab|ab*)bc', 'abc', '0,1', ascii(('abc', 'a'))),
+            ('a([bc]*)c*', 'abc', '0,1', ascii(('abc', 'bc'))),
+            ('a([bc]*)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))),
+            ('a([bc]+)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))),
+            ('a([bc]*)(c+d)', 'abcd', '0,1,2', ascii(('abcd', 'b', 'cd'))),
+            ('a[bcd]*dcdcde', 'adcdcde', '0', ascii('adcdcde')),
+            ('a[bcd]+dcdcde', 'adcdcde', '', ascii(None)),
+            ('(ab|a)b*c', 'abc', '0,1', ascii(('abc', 'ab'))),
+            ('((a)(b)c)(d)', 'abcd', '1,2,3,4', ascii(('abc', 'a', 'b', 'd'))),
+            ('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', '0', ascii('alpha')),
+
+            ('^a(bc+|b[eh])g|.h$', 'abh', '0,1', ascii(('bh', None))),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'effgz', '0,1,2', ascii(('effgz',
+              'effgz', None))),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'ij', '0,1,2', ascii(('ij', 'ij',
+              'j'))),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'effg', '', ascii(None)),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'bcdd', '', ascii(None)),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'reffgz', '0,1,2', ascii(('effgz',
+              'effgz', None))),
+            ('(((((((((a)))))))))', 'a', '0', ascii('a')),
+            ('multiple words of text', 'uh-uh', '', ascii(None)),
+            ('multiple words', 'multiple words, yeah', '0',
+              ascii('multiple words')),
+            ('(.*)c(.*)', 'abcde', '0,1,2', ascii(('abcde', 'ab', 'de'))),
+
+            ('\\((.*), (.*)\\)', '(a, b)', '2,1', ascii(('b', 'a'))),
+            ('[k]', 'ab', '', ascii(None)),
+            ('a[-]?c', 'ac', '0', ascii('ac')),
+            ('(abc)\\1', 'abcabc', '1', ascii('abc')),
+            ('([a-c]*)\\1', 'abcabc', '1', ascii('abc')),
+            ('^(.+)?B', 'AB', '1', ascii('A')),
+            ('(a+).\\1$', 'aaaaa', '0,1', ascii(('aaaaa', 'aa'))),
+            ('^(a+).\\1$', 'aaaa', '', ascii(None)),
+            ('(abc)\\1', 'abcabc', '0,1', ascii(('abcabc', 'abc'))),
+            ('([a-c]+)\\1', 'abcabc', '0,1', ascii(('abcabc', 'abc'))),
+
+            ('(a)\\1', 'aa', '0,1', ascii(('aa', 'a'))),
+            ('(a+)\\1', 'aa', '0,1', ascii(('aa', 'a'))),
+            ('(a+)+\\1', 'aa', '0,1', ascii(('aa', 'a'))),
+            ('(a).+\\1', 'aba', '0,1', ascii(('aba', 'a'))),
+            ('(a)ba*\\1', 'aba', '0,1', ascii(('aba', 'a'))),
+            ('(aa|a)a\\1$', 'aaa', '0,1', ascii(('aaa', 'a'))),
+            ('(a|aa)a\\1$', 'aaa', '0,1', ascii(('aaa', 'a'))),
+            ('(a+)a\\1$', 'aaa', '0,1', ascii(('aaa', 'a'))),
+            ('([abc]*)\\1', 'abcabc', '0,1', ascii(('abcabc', 'abc'))),
+            ('(a)(b)c|ab', 'ab', '0,1,2', ascii(('ab', None, None))),
+
+            ('(a)+x', 'aaax', '0,1', ascii(('aaax', 'a'))),
+            ('([ac])+x', 'aacx', '0,1', ascii(('aacx', 'c'))),
+            ('([^/]*/)*sub1/', 'd:msgs/tdir/sub1/trial/away.cpp', '0,1',
+              ascii(('d:msgs/tdir/sub1/', 'tdir/'))),
+            ('([^.]*)\\.([^:]*):[T ]+(.*)', 'track1.title:TBlah blah blah',
+              '0,1,2,3', ascii(('track1.title:TBlah blah blah', 'track1',
+              'title', 'Blah blah blah'))),
+            ('([^N]*N)+', 'abNNxyzN', '0,1', ascii(('abNNxyzN', 'xyzN'))),
+            ('([^N]*N)+', 'abNNxyz', '0,1', ascii(('abNN', 'N'))),
+            ('([abc]*)x', 'abcx', '0,1', ascii(('abcx', 'abc'))),
+            ('([abc]*)x', 'abc', '', ascii(None)),
+            ('([xyz]*)x', 'abcx', '0,1', ascii(('x', ''))),
+            ('(a)+b|aac', 'aac', '0,1', ascii(('aac', None))),
+
+            # Test symbolic groups.
+            ('(?Paaa)a', 'aaaa', '', regex.error, self.BAD_GROUP_NAME),
+            ('(?Paaa)a', 'aaaa', '0,id', ascii(('aaaa', 'aaa'))),
+            ('(?Paa)(?P=id)', 'aaaa', '0,id', ascii(('aaaa', 'aa'))),
+            ('(?Paa)(?P=xd)', 'aaaa', '', regex.error, self.UNKNOWN_GROUP),
+
+            # Character properties.
+            (r"\g", "g", '0', ascii('g')),
+            (r"\g<1>", "g", '', regex.error, self.INVALID_GROUP_REF),
+            (r"(.)\g<1>", "gg", '0', ascii('gg')),
+            (r"(.)\g<1>", "gg", '', ascii(('gg', 'g'))),
+            (r"\N", "N", '0', ascii('N')),
+            (r"\N{LATIN SMALL LETTER A}", "a", '0', ascii('a')),
+            (r"\p", "p", '0', ascii('p')),
+            (r"\p{Ll}", "a", '0', ascii('a')),
+            (r"\P", "P", '0', ascii('P')),
+            (r"\P{Lu}", "p", '0', ascii('p')),
+
+            # All tests from Perl.
+            ('abc', 'abc', '0', ascii('abc')),
+            ('abc', 'xbc', '', ascii(None)),
+            ('abc', 'axc', '', ascii(None)),
+            ('abc', 'abx', '', ascii(None)),
+            ('abc', 'xabcy', '0', ascii('abc')),
+            ('abc', 'ababc', '0', ascii('abc')),
+
+            ('ab*c', 'abc', '0', ascii('abc')),
+            ('ab*bc', 'abc', '0', ascii('abc')),
+            ('ab*bc', 'abbc', '0', ascii('abbc')),
+            ('ab*bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab{0,}bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab+bc', 'abbc', '0', ascii('abbc')),
+            ('ab+bc', 'abc', '', ascii(None)),
+            ('ab+bc', 'abq', '', ascii(None)),
+            ('ab{1,}bc', 'abq', '', ascii(None)),
+            ('ab+bc', 'abbbbc', '0', ascii('abbbbc')),
+
+            ('ab{1,}bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab{1,3}bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab{3,4}bc', 'abbbbc', '0', ascii('abbbbc')),
+            ('ab{4,5}bc', 'abbbbc', '', ascii(None)),
+            ('ab?bc', 'abbc', '0', ascii('abbc')),
+            ('ab?bc', 'abc', '0', ascii('abc')),
+            ('ab{0,1}bc', 'abc', '0', ascii('abc')),
+            ('ab?bc', 'abbbbc', '', ascii(None)),
+            ('ab?c', 'abc', '0', ascii('abc')),
+            ('ab{0,1}c', 'abc', '0', ascii('abc')),
+
+            ('^abc$', 'abc', '0', ascii('abc')),
+            ('^abc$', 'abcc', '', ascii(None)),
+            ('^abc', 'abcc', '0', ascii('abc')),
+            ('^abc$', 'aabc', '', ascii(None)),
+            ('abc$', 'aabc', '0', ascii('abc')),
+            ('^', 'abc', '0', ascii('')),
+            ('$', 'abc', '0', ascii('')),
+            ('a.c', 'abc', '0', ascii('abc')),
+            ('a.c', 'axc', '0', ascii('axc')),
+            ('a.*c', 'axyzc', '0', ascii('axyzc')),
+
+            ('a.*c', 'axyzd', '', ascii(None)),
+            ('a[bc]d', 'abc', '', ascii(None)),
+            ('a[bc]d', 'abd', '0', ascii('abd')),
+            ('a[b-d]e', 'abd', '', ascii(None)),
+            ('a[b-d]e', 'ace', '0', ascii('ace')),
+            ('a[b-d]', 'aac', '0', ascii('ac')),
+            ('a[-b]', 'a-', '0', ascii('a-')),
+            ('a[b-]', 'a-', '0', ascii('a-')),
+            ('a[b-a]', '-', '', regex.error, self.BAD_CHAR_RANGE),
+            ('a[]b', '-', '', regex.error, self.BAD_SET),
+
+            ('a[', '-', '', regex.error, self.BAD_SET),
+            ('a]', 'a]', '0', ascii('a]')),
+            ('a[]]b', 'a]b', '0', ascii('a]b')),
+            ('a[^bc]d', 'aed', '0', ascii('aed')),
+            ('a[^bc]d', 'abd', '', ascii(None)),
+            ('a[^-b]c', 'adc', '0', ascii('adc')),
+            ('a[^-b]c', 'a-c', '', ascii(None)),
+            ('a[^]b]c', 'a]c', '', ascii(None)),
+            ('a[^]b]c', 'adc', '0', ascii('adc')),
+            ('ab|cd', 'abc', '0', ascii('ab')),
+
+            ('ab|cd', 'abcd', '0', ascii('ab')),
+            ('()ef', 'def', '0,1', ascii(('ef', ''))),
+            ('*a', '-', '', regex.error, self.NOTHING_TO_REPEAT),
+            ('(*)b', '-', '', regex.error, self.NOTHING_TO_REPEAT),
+            ('$b', 'b', '', ascii(None)),
+            ('a\\', '-', '', regex.error, self.BAD_ESCAPE),
+            ('a\\(b', 'a(b', '', ascii(('a(b',))),
+            ('a\\(*b', 'ab', '0', ascii('ab')),
+            ('a\\(*b', 'a((b', '0', ascii('a((b')),
+            ('a\\\\b', 'a\\b', '0', ascii('a\\b')),
+
+            ('abc)', '-', '', regex.error, self.TRAILING_CHARS),
+            ('(abc', '-', '', regex.error, self.MISSING_RPAREN),
+            ('((a))', 'abc', '0,1,2', ascii(('a', 'a', 'a'))),
+            ('(a)b(c)', 'abc', '0,1,2', ascii(('abc', 'a', 'c'))),
+            ('a+b+c', 'aabbabc', '0', ascii('abc')),
+            ('a{1,}b{1,}c', 'aabbabc', '0', ascii('abc')),
+            ('a**', '-', '', regex.error, self.MULTIPLE_REPEAT),
+            ('a.+?c', 'abcabc', '0', ascii('abc')),
+            ('(a+|b)*', 'ab', '0,1', ascii(('ab', 'b'))),
+            ('(a+|b){0,}', 'ab', '0,1', ascii(('ab', 'b'))),
+
+            ('(a+|b)+', 'ab', '0,1', ascii(('ab', 'b'))),
+            ('(a+|b){1,}', 'ab', '0,1', ascii(('ab', 'b'))),
+            ('(a+|b)?', 'ab', '0,1', ascii(('a', 'a'))),
+            ('(a+|b){0,1}', 'ab', '0,1', ascii(('a', 'a'))),
+            (')(', '-', '', regex.error, self.TRAILING_CHARS),
+            ('[^ab]*', 'cde', '0', ascii('cde')),
+            ('abc', '', '', ascii(None)),
+            ('a*', '', '0', ascii('')),
+            ('([abc])*d', 'abbbcd', '0,1', ascii(('abbbcd', 'c'))),
+            ('([abc])*bcd', 'abcd', '0,1', ascii(('abcd', 'a'))),
+
+            ('a|b|c|d|e', 'e', '0', ascii('e')),
+            ('(a|b|c|d|e)f', 'ef', '0,1', ascii(('ef', 'e'))),
+            ('abcd*efg', 'abcdefg', '0', ascii('abcdefg')),
+            ('ab*', 'xabyabbbz', '0', ascii('ab')),
+            ('ab*', 'xayabbbz', '0', ascii('a')),
+            ('(ab|cd)e', 'abcde', '0,1', ascii(('cde', 'cd'))),
+            ('[abhgefdc]ij', 'hij', '0', ascii('hij')),
+            ('^(ab|cd)e', 'abcde', '', ascii(None)),
+            ('(abc|)ef', 'abcdef', '0,1', ascii(('ef', ''))),
+            ('(a|b)c*d', 'abcd', '0,1', ascii(('bcd', 'b'))),
+
+            ('(ab|ab*)bc', 'abc', '0,1', ascii(('abc', 'a'))),
+            ('a([bc]*)c*', 'abc', '0,1', ascii(('abc', 'bc'))),
+            ('a([bc]*)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))),
+            ('a([bc]+)(c*d)', 'abcd', '0,1,2', ascii(('abcd', 'bc', 'd'))),
+            ('a([bc]*)(c+d)', 'abcd', '0,1,2', ascii(('abcd', 'b', 'cd'))),
+            ('a[bcd]*dcdcde', 'adcdcde', '0', ascii('adcdcde')),
+            ('a[bcd]+dcdcde', 'adcdcde', '', ascii(None)),
+            ('(ab|a)b*c', 'abc', '0,1', ascii(('abc', 'ab'))),
+            ('((a)(b)c)(d)', 'abcd', '1,2,3,4', ascii(('abc', 'a', 'b', 'd'))),
+            ('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', '0', ascii('alpha')),
+
+            ('^a(bc+|b[eh])g|.h$', 'abh', '0,1', ascii(('bh', None))),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'effgz', '0,1,2', ascii(('effgz',
+              'effgz', None))),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'ij', '0,1,2', ascii(('ij', 'ij',
+              'j'))),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'effg', '', ascii(None)),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'bcdd', '', ascii(None)),
+            ('(bc+d$|ef*g.|h?i(j|k))', 'reffgz', '0,1,2', ascii(('effgz',
+              'effgz', None))),
+            ('((((((((((a))))))))))', 'a', '10', ascii('a')),
+            ('((((((((((a))))))))))\\10', 'aa', '0', ascii('aa')),
+
+            # Python does not have the same rules for \\41 so this is a syntax error
+            #    ('((((((((((a))))))))))\\41', 'aa', '', ascii(None)),
+            #    ('((((((((((a))))))))))\\41', 'a!', '0', ascii('a!')),
+            ('((((((((((a))))))))))\\41', '', '', regex.error,
+              self.INVALID_GROUP_REF),
+            ('(?i)((((((((((a))))))))))\\41', '', '', regex.error,
+              self.INVALID_GROUP_REF),
+
+            ('(((((((((a)))))))))', 'a', '0', ascii('a')),
+            ('multiple words of text', 'uh-uh', '', ascii(None)),
+            ('multiple words', 'multiple words, yeah', '0',
+              ascii('multiple words')),
+            ('(.*)c(.*)', 'abcde', '0,1,2', ascii(('abcde', 'ab', 'de'))),
+            ('\\((.*), (.*)\\)', '(a, b)', '2,1', ascii(('b', 'a'))),
+            ('[k]', 'ab', '', ascii(None)),
+            ('a[-]?c', 'ac', '0', ascii('ac')),
+            ('(abc)\\1', 'abcabc', '1', ascii('abc')),
+            ('([a-c]*)\\1', 'abcabc', '1', ascii('abc')),
+            ('(?i)abc', 'ABC', '0', ascii('ABC')),
+
+            ('(?i)abc', 'XBC', '', ascii(None)),
+            ('(?i)abc', 'AXC', '', ascii(None)),
+            ('(?i)abc', 'ABX', '', ascii(None)),
+            ('(?i)abc', 'XABCY', '0', ascii('ABC')),
+            ('(?i)abc', 'ABABC', '0', ascii('ABC')),
+            ('(?i)ab*c', 'ABC', '0', ascii('ABC')),
+            ('(?i)ab*bc', 'ABC', '0', ascii('ABC')),
+            ('(?i)ab*bc', 'ABBC', '0', ascii('ABBC')),
+            ('(?i)ab*?bc', 'ABBBBC', '0', ascii('ABBBBC')),
+            ('(?i)ab{0,}?bc', 'ABBBBC', '0', ascii('ABBBBC')),
+
+            ('(?i)ab+?bc', 'ABBC', '0', ascii('ABBC')),
+            ('(?i)ab+bc', 'ABC', '', ascii(None)),
+            ('(?i)ab+bc', 'ABQ', '', ascii(None)),
+            ('(?i)ab{1,}bc', 'ABQ', '', ascii(None)),
+            ('(?i)ab+bc', 'ABBBBC', '0', ascii('ABBBBC')),
+            ('(?i)ab{1,}?bc', 'ABBBBC', '0', ascii('ABBBBC')),
+            ('(?i)ab{1,3}?bc', 'ABBBBC', '0', ascii('ABBBBC')),
+            ('(?i)ab{3,4}?bc', 'ABBBBC', '0', ascii('ABBBBC')),
+            ('(?i)ab{4,5}?bc', 'ABBBBC', '', ascii(None)),
+            ('(?i)ab??bc', 'ABBC', '0', ascii('ABBC')),
+
+            ('(?i)ab??bc', 'ABC', '0', ascii('ABC')),
+            ('(?i)ab{0,1}?bc', 'ABC', '0', ascii('ABC')),
+            ('(?i)ab??bc', 'ABBBBC', '', ascii(None)),
+            ('(?i)ab??c', 'ABC', '0', ascii('ABC')),
+            ('(?i)ab{0,1}?c', 'ABC', '0', ascii('ABC')),
+            ('(?i)^abc$', 'ABC', '0', ascii('ABC')),
+            ('(?i)^abc$', 'ABCC', '', ascii(None)),
+            ('(?i)^abc', 'ABCC', '0', ascii('ABC')),
+            ('(?i)^abc$', 'AABC', '', ascii(None)),
+            ('(?i)abc$', 'AABC', '0', ascii('ABC')),
+
+            ('(?i)^', 'ABC', '0', ascii('')),
+            ('(?i)$', 'ABC', '0', ascii('')),
+            ('(?i)a.c', 'ABC', '0', ascii('ABC')),
+            ('(?i)a.c', 'AXC', '0', ascii('AXC')),
+            ('(?i)a.*?c', 'AXYZC', '0', ascii('AXYZC')),
+            ('(?i)a.*c', 'AXYZD', '', ascii(None)),
+            ('(?i)a[bc]d', 'ABC', '', ascii(None)),
+            ('(?i)a[bc]d', 'ABD', '0', ascii('ABD')),
+            ('(?i)a[b-d]e', 'ABD', '', ascii(None)),
+            ('(?i)a[b-d]e', 'ACE', '0', ascii('ACE')),
+
+            ('(?i)a[b-d]', 'AAC', '0', ascii('AC')),
+            ('(?i)a[-b]', 'A-', '0', ascii('A-')),
+            ('(?i)a[b-]', 'A-', '0', ascii('A-')),
+            ('(?i)a[b-a]', '-', '', regex.error, self.BAD_CHAR_RANGE),
+            ('(?i)a[]b', '-', '', regex.error, self.BAD_SET),
+            ('(?i)a[', '-', '', regex.error, self.BAD_SET),
+            ('(?i)a]', 'A]', '0', ascii('A]')),
+            ('(?i)a[]]b', 'A]B', '0', ascii('A]B')),
+            ('(?i)a[^bc]d', 'AED', '0', ascii('AED')),
+            ('(?i)a[^bc]d', 'ABD', '', ascii(None)),
+
+            ('(?i)a[^-b]c', 'ADC', '0', ascii('ADC')),
+            ('(?i)a[^-b]c', 'A-C', '', ascii(None)),
+            ('(?i)a[^]b]c', 'A]C', '', ascii(None)),
+            ('(?i)a[^]b]c', 'ADC', '0', ascii('ADC')),
+            ('(?i)ab|cd', 'ABC', '0', ascii('AB')),
+            ('(?i)ab|cd', 'ABCD', '0', ascii('AB')),
+            ('(?i)()ef', 'DEF', '0,1', ascii(('EF', ''))),
+            ('(?i)*a', '-', '', regex.error, self.NOTHING_TO_REPEAT),
+            ('(?i)(*)b', '-', '', regex.error, self.NOTHING_TO_REPEAT),
+            ('(?i)$b', 'B', '', ascii(None)),
+
+            ('(?i)a\\', '-', '', regex.error, self.BAD_ESCAPE),
+            ('(?i)a\\(b', 'A(B', '', ascii(('A(B',))),
+            ('(?i)a\\(*b', 'AB', '0', ascii('AB')),
+            ('(?i)a\\(*b', 'A((B', '0', ascii('A((B')),
+            ('(?i)a\\\\b', 'A\\B', '0', ascii('A\\B')),
+            ('(?i)abc)', '-', '', regex.error, self.TRAILING_CHARS),
+            ('(?i)(abc', '-', '', regex.error, self.MISSING_RPAREN),
+            ('(?i)((a))', 'ABC', '0,1,2', ascii(('A', 'A', 'A'))),
+            ('(?i)(a)b(c)', 'ABC', '0,1,2', ascii(('ABC', 'A', 'C'))),
+            ('(?i)a+b+c', 'AABBABC', '0', ascii('ABC')),
+
+            ('(?i)a{1,}b{1,}c', 'AABBABC', '0', ascii('ABC')),
+            ('(?i)a**', '-', '', regex.error, self.MULTIPLE_REPEAT),
+            ('(?i)a.+?c', 'ABCABC', '0', ascii('ABC')),
+            ('(?i)a.*?c', 'ABCABC', '0', ascii('ABC')),
+            ('(?i)a.{0,5}?c', 'ABCABC', '0', ascii('ABC')),
+            ('(?i)(a+|b)*', 'AB', '0,1', ascii(('AB', 'B'))),
+            ('(?i)(a+|b){0,}', 'AB', '0,1', ascii(('AB', 'B'))),
+            ('(?i)(a+|b)+', 'AB', '0,1', ascii(('AB', 'B'))),
+            ('(?i)(a+|b){1,}', 'AB', '0,1', ascii(('AB', 'B'))),
+            ('(?i)(a+|b)?', 'AB', '0,1', ascii(('A', 'A'))),
+
+            ('(?i)(a+|b){0,1}', 'AB', '0,1', ascii(('A', 'A'))),
+            ('(?i)(a+|b){0,1}?', 'AB', '0,1', ascii(('', None))),
+            ('(?i))(', '-', '', regex.error, self.TRAILING_CHARS),
+            ('(?i)[^ab]*', 'CDE', '0', ascii('CDE')),
+            ('(?i)abc', '', '', ascii(None)),
+            ('(?i)a*', '', '0', ascii('')),
+            ('(?i)([abc])*d', 'ABBBCD', '0,1', ascii(('ABBBCD', 'C'))),
+            ('(?i)([abc])*bcd', 'ABCD', '0,1', ascii(('ABCD', 'A'))),
+            ('(?i)a|b|c|d|e', 'E', '0', ascii('E')),
+            ('(?i)(a|b|c|d|e)f', 'EF', '0,1', ascii(('EF', 'E'))),
+
+            ('(?i)abcd*efg', 'ABCDEFG', '0', ascii('ABCDEFG')),
+            ('(?i)ab*', 'XABYABBBZ', '0', ascii('AB')),
+            ('(?i)ab*', 'XAYABBBZ', '0', ascii('A')),
+            ('(?i)(ab|cd)e', 'ABCDE', '0,1', ascii(('CDE', 'CD'))),
+            ('(?i)[abhgefdc]ij', 'HIJ', '0', ascii('HIJ')),
+            ('(?i)^(ab|cd)e', 'ABCDE', '', ascii(None)),
+            ('(?i)(abc|)ef', 'ABCDEF', '0,1', ascii(('EF', ''))),
+            ('(?i)(a|b)c*d', 'ABCD', '0,1', ascii(('BCD', 'B'))),
+            ('(?i)(ab|ab*)bc', 'ABC', '0,1', ascii(('ABC', 'A'))),
+            ('(?i)a([bc]*)c*', 'ABC', '0,1', ascii(('ABC', 'BC'))),
+
+            ('(?i)a([bc]*)(c*d)', 'ABCD', '0,1,2', ascii(('ABCD', 'BC', 'D'))),
+            ('(?i)a([bc]+)(c*d)', 'ABCD', '0,1,2', ascii(('ABCD', 'BC', 'D'))),
+            ('(?i)a([bc]*)(c+d)', 'ABCD', '0,1,2', ascii(('ABCD', 'B', 'CD'))),
+            ('(?i)a[bcd]*dcdcde', 'ADCDCDE', '0', ascii('ADCDCDE')),
+            ('(?i)a[bcd]+dcdcde', 'ADCDCDE', '', ascii(None)),
+            ('(?i)(ab|a)b*c', 'ABC', '0,1', ascii(('ABC', 'AB'))),
+            ('(?i)((a)(b)c)(d)', 'ABCD', '1,2,3,4', ascii(('ABC', 'A', 'B',
+              'D'))),
+            ('(?i)[a-zA-Z_][a-zA-Z0-9_]*', 'ALPHA', '0', ascii('ALPHA')),
+            ('(?i)^a(bc+|b[eh])g|.h$', 'ABH', '0,1', ascii(('BH', None))),
+            ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'EFFGZ', '0,1,2', ascii(('EFFGZ',
+              'EFFGZ', None))),
+
+            ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'IJ', '0,1,2', ascii(('IJ', 'IJ',
+              'J'))),
+            ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'EFFG', '', ascii(None)),
+            ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'BCDD', '', ascii(None)),
+            ('(?i)(bc+d$|ef*g.|h?i(j|k))', 'REFFGZ', '0,1,2', ascii(('EFFGZ',
+              'EFFGZ', None))),
+            ('(?i)((((((((((a))))))))))', 'A', '10', ascii('A')),
+            ('(?i)((((((((((a))))))))))\\10', 'AA', '0', ascii('AA')),
+            #('(?i)((((((((((a))))))))))\\41', 'AA', '', ascii(None)),
+            #('(?i)((((((((((a))))))))))\\41', 'A!', '0', ascii('A!')),
+            ('(?i)(((((((((a)))))))))', 'A', '0', ascii('A')),
+            ('(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a))))))))))', 'A', '1',
+              ascii('A')),
+            ('(?i)(?:(?:(?:(?:(?:(?:(?:(?:(?:(a|b|c))))))))))', 'C', '1',
+              ascii('C')),
+            ('(?i)multiple words of text', 'UH-UH', '', ascii(None)),
+
+            ('(?i)multiple words', 'MULTIPLE WORDS, YEAH', '0',
+             ascii('MULTIPLE WORDS')),
+            ('(?i)(.*)c(.*)', 'ABCDE', '0,1,2', ascii(('ABCDE', 'AB', 'DE'))),
+            ('(?i)\\((.*), (.*)\\)', '(A, B)', '2,1', ascii(('B', 'A'))),
+            ('(?i)[k]', 'AB', '', ascii(None)),
+        #    ('(?i)abcd', 'ABCD', SUCCEED, 'found+"-"+\\found+"-"+\\\\found', ascii(ABCD-$&-\\ABCD)),
+        #    ('(?i)a(bc)d', 'ABCD', SUCCEED, 'g1+"-"+\\g1+"-"+\\\\g1', ascii(BC-$1-\\BC)),
+            ('(?i)a[-]?c', 'AC', '0', ascii('AC')),
+            ('(?i)(abc)\\1', 'ABCABC', '1', ascii('ABC')),
+            ('(?i)([a-c]*)\\1', 'ABCABC', '1', ascii('ABC')),
+            ('a(?!b).', 'abad', '0', ascii('ad')),
+            ('a(?=d).', 'abad', '0', ascii('ad')),
+            ('a(?=c|d).', 'abad', '0', ascii('ad')),
+
+            ('a(?:b|c|d)(.)', 'ace', '1', ascii('e')),
+            ('a(?:b|c|d)*(.)', 'ace', '1', ascii('e')),
+            ('a(?:b|c|d)+?(.)', 'ace', '1', ascii('e')),
+            ('a(?:b|(c|e){1,2}?|d)+?(.)', 'ace', '1,2', ascii(('c', 'e'))),
+
+            # Lookbehind: split by : but not if it is escaped by -.
+            ('(?]*?b', 'a>b', '', ascii(None)),
+            # Bug 490573: minimizing repeat problem.
+            (r'^a*?$', 'foo', '', ascii(None)),
+            # Bug 470582: nested groups problem.
+            (r'^((a)c)?(ab)$', 'ab', '1,2,3', ascii((None, None, 'ab'))),
+            # Another minimizing repeat problem (capturing groups in assertions).
+            ('^([ab]*?)(?=(b)?)c', 'abc', '1,2', ascii(('ab', None))),
+            ('^([ab]*?)(?!(b))c', 'abc', '1,2', ascii(('ab', None))),
+            ('^([ab]*?)(?(.){0,2})d", "abcd").captures(1),
+          ['b', 'c'])
+        self.assertEqual(regex.search(r"(.)+", "a").captures(1), ['a'])
+
+    def test_guards(self):
+        m = regex.search(r"(X.*?Y\s*){3}(X\s*)+AB:",
+          "XY\nX Y\nX  Y\nXY\nXX AB:")
+        self.assertEqual(m.span(0, 1, 2), ((3, 21), (12, 15), (16, 18)))
+
+        m = regex.search(r"(X.*?Y\s*){3,}(X\s*)+AB:",
+          "XY\nX Y\nX  Y\nXY\nXX AB:")
+        self.assertEqual(m.span(0, 1, 2), ((0, 21), (12, 15), (16, 18)))
+
+        m = regex.search(r'\d{4}(\s*\w)?\W*((?!\d)\w){2}', "9999XX")
+        self.assertEqual(m.span(0, 1, 2), ((0, 6), (-1, -1), (5, 6)))
+
+        m = regex.search(r'A\s*?.*?(\n+.*?\s*?){0,2}\(X', 'A\n1\nS\n1 (X')
+        self.assertEqual(m.span(0, 1), ((0, 10), (5, 8)))
+
+        m = regex.search(r'Derde\s*:', 'aaaaaa:\nDerde:')
+        self.assertEqual(m.span(), (8, 14))
+        m = regex.search(r'Derde\s*:', 'aaaaa:\nDerde:')
+        self.assertEqual(m.span(), (7, 13))
+
+    def test_turkic(self):
+        # Turkish has dotted and dotless I/i.
+        pairs = "I=i;I=\u0131;i=\u0130"
+
+        all_chars = set()
+        matching = set()
+        for pair in pairs.split(";"):
+            ch1, ch2 = pair.split("=")
+            all_chars.update((ch1, ch2))
+            matching.add((ch1, ch1))
+            matching.add((ch1, ch2))
+            matching.add((ch2, ch1))
+            matching.add((ch2, ch2))
+
+        for ch1 in all_chars:
+            for ch2 in all_chars:
+                m = regex.match(r"(?i)\A" + ch1 + r"\Z", ch2)
+                if m:
+                    if (ch1, ch2) not in matching:
+                        self.fail("{} matching {}".format(ascii(ch1),
+                          ascii(ch2)))
+                else:
+                    if (ch1, ch2) in matching:
+                        self.fail("{} not matching {}".format(ascii(ch1),
+                          ascii(ch2)))
+
+    def test_named_lists(self):
+        options = ["one", "two", "three"]
+        self.assertEqual(regex.match(r"333\L444", "333one444",
+          bar=options).group(), "333one444")
+        self.assertEqual(regex.match(r"(?i)333\L444", "333TWO444",
+          bar=options).group(), "333TWO444")
+        self.assertEqual(regex.match(r"333\L444", "333four444",
+          bar=options), None)
+
+        options = [b"one", b"two", b"three"]
+        self.assertEqual(regex.match(br"333\L444", b"333one444",
+          bar=options).group(), b"333one444")
+        self.assertEqual(regex.match(br"(?i)333\L444", b"333TWO444",
+          bar=options).group(), b"333TWO444")
+        self.assertEqual(regex.match(br"333\L444", b"333four444",
+          bar=options), None)
+
+        self.assertEqual(repr(type(regex.compile(r"3\L4\L+5",
+          bar=["one", "two", "three"]))), self.PATTERN_CLASS)
+
+        self.assertEqual(regex.findall(r"^\L", "solid QWERT",
+          options=set(['good', 'brilliant', '+s\\ol[i}d'])), [])
+        self.assertEqual(regex.findall(r"^\L", "+solid QWERT",
+          options=set(['good', 'brilliant', '+solid'])), ['+solid'])
+
+        options = ["STRASSE"]
+        self.assertEqual(regex.match(r"(?fi)\L",
+          "stra\N{LATIN SMALL LETTER SHARP S}e", words=options).span(), (0,
+          6))
+
+        options = ["STRASSE", "stress"]
+        self.assertEqual(regex.match(r"(?fi)\L",
+          "stra\N{LATIN SMALL LETTER SHARP S}e", words=options).span(), (0,
+          6))
+
+        options = ["stra\N{LATIN SMALL LETTER SHARP S}e"]
+        self.assertEqual(regex.match(r"(?fi)\L", "STRASSE",
+          words=options).span(), (0, 7))
+
+        options = ["kit"]
+        self.assertEqual(regex.search(r"(?i)\L", "SKITS",
+          words=options).span(), (1, 4))
+        self.assertEqual(regex.search(r"(?i)\L",
+          "SK\N{LATIN CAPITAL LETTER I WITH DOT ABOVE}TS",
+          words=options).span(), (1, 4))
+
+        self.assertEqual(regex.search(r"(?fi)\b(\w+) +\1\b",
+          " stra\N{LATIN SMALL LETTER SHARP S}e STRASSE ").span(), (1, 15))
+        self.assertEqual(regex.search(r"(?fi)\b(\w+) +\1\b",
+          " STRASSE stra\N{LATIN SMALL LETTER SHARP S}e ").span(), (1, 15))
+
+        self.assertEqual(regex.search(r"^\L$", "", options=[]).span(),
+          (0, 0))
+
+    def test_fuzzy(self):
+        # Some tests borrowed from TRE library tests.
+        self.assertEqual(repr(type(regex.compile('(fou){s,e<=1}'))),
+          self.PATTERN_CLASS)
+        self.assertEqual(repr(type(regex.compile('(fuu){s}'))),
+          self.PATTERN_CLASS)
+        self.assertEqual(repr(type(regex.compile('(fuu){s,e}'))),
+          self.PATTERN_CLASS)
+        self.assertEqual(repr(type(regex.compile('(anaconda){1i+1d<1,s<=1}'))),
+          self.PATTERN_CLASS)
+        self.assertEqual(repr(type(regex.compile('(anaconda){1i+1d<1,s<=1,e<=10}'))),
+          self.PATTERN_CLASS)
+        self.assertEqual(repr(type(regex.compile('(anaconda){s<=1,e<=1,1i+1d<1}'))),
+          self.PATTERN_CLASS)
+
+        text = 'molasses anaconda foo bar baz smith anderson '
+        self.assertEqual(regex.search('(znacnda){s<=1,e<=3,1i+1d<1}', text),
+          None)
+        self.assertEqual(regex.search('(znacnda){s<=1,e<=3,1i+1d<2}',
+          text).span(0, 1), ((9, 17), (9, 17)))
+        self.assertEqual(regex.search('(ananda){1i+1d<2}', text), None)
+        self.assertEqual(regex.search(r"(?:\bznacnda){e<=2}", text)[0],
+          "anaconda")
+        self.assertEqual(regex.search(r"(?:\bnacnda){e<=2}", text)[0],
+          "anaconda")
+
+        text = 'anaconda foo bar baz smith anderson'
+        self.assertEqual(regex.search('(fuu){i<=3,d<=3,e<=5}', text).span(0,
+          1), ((0, 0), (0, 0)))
+        self.assertEqual(regex.search('(?b)(fuu){i<=3,d<=3,e<=5}',
+          text).span(0, 1), ((9, 10), (9, 10)))
+        self.assertEqual(regex.search('(fuu){i<=2,d<=2,e<=5}', text).span(0,
+          1), ((7, 10), (7, 10)))
+        self.assertEqual(regex.search('(?e)(fuu){i<=2,d<=2,e<=5}',
+          text).span(0, 1), ((9, 10), (9, 10)))
+        self.assertEqual(regex.search('(fuu){i<=3,d<=3,e}', text).span(0, 1),
+          ((0, 0), (0, 0)))
+        self.assertEqual(regex.search('(?b)(fuu){i<=3,d<=3,e}', text).span(0,
+          1), ((9, 10), (9, 10)))
+
+        self.assertEqual(repr(type(regex.compile('(approximate){s<=3,1i+1d<3}'))),
+          self.PATTERN_CLASS)
+
+        # No cost limit.
+        self.assertEqual(regex.search('(foobar){e}',
+          'xirefoabralfobarxie').span(0, 1), ((0, 6), (0, 6)))
+        self.assertEqual(regex.search('(?e)(foobar){e}',
+          'xirefoabralfobarxie').span(0, 1), ((0, 3), (0, 3)))
+        self.assertEqual(regex.search('(?b)(foobar){e}',
+          'xirefoabralfobarxie').span(0, 1), ((11, 16), (11, 16)))
+
+        # At most two errors.
+        self.assertEqual(regex.search('(foobar){e<=2}',
+          'xirefoabrzlfd').span(0, 1), ((4, 9), (4, 9)))
+        self.assertEqual(regex.search('(foobar){e<=2}', 'xirefoabzlfd'), None)
+
+        # At most two inserts or substitutions and max two errors total.
+        self.assertEqual(regex.search('(foobar){i<=2,s<=2,e<=2}',
+          'oobargoobaploowap').span(0, 1), ((5, 11), (5, 11)))
+
+        # Find best whole word match for "foobar".
+        self.assertEqual(regex.search('\\b(foobar){e}\\b', 'zfoobarz').span(0,
+          1), ((0, 8), (0, 8)))
+        self.assertEqual(regex.search('\\b(foobar){e}\\b',
+          'boing zfoobarz goobar woop').span(0, 1), ((0, 6), (0, 6)))
+        self.assertEqual(regex.search('(?b)\\b(foobar){e}\\b',
+          'boing zfoobarz goobar woop').span(0, 1), ((15, 21), (15, 21)))
+
+        # Match whole string, allow only 1 error.
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobar').span(0, 1),
+          ((0, 6), (0, 6)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'xfoobar').span(0,
+          1), ((0, 7), (0, 7)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobarx').span(0,
+          1), ((0, 7), (0, 7)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'fooxbar').span(0,
+          1), ((0, 7), (0, 7)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'foxbar').span(0, 1),
+          ((0, 6), (0, 6)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'xoobar').span(0, 1),
+          ((0, 6), (0, 6)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobax').span(0, 1),
+          ((0, 6), (0, 6)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'oobar').span(0, 1),
+          ((0, 5), (0, 5)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'fobar').span(0, 1),
+          ((0, 5), (0, 5)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'fooba').span(0, 1),
+          ((0, 5), (0, 5)))
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'xfoobarx'), None)
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'foobarxx'), None)
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'xxfoobar'), None)
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'xfoxbar'), None)
+        self.assertEqual(regex.search('^(foobar){e<=1}$', 'foxbarx'), None)
+
+        # At most one insert, two deletes, and three substitutions.
+        # Additionally, deletes cost two and substitutes one, and total
+        # cost must be less than 4.
+        self.assertEqual(regex.search('(foobar){i<=1,d<=2,s<=3,2d+1s<4}',
+          '3oifaowefbaoraofuiebofasebfaobfaorfeoaro').span(0, 1), ((6, 13), (6,
+          13)))
+        self.assertEqual(regex.search('(?b)(foobar){i<=1,d<=2,s<=3,2d+1s<4}',
+          '3oifaowefbaoraofuiebofasebfaobfaorfeoaro').span(0, 1), ((34, 39),
+          (34, 39)))
+
+        # Partially fuzzy matches.
+        self.assertEqual(regex.search('foo(bar){e<=1}zap', 'foobarzap').span(0,
+          1), ((0, 9), (3, 6)))
+        self.assertEqual(regex.search('foo(bar){e<=1}zap', 'fobarzap'), None)
+        self.assertEqual(regex.search('foo(bar){e<=1}zap', 'foobrzap').span(0,
+          1), ((0, 8), (3, 5)))
+
+        text = ('www.cnn.com 64.236.16.20\nwww.slashdot.org 66.35.250.150\n'
+          'For useful information, use www.slashdot.org\nthis is demo data!\n')
+        self.assertEqual(regex.search(r'(?s)^.*(dot.org){e}.*$', text).span(0,
+          1), ((0, 120), (120, 120)))
+        self.assertEqual(regex.search(r'(?es)^.*(dot.org){e}.*$', text).span(0,
+          1), ((0, 120), (93, 100)))
+        self.assertEqual(regex.search(r'^.*(dot.org){e}.*$', text).span(0, 1),
+          ((0, 119), (24, 101)))
+
+        # Behaviour is unexpected, but arguably not wrong. It first finds the
+        # best match, then the best in what follows, etc.
+        self.assertEqual(regex.findall(r"\b\L{e<=1}\b",
+          " book cot dog desk ", words="cat dog".split()), ["cot", "dog"])
+        self.assertEqual(regex.findall(r"\b\L{e<=1}\b",
+          " book dog cot desk ", words="cat dog".split()), [" dog", "cot"])
+        self.assertEqual(regex.findall(r"(?e)\b\L{e<=1}\b",
+          " book dog cot desk ", words="cat dog".split()), ["dog", "cot"])
+        self.assertEqual(regex.findall(r"(?r)\b\L{e<=1}\b",
+          " book cot dog desk ", words="cat dog".split()), ["dog ", "cot"])
+        self.assertEqual(regex.findall(r"(?er)\b\L{e<=1}\b",
+          " book cot dog desk ", words="cat dog".split()), ["dog", "cot"])
+        self.assertEqual(regex.findall(r"(?r)\b\L{e<=1}\b",
+          " book dog cot desk ", words="cat dog".split()), ["cot", "dog"])
+        self.assertEqual(regex.findall(br"\b\L{e<=1}\b",
+          b" book cot dog desk ", words=b"cat dog".split()), [b"cot", b"dog"])
+        self.assertEqual(regex.findall(br"\b\L{e<=1}\b",
+          b" book dog cot desk ", words=b"cat dog".split()), [b" dog", b"cot"])
+        self.assertEqual(regex.findall(br"(?e)\b\L{e<=1}\b",
+          b" book dog cot desk ", words=b"cat dog".split()), [b"dog", b"cot"])
+        self.assertEqual(regex.findall(br"(?r)\b\L{e<=1}\b",
+          b" book cot dog desk ", words=b"cat dog".split()), [b"dog ", b"cot"])
+        self.assertEqual(regex.findall(br"(?er)\b\L{e<=1}\b",
+          b" book cot dog desk ", words=b"cat dog".split()), [b"dog", b"cot"])
+        self.assertEqual(regex.findall(br"(?r)\b\L{e<=1}\b",
+          b" book dog cot desk ", words=b"cat dog".split()), [b"cot", b"dog"])
+
+        self.assertEqual(regex.search(r"(\w+) (\1{e<=1})", "foo fou").groups(),
+          ("foo", "fou"))
+        self.assertEqual(regex.search(r"(?r)(\2{e<=1}) (\w+)",
+          "foo fou").groups(), ("foo", "fou"))
+        self.assertEqual(regex.search(br"(\w+) (\1{e<=1})",
+          b"foo fou").groups(), (b"foo", b"fou"))
+
+        self.assertEqual(regex.findall(r"(?:(?:QR)+){e}", "abcde"), ["abcde",
+          ""])
+        self.assertEqual(regex.findall(r"(?:Q+){e}", "abc"), ["abc", ""])
+
+        # Hg issue 41: = for fuzzy matches
+        self.assertEqual(regex.match(r"(?:service detection){0[^()]+)|(?R))*\)", "(ab(cd)ef)")[
+          : ], ("(ab(cd)ef)", "ef"))
+        self.assertEqual(regex.search(r"\(((?>[^()]+)|(?R))*\)",
+          "(ab(cd)ef)").captures(1), ["ab", "cd", "(cd)", "ef"])
+
+        self.assertEqual(regex.search(r"(?r)\(((?R)|(?>[^()]+))*\)",
+          "(ab(cd)ef)")[ : ], ("(ab(cd)ef)", "ab"))
+        self.assertEqual(regex.search(r"(?r)\(((?R)|(?>[^()]+))*\)",
+          "(ab(cd)ef)").captures(1), ["ef", "cd", "(cd)", "ab"])
+
+        self.assertEqual(regex.search(r"\(([^()]+|(?R))*\)",
+          "some text (a(b(c)d)e) more text")[ : ], ("(a(b(c)d)e)", "e"))
+
+        self.assertEqual(regex.search(r"(?r)\(((?R)|[^()]+)*\)",
+          "some text (a(b(c)d)e) more text")[ : ], ("(a(b(c)d)e)", "a"))
+
+        self.assertEqual(regex.search(r"(foo(\(((?:(?>[^()]+)|(?2))*)\)))",
+          "foo(bar(baz)+baz(bop))")[ : ], ("foo(bar(baz)+baz(bop))",
+          "foo(bar(baz)+baz(bop))", "(bar(baz)+baz(bop))",
+          "bar(baz)+baz(bop)"))
+
+        self.assertEqual(regex.search(r"(?r)(foo(\(((?:(?2)|(?>[^()]+))*)\)))",
+          "foo(bar(baz)+baz(bop))")[ : ], ("foo(bar(baz)+baz(bop))",
+          "foo(bar(baz)+baz(bop))", "(bar(baz)+baz(bop))",
+          "bar(baz)+baz(bop)"))
+
+        rgx = regex.compile(r"""^\s*(<\s*([a-zA-Z:]+)(?:\s*[a-zA-Z:]*\s*=\s*(?:'[^']*'|"[^"]*"))*\s*(/\s*)?>(?:[^<>]*|(?1))*(?(3)|<\s*/\s*\2\s*>))\s*$""")
+        self.assertEqual(bool(rgx.search('')), True)
+        self.assertEqual(bool(rgx.search('')), False)
+        self.assertEqual(bool(rgx.search('')), True)
+        self.assertEqual(bool(rgx.search('')), False)
+        self.assertEqual(bool(rgx.search('')), False)
+
+        self.assertEqual(bool(rgx.search('')), False)
+        self.assertEqual(bool(rgx.search('')), True)
+        self.assertEqual(bool(rgx.search('<    fooo   /  >')), True)
+        # The next regex should and does match. Perl 5.14 agrees.
+        #self.assertEqual(bool(rgx.search('foo')), False)
+        self.assertEqual(bool(rgx.search('foo')), False)
+
+        self.assertEqual(bool(rgx.search('foo')), True)
+        self.assertEqual(bool(rgx.search('foo')), True)
+        self.assertEqual(bool(rgx.search('')), True)
+
+    def test_copy(self):
+        # PatternObjects are immutable, therefore there's no need to clone them.
+        r = regex.compile("a")
+        self.assertTrue(copy.copy(r) is r)
+        self.assertTrue(copy.deepcopy(r) is r)
+
+        # MatchObjects are normally mutable because the target string can be
+        # detached. However, after the target string has been detached, a
+        # MatchObject becomes immutable, so there's no need to clone it.
+        m = r.match("a")
+        self.assertTrue(copy.copy(m) is not m)
+        self.assertTrue(copy.deepcopy(m) is not m)
+
+        self.assertTrue(m.string is not None)
+        m2 = copy.copy(m)
+        m2.detach_string()
+        self.assertTrue(m.string is not None)
+        self.assertTrue(m2.string is None)
+
+        # The following behaviour matches that of the re module.
+        it = regex.finditer(".", "ab")
+        it2 = copy.copy(it)
+        self.assertEqual(next(it).group(), "a")
+        self.assertEqual(next(it2).group(), "b")
+
+        # The following behaviour matches that of the re module.
+        it = regex.finditer(".", "ab")
+        it2 = copy.deepcopy(it)
+        self.assertEqual(next(it).group(), "a")
+        self.assertEqual(next(it2).group(), "b")
+
+        # The following behaviour is designed to match that of copying 'finditer'.
+        it = regex.splititer(" ", "a b")
+        it2 = copy.copy(it)
+        self.assertEqual(next(it), "a")
+        self.assertEqual(next(it2), "b")
+
+        # The following behaviour is designed to match that of copying 'finditer'.
+        it = regex.splititer(" ", "a b")
+        it2 = copy.deepcopy(it)
+        self.assertEqual(next(it), "a")
+        self.assertEqual(next(it2), "b")
+
+    def test_format(self):
+        self.assertEqual(regex.subf(r"(\w+) (\w+)", "{0} => {2} {1}",
+          "foo bar"), "foo bar => bar foo")
+        self.assertEqual(regex.subf(r"(?\w+) (?\w+)",
+          "{word2} {word1}", "foo bar"), "bar foo")
+
+        self.assertEqual(regex.subfn(r"(\w+) (\w+)", "{0} => {2} {1}",
+          "foo bar"), ("foo bar => bar foo", 1))
+        self.assertEqual(regex.subfn(r"(?\w+) (?\w+)",
+          "{word2} {word1}", "foo bar"), ("bar foo", 1))
+
+        self.assertEqual(regex.match(r"(\w+) (\w+)",
+          "foo bar").expandf("{0} => {2} {1}"), "foo bar => bar foo")
+
+    def test_fullmatch(self):
+        self.assertEqual(bool(regex.fullmatch(r"abc", "abc")), True)
+        self.assertEqual(bool(regex.fullmatch(r"abc", "abcx")), False)
+        self.assertEqual(bool(regex.fullmatch(r"abc", "abcx", endpos=3)), True)
+
+        self.assertEqual(bool(regex.fullmatch(r"abc", "xabc", pos=1)), True)
+        self.assertEqual(bool(regex.fullmatch(r"abc", "xabcy", pos=1)), False)
+        self.assertEqual(bool(regex.fullmatch(r"abc", "xabcy", pos=1,
+          endpos=4)), True)
+
+        self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "abc")), True)
+        self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "abcx")), False)
+        self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "abcx", endpos=3)),
+          True)
+
+        self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "xabc", pos=1)),
+          True)
+        self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "xabcy", pos=1)),
+          False)
+        self.assertEqual(bool(regex.fullmatch(r"(?r)abc", "xabcy", pos=1,
+          endpos=4)), True)
+
+    def test_issue_18468(self):
+        self.assertTypedEqual(regex.sub('y', 'a', 'xyz'), 'xaz')
+        self.assertTypedEqual(regex.sub('y', StrSubclass('a'),
+          StrSubclass('xyz')), 'xaz')
+        self.assertTypedEqual(regex.sub(b'y', b'a', b'xyz'), b'xaz')
+        self.assertTypedEqual(regex.sub(b'y', BytesSubclass(b'a'),
+          BytesSubclass(b'xyz')), b'xaz')
+        self.assertTypedEqual(regex.sub(b'y', bytearray(b'a'),
+          bytearray(b'xyz')), b'xaz')
+        self.assertTypedEqual(regex.sub(b'y', memoryview(b'a'),
+          memoryview(b'xyz')), b'xaz')
+
+        for string in ":a:b::c", StrSubclass(":a:b::c"):
+            self.assertTypedEqual(regex.split(":", string), ['', 'a', 'b', '',
+              'c'])
+            if sys.version_info >= (3, 7, 0):
+                self.assertTypedEqual(regex.split(":*", string), ['', '', 'a',
+                  '', 'b', '', 'c', ''])
+                self.assertTypedEqual(regex.split("(:*)", string), ['', ':',
+                  '', '', 'a', ':', '', '', 'b', '::', '', '', 'c', '', ''])
+            else:
+                self.assertTypedEqual(regex.split(":*", string), ['', 'a', 'b',
+                  'c'])
+                self.assertTypedEqual(regex.split("(:*)", string), ['', ':',
+                  'a', ':', 'b', '::', 'c'])
+
+        for string in (b":a:b::c", BytesSubclass(b":a:b::c"),
+          bytearray(b":a:b::c"), memoryview(b":a:b::c")):
+            self.assertTypedEqual(regex.split(b":", string), [b'', b'a', b'b',
+              b'', b'c'])
+            if sys.version_info >= (3, 7, 0):
+                self.assertTypedEqual(regex.split(b":*", string), [b'', b'',
+                  b'a', b'', b'b', b'', b'c', b''])
+                self.assertTypedEqual(regex.split(b"(:*)", string), [b'', b':',
+                  b'', b'', b'a', b':', b'', b'', b'b', b'::', b'', b'', b'c',
+                  b'', b''])
+            else:
+                self.assertTypedEqual(regex.split(b":*", string), [b'', b'a',
+                  b'b', b'c'])
+                self.assertTypedEqual(regex.split(b"(:*)", string), [b'', b':',
+                  b'a', b':', b'b', b'::', b'c'])
+
+        for string in "a:b::c:::d", StrSubclass("a:b::c:::d"):
+            self.assertTypedEqual(regex.findall(":+", string), [":", "::",
+              ":::"])
+            self.assertTypedEqual(regex.findall("(:+)", string), [":", "::",
+              ":::"])
+            self.assertTypedEqual(regex.findall("(:)(:*)", string), [(":", ""),
+              (":", ":"), (":", "::")])
+
+        for string in (b"a:b::c:::d", BytesSubclass(b"a:b::c:::d"),
+          bytearray(b"a:b::c:::d"), memoryview(b"a:b::c:::d")):
+            self.assertTypedEqual(regex.findall(b":+", string), [b":", b"::",
+              b":::"])
+            self.assertTypedEqual(regex.findall(b"(:+)", string), [b":", b"::",
+              b":::"])
+            self.assertTypedEqual(regex.findall(b"(:)(:*)", string), [(b":",
+              b""), (b":", b":"), (b":", b"::")])
+
+        for string in 'a', StrSubclass('a'):
+            self.assertEqual(regex.match('a', string).groups(), ())
+            self.assertEqual(regex.match('(a)', string).groups(), ('a',))
+            self.assertEqual(regex.match('(a)', string).group(0), 'a')
+            self.assertEqual(regex.match('(a)', string).group(1), 'a')
+            self.assertEqual(regex.match('(a)', string).group(1, 1), ('a',
+              'a'))
+
+        for string in (b'a', BytesSubclass(b'a'), bytearray(b'a'),
+          memoryview(b'a')):
+            self.assertEqual(regex.match(b'a', string).groups(), ())
+            self.assertEqual(regex.match(b'(a)', string).groups(), (b'a',))
+            self.assertEqual(regex.match(b'(a)', string).group(0), b'a')
+            self.assertEqual(regex.match(b'(a)', string).group(1), b'a')
+            self.assertEqual(regex.match(b'(a)', string).group(1, 1), (b'a',
+              b'a'))
+
+    def test_partial(self):
+        self.assertEqual(regex.match('ab', 'a', partial=True).partial, True)
+        self.assertEqual(regex.match('ab', 'a', partial=True).span(), (0, 1))
+        self.assertEqual(regex.match(r'cats', 'cat', partial=True).partial,
+          True)
+        self.assertEqual(regex.match(r'cats', 'cat', partial=True).span(), (0,
+          3))
+        self.assertEqual(regex.match(r'cats', 'catch', partial=True), None)
+        self.assertEqual(regex.match(r'abc\w{3}', 'abcdef',
+          partial=True).partial, False)
+        self.assertEqual(regex.match(r'abc\w{3}', 'abcdef',
+          partial=True).span(), (0, 6))
+        self.assertEqual(regex.match(r'abc\w{3}', 'abcde',
+          partial=True).partial, True)
+        self.assertEqual(regex.match(r'abc\w{3}', 'abcde',
+          partial=True).span(), (0, 5))
+
+        self.assertEqual(regex.match(r'\d{4}$', '1234', partial=True).partial,
+          False)
+
+        self.assertEqual(regex.match(r'\L', 'post', partial=True,
+          words=['post']).partial, False)
+        self.assertEqual(regex.match(r'\L', 'post', partial=True,
+          words=['post']).span(), (0, 4))
+        self.assertEqual(regex.match(r'\L', 'pos', partial=True,
+          words=['post']).partial, True)
+        self.assertEqual(regex.match(r'\L', 'pos', partial=True,
+          words=['post']).span(), (0, 3))
+
+        self.assertEqual(regex.match(r'(?fi)\L', 'POST', partial=True,
+          words=['po\uFB06']).partial, False)
+        self.assertEqual(regex.match(r'(?fi)\L', 'POST', partial=True,
+          words=['po\uFB06']).span(), (0, 4))
+        self.assertEqual(regex.match(r'(?fi)\L', 'POS', partial=True,
+          words=['po\uFB06']).partial, True)
+        self.assertEqual(regex.match(r'(?fi)\L', 'POS', partial=True,
+          words=['po\uFB06']).span(), (0, 3))
+        self.assertEqual(regex.match(r'(?fi)\L', 'po\uFB06',
+          partial=True, words=['POS']), None)
+
+        self.assertEqual(regex.match(r'[a-z]*4R$', 'a', partial=True).span(),
+          (0, 1))
+        self.assertEqual(regex.match(r'[a-z]*4R$', 'ab', partial=True).span(),
+          (0, 2))
+        self.assertEqual(regex.match(r'[a-z]*4R$', 'ab4', partial=True).span(),
+          (0, 3))
+        self.assertEqual(regex.match(r'[a-z]*4R$', 'a4', partial=True).span(),
+          (0, 2))
+        self.assertEqual(regex.match(r'[a-z]*4R$', 'a4R', partial=True).span(),
+          (0, 3))
+        self.assertEqual(regex.match(r'[a-z]*4R$', '4a', partial=True), None)
+        self.assertEqual(regex.match(r'[a-z]*4R$', 'a44', partial=True), None)
+
+    def test_hg_bugs(self):
+        # Hg issue 28: regex.compile("(?>b)") causes "TypeError: 'Character'
+        # object is not subscriptable"
+        self.assertEqual(bool(regex.compile("(?>b)", flags=regex.V1)), True)
+
+        # Hg issue 29: regex.compile("^((?>\w+)|(?>\s+))*$") causes
+        # "TypeError: 'GreedyRepeat' object is not iterable"
+        self.assertEqual(bool(regex.compile(r"^((?>\w+)|(?>\s+))*$",
+          flags=regex.V1)), True)
+
+        # Hg issue 31: atomic and normal groups in recursive patterns
+        self.assertEqual(regex.findall(r"\((?:(?>[^()]+)|(?R))*\)",
+          "a(bcd(e)f)g(h)"), ['(bcd(e)f)', '(h)'])
+        self.assertEqual(regex.findall(r"\((?:(?:[^()]+)|(?R))*\)",
+          "a(bcd(e)f)g(h)"), ['(bcd(e)f)', '(h)'])
+        self.assertEqual(regex.findall(r"\((?:(?>[^()]+)|(?R))*\)",
+          "a(b(cd)e)f)g)h"), ['(b(cd)e)'])
+        self.assertEqual(regex.findall(r"\((?:(?>[^()]+)|(?R))*\)",
+          "a(bc(d(e)f)gh"), ['(d(e)f)'])
+        self.assertEqual(regex.findall(r"(?r)\((?:(?>[^()]+)|(?R))*\)",
+          "a(bc(d(e)f)gh"), ['(d(e)f)'])
+        self.assertEqual([m.group() for m in
+          regex.finditer(r"\((?:[^()]*+|(?0))*\)", "a(b(c(de)fg)h")],
+          ['(c(de)fg)'])
+
+        # Hg issue 32: regex.search("a(bc)d", "abcd", regex.I|regex.V1) returns
+        # None
+        self.assertEqual(regex.search("a(bc)d", "abcd", regex.I |
+          regex.V1).group(0), "abcd")
+
+        # Hg issue 33: regex.search("([\da-f:]+)$", "E", regex.I|regex.V1)
+        # returns None
+        self.assertEqual(regex.search(r"([\da-f:]+)$", "E", regex.I |
+          regex.V1).group(0), "E")
+        self.assertEqual(regex.search(r"([\da-f:]+)$", "e", regex.I |
+          regex.V1).group(0), "e")
+
+        # Hg issue 34: regex.search("^(?=ab(de))(abd)(e)", "abde").groups()
+        # returns (None, 'abd', 'e') instead of ('de', 'abd', 'e')
+        self.assertEqual(regex.search("^(?=ab(de))(abd)(e)", "abde").groups(),
+          ('de', 'abd', 'e'))
+
+        # Hg issue 35: regex.compile("\ ", regex.X) causes "_regex_core.error:
+        # bad escape"
+        self.assertEqual(bool(regex.match(r"\ ", " ", flags=regex.X)), True)
+
+        # Hg issue 36: regex.search("^(a|)\1{2}b", "b") returns None
+        self.assertEqual(regex.search(r"^(a|)\1{2}b", "b").group(0, 1), ('b',
+          ''))
+
+        # Hg issue 37: regex.search("^(a){0,0}", "abc").group(0,1) returns
+        # ('a', 'a') instead of ('', None)
+        self.assertEqual(regex.search("^(a){0,0}", "abc").group(0, 1), ('',
+          None))
+
+        # Hg issue 38: regex.search("(?>.*/)b", "a/b") returns None
+        self.assertEqual(regex.search("(?>.*/)b", "a/b").group(0), "a/b")
+
+        # Hg issue 39: regex.search("((?i)blah)\\s+\\1", "blah BLAH") doesn't
+        # return None
+        # Changed to positional flags in regex 2023.12.23.
+        self.assertEqual(regex.search(r"((?i)blah)\s+\1", "blah BLAH"), None)
+
+        # Hg issue 40: regex.search("(\()?[^()]+(?(1)\)|)", "(abcd").group(0)
+        # returns "bcd" instead of "abcd"
+        self.assertEqual(regex.search(r"(\()?[^()]+(?(1)\)|)",
+          "(abcd").group(0), "abcd")
+
+        # Hg issue 42: regex.search("(a*)*", "a", flags=regex.V1).span(1)
+        # returns (0, 1) instead of (1, 1)
+        self.assertEqual(regex.search("(a*)*", "a").span(1), (1, 1))
+        self.assertEqual(regex.search("(a*)*", "aa").span(1), (2, 2))
+        self.assertEqual(regex.search("(a*)*", "aaa").span(1), (3, 3))
+
+        # Hg issue 43: regex.compile("a(?#xxx)*") causes "_regex_core.error:
+        # nothing to repeat"
+        self.assertEqual(regex.search("a(?#xxx)*", "aaa").group(), "aaa")
+
+        # Hg issue 44: regex.compile("(?=abc){3}abc") causes
+        # "_regex_core.error: nothing to repeat"
+        self.assertEqual(regex.search("(?=abc){3}abc", "abcabcabc").span(), (0,
+          3))
+
+        # Hg issue 45: regex.compile("^(?:a(?:(?:))+)+") causes
+        # "_regex_core.error: nothing to repeat"
+        self.assertEqual(regex.search("^(?:a(?:(?:))+)+", "a").span(), (0, 1))
+        self.assertEqual(regex.search("^(?:a(?:(?:))+)+", "aa").span(), (0, 2))
+
+        # Hg issue 46: regex.compile("a(?x: b c )d") causes
+        # "_regex_core.error: missing )"
+        self.assertEqual(regex.search("a(?x: b c )d", "abcd").group(0), "abcd")
+
+        # Hg issue 47: regex.compile("a#comment\n*", flags=regex.X) causes
+        # "_regex_core.error: nothing to repeat"
+        self.assertEqual(regex.search("a#comment\n*", "aaa",
+          flags=regex.X).group(0), "aaa")
+
+        # Hg issue 48: regex.search("(a(?(1)\\1)){4}", "a"*10,
+        # flags=regex.V1).group(0,1) returns ('aaaaa', 'a') instead of ('aaaaaaaaaa', 'aaaa')
+        self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){1}",
+          "aaaaaaaaaa").span(0, 1), ((0, 1), (0, 1)))
+        self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){2}",
+          "aaaaaaaaaa").span(0, 1), ((0, 3), (1, 3)))
+        self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){3}",
+          "aaaaaaaaaa").span(0, 1), ((0, 6), (3, 6)))
+        self.assertEqual(regex.search(r"(?V1)(a(?(1)\1)){4}",
+          "aaaaaaaaaa").span(0, 1), ((0, 10), (6, 10)))
+
+        # Hg issue 49: regex.search("(a)(?<=b(?1))", "baz", regex.V1) returns
+        # None incorrectly
+        self.assertEqual(regex.search("(?V1)(a)(?<=b(?1))", "baz").group(0),
+          "a")
+
+        # Hg issue 50: not all keywords are found by named list with
+        # overlapping keywords when full Unicode casefolding is required
+        self.assertEqual(regex.findall(r'(?fi)\L',
+          'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05',
+          keywords=['post','pos']), ['POST', 'Post', 'post', 'po\u017Ft',
+          'po\uFB06', 'po\uFB05'])
+        self.assertEqual(regex.findall(r'(?fi)pos|post',
+          'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05'), ['POS',
+          'Pos', 'pos', 'po\u017F', 'po\uFB06', 'po\uFB05'])
+        self.assertEqual(regex.findall(r'(?fi)post|pos',
+          'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05'), ['POST',
+          'Post', 'post', 'po\u017Ft', 'po\uFB06', 'po\uFB05'])
+        self.assertEqual(regex.findall(r'(?fi)post|another',
+          'POST, Post, post, po\u017Ft, po\uFB06, and po\uFB05'), ['POST',
+          'Post', 'post', 'po\u017Ft', 'po\uFB06', 'po\uFB05'])
+
+        # Hg issue 51: regex.search("((a)(?1)|(?2))", "a", flags=regex.V1)
+        # returns None incorrectly
+        self.assertEqual(regex.search("(?V1)((a)(?1)|(?2))", "a").group(0, 1,
+          2), ('a', 'a', None))
+
+        # Hg issue 52: regex.search("(\\1xx|){6}", "xx",
+        # flags=regex.V1).span(0,1) returns incorrect value
+        self.assertEqual(regex.search(r"(?V1)(\1xx|){6}", "xx").span(0, 1),
+          ((0, 2), (2, 2)))
+
+        # Hg issue 53: regex.search("(a|)+", "a") causes MemoryError
+        self.assertEqual(regex.search("(a|)+", "a").group(0, 1), ("a", ""))
+
+        # Hg issue 54: regex.search("(a|)*\\d", "a"*80) causes MemoryError
+        self.assertEqual(regex.search(r"(a|)*\d", "a" * 80), None)
+
+        # Hg issue 55: regex.search("^(?:a?b?)*$", "ac") take a very long time.
+        self.assertEqual(regex.search("^(?:a?b?)*$", "ac"), None)
+
+        # Hg issue 58: bad named character escape sequences like "\\N{1}"
+        # treats as "N"
+        self.assertRaisesRegex(regex.error, self.UNDEF_CHAR_NAME, lambda:
+          regex.compile("\\N{1}"))
+
+        # Hg issue 59: regex.search("\\Z", "a\na\n") returns None incorrectly
+        self.assertEqual(regex.search("\\Z", "a\na\n").span(0), (4, 4))
+
+        # Hg issue 60: regex.search("(q1|.)*(q2|.)*(x(a|bc)*y){2,}", "xayxay")
+        # returns None incorrectly
+        self.assertEqual(regex.search("(q1|.)*(q2|.)*(x(a|bc)*y){2,}",
+          "xayxay").group(0), "xayxay")
+
+        # Hg issue 61: regex.search("[^a]", "A", regex.I).group(0) returns ''
+        # incorrectly
+        self.assertEqual(regex.search("(?i)[^a]", "A"), None)
+
+        # Hg issue 63: regex.search("[[:ascii:]]", "\N{KELVIN SIGN}",
+        # flags=regex.I|regex.V1) doesn't return None
+        self.assertEqual(regex.search("(?i)[[:ascii:]]", "\N{KELVIN SIGN}"),
+          None)
+
+        # Hg issue 66: regex.search("((a|b(?1)c){3,5})", "baaaaca",
+        # flags=regex.V1).groups() returns ('baaaac', 'baaaac') instead of ('aaaa', 'a')
+        self.assertEqual(regex.search("((a|b(?1)c){3,5})", "baaaaca").group(0,
+          1, 2), ('aaaa', 'aaaa', 'a'))
+
+        # Hg issue 71: non-greedy quantifier in lookbehind
+        self.assertEqual(regex.findall(r"(?<=:\S+ )\w+", ":9 abc :10 def"),
+          ['abc', 'def'])
+        self.assertEqual(regex.findall(r"(?<=:\S* )\w+", ":9 abc :10 def"),
+          ['abc', 'def'])
+        self.assertEqual(regex.findall(r"(?<=:\S+? )\w+", ":9 abc :10 def"),
+          ['abc', 'def'])
+        self.assertEqual(regex.findall(r"(?<=:\S*? )\w+", ":9 abc :10 def"),
+          ['abc', 'def'])
+
+        # Hg issue 73: conditional patterns
+        self.assertEqual(regex.search(r"(?:fe)?male", "female").group(),
+          "female")
+        self.assertEqual([m.group() for m in
+          regex.finditer(r"(fe)?male: h(?(1)(er)|(is)) (\w+)",
+          "female: her dog; male: his cat. asdsasda")], ['female: her dog',
+          'male: his cat'])
+
+        # Hg issue 78: "Captures" doesn't work for recursive calls
+        self.assertEqual(regex.search(r'(?\((?:[^()]++|(?&rec))*\))',
+          'aaa(((1+0)+1)+1)bbb').captures('rec'), ['(1+0)', '((1+0)+1)',
+          '(((1+0)+1)+1)'])
+
+        # Hg issue 80: Escape characters throws an exception
+        self.assertRaisesRegex(regex.error, self.BAD_ESCAPE, lambda:
+          regex.sub('x', '\\', 'x'), )
+
+        # Hg issue 82: error range does not work
+        fz = "(CAGCCTCCCATTTCAGAATATACATCC){1a(?b))', "ab").spans("x"), [(1,
+          2), (0, 2)])
+
+        # Hg issue 91: match.expand is extremely slow
+        # Check that the replacement cache works.
+        self.assertEqual(regex.sub(r'(-)', lambda m: m.expand(r'x'), 'a-b-c'),
+          'axbxc')
+
+        # Hg issue 94: Python crashes when executing regex updates
+        # pattern.findall
+        rx = regex.compile(r'\bt(est){i<2}', flags=regex.V1)
+        self.assertEqual(rx.search("Some text"), None)
+        self.assertEqual(rx.findall("Some text"), [])
+
+        # Hg issue 95: 'pos' for regex.error
+        self.assertRaisesRegex(regex.error, self.MULTIPLE_REPEAT, lambda:
+          regex.compile(r'.???'))
+
+        # Hg issue 97: behaviour of regex.escape's special_only is wrong
+        #
+        # Hg issue 244: Make `special_only=True` the default in
+        # `regex.escape()`
+        self.assertEqual(regex.escape('foo!?', special_only=False), 'foo\\!\\?')
+        self.assertEqual(regex.escape('foo!?', special_only=True), 'foo!\\?')
+        self.assertEqual(regex.escape('foo!?'), 'foo!\\?')
+
+        self.assertEqual(regex.escape(b'foo!?', special_only=False), b'foo\\!\\?')
+        self.assertEqual(regex.escape(b'foo!?', special_only=True),
+          b'foo!\\?')
+        self.assertEqual(regex.escape(b'foo!?'), b'foo!\\?')
+
+        # Hg issue 100: strange results from regex.search
+        self.assertEqual(regex.search('^([^z]*(?:WWWi|W))?$',
+          'WWWi').groups(), ('WWWi', ))
+        self.assertEqual(regex.search('^([^z]*(?:WWWi|w))?$',
+          'WWWi').groups(), ('WWWi', ))
+        self.assertEqual(regex.search('^([^z]*?(?:WWWi|W))?$',
+          'WWWi').groups(), ('WWWi', ))
+
+        # Hg issue 101: findall() broken (seems like memory corruption)
+        pat = regex.compile(r'xxx', flags=regex.FULLCASE | regex.UNICODE)
+        self.assertEqual([x.group() for x in pat.finditer('yxxx')], ['xxx'])
+        self.assertEqual(pat.findall('yxxx'), ['xxx'])
+
+        raw = 'yxxx'
+        self.assertEqual([x.group() for x in pat.finditer(raw)], ['xxx'])
+        self.assertEqual(pat.findall(raw), ['xxx'])
+
+        pat = regex.compile(r'xxx', flags=regex.FULLCASE | regex.IGNORECASE |
+          regex.UNICODE)
+        self.assertEqual([x.group() for x in pat.finditer('yxxx')], ['xxx'])
+        self.assertEqual(pat.findall('yxxx'), ['xxx'])
+
+        raw = 'yxxx'
+        self.assertEqual([x.group() for x in pat.finditer(raw)], ['xxx'])
+        self.assertEqual(pat.findall(raw), ['xxx'])
+
+        # Hg issue 106: * operator not working correctly with sub()
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.sub('(?V0).*', 'x', 'test'), 'xx')
+        else:
+            self.assertEqual(regex.sub('(?V0).*', 'x', 'test'), 'x')
+        self.assertEqual(regex.sub('(?V1).*', 'x', 'test'), 'xx')
+
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.sub('(?V0).*?', '|', 'test'), '|||||||||')
+        else:
+            self.assertEqual(regex.sub('(?V0).*?', '|', 'test'), '|t|e|s|t|')
+        self.assertEqual(regex.sub('(?V1).*?', '|', 'test'), '|||||||||')
+
+        # Hg issue 112: re: OK, but regex: SystemError
+        self.assertEqual(regex.sub(r'^(@)\n(?!.*?@)(.*)',
+          r'\1\n==========\n\2', '@\n', flags=regex.DOTALL), '@\n==========\n')
+
+        # Hg issue 109: Edit distance of fuzzy match
+        self.assertEqual(regex.match(r'(?:cats|cat){e<=1}',
+         'caz').fuzzy_counts, (1, 0, 0))
+        self.assertEqual(regex.match(r'(?e)(?:cats|cat){e<=1}',
+          'caz').fuzzy_counts, (1, 0, 0))
+        self.assertEqual(regex.match(r'(?b)(?:cats|cat){e<=1}',
+          'caz').fuzzy_counts, (1, 0, 0))
+
+        self.assertEqual(regex.match(r'(?:cat){e<=1}', 'caz').fuzzy_counts,
+          (1, 0, 0))
+        self.assertEqual(regex.match(r'(?e)(?:cat){e<=1}',
+          'caz').fuzzy_counts, (1, 0, 0))
+        self.assertEqual(regex.match(r'(?b)(?:cat){e<=1}',
+          'caz').fuzzy_counts, (1, 0, 0))
+
+        self.assertEqual(regex.match(r'(?:cats){e<=2}', 'c ats').fuzzy_counts,
+          (1, 1, 0))
+        self.assertEqual(regex.match(r'(?e)(?:cats){e<=2}',
+          'c ats').fuzzy_counts, (0, 1, 0))
+        self.assertEqual(regex.match(r'(?b)(?:cats){e<=2}',
+          'c ats').fuzzy_counts, (0, 1, 0))
+
+        self.assertEqual(regex.match(r'(?:cats){e<=2}',
+          'c a ts').fuzzy_counts, (0, 2, 0))
+        self.assertEqual(regex.match(r'(?e)(?:cats){e<=2}',
+          'c a ts').fuzzy_counts, (0, 2, 0))
+        self.assertEqual(regex.match(r'(?b)(?:cats){e<=2}',
+          'c a ts').fuzzy_counts, (0, 2, 0))
+
+        self.assertEqual(regex.match(r'(?:cats){e<=1}', 'c ats').fuzzy_counts,
+          (0, 1, 0))
+        self.assertEqual(regex.match(r'(?e)(?:cats){e<=1}',
+          'c ats').fuzzy_counts, (0, 1, 0))
+        self.assertEqual(regex.match(r'(?b)(?:cats){e<=1}',
+          'c ats').fuzzy_counts, (0, 1, 0))
+
+        # Hg issue 115: Infinite loop when processing backreferences
+        self.assertEqual(regex.findall(r'\bof ([a-z]+) of \1\b',
+          'To make use of one of these modules'), [])
+
+        # Hg issue 125: Reference to entire match (\g<0>) in
+        # Pattern.sub() doesn't work as of 2014.09.22 release.
+        self.assertEqual(regex.sub(r'x', r'\g<0>', 'x'), 'x')
+
+        # Unreported issue: no such builtin as 'ascii' in Python 2.
+        self.assertEqual(bool(regex.match(r'a', 'a', regex.DEBUG)), True)
+
+        # Hg issue 131: nested sets behaviour
+        self.assertEqual(regex.findall(r'(?V1)[[b-e]--cd]', 'abcdef'), ['b',
+          'e'])
+        self.assertEqual(regex.findall(r'(?V1)[b-e--cd]', 'abcdef'), ['b',
+          'e'])
+        self.assertEqual(regex.findall(r'(?V1)[[bcde]--cd]', 'abcdef'), ['b',
+          'e'])
+        self.assertEqual(regex.findall(r'(?V1)[bcde--cd]', 'abcdef'), ['b',
+          'e'])
+
+        # Hg issue 132: index out of range on null property \p{}
+        self.assertRaisesRegex(regex.error, '^unknown property at position 4$',
+          lambda: regex.compile(r'\p{}'))
+
+        # Issue 23692.
+        self.assertEqual(regex.match('(?:()|(?(1)()|z)){2}(?(2)a|z)',
+          'a').group(0, 1, 2), ('a', '', ''))
+        self.assertEqual(regex.match('(?:()|(?(1)()|z)){0,2}(?(2)a|z)',
+          'a').group(0, 1, 2), ('a', '', ''))
+
+        # Hg issue 137: Posix character class :punct: does not seem to be
+        # supported.
+
+        # Posix compatibility as recommended here:
+        # http://www.unicode.org/reports/tr18/#Compatibility_Properties
+
+        # Posix in Unicode.
+        chars = ''.join(chr(c) for c in range(0x10000))
+
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:alnum:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[\p{Alpha}\p{PosixDigit}]+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:alpha:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''\p{Alpha}+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:ascii:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[\p{InBasicLatin}]+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:blank:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[\p{gc=Space_Separator}\t]+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:cntrl:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''\p{gc=Control}+''', chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:digit:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[0-9]+''', chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:graph:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[^\p{Space}\p{gc=Control}\p{gc=Surrogate}\p{gc=Unassigned}]+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:lower:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''\p{Lower}+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:print:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''(?V1)[\p{Graph}\p{Blank}--\p{Cntrl}]+''', chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:punct:]]+''',
+          chars))),
+          ascii(''.join(regex.findall(r'''(?V1)[\p{gc=Punctuation}\p{gc=Symbol}--\p{Alpha}]+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:space:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''\p{Whitespace}+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:upper:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''\p{Upper}+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:word:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[\p{Alpha}\p{gc=Mark}\p{Digit}\p{gc=Connector_Punctuation}\p{Join_Control}]+''',
+          chars))))
+        self.assertEqual(ascii(''.join(regex.findall(r'''[[:xdigit:]]+''',
+          chars))), ascii(''.join(regex.findall(r'''[0-9A-Fa-f]+''',
+          chars))))
+
+        # Posix in ASCII.
+        chars = bytes(range(0x100))
+
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:alnum:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[\p{Alpha}\p{PosixDigit}]+''',
+          chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:alpha:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Alpha}+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:ascii:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[\x00-\x7F]+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:blank:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[\p{gc=Space_Separator}\t]+''',
+          chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:cntrl:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)\p{gc=Control}+''',
+          chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:digit:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[0-9]+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:graph:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[^\p{Space}\p{gc=Control}\p{gc=Surrogate}\p{gc=Unassigned}]+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:lower:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Lower}+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:print:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?aV1)[\p{Graph}\p{Blank}--\p{Cntrl}]+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:punct:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?aV1)[\p{gc=Punctuation}\p{gc=Symbol}--\p{Alpha}]+''',
+          chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:space:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Whitespace}+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:upper:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)\p{Upper}+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:word:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[\p{Alpha}\p{gc=Mark}\p{Digit}\p{gc=Connector_Punctuation}\p{Join_Control}]+''', chars))))
+        self.assertEqual(ascii(b''.join(regex.findall(br'''(?a)[[:xdigit:]]+''',
+          chars))), ascii(b''.join(regex.findall(br'''(?a)[0-9A-Fa-f]+''', chars))))
+
+        # Hg issue 138: grapheme anchored search not working properly.
+        self.assertEqual(ascii(regex.search(r'\X$', 'ab\u2103').group()),
+          ascii('\u2103'))
+
+        # Hg issue 139: Regular expression with multiple wildcards where first
+        # should match empty string does not always work.
+        self.assertEqual(regex.search("([^L]*)([^R]*R)", "LtR").groups(), ('',
+          'LtR'))
+
+        # Hg issue 140: Replace with REVERSE and groups has unexpected
+        # behavior.
+        self.assertEqual(regex.sub(r'(.)', r'x\1y', 'ab'), 'xayxby')
+        self.assertEqual(regex.sub(r'(?r)(.)', r'x\1y', 'ab'), 'xayxby')
+        self.assertEqual(regex.subf(r'(.)', 'x{1}y', 'ab'), 'xayxby')
+        self.assertEqual(regex.subf(r'(?r)(.)', 'x{1}y', 'ab'), 'xayxby')
+
+        # Hg issue 141: Crash on a certain partial match.
+        self.assertEqual(regex.fullmatch('(a)*abc', 'ab',
+          partial=True).span(), (0, 2))
+        self.assertEqual(regex.fullmatch('(a)*abc', 'ab',
+          partial=True).partial, True)
+
+        # Hg issue 143: Partial matches have incorrect span if prefix is '.'
+        # wildcard.
+        self.assertEqual(regex.search('OXRG', 'OOGOX', partial=True).span(),
+          (3, 5))
+        self.assertEqual(regex.search('.XRG', 'OOGOX', partial=True).span(),
+          (3, 5))
+        self.assertEqual(regex.search('.{1,3}XRG', 'OOGOX',
+          partial=True).span(), (1, 5))
+
+        # Hg issue 144: Latest version problem with matching 'R|R'.
+        self.assertEqual(regex.match('R|R', 'R').span(), (0, 1))
+
+        # Hg issue 146: Forced-fail (?!) works improperly in conditional.
+        self.assertEqual(regex.match(r'(.)(?(1)(?!))', 'xy'), None)
+
+        # Groups cleared after failure.
+        self.assertEqual(regex.findall(r'(y)?(\d)(?(1)\b\B)', 'ax1y2z3b'),
+          [('', '1'), ('', '2'), ('', '3')])
+        self.assertEqual(regex.findall(r'(y)?+(\d)(?(1)\b\B)', 'ax1y2z3b'),
+          [('', '1'), ('', '2'), ('', '3')])
+
+        # Hg issue 147: Fuzzy match can return match points beyond buffer end.
+        self.assertEqual([m.span() for m in regex.finditer(r'(?i)(?:error){e}',
+          'regex failure')], [(0, 5), (5, 10), (10, 13), (13, 13)])
+        self.assertEqual([m.span() for m in
+          regex.finditer(r'(?fi)(?:error){e}', 'regex failure')], [(0, 5), (5,
+          10), (10, 13), (13, 13)])
+
+        # Hg issue 150: Have an option for POSIX-compatible longest match of
+        # alternates.
+        self.assertEqual(regex.search(r'(?p)\d+(\w(\d*)?|[eE]([+-]\d+))',
+          '10b12')[0], '10b12')
+        self.assertEqual(regex.search(r'(?p)\d+(\w(\d*)?|[eE]([+-]\d+))',
+          '10E+12')[0], '10E+12')
+
+        self.assertEqual(regex.search(r'(?p)(\w|ae|oe|ue|ss)', 'ae')[0], 'ae')
+        self.assertEqual(regex.search(r'(?p)one(self)?(selfsufficient)?',
+          'oneselfsufficient')[0], 'oneselfsufficient')
+
+        # Hg issue 151: Request: \K.
+        self.assertEqual(regex.search(r'(ab\Kcd)', 'abcd').group(0, 1), ('cd',
+          'abcd'))
+        self.assertEqual(regex.findall(r'\w\w\K\w\w', 'abcdefgh'), ['cd',
+          'gh'])
+        self.assertEqual(regex.findall(r'(\w\w\K\w\w)', 'abcdefgh'), ['abcd',
+          'efgh'])
+
+        self.assertEqual(regex.search(r'(?r)(ab\Kcd)', 'abcd').group(0, 1),
+          ('ab', 'abcd'))
+        self.assertEqual(regex.findall(r'(?r)\w\w\K\w\w', 'abcdefgh'), ['ef',
+          'ab'])
+        self.assertEqual(regex.findall(r'(?r)(\w\w\K\w\w)', 'abcdefgh'),
+          ['efgh', 'abcd'])
+
+        # Hg issue 152: Request: Request: (?(DEFINE)...).
+        self.assertEqual(regex.search(r'(?(DEFINE)(?\d+)(?\w+))(?&quant) (?&item)',
+          '5 elephants')[0], '5 elephants')
+
+        self.assertEqual(regex.search(r'(?&routine)(?(DEFINE)(?.))', 'a').group('routine'), None)
+        self.assertEqual(regex.search(r'(?&routine)(?(DEFINE)(?.))', 'a').captures('routine'), ['a'])
+
+        # Hg issue 153: Request: (*SKIP).
+        self.assertEqual(regex.search(r'12(*FAIL)|3', '123')[0], '3')
+        self.assertEqual(regex.search(r'(?r)12(*FAIL)|3', '123')[0], '3')
+
+        self.assertEqual(regex.search(r'\d+(*PRUNE)\d', '123'), None)
+        self.assertEqual(regex.search(r'\d+(?=(*PRUNE))\d', '123')[0], '123')
+        self.assertEqual(regex.search(r'\d+(*PRUNE)bcd|[3d]', '123bcd')[0],
+          '123bcd')
+        self.assertEqual(regex.search(r'\d+(*PRUNE)bcd|[3d]', '123zzd')[0],
+          'd')
+        self.assertEqual(regex.search(r'\d+?(*PRUNE)bcd|[3d]', '123bcd')[0],
+          '3bcd')
+        self.assertEqual(regex.search(r'\d+?(*PRUNE)bcd|[3d]', '123zzd')[0],
+          'd')
+        self.assertEqual(regex.search(r'\d++(?<=3(*PRUNE))zzd|[4d]$',
+          '123zzd')[0], '123zzd')
+        self.assertEqual(regex.search(r'\d++(?<=3(*PRUNE))zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'\d++(?<=(*PRUNE)3)zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'\d++(?<=2(*PRUNE)3)zzd|[3d]$',
+          '124zzd')[0], 'd')
+
+        self.assertEqual(regex.search(r'(?r)\d(*PRUNE)\d+', '123'), None)
+        self.assertEqual(regex.search(r'(?r)\d(?<=(*PRUNE))\d+', '123')[0],
+          '123')
+        self.assertEqual(regex.search(r'(?r)\d+(*PRUNE)bcd|[3d]',
+          '123bcd')[0], '123bcd')
+        self.assertEqual(regex.search(r'(?r)\d+(*PRUNE)bcd|[3d]',
+          '123zzd')[0], 'd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=3(*PRUNE))zzd|[4d]$',
+          '123zzd')[0], '123zzd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=3(*PRUNE))zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=(*PRUNE)3)zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=2(*PRUNE)3)zzd|[3d]$',
+          '124zzd')[0], 'd')
+
+        self.assertEqual(regex.search(r'\d+(*SKIP)bcd|[3d]', '123bcd')[0],
+          '123bcd')
+        self.assertEqual(regex.search(r'\d+(*SKIP)bcd|[3d]', '123zzd')[0],
+          'd')
+        self.assertEqual(regex.search(r'\d+?(*SKIP)bcd|[3d]', '123bcd')[0],
+          '3bcd')
+        self.assertEqual(regex.search(r'\d+?(*SKIP)bcd|[3d]', '123zzd')[0],
+          'd')
+        self.assertEqual(regex.search(r'\d++(?<=3(*SKIP))zzd|[4d]$',
+          '123zzd')[0], '123zzd')
+        self.assertEqual(regex.search(r'\d++(?<=3(*SKIP))zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'\d++(?<=(*SKIP)3)zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'\d++(?<=2(*SKIP)3)zzd|[3d]$',
+          '124zzd')[0], 'd')
+
+        self.assertEqual(regex.search(r'(?r)\d+(*SKIP)bcd|[3d]', '123bcd')[0],
+          '123bcd')
+        self.assertEqual(regex.search(r'(?r)\d+(*SKIP)bcd|[3d]', '123zzd')[0],
+          'd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=3(*SKIP))zzd|[4d]$',
+          '123zzd')[0], '123zzd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=3(*SKIP))zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=(*SKIP)3)zzd|[4d]$',
+          '124zzd')[0], 'd')
+        self.assertEqual(regex.search(r'(?r)\d++(?<=2(*SKIP)3)zzd|[3d]$',
+          '124zzd')[0], 'd')
+
+        # Hg issue 154: Segmentation fault 11 when working with an atomic group
+        text = """June 30, December 31, 2013 2012
+some words follow:
+more words and numbers 1,234,567 9,876,542
+more words and numbers 1,234,567 9,876,542"""
+        self.assertEqual(len(regex.findall(r'(?2014|2013 ?2012)', text)), 1)
+
+        # Hg issue 156: regression on atomic grouping
+        self.assertEqual(regex.match('1(?>2)', '12').span(), (0, 2))
+
+        # Hg issue 157: regression: segfault on complex lookaround
+        self.assertEqual(regex.match(r'(?V1w)(?=(?=[^A-Z]*+[A-Z])(?=[^a-z]*+[a-z]))(?=\D*+\d)(?=\p{Alphanumeric}*+\P{Alphanumeric})\A(?s:.){8,255}+\Z',
+          'AAaa11!!')[0], 'AAaa11!!')
+
+        # Hg issue 158: Group issue with (?(DEFINE)...)
+        TEST_REGEX = regex.compile(r'''(?smx)
+(?(DEFINE)
+  (?
+   ^,[^,]+,
+   )
+)
+
+# Group 2 is defined on this line
+^,([^,]+),
+
+(?:(?!(?&subcat)[\r\n]+(?&subcat)).)+
+''')
+
+        TEST_DATA = '''
+,Cat 1,
+,Brand 1,
+some
+thing
+,Brand 2,
+other
+things
+,Cat 2,
+,Brand,
+Some
+thing
+'''
+
+        self.assertEqual([m.span(1, 2) for m in
+          TEST_REGEX.finditer(TEST_DATA)], [((-1, -1), (2, 7)), ((-1, -1), (54,
+          59))])
+
+        # Hg issue 161: Unexpected fuzzy match results
+        self.assertEqual(regex.search('(abcdefgh){e}',
+          '******abcdefghijklmnopqrtuvwxyz', regex.BESTMATCH).span(), (6, 14))
+        self.assertEqual(regex.search('(abcdefghi){e}',
+          '******abcdefghijklmnopqrtuvwxyz', regex.BESTMATCH).span(), (6, 15))
+
+        # Hg issue 163: allow lookarounds in conditionals.
+        self.assertEqual(regex.match(r'(?:(?=\d)\d+\b|\w+)', '123abc').span(),
+          (0, 6))
+        self.assertEqual(regex.match(r'(?(?=\d)\d+\b|\w+)', '123abc'), None)
+        self.assertEqual(regex.search(r'(?(?<=love\s)you|(?<=hate\s)her)',
+          "I love you").span(), (7, 10))
+        self.assertEqual(regex.findall(r'(?(?<=love\s)you|(?<=hate\s)her)',
+          "I love you but I don't hate her either"), ['you', 'her'])
+
+        # Hg issue 180: bug of POSIX matching.
+        self.assertEqual(regex.search(r'(?p)a*(.*?)', 'aaabbb').group(0, 1),
+          ('aaabbb', 'bbb'))
+        self.assertEqual(regex.search(r'(?p)a*(.*)', 'aaabbb').group(0, 1),
+          ('aaabbb', 'bbb'))
+        self.assertEqual(regex.sub(r'(?p)a*(.*?)', r'\1', 'aaabbb'), 'bbb')
+        self.assertEqual(regex.sub(r'(?p)a*(.*)', r'\1', 'aaabbb'), 'bbb')
+
+        # Hg issue 192: Named lists reverse matching doesn't work with
+        # IGNORECASE and V1
+        self.assertEqual(regex.match(r'(?irV0)\L', '21', kw=['1']).span(),
+          (1, 2))
+        self.assertEqual(regex.match(r'(?irV1)\L', '21', kw=['1']).span(),
+          (1, 2))
+
+        # Hg issue 193: Alternation and .REVERSE flag.
+        self.assertEqual(regex.search('a|b', '111a222').span(), (3, 4))
+        self.assertEqual(regex.search('(?r)a|b', '111a222').span(), (3, 4))
+
+        # Hg issue 194: .FULLCASE and Backreference
+        self.assertEqual(regex.search(r'(?if)<(CLI)><\1>',
+          '').span(), (0, 10))
+        self.assertEqual(regex.search(r'(?if)<(CLI)><\1>',
+          '').span(), (0, 10))
+        self.assertEqual(regex.search(r'(?ifr)<\1><(CLI)>',
+          '').span(), (0, 10))
+
+        # Hg issue 195: Pickle (or otherwise serial) the compiled regex
+        r = regex.compile(r'\L', options=['foo', 'bar'])
+        p = pickle.dumps(r)
+        r = pickle.loads(p)
+        self.assertEqual(r.match('foo').span(), (0, 3))
+
+        # Hg issue 196: Fuzzy matching on repeated regex not working as
+        # expected
+        self.assertEqual(regex.match('(x{6}){e<=1}', 'xxxxxx',
+          flags=regex.BESTMATCH).span(), (0, 6))
+        self.assertEqual(regex.match('(x{6}){e<=1}', 'xxxxx',
+          flags=regex.BESTMATCH).span(), (0, 5))
+        self.assertEqual(regex.match('(x{6}){e<=1}', 'x',
+          flags=regex.BESTMATCH), None)
+        self.assertEqual(regex.match('(?r)(x{6}){e<=1}', 'xxxxxx',
+          flags=regex.BESTMATCH).span(), (0, 6))
+        self.assertEqual(regex.match('(?r)(x{6}){e<=1}', 'xxxxx',
+          flags=regex.BESTMATCH).span(), (0, 5))
+        self.assertEqual(regex.match('(?r)(x{6}){e<=1}', 'x',
+          flags=regex.BESTMATCH), None)
+
+        # Hg issue 197: ValueError in regex.compile
+        self.assertRaises(regex.error, lambda:
+          regex.compile(b'00000\\0\\00\\^\50\\00\\U05000000'))
+
+        # Hg issue 198: ValueError in regex.compile
+        self.assertRaises(regex.error, lambda: regex.compile(b"{e', '22', aa=['121',
+          '22'])), True)
+        self.assertEqual(bool(regex.search(r'(?ri)\L', '22', aa=['121',
+          '22'])), True)
+        self.assertEqual(bool(regex.search(r'(?fi)\L', '22', aa=['121',
+          '22'])), True)
+        self.assertEqual(bool(regex.search(r'(?fri)\L', '22', aa=['121',
+          '22'])), True)
+
+        # Hg issue 208: Named list, (?ri) flags, Backreference
+        self.assertEqual(regex.search(r'(?r)\1dog..(?<=(\L))$', 'ccdogcc',
+          aa=['bcb', 'cc']). span(), (0, 7))
+        self.assertEqual(regex.search(r'(?ir)\1dog..(?<=(\L))$',
+          'ccdogcc', aa=['bcb', 'cc']). span(), (0, 7))
+
+        # Hg issue 210: Fuzzy matching and Backreference
+        self.assertEqual(regex.search(r'(2)(?:\1{5}){e<=1}',
+          '3222212').span(), (1, 7))
+        self.assertEqual(regex.search(r'(\d)(?:\1{5}){e<=1}',
+          '3222212').span(), (1, 7))
+
+        # Hg issue 211: Segmentation fault with recursive matches and atomic
+        # groups
+        self.assertEqual(regex.match(r'''\A(?P(?>\((?&whole)\)|[+\-]))\Z''',
+          '((-))').span(), (0, 5))
+        self.assertEqual(regex.match(r'''\A(?P(?>\((?&whole)\)|[+\-]))\Z''',
+          '((-)+)'), None)
+
+        # Hg issue 212: Unexpected matching difference with .*? between re and
+        # regex
+        self.assertEqual(regex.match(r"x.*? (.).*\1(.*)\1",
+          'x  |y| z|').span(), (0, 9))
+        self.assertEqual(regex.match(r"\.sr (.*?) (.)(.*)\2(.*)\2(.*)",
+          r'.sr  h |||').span(), (0, 35))
+
+        # Hg issue 213: Segmentation Fault
+        a = '"\\xF9\\x80\\xAEqdz\\x95L\\xA7\\x89[\\xFE \\x91)\\xF9]\\xDB\'\\x99\\x09=\\x00\\xFD\\x98\\x22\\xDD\\xF1\\xB6\\xC3 Z\\xB6gv\\xA5x\\x93P\\xE1r\\x14\\x8Cv\\x0C\\xC0w\\x15r\\xFFc%" '
+        py_regex_pattern = r'''(?P((?>(?"(?>\\.|[^\\"]+)+"|""|(?>'(?>\\.|[^\\']+)+')|''|(?>`(?>\\.|[^\\`]+)+`)|``)))) (?P((?>(?"(?>\\.|[^\\"]+)+"|""|(?>'(?>\\.|[^\\']+)+')|''|(?>`(?>\\.|[^\\`]+)+`)|``))))'''
+        self.assertEqual(bool(regex.search(py_regex_pattern, a)), False)
+
+        # Hg Issue 216: Invalid match when using negative lookbehind and pipe
+        self.assertEqual(bool(regex.match('foo(?<=foo)', 'foo')), True)
+        self.assertEqual(bool(regex.match('foo(?.*\!\w*\:.*)|(?P.*))',
+          '!')), False)
+
+        # Hg issue 220: Misbehavior of group capture with OR operand
+        self.assertEqual(regex.match(r'\w*(ea)\w*|\w*e(?!a)\w*',
+          'easier').groups(), ('ea', ))
+
+        # Hg issue 225: BESTMATCH in fuzzy match not working
+        self.assertEqual(regex.search('(^1234$){i,d}', '12234',
+          regex.BESTMATCH).span(), (0, 5))
+        self.assertEqual(regex.search('(^1234$){i,d}', '12234',
+          regex.BESTMATCH).fuzzy_counts, (0, 1, 0))
+
+        self.assertEqual(regex.search('(^1234$){s,i,d}', '12234',
+          regex.BESTMATCH).span(), (0, 5))
+        self.assertEqual(regex.search('(^1234$){s,i,d}', '12234',
+          regex.BESTMATCH).fuzzy_counts, (0, 1, 0))
+
+        # Hg issue 226: Error matching at start of string
+        self.assertEqual(regex.search('(^123$){s,i,d}', 'xxxxxxxx123',
+          regex.BESTMATCH).span(), (0, 11))
+        self.assertEqual(regex.search('(^123$){s,i,d}', 'xxxxxxxx123',
+          regex.BESTMATCH).fuzzy_counts, (0, 8, 0))
+
+        # Hg issue 227: Incorrect behavior for ? operator with UNICODE +
+        # IGNORECASE
+        self.assertEqual(regex.search(r'a?yz', 'xxxxyz', flags=regex.FULLCASE |
+          regex.IGNORECASE).span(), (4, 6))
+
+        # Hg issue 230: Is it a bug of (?(DEFINE)...)
+        self.assertEqual(regex.findall(r'(?:(?![a-d]).)+', 'abcdefgh'),
+          ['efgh'])
+        self.assertEqual(regex.findall(r'''(?(DEFINE)(?P(?:(?![a-d]).)))(?&mydef)+''',
+          'abcdefgh'), ['efgh'])
+
+        # Hg issue 238: Not fully re backward compatible
+        self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){1,3}',
+          '"Erm....yes. T..T...Thank you for that."'), [('Erm....', 'Erm',
+          '....'), ('T...', 'T', '...')])
+        self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){3}',
+          '"Erm....yes. T..T...Thank you for that."'), [])
+        self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){2}',
+          '"Erm....yes. T..T...Thank you for that."'), [('T...', 'T', '...')])
+        self.assertEqual(regex.findall(r'((\w{1,3})(\.{2,10})){1}',
+          '"Erm....yes. T..T...Thank you for that."'), [('Erm....', 'Erm',
+          '....'), ('T..', 'T', '..'), ('T...', 'T', '...')])
+
+        # Hg issue 247: Unexpected result with fuzzy matching and lookahead
+        # expression
+        self.assertEqual(regex.search(r'(?:ESTONIA(?!\w)){e<=1}',
+          'ESTONIAN WORKERS').group(), 'ESTONIAN')
+        self.assertEqual(regex.search(r'(?:ESTONIA(?=\W)){e<=1}',
+          'ESTONIAN WORKERS').group(), 'ESTONIAN')
+
+        self.assertEqual(regex.search(r'(?:(?.))(?&func)',
+          'abc').groups(), (None, ))
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?&func)',
+          'abc').groupdict(), {'func': None})
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?&func)',
+          'abc').capturesdict(), {'func': ['a']})
+
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?=(?&func))',
+          'abc').groups(), (None, ))
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?=(?&func))',
+          'abc').groupdict(), {'func': None})
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.))(?=(?&func))',
+          'abc').capturesdict(), {'func': ['a']})
+
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.)).(?<=(?&func))',
+          'abc').groups(), (None, ))
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.)).(?<=(?&func))',
+          'abc').groupdict(), {'func': None})
+        self.assertEqual(regex.search(r'(?(DEFINE)(?.)).(?<=(?&func))',
+          'abc').capturesdict(), {'func': ['a']})
+
+        # Hg issue 271: Comment logic different between Re and Regex
+        self.assertEqual(bool(regex.match(r'ab(?#comment\))cd', 'abcd')), True)
+
+        # Hg issue 276: Partial Matches yield incorrect matches and bounds
+        self.assertEqual(regex.search(r'[a-z]+ [a-z]*?:', 'foo bar',
+          partial=True).span(), (0, 7))
+        self.assertEqual(regex.search(r'(?r):[a-z]*? [a-z]+', 'foo bar',
+          partial=True).span(), (0, 7))
+
+        # Hg issue 291: Include Script Extensions as a supported Unicode property
+        self.assertEqual(bool(regex.match(r'(?u)\p{Script:Beng}',
+          '\u09EF')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{Script:Bengali}',
+          '\u09EF')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Bengali}',
+          '\u09EF')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Beng}',
+          '\u09EF')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Cakm}',
+          '\u09EF')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{Script_Extensions:Sylo}',
+          '\u09EF')), True)
+
+        # Hg issue #293: scx (Script Extensions) property currently matches
+        # incorrectly
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Latin}', 'P')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Ahom}', 'P')), False)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Common}', '4')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Caucasian_Albanian}', '4')),
+          False)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Arabic}', '\u062A')), True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Balinese}', '\u062A')),
+          False)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Devanagari}', '\u091C')),
+          True)
+        self.assertEqual(bool(regex.match(r'(?u)\p{scx:Batak}', '\u091C')), False)
+
+        # Hg issue 296: Group references are not taken into account when group is reporting the last match
+        self.assertEqual(regex.fullmatch('(?P.)*(?&x)', 'abc').captures('x'),
+          ['a', 'b', 'c'])
+        self.assertEqual(regex.fullmatch('(?P.)*(?&x)', 'abc').group('x'),
+          'b')
+
+        self.assertEqual(regex.fullmatch('(?P.)(?P.)(?P.)',
+          'abc').captures('x'), ['a', 'b', 'c'])
+        self.assertEqual(regex.fullmatch('(?P.)(?P.)(?P.)',
+          'abc').group('x'), 'c')
+
+        # Hg issue 299: Partial gives misleading results with "open ended" regexp
+        self.assertEqual(regex.match('(?:ab)*', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)*', 'abab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)*?', '', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)*+', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)*+', 'abab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)+', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)+', 'abab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)+?', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)++', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?:ab)++', 'abab', partial=True).partial,
+          False)
+
+        self.assertEqual(regex.match('(?r)(?:ab)*', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)*', 'abab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)*?', '', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)*+', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)*+', 'abab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)+', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)+', 'abab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)+?', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)++', 'ab', partial=True).partial,
+          False)
+        self.assertEqual(regex.match('(?r)(?:ab)++', 'abab', partial=True).partial,
+          False)
+
+        self.assertEqual(regex.match('a*', '', partial=True).partial, False)
+        self.assertEqual(regex.match('a*?', '', partial=True).partial, False)
+        self.assertEqual(regex.match('a*+', '', partial=True).partial, False)
+        self.assertEqual(regex.match('a+', '', partial=True).partial, True)
+        self.assertEqual(regex.match('a+?', '', partial=True).partial, True)
+        self.assertEqual(regex.match('a++', '', partial=True).partial, True)
+        self.assertEqual(regex.match('a+', 'a', partial=True).partial, False)
+        self.assertEqual(regex.match('a+?', 'a', partial=True).partial, False)
+        self.assertEqual(regex.match('a++', 'a', partial=True).partial, False)
+
+        self.assertEqual(regex.match('(?r)a*', '', partial=True).partial, False)
+        self.assertEqual(regex.match('(?r)a*?', '', partial=True).partial, False)
+        self.assertEqual(regex.match('(?r)a*+', '', partial=True).partial, False)
+        self.assertEqual(regex.match('(?r)a+', '', partial=True).partial, True)
+        self.assertEqual(regex.match('(?r)a+?', '', partial=True).partial, True)
+        self.assertEqual(regex.match('(?r)a++', '', partial=True).partial, True)
+        self.assertEqual(regex.match('(?r)a+', 'a', partial=True).partial, False)
+        self.assertEqual(regex.match('(?r)a+?', 'a', partial=True).partial, False)
+        self.assertEqual(regex.match('(?r)a++', 'a', partial=True).partial, False)
+
+        self.assertEqual(regex.match(r"(?:\s*\w+'*)+", 'whatever', partial=True).partial,
+          False)
+
+        # Hg issue 300: segmentation fault
+        pattern = ('(?PGGCGTCACACTTTGCTATGCCATAGCAT[AG]TTTATCCATAAGA'
+          'TTAGCGGATCCTACCTGACGCTTTTTATCGCAACTCTCTACTGTTTCTCCATAACAGAACATATTGA'
+          'CTATCCGGTATTACCCGGCATGACAGGAGTAAAA){e<=1}'
+          '(?P[ACGT]{1059}){e<=2}'
+          '(?PTAATCGTCTTGTTTGATACACAAGGGTCGCATCTGCGGCCCTTTTGCTTTTTTAAG'
+          'TTGTAAGGATATGCCATTCTAGA){e<=0}'
+          '(?P[ACGT]{18}){e<=0}'
+          '(?PAGATCGG[CT]AGAGCGTCGTGTAGGGAAAGAGTGTGG){e<=1}')
+
+        text = ('GCACGGCGTCACACTTTGCTATGCCATAGCATATTTATCCATAAGATTAGCGGATCCTACC'
+          'TGACGCTTTTTATCGCAACTCTCTACTGTTTCTCCATAACAGAACATATTGACTATCCGGTATTACC'
+          'CGGCATGACAGGAGTAAAAATGGCTATCGACGAAAACAAACAGAAAGCGTTGGCGGCAGCACTGGGC'
+          'CAGATTGAGAAACAATTTGGTAAAGGCTCCATCATGCGCCTGGGTGAAGACCGTTCCATGGATGTGG'
+          'AAACCATCTCTACCGGTTCGCTTTCACTGGATATCGCGCTTGGGGCAGGTGGTCTGCCGATGGGCCG'
+          'TATCGTCGAAATCTACGGACCGGAATCTTCCGGTAAAACCACGCTGACGCTGCAGGTGATCGCCGCA'
+          'GCGCAGCGTGAAGGTAAAACCTGTGCGTTTATCGATGCTGAACACGCGCTGGACCCAATCTACGCAC'
+          'GTAAACTGGGCGTCGATATCGACAACCTGCTGTGCTCCCAGCCGGACACCGGCGAGCAGGCACTGGA'
+          'AATCTGTGACGCCCTGGCGCGTTCTGGCGCAGTAGACGTTATCGTCGTTGACTCCGTGGCGGCACTG'
+          'ACGCCGAAAGCGGAAATCGAAGGCGAAATCGGCGACTCTCATATGGGCCTTGCGGCACGTATGATGA'
+          'GCCAGGCGATGCGTAAGCTGGCGGGTAACCTGAAGCAGTCCAACACGCTGCTGATCTTCATCAACCC'
+          'CATCCGTATGAAAATTGGTGTGATGTTCGGCAACCCGGAAACCACTTACCGGTGGTAACGCGCTGAA'
+          'ATTCTACGCCTCTGTTCGTCTCGACATCCGTTAAATCGGCGCGGTGAAAGAGGGCGAAAACGTGGTG'
+          'GGTAGCGAAACCCGCGTGAAAGTGGTGAAGAACAAAATCGCTGCGCCGTTTAAACAGGCTGAATTCC'
+          'AGATCCTCTACGGCGAAGGTATCAACTTCTACCCCGAACTGGTTGACCTGGGCGTAAAAGAGAAGCT'
+          'GATCGAGAAAGCAGGCGCGTGGTACAGCTACAAAGGTGAGAAGATCGGTCAGGGTAAAGCGAATGCG'
+          'ACTGCCTGGCTGAAATTTAACCCGGAAACCGCGAAAGAGATCGAGTGAAAAGTACGTGAGTTGCTGC'
+          'TGAGCAACCCGAACTCAACGCCGGATTTCTCTGTAGATGATAGCGAAGGCGTAGCAGAAACTAACGA'
+          'AGATTTTTAATCGTCTTGTTTGATACACAAGGGTCGCATCTGCGGCCCTTTTGCTTTTTTAAGTTGT'
+          'AAGGATATGCCATTCTAGACAGTTAACACACCAACAAAGATCGGTAGAGCGTCGTGTAGGGAAAGAG'
+          'TGTGGTACC')
+
+        m = regex.search(pattern, text, flags=regex.BESTMATCH)
+        self.assertEqual(m.fuzzy_counts, (0, 1, 0))
+        self.assertEqual(m.fuzzy_changes, ([], [1206], []))
+
+        # Hg issue 306: Fuzzy match parameters not respecting quantifier scope
+        self.assertEqual(regex.search(r'(?e)(dogf(((oo){e<1})|((00){e<1}))d){e<2}',
+          'dogfood').fuzzy_counts, (0, 0, 0))
+        self.assertEqual(regex.search(r'(?e)(dogf(((oo){e<1})|((00){e<1}))d){e<2}',
+          'dogfoot').fuzzy_counts, (1, 0, 0))
+
+        # Hg issue 312: \X not matching graphemes with zero-width-joins
+        self.assertEqual(regex.findall(r'\X',
+          '\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466'),
+          ['\U0001F468\u200D\U0001F469\u200D\U0001F467\u200D\U0001F466'])
+
+        # Hg issue 320: Abnormal performance
+        self.assertEqual(bool(regex.search(r'(?=a)a', 'a')), True)
+        self.assertEqual(bool(regex.search(r'(?!b)a', 'a')), True)
+
+        # Hg issue 327: .fullmatch() causes MemoryError
+        self.assertEqual(regex.fullmatch(r'((\d)*?)*?', '123').span(), (0, 3))
+
+        # Hg issue 329: Wrong group matches when question mark quantifier is used within a look behind
+        self.assertEqual(regex.search(r'''(?(DEFINE)(?(?THIS_SHOULD_NOT_MATCHx?)|(?right))).*(?<=(?&mydef).*)''',
+          'x right').capturesdict(), {'mydef': ['right'], 'wrong': [], 'right':
+          ['right']})
+
+        # Hg issue 338: specifying allowed characters when fuzzy-matching
+        self.assertEqual(bool(regex.match(r'(?:cat){e<=1:[u]}', 'cut')), True)
+        self.assertEqual(bool(regex.match(r'(?:cat){e<=1:u}', 'cut')), True)
+
+        # Hg issue 353: fuzzy changes negative indexes
+        self.assertEqual(regex.search(r'(?be)(AGTGTTCCCCGCGCCAGCGGGGATAAACCG){s<=5,i<=5,d<=5,s+i+d<=10}',
+          'TTCCCCGCGCCAGCGGGGATAAACCG').fuzzy_changes, ([], [], [0, 1, 3, 5]))
+
+        # Git issue 364: Contradictory values in fuzzy_counts and fuzzy_changes
+        self.assertEqual(regex.match(r'(?:bc){e}', 'c').fuzzy_counts, (1, 0,
+          1))
+        self.assertEqual(regex.match(r'(?:bc){e}', 'c').fuzzy_changes, ([0],
+          [], [1]))
+        self.assertEqual(regex.match(r'(?e)(?:bc){e}', 'c').fuzzy_counts, (0,
+          0, 1))
+        self.assertEqual(regex.match(r'(?e)(?:bc){e}', 'c').fuzzy_changes,
+          ([], [], [0]))
+        self.assertEqual(regex.match(r'(?b)(?:bc){e}', 'c').fuzzy_counts, (0,
+          0, 1))
+        self.assertEqual(regex.match(r'(?b)(?:bc){e}', 'c').fuzzy_changes,
+          ([], [], [0]))
+
+        # Git issue 370: Confusions about Fuzzy matching behavior
+        self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){e}',
+          '$ 10,112.111.12').fuzzy_counts, (6, 0, 5))
+        self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=1}',
+          '$ 10,112.111.12').fuzzy_counts, (1, 0, 0))
+        self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=1,i<=1,d<=1}',
+          '$ 10,112.111.12').fuzzy_counts, (1, 0, 0))
+        self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=3}',
+          '$ 10,1a2.111.12').fuzzy_counts, (2, 0, 0))
+        self.assertEqual(regex.match('(?e)(?:^(\\$ )?\\d{1,3}(,\\d{3})*(\\.\\d{2})$){s<=2}',
+          '$ 10,1a2.111.12').fuzzy_counts, (2, 0, 0))
+
+        self.assertEqual(regex.fullmatch(r'(?e)(?:0?,0(?:,0)?){s<=1,d<=1}',
+          ',0;0').fuzzy_counts, (1, 0, 0))
+        self.assertEqual(regex.fullmatch(r'(?e)(?:0??,0(?:,0)?){s<=1,d<=1}',
+          ',0;0').fuzzy_counts, (1, 0, 0))
+
+        # Git issue 371: Specifying character set when fuzzy-matching allows characters not in the set
+        self.assertEqual(regex.search(r"\b(?e)(?:\d{6,20}){i<=5:[\-\\\/]}\b",
+          "cat dog starting at 00:01132.000. hello world"), None)
+
+        # Git issue 385: Comments in expressions
+        self.assertEqual(bool(regex.compile('(?#)')), True)
+        self.assertEqual(bool(regex.compile('(?x)(?#)')), True)
+
+        # Git issue 394: Unexpected behaviour in fuzzy matching with limited character set with IGNORECASE flag
+        self.assertEqual(regex.findall(r'(\d+){i<=2:[ab]}', '123X4Y5'),
+          ['123', '4', '5'])
+        self.assertEqual(regex.findall(r'(?i)(\d+){i<=2:[ab]}', '123X4Y5'),
+          ['123', '4', '5'])
+
+        # Git issue 403: Fuzzy matching with wrong distance (unnecessary substitutions)
+        self.assertEqual(regex.match(r'^(test){e<=5}$', 'terstin',
+          flags=regex.B).fuzzy_counts, (0, 3, 0))
+
+        # Git issue 408: regex fails with a quantified backreference but succeeds with repeated backref
+        self.assertEqual(bool(regex.match(r"(?:(x*)\1\1\1)*x$", "x" * 5)), True)
+        self.assertEqual(bool(regex.match(r"(?:(x*)\1{3})*x$", "x" * 5)), True)
+
+        # Git issue 415: Fuzzy character restrictions don't apply to insertions at "right edge"
+        self.assertEqual(regex.match(r't(?:es){s<=1:\d}t', 'te5t').group(),
+          'te5t')
+        self.assertEqual(regex.match(r't(?:es){s<=1:\d}t', 'tezt'), None)
+        self.assertEqual(regex.match(r't(?:es){i<=1:\d}t', 'tes5t').group(),
+          'tes5t')
+        self.assertEqual(regex.match(r't(?:es){i<=1:\d}t', 'teszt'), None)
+        self.assertEqual(regex.match(r't(?:es){i<=1:\d}t',
+          'tes5t').fuzzy_changes, ([], [3], []))
+        self.assertEqual(regex.match(r't(es){i<=1,0.*)(?PCTTCC){e<=1}(?P([ACGT]){4,6})(?PCAATACCGACTCCTCACTGTGT){e<=2}(?P([ACGT]){0,6}$)'
+
+        m = regex.match(pattern, sequence, flags=regex.BESTMATCH)
+        self.assertEqual(m.span(), (0, 50))
+        self.assertEqual(m.groupdict(), {'insert': 'TTCAGACGTGTGCT', 'anchor': 'CTTCC', 'umi': 'GATCT', 'sid': 'CAATACCGACTCCTCACTGTGT', 'end': 'GTCT'})
+
+        m = regex.match(pattern, sequence, flags=regex.ENHANCEMATCH)
+        self.assertEqual(m.span(), (0, 50))
+        self.assertEqual(m.groupdict(), {'insert': 'TTCAGACGTGTGCT', 'anchor': 'CTTCC', 'umi': 'GATCT', 'sid': 'CAATACCGACTCCTCACTGTGT', 'end': 'GTCT'})
+
+        # Git issue 433: Disagreement between fuzzy_counts and fuzzy_changes
+        pattern = r'(?P.*)(?PAACACTGG){e<=1}(?P([AT][CG]){5}){e<=2}(?PGTAACCGAAG){e<=2}(?P([ACGT]){0,6}$)'
+
+        sequence = 'GGAAAACACTGGTCTCAGTCTCGTAACCGAAGTGGTCG'
+        m = regex.match(pattern, sequence, flags=regex.BESTMATCH)
+        self.assertEqual(m.fuzzy_counts, (0, 0, 0))
+        self.assertEqual(m.fuzzy_changes, ([], [], []))
+
+        sequence = 'GGAAAACACTGGTCTCAGTCTCGTCCCCGAAGTGGTCG'
+        m = regex.match(pattern, sequence, flags=regex.BESTMATCH)
+        self.assertEqual(m.fuzzy_counts, (2, 0, 0))
+        self.assertEqual(m.fuzzy_changes, ([24, 25], [], []))
+
+        # Git issue 439: Unmatched groups: sub vs subf
+        self.assertEqual(regex.sub(r'(test1)|(test2)', r'matched: \1\2', 'test1'), 'matched: test1')
+        self.assertEqual(regex.subf(r'(test1)|(test2)', r'matched: {1}{2}', 'test1'), 'matched: test1')
+        self.assertEqual(regex.search(r'(test1)|(test2)', 'matched: test1').expand(r'matched: \1\2'), 'matched: test1'),
+        self.assertEqual(regex.search(r'(test1)|(test2)', 'matched: test1').expandf(r'matched: {1}{2}'), 'matched: test1')
+
+        # Git issue 442: Fuzzy regex matching doesn't seem to test insertions correctly
+        self.assertEqual(regex.search(r"(?:\bha\b){i:[ ]}", "having"), None)
+        self.assertEqual(regex.search(r"(?:\bha\b){i:[ ]}", "having", flags=regex.I), None)
+
+        # Git issue 467: Scoped inline flags 'a', 'u' and 'L' affect global flags
+        self.assertEqual(regex.match(r'(?a:\w)\w', 'd\N{CYRILLIC SMALL LETTER ZHE}').span(), (0, 2))
+        self.assertEqual(regex.match(r'(?a:\w)(?u:\w)', 'd\N{CYRILLIC SMALL LETTER ZHE}').span(), (0, 2))
+
+        # Git issue 473: Emoji classified as letter
+        self.assertEqual(regex.match(r'^\p{LC}+$', '\N{SMILING CAT FACE WITH OPEN MOUTH}'), None)
+        self.assertEqual(regex.match(r'^\p{So}+$', '\N{SMILING CAT FACE WITH OPEN MOUTH}').span(), (0, 1))
+
+        # Git issue 474: regex has no equivalent to `re.Match.groups()` for captures
+        self.assertEqual(regex.match(r'(.)+', 'abc').allcaptures(), (['abc'], ['a', 'b', 'c']))
+        self.assertEqual(regex.match(r'(.)+', 'abc').allspans(), ([(0, 3)], [(0, 1), (1, 2), (2, 3)]))
+
+        # Git issue 477: \v for vertical spacing
+        self.assertEqual(bool(regex.fullmatch(r'\p{HorizSpace}+', '\t \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000')), True)
+        self.assertEqual(bool(regex.fullmatch(r'\p{VertSpace}+', '\n\v\f\r\x85\u2028\u2029')), True)
+
+        # Git issue 479: Segmentation fault when using conditional pattern
+        self.assertEqual(regex.match(r'(?(?<=A)|(?(?![^B])C|D))', 'A'), None)
+        self.assertEqual(regex.search(r'(?(?<=A)|(?(?![^B])C|D))', 'A').span(), (1, 1))
+
+        # Git issue 494: Backtracking failure matching regex ^a?(a?)b?c\1$ against string abca
+        self.assertEqual(regex.search(r"^a?(a?)b?c\1$", "abca").span(), (0, 4))
+
+        # Git issue 498: Conditional negative lookahead inside positive lookahead fails to match
+        self.assertEqual(regex.match(r'(?(?=a).|..)', 'ab').span(), (0, 1))
+        self.assertEqual(regex.match(r'(?(?=b).|..)', 'ab').span(), (0, 2))
+        self.assertEqual(regex.match(r'(?(?!a).|..)', 'ab').span(), (0, 2))
+        self.assertEqual(regex.match(r'(?(?!b).|..)', 'ab').span(), (0, 1))
+
+        # Git issue 525: segfault when fuzzy matching empty list
+        self.assertEqual(regex.match(r"(\L){e<=5}", "blah", foo=[]).span(), (0, 0))
+
+        # Git issue 527: `VERBOSE`/`X` flag breaks `\N` escapes
+        self.assertEqual(regex.compile(r'\N{LATIN SMALL LETTER A}').match('a').span(), (0, 1))
+        self.assertEqual(regex.compile(r'\N{LATIN SMALL LETTER A}', flags=regex.X).match('a').span(), (0, 1))
+
+        # Git issue 539: Bug: Partial matching fails on a simple example
+        self.assertEqual(regex.match(r"[^/]*b/ccc", "b/ccc", partial=True).span(), (0, 5))
+        self.assertEqual(regex.match(r"[^/]*b/ccc", "b/ccb", partial=True), None)
+        self.assertEqual(regex.match(r"[^/]*b/ccc", "b/cc", partial=True).span(), (0, 4))
+        self.assertEqual(regex.match(r"[^/]*b/xyz", "b/xy", partial=True).span(), (0, 4))
+        self.assertEqual(regex.match(r"[^/]*b/xyz", "b/yz", partial=True), None)
+
+        self.assertEqual(regex.match(r"(?i)[^/]*b/ccc", "b/ccc", partial=True).span(), (0, 5))
+        self.assertEqual(regex.match(r"(?i)[^/]*b/ccc", "b/ccb", partial=True), None)
+        self.assertEqual(regex.match(r"(?i)[^/]*b/ccc", "b/cc", partial=True).span(), (0, 4))
+        self.assertEqual(regex.match(r"(?i)[^/]*b/xyz", "b/xy", partial=True).span(), (0, 4))
+        self.assertEqual(regex.match(r"(?i)[^/]*b/xyz", "b/yz", partial=True), None)
+
+        # Git issue 546: Partial match not working in some instances with non-greedy capture
+        self.assertEqual(bool(regex.match(r'.*?', '<', partial=True)), True)
+        self.assertEqual(bool(regex.match(r'.*?', '.*?', '', partial=True)), True)
+        self.assertEqual(bool(regex.match(r'.*?', 'x', partial=True)), True)
+        self.assertEqual(bool(regex.match(r'.*?', 'xyz abc', partial=True)), True)
+        self.assertEqual(bool(regex.match(r'.*?', 'xyz abc foo', partial=True)), True)
+        self.assertEqual(bool(regex.match(r'.*?', 'xyz abc foo ', partial=True)), True)
+        self.assertEqual(bool(regex.match(r'.*?', 'xyz abc foo bar', partial=True)), True)
+
+        # Git issue 551:
+        self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]]', 'a')), True)
+        self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]-a]', 'a')), True)
+        self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]--a]', 'a')), False)
+        self.assertEqual(bool(regex.match(r'(?V1)[[a-z]--b]', 'a')), True)
+        self.assertEqual(bool(regex.match(r'(?V1)[[\s\S]--b]', 'a')), True)
+        self.assertEqual(bool(regex.match(r'(?V1)[a-[\s\S]]', 'a')), True)
+        self.assertEqual(bool(regex.match(r'(?V1)[a--[\s\S]]', 'a')), False)
+
+        self.assertEqual(regex.search(r'(?ifu)(H\N{LATIN SMALL LETTER O WITH DIAERESIS}gskolan?)[\\s\\S]*p',
+          'Yrkesh\N{LATIN SMALL LETTER O WITH DIAERESIS}gskola . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen . Studie\N{LATIN SMALL LETTER A WITH DIAERESIS}mnen'),
+          None)
+
+        # Git issue 572: Inline ASCII modifier doesn't seem to affect anything
+        self.assertEqual(bool(regex.match(r'\d', '\uFF19')), True)
+        self.assertEqual(bool(regex.match(r'(?a:\d)', '\uFF19')), False)
+
+        # Git issue 575: Issues with ASCII/Unicode modifiers
+        self.assertEqual(regex.findall('\\d', '9\uFF19'), ['9', '\uff19'])
+        self.assertEqual(regex.findall('(?u:\\d)', '9\uFF19'), ['9', '\uff19'])
+        self.assertEqual(regex.findall('(?a:\\d)', '9\uFF19'), ['9'])
+
+        self.assertEqual(regex.findall('\\d', '9\uFF19', flags=regex.U), ['9', '\uff19'])
+        self.assertEqual(regex.findall('(?u:\\d)', '9\uFF19', flags=regex.U), ['9', '\uff19'])
+        self.assertEqual(regex.findall('(?a:\\d)', '9\uFF19', flags=regex.U), ['9'])
+
+        self.assertEqual(regex.findall('\\d', '9\uFF19', flags=regex.A), ['9'])
+        self.assertEqual(regex.findall('(?u:\\d)', '9\uFF19', flags=regex.A), ['9', '\uff19'])
+        self.assertEqual(regex.findall('(?a:\\d)', '9\uFF19', flags=regex.A), ['9'])
+
+        self.assertEqual(len(regex.findall(r'\p{L}', ''.join(chr(c) for c in range(0x100)), flags=0)), 117)
+        self.assertEqual(len(regex.findall(r'\p{L}', ''.join(chr(c) for c in range(0x100)), flags=regex.A)), 52)
+        self.assertEqual(len(regex.findall(r'\p{L}', ''.join(chr(c) for c in range(0x100)), flags=regex.U)), 117)
+
+        self.assertEqual(len(regex.findall(r'(?a:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=0)), 52)
+        self.assertEqual(len(regex.findall(r'(?a:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.A)), 52)
+        self.assertEqual(len(regex.findall(r'(?a:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.U)), 52)
+
+        self.assertEqual(len(regex.findall(r'(?u:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=0)), 117)
+        self.assertEqual(len(regex.findall(r'(?u:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.A)), 117)
+        self.assertEqual(len(regex.findall(r'(?u:\p{L})', ''.join(chr(c) for c in range(0x100)), flags=regex.U)), 117)
+
+        # Git issue 580: Regression in v2025.7.31: \P{L} no longer matches in simple patterns
+        self.assertEqual(bool(regex.match(r"\A\P{L}?\p{L}", "hello,")), True)
+        self.assertEqual(bool(regex.fullmatch(r"\A\P{L}*(?P\p{L}+)\P{L}*\Z", "hello,")), True)
+
+        # Git issue 584: AttributeError: 'AnyAll' object has no attribute 'positive'
+        self.assertEqual(bool(regex.compile('(\\s|\\S)')), True)
+
+        # Git PR 585: Fix AttributeError: 'AnyAll' object has no attribute '_key'
+        self.assertEqual(bool(regex.compile('(?:[\\S\\s]|[A-D][M-Z])')), True)
+
+    def test_fuzzy_ext(self):
+        self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}', 'e')),
+          True)
+        self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', 'e')),
+          True)
+        self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', '-')),
+          False)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}', '-')),
+          False)
+
+        self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', 'ae')),
+          True)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}',
+          'ae')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?:a){e<=1:[a-z]}', 'a-')),
+          False)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)(?:a){e<=1:[a-z]}',
+          'a-')), False)
+
+        self.assertEqual(bool(regex.fullmatch(r'(?:ab){e<=1:[a-z]}', 'ae')),
+           True)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)(?:ab){e<=1:[a-z]}',
+           'ae')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?:ab){e<=1:[a-z]}', 'a-')),
+           False)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)(?:ab){e<=1:[a-z]}',
+           'a-')), False)
+
+        self.assertEqual(bool(regex.fullmatch(r'(a)\1{e<=1:[a-z]}', 'ae')),
+           True)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)\1{e<=1:[a-z]}(a)',
+           'ea')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(a)\1{e<=1:[a-z]}', 'a-')),
+           False)
+        self.assertEqual(bool(regex.fullmatch(r'(?r)\1{e<=1:[a-z]}(a)',
+           '-a')), False)
+
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          'ts')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          'st')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          'st')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          'ts')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          '-s')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          's-')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          's-')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(?:\N{LATIN SMALL LETTER SHARP S}){e<=1:[a-z]}',
+          '-s')), False)
+
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}',
+           'ssst')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}',
+           'ssts')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(\N{LATIN SMALL LETTER SHARP S})',
+           'stss')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(\N{LATIN SMALL LETTER SHARP S})',
+           'tsss')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}',
+           'ss-s')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}',
+           'sss-')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}',
+           '-s')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(\N{LATIN SMALL LETTER SHARP S})\1{e<=1:[a-z]}',
+           's-')), False)
+
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}',
+           '\N{LATIN SMALL LETTER SHARP S}ts')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}',
+           '\N{LATIN SMALL LETTER SHARP S}st')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(ss)',
+           'st\N{LATIN SMALL LETTER SHARP S}')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)\1{e<=1:[a-z]}(ss)',
+           'ts\N{LATIN SMALL LETTER SHARP S}')), True)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}',
+           '\N{LATIN SMALL LETTER SHARP S}-s')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?fiu)(ss)\1{e<=1:[a-z]}',
+           '\N{LATIN SMALL LETTER SHARP S}s-')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(ss)\1{e<=1:[a-z]}',
+           's-\N{LATIN SMALL LETTER SHARP S}')), False)
+        self.assertEqual(bool(regex.fullmatch(r'(?firu)(ss)\1{e<=1:[a-z]}',
+           '-s\N{LATIN SMALL LETTER SHARP S}')), False)
+
+    def test_subscripted_captures(self):
+        self.assertEqual(regex.match(r'(?P.)+',
+          'abc').expandf('{0} {0[0]} {0[-1]}'), 'abc abc abc')
+        self.assertEqual(regex.match(r'(?P.)+',
+          'abc').expandf('{1} {1[0]} {1[1]} {1[2]} {1[-1]} {1[-2]} {1[-3]}'),
+          'c a b c c b a')
+        self.assertEqual(regex.match(r'(?P.)+',
+          'abc').expandf('{x} {x[0]} {x[1]} {x[2]} {x[-1]} {x[-2]} {x[-3]}'),
+          'c a b c c b a')
+
+        self.assertEqual(regex.subf(r'(?P.)+', r'{0} {0[0]} {0[-1]}',
+          'abc'), 'abc abc abc')
+        self.assertEqual(regex.subf(r'(?P.)+',
+          '{1} {1[0]} {1[1]} {1[2]} {1[-1]} {1[-2]} {1[-3]}', 'abc'),
+          'c a b c c b a')
+        self.assertEqual(regex.subf(r'(?P.)+',
+          '{x} {x[0]} {x[1]} {x[2]} {x[-1]} {x[-2]} {x[-3]}', 'abc'),
+          'c a b c c b a')
+
+    def test_more_zerowidth(self):
+        if sys.version_info >= (3, 7, 0):
+            self.assertEqual(regex.split(r'\b|:+', 'a::bc'), ['', 'a', '', '',
+              'bc', ''])
+            self.assertEqual(regex.sub(r'\b|:+', '-', 'a::bc'), '-a---bc-')
+            self.assertEqual(regex.findall(r'\b|:+', 'a::bc'), ['', '', '::',
+              '', ''])
+            self.assertEqual([m.span() for m in regex.finditer(r'\b|:+',
+              'a::bc')], [(0, 0), (1, 1), (1, 3), (3, 3), (5, 5)])
+            self.assertEqual([m.span() for m in regex.finditer(r'(?m)^\s*?$',
+              'foo\n\n\nbar')], [(4, 4), (4, 5), (5, 5)])
+
+    def test_line_ending(self):
+      self.assertEqual(regex.findall(r'\R', '\r\n\n\x0B\f\r\x85\u2028\u2029'),
+        ['\r\n', '\n', '\x0B', '\f', '\r', '\x85', '\u2028', '\u2029'])
+      self.assertEqual(regex.findall(br'\R', b'\r\n\n\x0B\f\r\x85'), [b'\r\n',
+        b'\n', b'\x0B', b'\f', b'\r'])
+
+def test_main():
+    unittest.main(verbosity=2)
+
+if __name__ == "__main__":
+    test_main()
diff --git a/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/INSTALLER b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/METADATA b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..a9eb4a8c9e1edd621c611e86898601ea35f73dd3
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/METADATA
@@ -0,0 +1,136 @@
+Metadata-Version: 2.4
+Name: safetensors
+Version: 0.8.0rc0
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Education
+Classifier: Intended Audience :: Science/Research
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
+Classifier: Typing :: Typed
+Requires-Dist: safetensors[torch] ; extra == 'all'
+Requires-Dist: safetensors[numpy] ; extra == 'all'
+Requires-Dist: safetensors[pinned-tf] ; extra == 'all'
+Requires-Dist: safetensors[jax] ; extra == 'all'
+Requires-Dist: safetensors[paddlepaddle] ; extra == 'all'
+Requires-Dist: safetensors[convert] ; extra == 'all'
+Requires-Dist: safetensors[quality] ; extra == 'all'
+Requires-Dist: safetensors[testing] ; extra == 'all'
+Requires-Dist: safetensors[torch] ; extra == 'convert'
+Requires-Dist: huggingface-hub>=1.4 ; extra == 'convert'
+Requires-Dist: safetensors[all] ; extra == 'dev'
+Requires-Dist: safetensors[numpy] ; extra == 'jax'
+Requires-Dist: flax>=0.6.3 ; extra == 'jax'
+Requires-Dist: jax>=0.3.25 ; extra == 'jax'
+Requires-Dist: jaxlib>=0.3.25 ; extra == 'jax'
+Requires-Dist: mlx>=0.0.9 ; extra == 'mlx'
+Requires-Dist: numpy>=1.24.6 ; extra == 'numpy'
+Requires-Dist: safetensors[numpy] ; extra == 'paddlepaddle'
+Requires-Dist: paddlepaddle>=2.4.1 ; extra == 'paddlepaddle'
+Requires-Dist: safetensors[numpy] ; extra == 'pinned-tf'
+Requires-Dist: tensorflow==2.18.0 ; extra == 'pinned-tf'
+Requires-Dist: ruff ; extra == 'quality'
+Requires-Dist: safetensors[numpy] ; extra == 'tensorflow'
+Requires-Dist: tensorflow>=2.11.0 ; extra == 'tensorflow'
+Requires-Dist: safetensors[numpy] ; extra == 'testing'
+Requires-Dist: h5py>=3.7.0 ; extra == 'testing'
+Requires-Dist: setuptools-rust>=1.12.0 ; extra == 'testing'
+Requires-Dist: pytest>=9.0 ; extra == 'testing'
+Requires-Dist: pytest-benchmark>=5.2 ; extra == 'testing'
+Requires-Dist: hypothesis>=6.70.2 ; extra == 'testing'
+Requires-Dist: fsspec>=2024.6.0 ; extra == 'testing'
+Requires-Dist: s3fs>=2024.6.0 ; extra == 'testing'
+Requires-Dist: safetensors[numpy] ; extra == 'testingfree'
+Requires-Dist: setuptools-rust>=1.12.0 ; extra == 'testingfree'
+Requires-Dist: pytest>=9.0 ; extra == 'testingfree'
+Requires-Dist: pytest-benchmark>=5.2 ; extra == 'testingfree'
+Requires-Dist: hypothesis>=6.70.2 ; extra == 'testingfree'
+Requires-Dist: safetensors[numpy] ; extra == 'torch'
+Requires-Dist: torch>=2.4 ; extra == 'torch'
+Provides-Extra: all
+Provides-Extra: convert
+Provides-Extra: dev
+Provides-Extra: jax
+Provides-Extra: mlx
+Provides-Extra: numpy
+Provides-Extra: paddlepaddle
+Provides-Extra: pinned-tf
+Provides-Extra: quality
+Provides-Extra: tensorflow
+Provides-Extra: testing
+Provides-Extra: testingfree
+Provides-Extra: torch
+License-File: LICENSE
+Author-email: Nicolas Patry , Luc Georges , Daniël De Kok 
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
+Project-URL: Homepage, https://github.com/huggingface/safetensors
+Project-URL: Source, https://github.com/huggingface/safetensors
+
+## Installation
+
+```
+pip install safetensors
+```
+
+
+## Usage
+
+### Numpy
+
+```python
+from safetensors.numpy import save_file, load_file
+import numpy as np
+
+tensors = {
+   "a": np.zeros((2, 2)),
+   "b": np.zeros((2, 3), dtype=np.uint8)
+}
+
+save_file(tensors, "./model.safetensors")
+
+
+# Now loading
+loaded = load_file("./model.safetensors")
+```
+
+### Torch
+
+```python
+from safetensors.torch import save_file, load_file
+import torch
+
+tensors = {
+   "a": torch.zeros((2, 2)),
+   "b": torch.zeros((2, 3), dtype=torch.uint8)
+}
+
+save_file(tensors, "./model.safetensors")
+
+
+# Now loading
+loaded = load_file("./model.safetensors")
+```
+
+### Developing
+
+```
+# inside ./safetensors/bindings/python
+pip install .[dev]
+```
+Should be enough to install this library locally.
+
+### Testing
+
+```
+# inside ./safetensors/bindings/python
+pip install .[dev]
+pytest -sv tests/
+```
+
diff --git a/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/RECORD b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..cb55816dc163c524af86278079b9e01bad63c16c
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/RECORD
@@ -0,0 +1,23 @@
+safetensors-0.8.0rc0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+safetensors-0.8.0rc0.dist-info/METADATA,sha256=UmCgwPBFfnrUZDCa_LcLF9xvkxa4Yw311Qwv0gkkCVA,4330
+safetensors-0.8.0rc0.dist-info/RECORD,,
+safetensors-0.8.0rc0.dist-info/WHEEL,sha256=9kzpZO_gHswD-xgob51GZv4qleaMR4my9uTbzxbDDpM,145
+safetensors-0.8.0rc0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
+safetensors-0.8.0rc0.dist-info/sboms/safetensors-python.cyclonedx.json,sha256=pkrDGZwrrkdahmBarU8r9a8SCznBG-Dj9omxqvbfvkA,36647
+safetensors/__init__.py,sha256=ksmIKJuMIlqS8l5IetXXoet-Mm7sD-38a3Xm8E2F4y8,210
+safetensors/__init__.pyi,sha256=n_vTd8d6OEL-TADKRx41TuBcQFQ73zEG194TqyfFpgM,8339
+safetensors/__pycache__/__init__.cpython-311.pyc,,
+safetensors/__pycache__/flax.cpython-311.pyc,,
+safetensors/__pycache__/mlx.cpython-311.pyc,,
+safetensors/__pycache__/numpy.cpython-311.pyc,,
+safetensors/__pycache__/paddle.cpython-311.pyc,,
+safetensors/__pycache__/tensorflow.cpython-311.pyc,,
+safetensors/__pycache__/torch.cpython-311.pyc,,
+safetensors/_safetensors_rust.abi3.so,sha256=Vr1ClsZyAL3HgzymJlzmkDG9OyYgiCJeTs7cXGfDtSc,1195744
+safetensors/flax.py,sha256=T59elUqzVDyGYGdR78QzNEuwyAc8KrEO0EuLBSKOnUs,3853
+safetensors/mlx.py,sha256=IR51jRpcJq6epb0Agj8VsxI9xqBS6NjeAJnr-Ny0jJU,3850
+safetensors/numpy.py,sha256=21hf3cGirPGBLMfqjAS5Sd9l-dxzEq5OO-TH6-JZBSU,5343
+safetensors/paddle.py,sha256=25vtrX-IjxQrCyA0IDfqLLNPe13fZO9Is7TXMgbCQNI,9155
+safetensors/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+safetensors/tensorflow.py,sha256=AZ-O7-gM-JqTfjczZyCUAHm3Er-GSQnQWaFyY7mAIQc,3903
+safetensors/torch.py,sha256=ZIqBh5C_rOGNq1_CDeux_o1FepeCZ0kJDnPT7h86zJE,19886
diff --git a/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/WHEEL b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..ddd01cd8e5dd17aaa31b15f82c0be39721eaf6e1
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: maturin (1.13.1)
+Root-Is-Purelib: false
+Tag: cp310-abi3-manylinux_2_17_x86_64
+Tag: cp310-abi3-manylinux2014_x86_64
diff --git a/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/licenses/LICENSE b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/licenses/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/sboms/safetensors-python.cyclonedx.json b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/sboms/safetensors-python.cyclonedx.json
new file mode 100644
index 0000000000000000000000000000000000000000..1b10641fbf98978bceb8851087f62b530b67dfcd
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors-0.8.0rc0.dist-info/sboms/safetensors-python.cyclonedx.json
@@ -0,0 +1,1182 @@
+{
+  "bomFormat": "CycloneDX",
+  "specVersion": "1.5",
+  "version": 1,
+  "serialNumber": "urn:uuid:05c2a05f-7ce4-4b2f-a10a-e84f41b71d5d",
+  "metadata": {
+    "timestamp": "2026-04-14T14:28:32.949235810Z",
+    "tools": [
+      {
+        "vendor": "CycloneDX",
+        "name": "cargo-cyclonedx",
+        "version": "0.5.9"
+      }
+    ],
+    "component": {
+      "type": "library",
+      "bom-ref": "path+file:///home/runner/work/safetensors/safetensors/bindings/python#safetensors-python@0.8.0-rc.0",
+      "name": "safetensors-python",
+      "version": "0.8.0-rc.0",
+      "scope": "required",
+      "purl": "pkg:cargo/safetensors-python@0.8.0-rc.0?download_url=file://.",
+      "components": [
+        {
+          "type": "library",
+          "bom-ref": "path+file:///home/runner/work/safetensors/safetensors/bindings/python#safetensors-python@0.8.0-rc.0 bin-target-0",
+          "name": "safetensors_rust",
+          "version": "0.8.0-rc.0",
+          "purl": "pkg:cargo/safetensors-python@0.8.0-rc.0?download_url=file://.#src/lib.rs"
+        }
+      ]
+    },
+    "properties": [
+      {
+        "name": "cdx:rustc:sbom:target:all_targets",
+        "value": "true"
+      }
+    ]
+  },
+  "components": [
+    {
+      "type": "library",
+      "bom-ref": "path+file:///home/runner/work/safetensors/safetensors/safetensors#0.8.0-rc.0",
+      "name": "safetensors",
+      "version": "0.8.0-rc.0",
+      "description": "Provides functions to read and write safetensors which aim to be safer than their PyTorch counterpart. The format is 8 bytes which is an unsized int, being the size of a JSON header, the JSON header refers the `dtype` the `shape` and `data_offsets` which are the offsets for the values in the rest of the file. ",
+      "scope": "required",
+      "licenses": [
+        {
+          "expression": "Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/safetensors@0.8.0-rc.0?download_url=file:///home/runner/work/safetensors/safetensors/safetensors",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/safetensors/"
+        },
+        {
+          "type": "website",
+          "url": "https://github.com/huggingface/safetensors"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/huggingface/safetensors"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21",
+      "author": "Zakarum ",
+      "name": "allocator-api2",
+      "version": "0.2.21",
+      "description": "Mirror of Rust's allocator API",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/allocator-api2@0.2.21",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/allocator-api2"
+        },
+        {
+          "type": "website",
+          "url": "https://github.com/zakarumych/allocator-api2"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/zakarumych/allocator-api2"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0",
+      "author": "Josh Stone ",
+      "name": "autocfg",
+      "version": "1.5.0",
+      "description": "Automatic cfg for Rust compiler features",
+      "scope": "excluded",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "Apache-2.0 OR MIT"
+        }
+      ],
+      "purl": "pkg:cargo/autocfg@1.5.0",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/autocfg/"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/cuviper/autocfg"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2",
+      "name": "equivalent",
+      "version": "1.0.2",
+      "description": "Traits for key comparison in maps.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "Apache-2.0 OR MIT"
+        }
+      ],
+      "purl": "pkg:cargo/equivalent@1.0.2",
+      "externalReferences": [
+        {
+          "type": "vcs",
+          "url": "https://github.com/indexmap-rs/equivalent"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0",
+      "author": "Orson Peters ",
+      "name": "foldhash",
+      "version": "0.2.0",
+      "description": "A fast, non-cryptographic, minimally DoS-resistant hashing algorithm.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "Zlib"
+        }
+      ],
+      "purl": "pkg:cargo/foldhash@0.2.0",
+      "externalReferences": [
+        {
+          "type": "vcs",
+          "url": "https://github.com/orlp/foldhash"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1",
+      "author": "Amanieu d'Antras ",
+      "name": "hashbrown",
+      "version": "0.16.1",
+      "description": "A Rust port of Google's SwissTable hash map",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/hashbrown@0.16.1",
+      "externalReferences": [
+        {
+          "type": "vcs",
+          "url": "https://github.com/rust-lang/hashbrown"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0",
+      "name": "heck",
+      "version": "0.5.0",
+      "description": "heck is a case conversion library.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/heck@0.5.0",
+      "externalReferences": [
+        {
+          "type": "vcs",
+          "url": "https://github.com/withoutboats/heck"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7",
+      "author": "David Tolnay ",
+      "name": "indoc",
+      "version": "2.0.7",
+      "description": "Indented document literals",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/indoc@2.0.7",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/indoc"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/indoc"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18",
+      "author": "David Tolnay ",
+      "name": "itoa",
+      "version": "1.0.18",
+      "description": "Fast integer primitive to string conversion",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/itoa@1.0.18",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/itoa"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/itoa"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185",
+      "author": "The Rust Project Developers",
+      "name": "libc",
+      "version": "0.2.185",
+      "description": "Raw FFI bindings to platform libraries like libc.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/libc@0.2.185",
+      "externalReferences": [
+        {
+          "type": "vcs",
+          "url": "https://github.com/rust-lang/libc"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0",
+      "author": "Andrew Gallant , bluss",
+      "name": "memchr",
+      "version": "2.8.0",
+      "description": "Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for 1, 2 or 3 byte search and single substring search. ",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "Unlicense OR MIT"
+        }
+      ],
+      "purl": "pkg:cargo/memchr@2.8.0",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/memchr/"
+        },
+        {
+          "type": "website",
+          "url": "https://github.com/BurntSushi/memchr"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/BurntSushi/memchr"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memmap2@0.9.10",
+      "author": "Dan Burkert , Yevhenii Reizner , The Contributors",
+      "name": "memmap2",
+      "version": "0.9.10",
+      "description": "Cross-platform Rust API for memory-mapped file IO",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/memmap2@0.9.10",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/memmap2"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/RazrFalcon/memmap2-rs"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1",
+      "author": "Gilad Naaman ",
+      "name": "memoffset",
+      "version": "0.9.1",
+      "description": "offset_of functionality for Rust structs.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT"
+        }
+      ],
+      "purl": "pkg:cargo/memoffset@0.9.1",
+      "externalReferences": [
+        {
+          "type": "vcs",
+          "url": "https://github.com/Gilnaa/memoffset"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4",
+      "author": "Aleksey Kladov ",
+      "name": "once_cell",
+      "version": "1.21.4",
+      "description": "Single assignment cells and lazy values.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/once_cell@1.21.4",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/once_cell"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/matklad/once_cell"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106",
+      "author": "David Tolnay , Alex Crichton ",
+      "name": "proc-macro2",
+      "version": "1.0.106",
+      "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/proc-macro2@1.0.106",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/proc-macro2"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/proc-macro2"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.25.1",
+      "author": "PyO3 Project and Contributors ",
+      "name": "pyo3-build-config",
+      "version": "0.25.1",
+      "description": "Build configuration for the PyO3 ecosystem",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "458eb0c55e7ece017adeba38f2248ff3ac615e53660d7c71a238d7d2a01c7598"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/pyo3-build-config@0.25.1",
+      "externalReferences": [
+        {
+          "type": "website",
+          "url": "https://github.com/pyo3/pyo3"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/pyo3/pyo3"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.25.1",
+      "author": "PyO3 Project and Contributors ",
+      "name": "pyo3-ffi",
+      "version": "0.25.1",
+      "description": "Python-API bindings for the PyO3 ecosystem",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "7114fe5457c61b276ab77c5055f206295b812608083644a5c5b2640c3102565c"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/pyo3-ffi@0.25.1",
+      "externalReferences": [
+        {
+          "type": "website",
+          "url": "https://github.com/pyo3/pyo3"
+        },
+        {
+          "type": "other",
+          "url": "python"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/pyo3/pyo3"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.25.1",
+      "author": "PyO3 Project and Contributors ",
+      "name": "pyo3-macros-backend",
+      "version": "0.25.1",
+      "description": "Code generation for PyO3 package",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "4109984c22491085343c05b0dbc54ddc405c3cf7b4374fc533f5c3313a572ccc"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/pyo3-macros-backend@0.25.1",
+      "externalReferences": [
+        {
+          "type": "website",
+          "url": "https://github.com/pyo3/pyo3"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/pyo3/pyo3"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.25.1",
+      "author": "PyO3 Project and Contributors ",
+      "name": "pyo3-macros",
+      "version": "0.25.1",
+      "description": "Proc macros for PyO3 package",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "a8725c0a622b374d6cb051d11a0983786448f7785336139c3c94f5aa6bef7e50"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/pyo3-macros@0.25.1",
+      "externalReferences": [
+        {
+          "type": "website",
+          "url": "https://github.com/pyo3/pyo3"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/pyo3/pyo3"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.25.1",
+      "author": "PyO3 Project and Contributors ",
+      "name": "pyo3",
+      "version": "0.25.1",
+      "description": "Bindings to Python interpreter",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "8970a78afe0628a3e3430376fc5fd76b6b45c4d43360ffd6cdd40bdde72b682a"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/pyo3@0.25.1",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/crate/pyo3/"
+        },
+        {
+          "type": "website",
+          "url": "https://github.com/pyo3/pyo3"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/pyo3/pyo3"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45",
+      "author": "David Tolnay ",
+      "name": "quote",
+      "version": "1.0.45",
+      "description": "Quasi-quoting macro quote!(...)",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/quote@1.0.45",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/quote/"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/quote"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22",
+      "author": "David Tolnay ",
+      "name": "rustversion",
+      "version": "1.0.22",
+      "description": "Conditional compilation according to rustc compiler version",
+      "scope": "excluded",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/rustversion@1.0.22",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/rustversion"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/rustversion"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228",
+      "author": "Erick Tryzelaar , David Tolnay ",
+      "name": "serde",
+      "version": "1.0.228",
+      "description": "A generic serialization/deserialization framework",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/serde@1.0.228",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/serde"
+        },
+        {
+          "type": "website",
+          "url": "https://serde.rs"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/serde-rs/serde"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228",
+      "author": "Erick Tryzelaar , David Tolnay ",
+      "name": "serde_core",
+      "version": "1.0.228",
+      "description": "Serde traits only, with no support for derive -- use the `serde` crate instead",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/serde_core@1.0.228",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/serde_core"
+        },
+        {
+          "type": "website",
+          "url": "https://serde.rs"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/serde-rs/serde"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228",
+      "author": "Erick Tryzelaar , David Tolnay ",
+      "name": "serde_derive",
+      "version": "1.0.228",
+      "description": "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/serde_derive@1.0.228",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://serde.rs/derive.html"
+        },
+        {
+          "type": "website",
+          "url": "https://serde.rs"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/serde-rs/serde"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149",
+      "author": "Erick Tryzelaar , David Tolnay ",
+      "name": "serde_json",
+      "version": "1.0.149",
+      "description": "A JSON serialization file format",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/serde_json@1.0.149",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/serde_json"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/serde-rs/json"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117",
+      "author": "David Tolnay ",
+      "name": "syn",
+      "version": "2.0.117",
+      "description": "Parser for Rust source code",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/syn@2.0.117",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/syn"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/syn"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5",
+      "author": "Dan Gohman ",
+      "name": "target-lexicon",
+      "version": "0.13.5",
+      "description": "LLVM target triple types",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "Apache-2.0 WITH LLVM-exception"
+        }
+      ],
+      "purl": "pkg:cargo/target-lexicon@0.13.5",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/target-lexicon/"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/bytecodealliance/target-lexicon"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24",
+      "author": "David Tolnay ",
+      "name": "unicode-ident",
+      "version": "1.0.24",
+      "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "(MIT OR Apache-2.0) AND Unicode-3.0"
+        }
+      ],
+      "purl": "pkg:cargo/unicode-ident@1.0.24",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/unicode-ident"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/unicode-ident"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unindent@0.2.4",
+      "author": "David Tolnay ",
+      "name": "unindent",
+      "version": "0.2.4",
+      "description": "Remove a column of leading whitespace from a string",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT OR Apache-2.0"
+        }
+      ],
+      "purl": "pkg:cargo/unindent@0.2.4",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/unindent"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/indoc"
+        }
+      ]
+    },
+    {
+      "type": "library",
+      "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21",
+      "author": "David Tolnay ",
+      "name": "zmij",
+      "version": "1.0.21",
+      "description": "A double-to-string conversion algorithm based on Schubfach and yy",
+      "scope": "required",
+      "hashes": [
+        {
+          "alg": "SHA-256",
+          "content": "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+        }
+      ],
+      "licenses": [
+        {
+          "expression": "MIT"
+        }
+      ],
+      "purl": "pkg:cargo/zmij@1.0.21",
+      "externalReferences": [
+        {
+          "type": "documentation",
+          "url": "https://docs.rs/zmij"
+        },
+        {
+          "type": "vcs",
+          "url": "https://github.com/dtolnay/zmij"
+        }
+      ]
+    }
+  ],
+  "dependencies": [
+    {
+      "ref": "path+file:///home/runner/work/safetensors/safetensors/bindings/python#safetensors-python@0.8.0-rc.0",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#memmap2@0.9.10",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.25.1",
+        "path+file:///home/runner/work/safetensors/safetensors/safetensors#0.8.0-rc.0",
+        "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149"
+      ]
+    },
+    {
+      "ref": "path+file:///home/runner/work/safetensors/safetensors/safetensors#0.8.0-rc.0",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1",
+        "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228",
+        "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21",
+        "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2",
+        "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0",
+        "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#memmap2@0.9.10",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.25.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4",
+        "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.25.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.25.1"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.25.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0",
+        "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.25.1",
+        "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45",
+        "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.25.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.25.1",
+        "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45",
+        "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.25.1",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7",
+        "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.185",
+        "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1",
+        "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.25.1",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.25.1",
+        "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.25.1",
+        "registry+https://github.com/rust-lang/crates.io-index#unindent@0.2.4"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228",
+        "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106",
+        "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45",
+        "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18",
+        "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0",
+        "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228",
+        "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117",
+      "dependsOn": [
+        "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106",
+        "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45",
+        "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24"
+      ]
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#unindent@0.2.4"
+    },
+    {
+      "ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21"
+    }
+  ]
+}
\ No newline at end of file
diff --git a/lib/python3.11/site-packages/safetensors/__init__.py b/lib/python3.11/site-packages/safetensors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..284c63303317e6648103c4cf03f3db407cb8d527
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/__init__.py
@@ -0,0 +1,11 @@
+# Re-export this
+from ._safetensors_rust import (  # noqa: F401
+    SafetensorError,
+    TensorSpec,
+    __version__,
+    deserialize,
+    safe_open,
+    _safe_open_handle,
+    serialize,
+    serialize_file,
+)
diff --git a/lib/python3.11/site-packages/safetensors/__init__.pyi b/lib/python3.11/site-packages/safetensors/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8c7af9ec06d3cc77f4a5f062873af7c1ce5cfb7c
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/__init__.pyi
@@ -0,0 +1,275 @@
+# Generated content — partially. The structure and docstrings are produced by
+# `python stub.py`. The following are hand-edited additions that must be
+# re-applied after each regeneration:
+#   - module-level imports (`os`, `typing`)
+#   - `__version__: str`
+#   - type annotations on `TensorSpec` / `serialize` / `serialize_file`
+#
+# TODO: once we upgrade pyo3 to >= 0.28, replace `stub.py` with a dedicated
+# `tools/stub-gen` binary using `pyo3-introspection`,
+# mirroring how `huggingface/tokenizers` does it (see PR #1928).
+# That generator emits typed stubs directly from Rust
+# signatures — no hand-editing, no drift.
+import os
+from typing import Dict, List, Optional, Sequence, Union
+
+__version__: str
+
+@staticmethod
+def deserialize(bytes):
+    """
+    Opens a safetensors lazily and returns tensors as asked
+
+    Args:
+        data (`bytes`):
+            The byte content of a file
+
+    Returns:
+        (`List[str, Dict[str, Dict[str, any]]]`):
+            The deserialized content is like:
+                [("tensor_name", {"shape": [2, 3], "dtype": "F32", "data": b"\0\0.." }), (...)]
+    """
+    pass
+
+@staticmethod
+def serialize(
+    tensor_dict: Dict[str, TensorSpec],
+    metadata: Optional[Dict[str, str]] = None,
+) -> bytes:
+    """
+    Serializes raw data.
+
+    NOTE: the caller is required to ensure any pointer passed via `TensorSpec.data_ptr` is valid
+    and stays alive for the duration of the serialization.
+    We will remove the need for the caller to hold references themselves when we drop support for
+    python versions prior to 3.11 where the `PyBuffer` API is available.
+    Creating a `PyBuffer` will enable us to hold a reference to each passed in data array,
+    increasing its ref count preventing the gc from collecting it while we serialize.
+
+    Args:
+        tensor_dict (`Dict[str, TensorSpec]`):
+            Mapping of tensor name to its `TensorSpec`, e.g.:
+                {"tensor_name": TensorSpec(dtype="float32", shape=[2, 3], data_ptr=1234, data_len=24)}
+        metadata (`Dict[str, str]`, *optional*):
+            The optional purely text annotations
+
+    Returns:
+        (`bytes`):
+            The serialized content.
+    """
+    pass
+
+@staticmethod
+def serialize_file(
+    tensor_dict: Dict[str, TensorSpec],
+    filename: Union[str, "os.PathLike[str]"],
+    metadata: Optional[Dict[str, str]] = None,
+) -> None:
+    """
+    Serializes raw data into file.
+
+    NOTE: the caller is required to ensure any pointer passed via `TensorSpec.data_ptr` is valid
+    and stays alive for the duration of the serialization.
+    We will remove the need for the caller to hold references themselves when we drop support for
+    python versions prior to 3.11 where the `PyBuffer` API is available.
+    Creating a `PyBuffer` will enable us to hold a reference to each passed in data array,
+    increasing its ref count preventing the gc from collecting it while we serialize.
+
+    Args:
+        tensor_dict (`Dict[str, TensorSpec]`):
+            Mapping of tensor name to its `TensorSpec`, e.g.:
+                {"tensor_name": TensorSpec(dtype="float32", shape=[2, 3], data_ptr=1234, data_len=24)}
+        filename (`str`, or `os.PathLike`):
+            The name of the file to write into.
+        metadata (`Dict[str, str]`, *optional*):
+            The optional purely text annotations
+
+    Returns:
+        (`NoneType`):
+            On success return None
+    """
+    pass
+
+class TensorSpec:
+    """
+    Describes a single tensor passed to [`serialize`] / [`serialize_file`].
+
+    Constructed from Python as `TensorSpec(dtype, shape, data_ptr, data_len)`.
+    The dtype string is validated at construction; an unknown dtype raises
+    immediately rather than failing further inside the serializer.
+
+    `shape` is the logical (header) shape — the number of elements along each
+    axis as recorded in the safetensors header. For packed dtypes like
+    `float4_e2m1fn_x2` (two F4 values per byte), callers may pass the storage
+    shape reported by their framework (e.g. `torch.Size`); the constructor
+    transparently doubles the last dimension so `spec.shape` always reflects
+    the logical element count.
+
+    SAFETY: `data_ptr` is a raw memory address. The caller must ensure the
+    underlying buffer stays alive for the duration of every `serialize` /
+    `serialize_file` call that consumes this spec.
+    """
+    def __init__(
+        self,
+        *,
+        dtype: str,
+        shape: Sequence[int],
+        data_ptr: int,
+        data_len: int,
+    ) -> None:
+        pass
+
+    @property
+    def data_len(self) -> int:
+        """
+        The length of the tensor's buffer in bytes.
+        """
+        pass
+
+    @property
+    def data_ptr(self) -> int:
+        """
+        The raw memory address of the tensor's contiguous buffer.
+        """
+        pass
+
+    @property
+    def dtype(self) -> str:
+        """
+        The tensor's dtype as its safetensors format code (e.g. `"F32"`, `"BF16"`,
+        `"F8_E5M2FNUZ"`). This is the identifier written into the safetensors
+        header, not the Python constructor-style name (`"float32"` etc.).
+        """
+        pass
+
+    @property
+    def shape(self) -> List[int]:
+        """
+        The tensor's logical shape — the element-count shape recorded in the
+        safetensors header. For packed dtypes like `float4_e2m1fn_x2`, this is
+        the last-dim-doubled version of whatever was passed to the constructor.
+        """
+        pass
+
+class safe_open:
+    """
+    Opens a safetensors lazily and returns tensors as asked
+
+    Args:
+        filename (`str`, or `os.PathLike`):
+            The filename to open
+
+        framework (`str`):
+            The framework you want you tensors in. Supported values:
+            `pt`, `tf`, `flax`, `numpy`.
+
+        device (`str`, defaults to `"cpu"`):
+            The device on which you want the tensors.
+    """
+    def __init__(self, filename, framework, device=...):
+        pass
+
+    def __enter__(self):
+        """
+        Start the context manager
+        """
+        pass
+
+    def __exit__(self, _exc_type, _exc_value, _traceback):
+        """
+        Exits the context manager
+        """
+        pass
+
+    def get_slice(self, name):
+        """
+        Returns a full slice view object
+
+        Args:
+            name (`str`):
+                The name of the tensor you want
+
+        Returns:
+            (`PySafeSlice`):
+                A dummy object you can slice into to get a real tensor
+        Example:
+        ```python
+        from safetensors import safe_open
+
+        with safe_open("model.safetensors", framework="pt", device=0) as f:
+            tensor_part = f.get_slice("embedding")[:, ::8]
+
+        ```
+        """
+        pass
+
+    def get_tensor(self, name):
+        """
+        Returns a full tensor
+
+        Args:
+            name (`str`):
+                The name of the tensor you want
+
+        Returns:
+            (`Tensor`):
+                The tensor in the framework you opened the file for.
+
+        Example:
+        ```python
+        from safetensors import safe_open
+
+        with safe_open("model.safetensors", framework="pt", device=0) as f:
+            tensor = f.get_tensor("embedding")
+
+        ```
+        """
+        pass
+
+    def keys(self):
+        """
+        Returns the names of the tensors in the file.
+
+        Returns:
+            (`List[str]`):
+                The name of the tensors contained in that file
+        """
+        pass
+
+    def metadata(self):
+        """
+        Return the special non tensor information in the header
+
+        Returns:
+            (`Dict[str, str]`):
+                The freeform metadata.
+        """
+        pass
+
+    def offset_keys(self):
+        """
+        Returns the names of the tensors in the file, ordered by offset.
+
+        Returns:
+            (`List[str]`):
+                The name of the tensors contained in that file
+        """
+        pass
+
+class SafetensorError(Exception):
+    """
+    Custom Python Exception for Safetensor errors.
+    """
+    def add_note(self, object, /):
+        """
+        Exception.add_note(note) --
+            add a note to the exception
+        """
+        pass
+
+    def with_traceback(self, object, /):
+        """
+        Exception.with_traceback(tb) --
+            set self.__traceback__ to tb and return self.
+        """
+        pass
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0204d30fdde936ce8a38c1b066c09889a280119
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/__init__.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/flax.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/flax.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6afb33562e0ad26a46cbbed2b56cdb246abb5f17
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/flax.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/mlx.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/mlx.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eeb83449cd61c636181c41298e74949fdcab33a4
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/mlx.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/numpy.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/numpy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c33085d1f0a0c403ed96217263d1dc0bbda954d3
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/numpy.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/paddle.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/paddle.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1d61f4901ba06898dee3521d913ca0927359a7e
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/paddle.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/tensorflow.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/tensorflow.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a41bb0d09a4c7694868ae2aee8440814eb9469cc
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/tensorflow.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/__pycache__/torch.cpython-311.pyc b/lib/python3.11/site-packages/safetensors/__pycache__/torch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c181e9916ca23f3e67faead1801a0c06de78c49
Binary files /dev/null and b/lib/python3.11/site-packages/safetensors/__pycache__/torch.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/safetensors/flax.py b/lib/python3.11/site-packages/safetensors/flax.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6471507dc44bff6c4a75e5b75a24241a693dad5
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/flax.py
@@ -0,0 +1,138 @@
+import os
+from typing import Dict, Optional, Union
+
+import numpy as np
+
+import jax.numpy as jnp
+from jax import Array
+from safetensors import numpy, safe_open
+
+
+def save(tensors: Dict[str, Array], metadata: Optional[Dict[str, str]] = None) -> bytes:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, Array]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `bytes`: The raw bytes representing the format
+
+    Example:
+
+    ```python
+    from safetensors.flax import save
+    from jax import numpy as jnp
+
+    tensors = {"embedding": jnp.zeros((512, 1024)), "attention": jnp.zeros((256, 256))}
+    byte_data = save(tensors)
+    ```
+    """
+    np_tensors = _jnp2np(tensors)
+    return numpy.save(np_tensors, metadata=metadata)
+
+
+def save_file(
+    tensors: Dict[str, Array],
+    filename: Union[str, os.PathLike],
+    metadata: Optional[Dict[str, str]] = None,
+) -> None:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, Array]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        filename (`str`, or `os.PathLike`)):
+            The filename we're saving into.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `None`
+
+    Example:
+
+    ```python
+    from safetensors.flax import save_file
+    from jax import numpy as jnp
+
+    tensors = {"embedding": jnp.zeros((512, 1024)), "attention": jnp.zeros((256, 256))}
+    save_file(tensors, "model.safetensors")
+    ```
+    """
+    np_tensors = _jnp2np(tensors)
+    return numpy.save_file(np_tensors, filename, metadata=metadata)
+
+
+def load(data: bytes) -> Dict[str, Array]:
+    """
+    Loads a safetensors file into flax format from pure bytes.
+
+    Args:
+        data (`bytes`):
+            The content of a safetensors file
+
+    Returns:
+        `Dict[str, Array]`: dictionary that contains name as key, value as `Array` on cpu
+
+    Example:
+
+    ```python
+    from safetensors.flax import load
+
+    file_path = "./my_folder/bert.safetensors"
+    with open(file_path, "rb") as f:
+        data = f.read()
+
+    loaded = load(data)
+    ```
+    """
+    flat = numpy.load(data)
+    return _np2jnp(flat)
+
+
+def load_file(filename: Union[str, os.PathLike]) -> Dict[str, Array]:
+    """
+    Loads a safetensors file into flax format.
+
+    Args:
+        filename (`str`, or `os.PathLike`)):
+            The name of the file which contains the tensors
+
+    Returns:
+        `Dict[str, Array]`: dictionary that contains name as key, value as `Array`
+
+    Example:
+
+    ```python
+    from safetensors.flax import load_file
+
+    file_path = "./my_folder/bert.safetensors"
+    loaded = load_file(file_path)
+    ```
+    """
+    result = {}
+    with safe_open(filename, framework="flax") as f:
+        for k in f.offset_keys():
+            result[k] = f.get_tensor(k)
+    return result
+
+
+def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, Array]:
+    for k, v in numpy_dict.items():
+        numpy_dict[k] = jnp.array(v)
+    return numpy_dict
+
+
+def _jnp2np(jnp_dict: Dict[str, Array]) -> Dict[str, np.array]:
+    for k, v in jnp_dict.items():
+        jnp_dict[k] = np.asarray(v)
+    return jnp_dict
diff --git a/lib/python3.11/site-packages/safetensors/mlx.py b/lib/python3.11/site-packages/safetensors/mlx.py
new file mode 100644
index 0000000000000000000000000000000000000000..985b73b98ef19afc2104ed1b2464fdeaf829d3bd
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/mlx.py
@@ -0,0 +1,140 @@
+import os
+from typing import Dict, Optional, Union
+
+import numpy as np
+
+import mlx.core as mx
+from safetensors import numpy, safe_open
+
+
+def save(
+    tensors: Dict[str, mx.array], metadata: Optional[Dict[str, str]] = None
+) -> bytes:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, mx.array]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `bytes`: The raw bytes representing the format
+
+    Example:
+
+    ```python
+    from safetensors.mlx import save
+    import mlx.core as mx
+
+    tensors = {"embedding": mx.zeros((512, 1024)), "attention": mx.zeros((256, 256))}
+    byte_data = save(tensors)
+    ```
+    """
+    np_tensors = _mx2np(tensors)
+    return numpy.save(np_tensors, metadata=metadata)
+
+
+def save_file(
+    tensors: Dict[str, mx.array],
+    filename: Union[str, os.PathLike],
+    metadata: Optional[Dict[str, str]] = None,
+) -> None:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, mx.array]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        filename (`str`, or `os.PathLike`)):
+            The filename we're saving into.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `None`
+
+    Example:
+
+    ```python
+    from safetensors.mlx import save_file
+    import mlx.core as mx
+
+    tensors = {"embedding": mx.zeros((512, 1024)), "attention": mx.zeros((256, 256))}
+    save_file(tensors, "model.safetensors")
+    ```
+    """
+    np_tensors = _mx2np(tensors)
+    return numpy.save_file(np_tensors, filename, metadata=metadata)
+
+
+def load(data: bytes) -> Dict[str, mx.array]:
+    """
+    Loads a safetensors file into MLX format from pure bytes.
+
+    Args:
+        data (`bytes`):
+            The content of a safetensors file
+
+    Returns:
+        `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array`
+
+    Example:
+
+    ```python
+    from safetensors.mlx import load
+
+    file_path = "./my_folder/bert.safetensors"
+    with open(file_path, "rb") as f:
+        data = f.read()
+
+    loaded = load(data)
+    ```
+    """
+    flat = numpy.load(data)
+    return _np2mx(flat)
+
+
+def load_file(filename: Union[str, os.PathLike]) -> Dict[str, mx.array]:
+    """
+    Loads a safetensors file into MLX format.
+
+    Args:
+        filename (`str`, or `os.PathLike`)):
+            The name of the file which contains the tensors
+
+    Returns:
+        `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array`
+
+    Example:
+
+    ```python
+    from safetensors.flax import load_file
+
+    file_path = "./my_folder/bert.safetensors"
+    loaded = load_file(file_path)
+    ```
+    """
+    result = {}
+    with safe_open(filename, framework="mlx") as f:
+        for k in f.offset_keys():
+            result[k] = f.get_tensor(k)
+    return result
+
+
+def _np2mx(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, mx.array]:
+    for k, v in numpy_dict.items():
+        numpy_dict[k] = mx.array(v)
+    return numpy_dict
+
+
+def _mx2np(mx_dict: Dict[str, mx.array]) -> Dict[str, np.array]:
+    new_dict = {}
+    for k, v in mx_dict.items():
+        new_dict[k] = np.asarray(v)
+    return new_dict
diff --git a/lib/python3.11/site-packages/safetensors/numpy.py b/lib/python3.11/site-packages/safetensors/numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..9061ba54bdc6b6f96a0863bc977fcce61467f1b9
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/numpy.py
@@ -0,0 +1,195 @@
+import os
+import sys
+from typing import Dict, List, Optional, Union
+
+import numpy as np
+
+from safetensors import TensorSpec, deserialize, safe_open, serialize, serialize_file
+
+
+def _flatten(
+    tensor_dict: Dict[str, np.ndarray], keep_alive_buffer: List
+) -> Dict[str, Dict]:
+    flattened = {}
+    for k, v in tensor_dict.items():
+        tensor = v
+        if not _is_little_endian(tensor):
+            tensor = tensor.byteswap(inplace=False)
+            keep_alive_buffer.append(tensor)
+        flattened[k] = TensorSpec(
+            dtype=tensor.dtype.name,
+            shape=tensor.shape,
+            data_ptr=tensor.ctypes.data,
+            data_len=tensor.nbytes,
+        )
+    return flattened
+
+
+def save(
+    tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] = None
+) -> bytes:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensor_dict (`Dict[str, np.ndarray]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `bytes`: The raw bytes representing the format
+
+    Example:
+
+    ```python
+    from safetensors.numpy import save
+    import numpy as np
+
+    tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))}
+    byte_data = save(tensors)
+    ```
+    """
+    keep_alive_buffer = []  # to keep byteswapped tensors alive
+    serialized = serialize(_flatten(tensor_dict, keep_alive_buffer), metadata=metadata)
+    result = bytes(serialized)
+    return result
+
+
+def save_file(
+    tensor_dict: Dict[str, np.ndarray],
+    filename: Union[str, os.PathLike],
+    metadata: Optional[Dict[str, str]] = None,
+) -> None:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensor_dict (`Dict[str, np.ndarray]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        filename (`str`, or `os.PathLike`)):
+            The filename we're saving into.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `None`
+
+    Example:
+
+    ```python
+    from safetensors.numpy import save_file
+    import numpy as np
+
+    tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))}
+    save_file(tensors, "model.safetensors")
+    ```
+    """
+    keep_alive_buffer = []  # to keep byteswapped tensors alive
+    serialize_file(
+        _flatten(tensor_dict, keep_alive_buffer), filename, metadata=metadata
+    )
+
+
+def load(data: bytes) -> Dict[str, np.ndarray]:
+    """
+    Loads a safetensors file into numpy format from pure bytes.
+
+    Args:
+        data (`bytes`):
+            The content of a safetensors file
+
+    Returns:
+        `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` on cpu
+
+    Example:
+
+    ```python
+    from safetensors.numpy import load
+
+    file_path = "./my_folder/bert.safetensors"
+    with open(file_path, "rb") as f:
+        data = f.read()
+
+    loaded = load(data)
+    ```
+    """
+    flat = deserialize(data)
+    return _view2np(flat)
+
+
+def load_file(filename: Union[str, os.PathLike]) -> Dict[str, np.ndarray]:
+    """
+    Loads a safetensors file into numpy format.
+
+    Args:
+        filename (`str`, or `os.PathLike`)):
+            The name of the file which contains the tensors
+
+    Returns:
+        `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray`
+
+    Example:
+
+    ```python
+    from safetensors.numpy import load_file
+
+    file_path = "./my_folder/bert.safetensors"
+    loaded = load_file(file_path)
+    ```
+    """
+    result = {}
+    with safe_open(filename, framework="np") as f:
+        for k in f.offset_keys():
+            result[k] = f.get_tensor(k)
+    return result
+
+
+_TYPES = {
+    "F64": np.float64,
+    "F32": np.float32,
+    "F16": np.float16,
+    "I64": np.int64,
+    "U64": np.uint64,
+    "I32": np.int32,
+    "U32": np.uint32,
+    "I16": np.int16,
+    "U16": np.uint16,
+    "I8": np.int8,
+    "U8": np.uint8,
+    "BOOL": bool,
+    "C64": np.complex64,
+}
+
+
+def _getdtype(dtype_str: str) -> np.dtype:
+    return _TYPES[dtype_str]
+
+
+def _view2np(safeview) -> Dict[str, np.ndarray]:
+    result = {}
+    for k, v in safeview:
+        dtype = _getdtype(v["dtype"])
+        arr = np.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
+        result[k] = arr
+    return result
+
+
+def _is_little_endian(tensor: np.ndarray) -> bool:
+    byteorder = tensor.dtype.byteorder
+    if byteorder == "=":
+        if sys.byteorder == "little":
+            return True
+        else:
+            return False
+    elif byteorder == "|":
+        return True
+    elif byteorder == "<":
+        return True
+    elif byteorder == ">":
+        return False
+    raise ValueError(f"Unexpected byte order {byteorder}")
diff --git a/lib/python3.11/site-packages/safetensors/paddle.py b/lib/python3.11/site-packages/safetensors/paddle.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ce90937ff99faf936747cfe8f6d76304eb592c5
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/paddle.py
@@ -0,0 +1,306 @@
+import os
+import sys
+from typing import Any, Dict, List, Optional, Union
+
+import numpy as np
+import paddle
+
+from safetensors import (
+    TensorSpec,
+    numpy,
+    deserialize,
+    safe_open,
+    serialize,
+    serialize_file,
+)
+
+
+def save(
+    tensors: Dict[str, paddle.Tensor], metadata: Optional[Dict[str, str]] = None
+) -> bytes:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, paddle.Tensor]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `bytes`: The raw bytes representing the format
+
+    Example:
+
+    ```python
+    from safetensors.paddle import save
+    import paddle
+
+    tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))}
+    byte_data = save(tensors)
+    ```
+    """
+    keep_references_alive = []
+    serialized = serialize(_flatten(tensors, keep_references_alive), metadata=metadata)
+    result = bytes(serialized)
+    return result
+
+
+def save_file(
+    tensors: Dict[str, paddle.Tensor],
+    filename: Union[str, os.PathLike],
+    metadata: Optional[Dict[str, str]] = None,
+) -> None:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, paddle.Tensor]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        filename (`str`, or `os.PathLike`)):
+            The filename we're saving into.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `None`
+
+    Example:
+
+    ```python
+    from safetensors.paddle import save_file
+    import paddle
+
+    tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))}
+    save_file(tensors, "model.safetensors")
+    ```
+    """
+    keep_references_alive = []
+    serialize_file(
+        _flatten(tensors, keep_references_alive), filename, metadata=metadata
+    )
+
+
+def load(data: bytes, device: str = "cpu") -> Dict[str, paddle.Tensor]:
+    """
+    Loads a safetensors file into paddle format from pure bytes.
+
+    Args:
+        data (`bytes`):
+            The content of a safetensors file
+
+    Returns:
+        `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor` on cpu
+
+    Example:
+
+    ```python
+    from safetensors.paddle import load
+
+    file_path = "./my_folder/bert.safetensors"
+    with open(file_path, "rb") as f:
+        data = f.read()
+
+    loaded = load(data)
+    ```
+    """
+    if paddle.__version__ >= "3.2.0":
+        flat = deserialize(data)
+        return _view2paddle(flat, device)
+    else:
+        flat = numpy.load(data)
+        return _np2paddle(flat, device)
+
+
+def load_file(
+    filename: Union[str, os.PathLike], device="cpu"
+) -> Dict[str, paddle.Tensor]:
+    """
+    Loads a safetensors file into paddle format.
+
+    Args:
+        filename (`str`, or `os.PathLike`)):
+            The name of the file which contains the tensors
+        device (`Union[Dict[str, any], str]`, *optional*, defaults to `cpu`):
+            The device where the tensors need to be located after load.
+            available options are all regular paddle device locations
+
+    Returns:
+        `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor`
+
+    Example:
+
+    ```python
+    from safetensors.paddle import load_file
+
+    file_path = "./my_folder/bert.safetensors"
+    loaded = load_file(file_path)
+    ```
+    """
+    result = {}
+    if paddle.__version__ >= "3.2.0":
+        with safe_open(filename, framework="paddle", device=device) as f:
+            for k in f.offset_keys():
+                result[k] = f.get_tensor(k)
+    else:
+        flat = numpy.load_file(filename)
+        result = _np2paddle(flat, device)
+    return result
+
+
+def _np2paddle(
+    numpy_dict: Dict[str, np.ndarray], device: str = "cpu"
+) -> Dict[str, paddle.Tensor]:
+    for k, v in numpy_dict.items():
+        numpy_dict[k] = paddle.to_tensor(v, place=device)
+    return numpy_dict
+
+
+def _paddle2np(paddle_dict: Dict[str, paddle.Tensor]) -> Dict[str, np.array]:
+    for k, v in paddle_dict.items():
+        paddle_dict[k] = v.detach().cpu().numpy()
+    return paddle_dict
+
+
+_SIZE = {
+    paddle.int64: 8,
+    paddle.float32: 4,
+    paddle.int32: 4,
+    paddle.bfloat16: 2,
+    paddle.float16: 2,
+    paddle.int16: 2,
+    paddle.uint8: 1,
+    paddle.int8: 1,
+    paddle.bool: 1,
+    paddle.float64: 8,
+    paddle.float8_e4m3fn: 1,
+    paddle.float8_e5m2: 1,
+    paddle.complex64: 8,
+    # XXX: These are not supported yet in paddle
+    # paddle.uint64: 8,
+    # paddle.uint32: 4,
+    # paddle.uint16: 2,
+    # paddle.float8_e8m0: 1,
+    # paddle.float4_e2m1_x2: 1,
+}
+
+_TYPES = {
+    "F64": paddle.float64,
+    "F32": paddle.float32,
+    "F16": paddle.float16,
+    "BF16": paddle.bfloat16,
+    "I64": paddle.int64,
+    "I32": paddle.int32,
+    "I16": paddle.int16,
+    "I8": paddle.int8,
+    "U8": paddle.uint8,
+    "BOOL": paddle.bool,
+    "F8_E4M3": paddle.float8_e4m3fn,
+    "F8_E5M2": paddle.float8_e5m2,
+}
+
+NPDTYPES = {
+    paddle.int64: np.int64,
+    paddle.float32: np.float32,
+    paddle.int32: np.int32,
+    # XXX: This is ok because both have the same width
+    paddle.bfloat16: np.float16,
+    paddle.float16: np.float16,
+    paddle.int16: np.int16,
+    paddle.uint8: np.uint8,
+    paddle.int8: np.int8,
+    paddle.bool: bool,
+    paddle.float64: np.float64,
+    # XXX: This is ok because both have the same width and byteswap is a no-op anyway
+    paddle.float8_e4m3fn: np.uint8,
+    paddle.float8_e5m2: np.uint8,
+}
+
+
+def _getdtype(dtype_str: str) -> paddle.dtype:
+    return _TYPES[dtype_str]
+
+
+def _view2paddle(safeview, device) -> Dict[str, paddle.Tensor]:
+    result = {}
+    for k, v in safeview:
+        dtype = _getdtype(v["dtype"])
+        if len(v["data"]) == 0:
+            # Workaround because frombuffer doesn't accept zero-size tensors
+            assert any(x == 0 for x in v["shape"])
+            arr = paddle.empty(v["shape"], dtype=dtype)
+        else:
+            arr = paddle.base.core.frombuffer(v["data"], dtype).reshape(v["shape"])
+            if device != "cpu":
+                arr = arr.to(device)
+        if sys.byteorder == "big":
+            arr = paddle.to_tensor(arr.numpy().byteswap(inplace=False), place=device)
+        result[k] = arr
+
+    return result
+
+
+def _to_ndarray(tensor: paddle.Tensor, name: str):
+    if not tensor.is_contiguous():
+        raise ValueError(
+            f"You are trying to save a non contiguous tensor: `{name}` which is not allowed. It either means you"
+            " are trying to save tensors which are reference of each other in which case it's recommended to save"
+            " only the full tensors, and reslice at load time, or simply call `.contiguous()` on your tensor to"
+            " pack it before saving."
+        )
+    if not tensor.place.is_cpu_place():
+        # Moving tensor to cpu before saving
+        tensor = tensor.cpu()
+
+    import ctypes
+
+    # When shape is empty (scalar), np.prod returns a float
+    # we need a int for the following calculations
+    length = int(np.prod(tensor.shape).item())
+    bytes_per_item = _SIZE[tensor.dtype]
+
+    total_bytes = length * bytes_per_item
+
+    ptr = tensor.data_ptr()
+    if ptr == 0:
+        return np.empty(
+            0
+        ), 0  # XXX: bogus value we don't really care if we return a tensor here
+    newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte))
+    data = np.ctypeslib.as_array(newptr, (total_bytes,))  # no internal copy
+    if sys.byteorder == "big":
+        npdtype = NPDTYPES[tensor.dtype]
+        # Not in place as that would potentially modify a live running model
+        data = data.view(npdtype).byteswap(inplace=False)
+    return data, tensor
+
+
+def _flatten(
+    tensors: Dict[str, paddle.Tensor], keep_alive_buffer: List
+) -> Dict[str, Dict[str, Any]]:
+    if not isinstance(tensors, dict):
+        raise ValueError(
+            f"Expected a dict of [str, paddle.Tensor] but received {type(tensors)}"
+        )
+
+    for k, v in tensors.items():
+        if not isinstance(v, paddle.Tensor):
+            raise ValueError(
+                f"Key `{k}` is invalid, expected paddle.Tensor but received {type(v)}"
+            )
+
+    flattened = {}
+    for k, v in tensors.items():
+        arr, tensor_ref = _to_ndarray(v, k)
+        keep_alive_buffer.append((arr, tensor_ref))
+        flattened[k] = TensorSpec(
+            dtype=str(v.dtype).split(".")[-1],
+            shape=v.shape,
+            data_ptr=arr.ctypes.data,
+            data_len=arr.nbytes,
+        )
+    return flattened
diff --git a/lib/python3.11/site-packages/safetensors/py.typed b/lib/python3.11/site-packages/safetensors/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/lib/python3.11/site-packages/safetensors/tensorflow.py b/lib/python3.11/site-packages/safetensors/tensorflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2bfc936ebae5350c0599a79c8ec3841fd6cda0c
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/tensorflow.py
@@ -0,0 +1,139 @@
+import os
+from typing import Dict, Optional, Union
+
+import numpy as np
+import tensorflow as tf
+
+from safetensors import numpy, safe_open
+
+
+def save(
+    tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]] = None
+) -> bytes:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, tf.Tensor]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `bytes`: The raw bytes representing the format
+
+    Example:
+
+    ```python
+    from safetensors.tensorflow import save
+    import tensorflow as tf
+
+    tensors = {"embedding": tf.zeros((512, 1024)), "attention": tf.zeros((256, 256))}
+    byte_data = save(tensors)
+    ```
+    """
+    np_tensors = _tf2np(tensors)
+    return numpy.save(np_tensors, metadata=metadata)
+
+
+def save_file(
+    tensors: Dict[str, tf.Tensor],
+    filename: Union[str, os.PathLike],
+    metadata: Optional[Dict[str, str]] = None,
+) -> None:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, tf.Tensor]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        filename (`str`, or `os.PathLike`)):
+            The filename we're saving into.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `None`
+
+    Example:
+
+    ```python
+    from safetensors.tensorflow import save_file
+    import tensorflow as tf
+
+    tensors = {"embedding": tf.zeros((512, 1024)), "attention": tf.zeros((256, 256))}
+    save_file(tensors, "model.safetensors")
+    ```
+    """
+    np_tensors = _tf2np(tensors)
+    return numpy.save_file(np_tensors, filename, metadata=metadata)
+
+
+def load(data: bytes) -> Dict[str, tf.Tensor]:
+    """
+    Loads a safetensors file into tensorflow format from pure bytes.
+
+    Args:
+        data (`bytes`):
+            The content of a safetensors file
+
+    Returns:
+        `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` on cpu
+
+    Example:
+
+    ```python
+    from safetensors.tensorflow import load
+
+    file_path = "./my_folder/bert.safetensors"
+    with open(file_path, "rb") as f:
+        data = f.read()
+
+    loaded = load(data)
+    ```
+    """
+    flat = numpy.load(data)
+    return _np2tf(flat)
+
+
+def load_file(filename: Union[str, os.PathLike]) -> Dict[str, tf.Tensor]:
+    """
+    Loads a safetensors file into tensorflow format.
+
+    Args:
+        filename (`str`, or `os.PathLike`)):
+            The name of the file which contains the tensors
+
+    Returns:
+        `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor`
+
+    Example:
+
+    ```python
+    from safetensors.tensorflow import load_file
+
+    file_path = "./my_folder/bert.safetensors"
+    loaded = load_file(file_path)
+    ```
+    """
+    result = {}
+    with safe_open(filename, framework="tf") as f:
+        for k in f.offset_keys():
+            result[k] = f.get_tensor(k)
+    return result
+
+
+def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]:
+    for k, v in numpy_dict.items():
+        numpy_dict[k] = tf.convert_to_tensor(v)
+    return numpy_dict
+
+
+def _tf2np(tf_dict: Dict[str, tf.Tensor]) -> Dict[str, np.array]:
+    for k, v in tf_dict.items():
+        tf_dict[k] = v.numpy()
+    return tf_dict
diff --git a/lib/python3.11/site-packages/safetensors/torch.py b/lib/python3.11/site-packages/safetensors/torch.py
new file mode 100644
index 0000000000000000000000000000000000000000..766f28cafa1e23c43d94f7f762ce1f163ad4291e
--- /dev/null
+++ b/lib/python3.11/site-packages/safetensors/torch.py
@@ -0,0 +1,582 @@
+import os
+import sys
+from collections import defaultdict
+from typing import Any, Dict, List, Optional, Set, Tuple, Union
+
+import torch
+from safetensors import (
+    TensorSpec,
+    deserialize,
+    safe_open,
+    serialize,
+    serialize_file,
+)
+
+
+def storage_ptr(tensor: torch.Tensor) -> int:
+    try:
+        return tensor.untyped_storage().data_ptr()
+    except Exception:
+        # Fallback for torch==1.10
+        try:
+            return tensor.storage().data_ptr()
+        except NotImplementedError:
+            # Fallback for meta storage
+            return 0
+
+
+def _end_ptr(tensor: torch.Tensor) -> int:
+    if tensor.nelement():
+        stop = tensor.view(-1)[-1].data_ptr() + _SIZE[tensor.dtype]
+    else:
+        stop = tensor.data_ptr()
+    return stop
+
+
+def storage_size(tensor: torch.Tensor) -> int:
+    try:
+        return tensor.untyped_storage().nbytes()
+    except AttributeError:
+        # Fallback for torch==1.10
+        try:
+            return tensor.storage().size() * _SIZE[tensor.dtype]
+        except NotImplementedError:
+            # Fallback for meta storage
+            # On torch >=2.0 this is the tensor size
+            return tensor.nelement() * _SIZE[tensor.dtype]
+
+
+def _filter_shared_not_shared(
+    tensors: List[Set[str]], state_dict: Dict[str, torch.Tensor]
+) -> List[Set[str]]:
+    filtered_tensors = []
+    for shared in tensors:
+        if len(shared) < 2:
+            filtered_tensors.append(shared)
+            continue
+
+        areas = []
+        for name in shared:
+            tensor = state_dict[name]
+            areas.append((tensor.data_ptr(), _end_ptr(tensor), name))
+        areas.sort()
+
+        _, last_stop, last_name = areas[0]
+        filtered_tensors.append({last_name})
+        for start, stop, name in areas[1:]:
+            if start >= last_stop:
+                filtered_tensors.append({name})
+            else:
+                filtered_tensors[-1].add(name)
+            last_stop = stop
+
+    return filtered_tensors
+
+
+def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]:
+    tensors = defaultdict(set)
+    for k, v in state_dict.items():
+        if (
+            v.device != torch.device("meta")
+            and storage_ptr(v) != 0
+            and storage_size(v) != 0
+        ):
+            # Need to add device as key because of multiple GPU.
+            tensors[(v.device, storage_ptr(v), storage_size(v))].add(k)
+    tensors = list(sorted(tensors.values()))
+    tensors = _filter_shared_not_shared(tensors, state_dict)
+    return tensors
+
+
+def _is_complete(tensor: torch.Tensor) -> bool:
+    return tensor.data_ptr() == storage_ptr(tensor) and tensor.nelement() * _SIZE[
+        tensor.dtype
+    ] == storage_size(tensor)
+
+
+def _remove_duplicate_names(
+    state_dict: Dict[str, torch.Tensor],
+    *,
+    preferred_names: Optional[List[str]] = None,
+    discard_names: Optional[List[str]] = None,
+) -> Dict[str, List[str]]:
+    if preferred_names is None:
+        preferred_names = []
+    preferred_names = set(preferred_names)
+    if discard_names is None:
+        discard_names = []
+    discard_names = set(discard_names)
+
+    shareds = _find_shared_tensors(state_dict)
+    to_remove = defaultdict(list)
+    for shared in shareds:
+        complete_names = set(
+            [name for name in shared if _is_complete(state_dict[name])]
+        )
+        if not complete_names:
+            raise RuntimeError(
+                "Error while trying to find names to remove to save state dict, but found no suitable name to keep"
+                f" for saving amongst: {shared}. None is covering the entire storage.Refusing to save/load the model"
+                " since you could be storing much more memory than needed. Please refer to"
+                " https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an"
+                " issue."
+            )
+
+        keep_name = sorted(list(complete_names))[0]
+
+        # Mechanism to preferentially select keys to keep
+        # coming from the on-disk file to allow
+        # loading models saved with a different choice
+        # of keep_name
+        preferred = complete_names.difference(discard_names)
+        if preferred:
+            keep_name = sorted(list(preferred))[0]
+
+        if preferred_names:
+            preferred = preferred_names.intersection(complete_names)
+            if preferred:
+                keep_name = sorted(list(preferred))[0]
+        for name in sorted(shared):
+            if name != keep_name:
+                to_remove[keep_name].append(name)
+    return to_remove
+
+
+def save_model(
+    model: torch.nn.Module,
+    filename: str,
+    metadata: Optional[Dict[str, str]] = None,
+    force_contiguous: bool = True,
+):
+    """
+    Saves a given torch model to specified filename.
+    This method exists specifically to avoid tensor sharing issues which are
+    not allowed in `safetensors`. [More information on tensor sharing](../torch_shared_tensors)
+
+    Args:
+        model (`torch.nn.Module`):
+            The model to save on disk.
+        filename (`str`):
+            The filename location to save the file
+        metadata (`Dict[str, str]`, *optional*):
+            Extra information to save along with the file.
+            Some metadata will be added for each dropped tensors.
+            This information will not be enough to recover the entire
+            shared structure but might help understanding things
+        force_contiguous (`boolean`, *optional*, defaults to True):
+            Forcing the state_dict to be saved as contiguous tensors.
+            This has no effect on the correctness of the model, but it
+            could potentially change performance if the layout of the tensor
+            was chosen specifically for that reason.
+    """
+    state_dict = model.state_dict()
+    to_removes = _remove_duplicate_names(state_dict)
+
+    for kept_name, to_remove_group in to_removes.items():
+        for to_remove in to_remove_group:
+            if metadata is None:
+                metadata = {}
+
+            if to_remove not in metadata:
+                # Do not override user data
+                metadata[to_remove] = kept_name
+            del state_dict[to_remove]
+    if force_contiguous:
+        state_dict = {k: v.contiguous() for k, v in state_dict.items()}
+    try:
+        save_file(state_dict, filename, metadata=metadata)
+    except ValueError as e:
+        msg = str(e)
+        msg += " Or use save_model(..., force_contiguous=True), read the docs for potential caveats."
+        raise ValueError(msg)
+
+
+def load_model(
+    model: torch.nn.Module,
+    filename: Union[str, os.PathLike],
+    strict: bool = True,
+    device: Union[str, int] = "cpu",
+) -> Tuple[List[str], List[str]]:
+    """
+    Loads a given filename onto a torch model.
+    This method exists specifically to avoid tensor sharing issues which are
+    not allowed in `safetensors`. [More information on tensor sharing](../torch_shared_tensors)
+
+    Args:
+        model (`torch.nn.Module`):
+            The model to load onto.
+        filename (`str`, or `os.PathLike`):
+            The filename location to load the file from.
+        strict (`bool`, *optional*, defaults to True):
+            Whether to fail if you're missing keys or having unexpected ones.
+            When false, the function simply returns missing and unexpected names.
+        device (`Union[str, int]`, *optional*, defaults to `cpu`):
+            The device where the tensors need to be located after load.
+            available options are all regular torch device locations.
+
+    Returns:
+        `(missing, unexpected): (List[str], List[str])`
+            `missing` are names in the model which were not modified during loading
+            `unexpected` are names that are on the file, but weren't used during
+            the load.
+    """
+    state_dict = load_file(filename, device=device)
+    model_state_dict = model.state_dict()
+    to_removes = _remove_duplicate_names(
+        model_state_dict, preferred_names=state_dict.keys()
+    )
+    missing, unexpected = model.load_state_dict(state_dict, strict=False)
+    missing = set(missing)
+    for to_remove_group in to_removes.values():
+        for to_remove in to_remove_group:
+            if to_remove not in missing:
+                unexpected.append(to_remove)
+            else:
+                missing.remove(to_remove)
+    if strict and (missing or unexpected):
+        missing_keys = ", ".join([f'"{k}"' for k in sorted(missing)])
+        unexpected_keys = ", ".join([f'"{k}"' for k in sorted(unexpected)])
+        error = f"Error(s) in loading state_dict for {model.__class__.__name__}:"
+        if missing:
+            error += f"\n    Missing key(s) in state_dict: {missing_keys}"
+        if unexpected:
+            error += f"\n    Unexpected key(s) in state_dict: {unexpected_keys}"
+        raise RuntimeError(error)
+    return missing, unexpected
+
+
+def save(
+    tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None
+) -> bytes:
+    """
+    Saves a dictionary of tensors into raw bytes in safetensors format.
+
+    Args:
+        tensors (`Dict[str, torch.Tensor]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `bytes`: The raw bytes representing the format
+
+    Example:
+
+    ```python
+    from safetensors.torch import save
+    import torch
+
+    tensors = {"embedding": torch.zeros((512, 1024)), "attention": torch.zeros((256, 256))}
+    byte_data = save(tensors)
+    ```
+    """
+    keep_references_alive = []  # to avoid garbage collection of temporary numpy arrays while we write to disk
+    serialized = serialize(
+        _flatten_as_ptr(tensors, keep_references_alive), metadata=metadata
+    )
+    result = bytes(serialized)
+    return result
+
+
+def save_file(
+    tensors: Dict[str, torch.Tensor],
+    filename: Union[str, os.PathLike],
+    metadata: Optional[Dict[str, str]] = None,
+):
+    """
+    Saves a dictionary of tensors into `filename` in safetensors format.
+    There is no mechanism in place to prevent the caller from modifying the data while a file save occurs,
+    please be wary when calling `save_file` and modifying tensors referenced in the `tensors` dict concurrently;
+    it may lead to corrupted files.
+
+    Args:
+        tensors (`Dict[str, torch.Tensor]`):
+            The incoming tensors. Tensors need to be contiguous and dense.
+        filename (`str`, or `os.PathLike`)):
+            The filename we're saving into.
+        metadata (`Dict[str, str]`, *optional*, defaults to `None`):
+            Optional text only metadata you might want to save in your header.
+            For instance it can be useful to specify more about the underlying
+            tensors. This is purely informative and does not affect tensor loading.
+
+    Returns:
+        `None`
+
+    Example:
+
+    ```python
+    from safetensors.torch import save_file
+    import torch
+
+    tensors = {"embedding": torch.zeros((512, 1024)), "attention": torch.zeros((256, 256))}
+    save_file(tensors, "model.safetensors")
+    ```
+    """
+    keep_references_alive = []  # to avoid garbage collection of temporary numpy arrays while we write to disk
+    serialize_file(
+        _flatten_as_ptr(tensors, keep_references_alive), filename, metadata=metadata
+    )
+
+
+def load_file(
+    filename: Union[str, os.PathLike], device: Union[str, int] = "cpu"
+) -> Dict[str, torch.Tensor]:
+    """
+    Loads a safetensors file into torch format.
+
+    Args:
+        filename (`str`, or `os.PathLike`):
+            The name of the file which contains the tensors
+        device (`Union[str, int]`, *optional*, defaults to `cpu`):
+            The device where the tensors need to be located after load.
+            available options are all regular torch device locations.
+
+    Returns:
+        `Dict[str, torch.Tensor]`: dictionary that contains name as key, value as `torch.Tensor`
+
+    Example:
+
+    ```python
+    from safetensors.torch import load_file
+
+    file_path = "./my_folder/bert.safetensors"
+    loaded = load_file(file_path)
+    ```
+    """
+    result = {}
+    with safe_open(filename, framework="pt", device=device) as f:
+        for k in f.offset_keys():
+            result[k] = f.get_tensor(k)
+    return result
+
+
+def load(data: bytes) -> Dict[str, torch.Tensor]:
+    """
+    Loads a safetensors file into torch format from pure bytes.
+
+    Args:
+        data (`bytes`):
+            The content of a safetensors file
+
+    Returns:
+        `Dict[str, torch.Tensor]`: dictionary that contains name as key, value as `torch.Tensor` on cpu
+
+    Example:
+
+    ```python
+    from safetensors.torch import load
+
+    file_path = "./my_folder/bert.safetensors"
+    with open(file_path, "rb") as f:
+        data = f.read()
+
+    loaded = load(data)
+    ```
+    """
+    flat = deserialize(data)
+    return _view2torch(flat)
+
+
+# torch.float8 formats require 2.1; we do not support these dtypes on earlier versions
+_float8_e4m3fn = getattr(torch, "float8_e4m3fn", None)
+_float8_e4m3fnuz = getattr(torch, "float8_e4m3fnuz", None)
+_float8_e5m2 = getattr(torch, "float8_e5m2", None)
+_float8_e5m2fnuz = getattr(torch, "float8_e5m2fnuz", None)
+_float8_e8m0 = getattr(torch, "float8_e8m0fnu", None)
+_float4_e2m1_x2 = getattr(torch, "float4_e2m1fn_x2", None)
+
+_SIZE = {
+    torch.int64: 8,
+    torch.float32: 4,
+    torch.int32: 4,
+    torch.bfloat16: 2,
+    torch.float16: 2,
+    torch.int16: 2,
+    torch.uint8: 1,
+    torch.int8: 1,
+    torch.bool: 1,
+    torch.float64: 8,
+    torch.complex64: 8,
+    _float8_e4m3fn: 1,
+    _float8_e4m3fnuz: 1,
+    _float8_e5m2: 1,
+    _float8_e5m2fnuz: 1,
+    _float8_e8m0: 1,
+    _float4_e2m1_x2: 1,
+}
+
+if hasattr(torch, "uint64"):  # Torch 2.3.0+
+    _SIZE.update(
+        {
+            torch.uint64: 8,
+            torch.uint32: 4,
+            torch.uint16: 2,
+        }
+    )
+
+_TYPES = {
+    "F64": torch.float64,
+    "F32": torch.float32,
+    "F16": torch.float16,
+    "BF16": torch.bfloat16,
+    "I64": torch.int64,
+    "I32": torch.int32,
+    "I16": torch.int16,
+    "I8": torch.int8,
+    "U8": torch.uint8,
+    "BOOL": torch.bool,
+    "F8_E4M3": _float8_e4m3fn,
+    "F8_E4M3FNUZ": _float8_e4m3fnuz,
+    "F8_E5M2": _float8_e5m2,
+    "F8_E5M2FNUZ": _float8_e5m2fnuz,
+    "C64": torch.complex64,
+}
+
+if hasattr(torch, "uint64"):  # Torch 2.3.0+
+    _TYPES.update(
+        {
+            "U64": torch.uint64,
+            "U32": torch.uint32,
+            "U16": torch.uint16,
+        }
+    )
+
+
+def _getdtype(dtype_str: str) -> torch.dtype:
+    return _TYPES[dtype_str]
+
+
+def _view2torch(safeview) -> Dict[str, torch.Tensor]:
+    result = {}
+    for k, v in safeview:
+        dtype = _getdtype(v["dtype"])
+        if len(v["data"]) == 0:
+            # Workaround because frombuffer doesn't accept zero-size tensors
+            assert any(x == 0 for x in v["shape"])
+            arr = torch.empty(v["shape"], dtype=dtype)
+        else:
+            arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"])
+        if sys.byteorder == "big":
+            arr = torch.from_numpy(arr.numpy().byteswap(inplace=False))
+        result[k] = arr
+
+    return result
+
+
+def _to_ndarray(tensor: torch.Tensor):
+    if tensor.device.type != "cpu":
+        # Moving tensor to cpu before saving
+        tensor = tensor.to("cpu")
+
+    import ctypes
+
+    import numpy as np
+
+    # When shape is empty (scalar), np.prod returns a float
+    # we need a int for the following calculations
+    length = int(np.prod(tensor.shape).item())
+    bytes_per_item = _SIZE[tensor.dtype]
+
+    total_bytes = length * bytes_per_item
+
+    ptr = tensor.data_ptr()
+    if ptr == 0:
+        return np.empty(
+            0
+        ), 0  # XXX: bogus value we don't really care if we return a tensor here
+    newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte))
+    data = np.ctypeslib.as_array(newptr, (total_bytes,))  # no internal copy
+    if sys.byteorder == "big":
+        NPDTYPES = {
+            torch.int64: np.int64,
+            torch.float32: np.float32,
+            torch.int32: np.int32,
+            # XXX: This is ok because both have the same width
+            torch.bfloat16: np.float16,
+            torch.float16: np.float16,
+            torch.int16: np.int16,
+            torch.uint8: np.uint8,
+            torch.int8: np.int8,
+            torch.bool: bool,
+            torch.float64: np.float64,
+            # XXX: This is ok because both have the same width and byteswap is a no-op anyway
+            _float8_e4m3fn: np.uint8,
+            _float8_e4m3fnuz: np.uint8,
+            _float8_e5m2: np.uint8,
+            _float8_e5m2fnuz: np.uint8,
+            _float8_e8m0: np.uint8,
+            _float4_e2m1_x2: np.uint8,
+            torch.complex64: np.complex64,
+        }
+        npdtype = NPDTYPES[tensor.dtype]
+        # Not in place as that would potentially modify a live running model
+        data = data.view(npdtype).byteswap(inplace=False)
+    return data, tensor
+
+
+def _evaluate_tensors_for_save(tensors: Dict[str, torch.Tensor]) -> None:
+    if not isinstance(tensors, dict):
+        raise ValueError(
+            f"Expected a dict of [str, torch.Tensor] but received {type(tensors)}"
+        )
+
+    sparse_tensors = []
+    for k, v in tensors.items():
+        if not isinstance(v, torch.Tensor):
+            raise ValueError(
+                f"Key `{k}` is invalid, expected torch.Tensor but received {type(v)}"
+            )
+
+        if v.layout != torch.strided:
+            sparse_tensors.append(k)
+
+    if sparse_tensors:
+        raise ValueError(
+            f"You are trying to save a sparse tensors: `{sparse_tensors}` which this library does not support."
+            " You can make it a dense tensor before saving with `.to_dense()` but be aware this might"
+            " make a much larger file than needed."
+        )
+
+    shared_pointers = _find_shared_tensors(tensors)
+    failing = []
+    for names in shared_pointers:
+        if len(names) > 1:
+            failing.append(names)
+
+    if failing:
+        raise RuntimeError(
+            f"""
+            Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}.
+            A potential way to correctly save your model is to use `save_model`.
+            More information at https://huggingface.co/docs/safetensors/torch_shared_tensors
+            """
+        )
+
+
+def _flatten_as_ptr(
+    tensors: Dict[str, torch.Tensor], keep_alive_buffer: List
+) -> Dict[str, Dict[str, Any]]:
+    _evaluate_tensors_for_save(tensors)
+    flattened = {}
+    for k, v in tensors.items():
+        # XXX: doing this check later on instead of in _evaluate_tensors_for_save
+        # since on old versions of torch, SparseTensorImpl do not implement is_contiguous
+        # and we do the sparsity check in _evaluate_tensors_for_save.
+        if not v.is_contiguous():
+            raise ValueError(
+                f"You are trying to save a non contiguous tensor: `{k}` which is not allowed. It either means you"
+                " are trying to save tensors which are reference of each other in which case it's recommended to save"
+                " only the full tensors, and reslice at load time, or simply call `.contiguous()` on your tensor to"
+                " pack it before saving."
+            )
+        arr, tensor_ref = _to_ndarray(v)
+        keep_alive_buffer.append((arr, tensor_ref))
+        flattened[k] = TensorSpec(
+            dtype=str(v.dtype).split(".")[-1],
+            shape=v.shape,
+            data_ptr=arr.ctypes.data,
+            data_len=arr.nbytes,
+        )
+    return flattened
diff --git a/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/INSTALLER b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/LICENSE b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..66aba18cab4ec4c67e7adbd4f722953231c1d33e
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) The python-semanticversion project
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met: 
+
+1. Redistributions of source code must retain the above copyright notice, this
+   list of conditions and the following disclaimer. 
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution. 
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/METADATA b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..d9d9d8a31337735dea30657a80a58462dfcffd26
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/METADATA
@@ -0,0 +1,324 @@
+Metadata-Version: 2.1
+Name: semantic-version
+Version: 2.10.0
+Summary: A library implementing the 'SemVer' scheme.
+Home-page: https://github.com/rbarrois/python-semanticversion
+Author: Raphaël Barrois
+Author-email: raphael.barrois+semver@polytechnique.org
+License: BSD
+Keywords: semantic version,versioning,version
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=2.7
+Description-Content-Type: text/x-rst
+Provides-Extra: dev
+Requires-Dist: Django (>=1.11) ; extra == 'dev'
+Requires-Dist: nose2 ; extra == 'dev'
+Requires-Dist: tox ; extra == 'dev'
+Requires-Dist: check-manifest ; extra == 'dev'
+Requires-Dist: coverage ; extra == 'dev'
+Requires-Dist: flake8 ; extra == 'dev'
+Requires-Dist: wheel ; extra == 'dev'
+Requires-Dist: zest.releaser[recommended] ; extra == 'dev'
+Requires-Dist: readme-renderer (<25.0) ; (python_version == "3.4") and extra == 'dev'
+Requires-Dist: colorama (<=0.4.1) ; (python_version == "3.4") and extra == 'dev'
+Provides-Extra: doc
+Requires-Dist: Sphinx ; extra == 'doc'
+Requires-Dist: sphinx-rtd-theme ; extra == 'doc'
+
+Introduction
+============
+
+This small python library provides a few tools to handle `SemVer`_ in Python.
+It follows strictly the 2.0.0 version of the SemVer scheme.
+
+.. image:: https://github.com/rbarrois/python-semanticversion/actions/workflows/test.yml/badge.svg
+    :target: https://github.com/rbarrois/python-semanticversion/actions/workflows/test.yml
+
+.. image:: https://img.shields.io/pypi/v/semantic_version.svg
+    :target: https://python-semanticversion.readthedocs.io/en/latest/changelog.html
+    :alt: Latest Version
+
+.. image:: https://img.shields.io/pypi/pyversions/semantic_version.svg
+    :target: https://pypi.python.org/pypi/semantic_version/
+    :alt: Supported Python versions
+
+.. image:: https://img.shields.io/pypi/wheel/semantic_version.svg
+    :target: https://pypi.python.org/pypi/semantic_version/
+    :alt: Wheel status
+
+.. image:: https://img.shields.io/pypi/l/semantic_version.svg
+    :target: https://pypi.python.org/pypi/semantic_version/
+    :alt: License
+
+Links
+-----
+
+- Package on `PyPI`_: https://pypi.org/project/semantic-version/
+- Doc on `ReadTheDocs `_: https://python-semanticversion.readthedocs.io/
+- Source on `GitHub `_: http://github.com/rbarrois/python-semanticversion/
+- Build on Github Actions: https://github.com/rbarrois/python-semanticversion/actions
+- Semantic Version specification: `SemVer`_
+
+
+Getting started
+===============
+
+Install the package from `PyPI`_, using pip:
+
+.. code-block:: sh
+
+    pip install semantic-version
+
+Or from GitHub:
+
+.. code-block:: sh
+
+    $ git clone git://github.com/rbarrois/python-semanticversion.git
+
+
+Import it in your code:
+
+
+.. code-block:: python
+
+    import semantic_version
+
+
+This module provides classes to handle semantic versions:
+
+- ``Version`` represents a version number (``0.1.1-alpha+build.2012-05-15``)
+- ``BaseSpec``-derived classes represent requirement specifications (``>=0.1.1,<0.3.0``):
+
+  - ``SimpleSpec`` describes a natural description syntax
+  - ``NpmSpec`` is used for NPM-style range descriptions.
+
+Versions
+--------
+
+Defining a ``Version`` is quite simple:
+
+
+.. code-block:: pycon
+
+    >>> import semantic_version
+    >>> v = semantic_version.Version('0.1.1')
+    >>> v.major
+    0
+    >>> v.minor
+    1
+    >>> v.patch
+    1
+    >>> v.prerelease
+    []
+    >>> v.build
+    []
+    >>> list(v)
+    [0, 1, 1, [], []]
+
+If the provided version string is invalid, a ``ValueError`` will be raised:
+
+.. code-block:: pycon
+
+    >>> semantic_version.Version('0.1')
+    Traceback (most recent call last):
+      File "", line 1, in 
+      File "/Users/rbarrois/dev/semantic_version/src/semantic_version/base.py", line 64, in __init__
+        major, minor, patch, prerelease, build = self.parse(version_string, partial)
+      File "/Users/rbarrois/dev/semantic_version/src/semantic_version/base.py", line 86, in parse
+        raise ValueError('Invalid version string: %r' % version_string)
+    ValueError: Invalid version string: '0.1'
+
+
+One may also create a ``Version`` with named components:
+
+.. code-block:: pycon
+
+    >>> semantic_version.Version(major=0, minor=1, patch=2)
+    Version('0.1.2')
+
+In that case, ``major``, ``minor`` and ``patch`` are mandatory, and must be integers.
+``prerelease`` and ``build``, if provided, must be tuples of strings:
+
+.. code-block:: pycon
+
+    >>> semantic_version.Version(major=0, minor=1, patch=2, prerelease=('alpha', '2'))
+    Version('0.1.2-alpha.2')
+
+
+Some user-supplied input might not match the semantic version scheme.
+For such cases, the ``Version.coerce`` method will try to convert any
+version-like string into a valid semver version:
+
+.. code-block:: pycon
+
+    >>> Version.coerce('0')
+    Version('0.0.0')
+    >>> Version.coerce('0.1.2.3.4')
+    Version('0.1.2+3.4')
+    >>> Version.coerce('0.1.2a3')
+    Version('0.1.2-a3')
+
+Working with versions
+"""""""""""""""""""""
+
+Obviously, versions can be compared:
+
+
+.. code-block:: pycon
+
+    >>> semantic_version.Version('0.1.1') < semantic_version.Version('0.1.2')
+    True
+    >>> semantic_version.Version('0.1.1') > semantic_version.Version('0.1.1-alpha')
+    True
+    >>> semantic_version.Version('0.1.1') <= semantic_version.Version('0.1.1-alpha')
+    False
+
+You can also get a new version that represents a bump in one of the version levels:
+
+.. code-block:: pycon
+
+    >>> v = semantic_version.Version('0.1.1+build')
+    >>> new_v = v.next_major()
+    >>> str(new_v)
+    '1.0.0'
+    >>> v = semantic_version.Version('1.1.1+build')
+    >>> new_v = v.next_minor()
+    >>> str(new_v)
+    '1.2.0'
+    >>> v = semantic_version.Version('1.1.1+build')
+    >>> new_v = v.next_patch()
+    >>> str(new_v)
+    '1.1.2'
+
+
+
+Requirement specification
+-------------------------
+
+python-semanticversion provides a couple of ways to describe a range of accepted
+versions:
+
+- The ``SimpleSpec`` class provides a simple, easily understood scheme --
+  somewhat inspired from PyPI range notations;
+- The ``NpmSpec`` class supports the whole NPM range specification scheme:
+
+  .. code-block:: pycon
+
+      >>> Version('0.1.2') in NpmSpec('0.1.0-alpha.2 .. 0.2.4')
+      True
+      >>> Version('0.1.2') in NpmSpec('>=0.1.1 <0.1.3 || 2.x')
+      True
+      >>> Version('2.3.4') in NpmSpec('>=0.1.1 <0.1.3 || 2.x')
+      True
+
+The ``SimpleSpec`` scheme
+"""""""""""""""""""""""""
+
+Basic usage is simply a comparator and a base version:
+
+.. code-block:: pycon
+
+    >>> s = SimpleSpec('>=0.1.1')  # At least 0.1.1
+    >>> s.match(Version('0.1.1'))
+    True
+    >>> s.match(Version('0.1.1-alpha1'))  # pre-release doesn't satisfy version spec
+    False
+    >>> s.match(Version('0.1.0'))
+    False
+
+Combining specifications can be expressed as follows:
+
+  .. code-block:: pycon
+
+      >>> SimpleSpec('>=0.1.1,<0.3.0')
+
+Simpler test syntax is also available using the ``in`` keyword:
+
+.. code-block:: pycon
+
+    >>> s = SimpleSpec('==0.1.1')
+    >>> Version('0.1.1+git7ccc72') in s  # build variants are equivalent to full versions
+    True
+    >>> Version('0.1.1-alpha1') in s     # pre-release variants don't match the full version.
+    False
+    >>> Version('0.1.2') in s
+    False
+
+
+Refer to the full documentation at
+https://python-semanticversion.readthedocs.io/en/latest/ for more details on the
+``SimpleSpec`` scheme.
+
+
+
+Using a specification
+"""""""""""""""""""""
+
+The ``SimpleSpec.filter`` method filters an iterable of ``Version``:
+
+.. code-block:: pycon
+
+    >>> s = SimpleSpec('>=0.1.0,<0.4.0')
+    >>> versions = (Version('0.%d.0' % i) for i in range(6))
+    >>> for v in s.filter(versions):
+    ...     print v
+    0.1.0
+    0.2.0
+    0.3.0
+
+It is also possible to select the 'best' version from such iterables:
+
+
+.. code-block:: pycon
+
+    >>> s = SimpleSpec('>=0.1.0,<0.4.0')
+    >>> versions = (Version('0.%d.0' % i) for i in range(6))
+    >>> s.select(versions)
+    Version('0.3.0')
+
+
+
+Contributing
+============
+
+In order to contribute to the source code:
+
+- Open an issue on `GitHub`_: https://github.com/rbarrois/python-semanticversion/issues
+- Fork the `repository `_
+  and submit a pull request on `GitHub`_
+- Or send me a patch (mailto:raphael.barrois+semver@polytechnique.org)
+
+When submitting patches or pull requests, you should respect the following rules:
+
+- Coding conventions are based on :pep:`8`
+- The whole test suite must pass after adding the changes
+- The test coverage for a new feature must be 100%
+- New features and methods should be documented in the ``reference`` section
+  and included in the ``changelog``
+- Include your name in the ``contributors`` section
+
+.. note:: All files should contain the following header::
+
+          # -*- encoding: utf-8 -*-
+          # Copyright (c) The python-semanticversion project
+
+.. _SemVer: http://semver.org/
+.. _PyPI: http://pypi.python.org/
+
+
diff --git a/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/RECORD b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..37bfa1152d3b51f340dcfe2b816ca67428874924
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/RECORD
@@ -0,0 +1,12 @@
+semantic_version-2.10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+semantic_version-2.10.0.dist-info/LICENSE,sha256=qF5-8vvGcNJnge1oRM0xp-itpl0hMo91oLAkAvquN-o,1317
+semantic_version-2.10.0.dist-info/METADATA,sha256=dBTUaaVpBGtqJGv7HxBaqxt6v9wyqVJT8VQy6jAVmqY,9687
+semantic_version-2.10.0.dist-info/RECORD,,
+semantic_version-2.10.0.dist-info/WHEEL,sha256=Z-nyYpwrcSqxfdux5Mbn_DQ525iP7J2DG3JgGvOYyTQ,110
+semantic_version-2.10.0.dist-info/top_level.txt,sha256=8WNFqF6w9sgwWGOgIxBq65HQ6zakOE7tCaGKz0inQlI,17
+semantic_version/__init__.py,sha256=6f5c-uBdxzZyyMmKQbijcQFQ_km9pCz5C5YWXW1B048,540
+semantic_version/__pycache__/__init__.cpython-311.pyc,,
+semantic_version/__pycache__/base.cpython-311.pyc,,
+semantic_version/__pycache__/django_fields.cpython-311.pyc,,
+semantic_version/base.py,sha256=WuLdqIg4g9zruxYsrPgoc8uaRjD8rwG6onWGTwylcQQ,48115
+semantic_version/django_fields.py,sha256=ctqNHIrK2BwhqEkXcUBbRvTGO7wZVdJU1ub-MTyqCt0,3510
diff --git a/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/WHEEL b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..01b8fc7d4a10cb8b4f1d21f11d3398d07d6b3478
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.36.2)
+Root-Is-Purelib: true
+Tag: py2-none-any
+Tag: py3-none-any
+
diff --git a/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/top_level.txt b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..fe3c35c52dae41a319c987afce4b234e644f5a70
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version-2.10.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+semantic_version
diff --git a/lib/python3.11/site-packages/semantic_version/__init__.py b/lib/python3.11/site-packages/semantic_version/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1528bda574c4e50f10e99a46551a4a4d9378a6b2
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version/__init__.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+
+from .base import compare, match, validate, SimpleSpec, NpmSpec, Spec, SpecItem, Version
+
+
+__author__ = "Raphaël Barrois "
+try:
+    # Python 3.8+
+    from importlib.metadata import version
+
+    __version__ = version("semantic_version")
+except ImportError:
+    import pkg_resources
+
+    __version__ = pkg_resources.get_distribution("semantic_version").version
diff --git a/lib/python3.11/site-packages/semantic_version/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/semantic_version/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6752e13b01a1ec33794100556834c4604c8196c6
Binary files /dev/null and b/lib/python3.11/site-packages/semantic_version/__pycache__/__init__.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/semantic_version/__pycache__/base.cpython-311.pyc b/lib/python3.11/site-packages/semantic_version/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b9b139d36eee747843ed01df52b31107071821b
Binary files /dev/null and b/lib/python3.11/site-packages/semantic_version/__pycache__/base.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/semantic_version/__pycache__/django_fields.cpython-311.pyc b/lib/python3.11/site-packages/semantic_version/__pycache__/django_fields.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f8af2eb715f9d08f21d5b8e0f4e06ccb078cd43
Binary files /dev/null and b/lib/python3.11/site-packages/semantic_version/__pycache__/django_fields.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/semantic_version/base.py b/lib/python3.11/site-packages/semantic_version/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..777c27ac463f34996d0281fb7a68e5f6c7fb9a9c
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version/base.py
@@ -0,0 +1,1449 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+import functools
+import re
+import warnings
+
+
+def _has_leading_zero(value):
+    return (value
+            and value[0] == '0'
+            and value.isdigit()
+            and value != '0')
+
+
+class MaxIdentifier(object):
+    __slots__ = []
+
+    def __repr__(self):
+        return 'MaxIdentifier()'
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__)
+
+
+@functools.total_ordering
+class NumericIdentifier(object):
+    __slots__ = ['value']
+
+    def __init__(self, value):
+        self.value = int(value)
+
+    def __repr__(self):
+        return 'NumericIdentifier(%r)' % self.value
+
+    def __eq__(self, other):
+        if isinstance(other, NumericIdentifier):
+            return self.value == other.value
+        return NotImplemented
+
+    def __lt__(self, other):
+        if isinstance(other, MaxIdentifier):
+            return True
+        elif isinstance(other, AlphaIdentifier):
+            return True
+        elif isinstance(other, NumericIdentifier):
+            return self.value < other.value
+        else:
+            return NotImplemented
+
+
+@functools.total_ordering
+class AlphaIdentifier(object):
+    __slots__ = ['value']
+
+    def __init__(self, value):
+        self.value = value.encode('ascii')
+
+    def __repr__(self):
+        return 'AlphaIdentifier(%r)' % self.value
+
+    def __eq__(self, other):
+        if isinstance(other, AlphaIdentifier):
+            return self.value == other.value
+        return NotImplemented
+
+    def __lt__(self, other):
+        if isinstance(other, MaxIdentifier):
+            return True
+        elif isinstance(other, NumericIdentifier):
+            return False
+        elif isinstance(other, AlphaIdentifier):
+            return self.value < other.value
+        else:
+            return NotImplemented
+
+
+class Version(object):
+
+    version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(?:-([0-9a-zA-Z.-]+))?(?:\+([0-9a-zA-Z.-]+))?$')
+    partial_version_re = re.compile(r'^(\d+)(?:\.(\d+)(?:\.(\d+))?)?(?:-([0-9a-zA-Z.-]*))?(?:\+([0-9a-zA-Z.-]*))?$')
+
+    def __init__(
+            self,
+            version_string=None,
+            major=None,
+            minor=None,
+            patch=None,
+            prerelease=None,
+            build=None,
+            partial=False):
+        if partial:
+            warnings.warn(
+                "Partial versions will be removed in 3.0; use SimpleSpec('1.x.x') instead.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+        has_text = version_string is not None
+        has_parts = not (major is minor is patch is prerelease is build is None)
+        if not has_text ^ has_parts:
+            raise ValueError("Call either Version('1.2.3') or Version(major=1, ...).")
+
+        if has_text:
+            major, minor, patch, prerelease, build = self.parse(version_string, partial)
+        else:
+            # Convenience: allow to omit prerelease/build.
+            prerelease = tuple(prerelease or ())
+            if not partial:
+                build = tuple(build or ())
+            self._validate_kwargs(major, minor, patch, prerelease, build, partial)
+
+        self.major = major
+        self.minor = minor
+        self.patch = patch
+        self.prerelease = prerelease
+        self.build = build
+
+        self.partial = partial
+
+        # Cached precedence keys
+        # _cmp_precedence_key is used for semver-precedence comparison
+        self._cmp_precedence_key = self._build_precedence_key(with_build=False)
+        # _sort_precedence_key is used for self.precedence_key, esp. for sorted(...)
+        self._sort_precedence_key = self._build_precedence_key(with_build=True)
+
+    @classmethod
+    def _coerce(cls, value, allow_none=False):
+        if value is None and allow_none:
+            return value
+        return int(value)
+
+    def next_major(self):
+        if self.prerelease and self.minor == self.patch == 0:
+            return Version(
+                major=self.major,
+                minor=0,
+                patch=0,
+                partial=self.partial,
+            )
+        else:
+            return Version(
+                major=self.major + 1,
+                minor=0,
+                patch=0,
+                partial=self.partial,
+            )
+
+    def next_minor(self):
+        if self.prerelease and self.patch == 0:
+            return Version(
+                major=self.major,
+                minor=self.minor,
+                patch=0,
+                partial=self.partial,
+            )
+        else:
+            return Version(
+                major=self.major,
+                minor=self.minor + 1,
+                patch=0,
+                partial=self.partial,
+            )
+
+    def next_patch(self):
+        if self.prerelease:
+            return Version(
+                major=self.major,
+                minor=self.minor,
+                patch=self.patch,
+                partial=self.partial,
+            )
+        else:
+            return Version(
+                major=self.major,
+                minor=self.minor,
+                patch=self.patch + 1,
+                partial=self.partial,
+            )
+
+    def truncate(self, level='patch'):
+        """Return a new Version object, truncated up to the selected level."""
+        if level == 'build':
+            return self
+        elif level == 'prerelease':
+            return Version(
+                major=self.major,
+                minor=self.minor,
+                patch=self.patch,
+                prerelease=self.prerelease,
+                partial=self.partial,
+            )
+        elif level == 'patch':
+            return Version(
+                major=self.major,
+                minor=self.minor,
+                patch=self.patch,
+                partial=self.partial,
+            )
+        elif level == 'minor':
+            return Version(
+                major=self.major,
+                minor=self.minor,
+                patch=None if self.partial else 0,
+                partial=self.partial,
+            )
+        elif level == 'major':
+            return Version(
+                major=self.major,
+                minor=None if self.partial else 0,
+                patch=None if self.partial else 0,
+                partial=self.partial,
+            )
+        else:
+            raise ValueError("Invalid truncation level `%s`." % level)
+
+    @classmethod
+    def coerce(cls, version_string, partial=False):
+        """Coerce an arbitrary version string into a semver-compatible one.
+
+        The rule is:
+        - If not enough components, fill minor/patch with zeroes; unless
+          partial=True
+        - If more than 3 dot-separated components, extra components are "build"
+          data. If some "build" data already appeared, append it to the
+          extra components
+
+        Examples:
+            >>> Version.coerce('0.1')
+            Version(0, 1, 0)
+            >>> Version.coerce('0.1.2.3')
+            Version(0, 1, 2, (), ('3',))
+            >>> Version.coerce('0.1.2.3+4')
+            Version(0, 1, 2, (), ('3', '4'))
+            >>> Version.coerce('0.1+2-3+4_5')
+            Version(0, 1, 0, (), ('2-3', '4-5'))
+        """
+        base_re = re.compile(r'^\d+(?:\.\d+(?:\.\d+)?)?')
+
+        match = base_re.match(version_string)
+        if not match:
+            raise ValueError(
+                "Version string lacks a numerical component: %r"
+                % version_string
+            )
+
+        version = version_string[:match.end()]
+        if not partial:
+            # We need a not-partial version.
+            while version.count('.') < 2:
+                version += '.0'
+
+        # Strip leading zeros in components
+        # Version is of the form nn, nn.pp or nn.pp.qq
+        version = '.'.join(
+            # If the part was '0', we end up with an empty string.
+            part.lstrip('0') or '0'
+            for part in version.split('.')
+        )
+
+        if match.end() == len(version_string):
+            return Version(version, partial=partial)
+
+        rest = version_string[match.end():]
+
+        # Cleanup the 'rest'
+        rest = re.sub(r'[^a-zA-Z0-9+.-]', '-', rest)
+
+        if rest[0] == '+':
+            # A 'build' component
+            prerelease = ''
+            build = rest[1:]
+        elif rest[0] == '.':
+            # An extra version component, probably 'build'
+            prerelease = ''
+            build = rest[1:]
+        elif rest[0] == '-':
+            rest = rest[1:]
+            if '+' in rest:
+                prerelease, build = rest.split('+', 1)
+            else:
+                prerelease, build = rest, ''
+        elif '+' in rest:
+            prerelease, build = rest.split('+', 1)
+        else:
+            prerelease, build = rest, ''
+
+        build = build.replace('+', '.')
+
+        if prerelease:
+            version = '%s-%s' % (version, prerelease)
+        if build:
+            version = '%s+%s' % (version, build)
+
+        return cls(version, partial=partial)
+
+    @classmethod
+    def parse(cls, version_string, partial=False, coerce=False):
+        """Parse a version string into a tuple of components:
+           (major, minor, patch, prerelease, build).
+
+        Args:
+            version_string (str), the version string to parse
+            partial (bool), whether to accept incomplete input
+            coerce (bool), whether to try to map the passed in string into a
+                valid Version.
+        """
+        if not version_string:
+            raise ValueError('Invalid empty version string: %r' % version_string)
+
+        if partial:
+            version_re = cls.partial_version_re
+        else:
+            version_re = cls.version_re
+
+        match = version_re.match(version_string)
+        if not match:
+            raise ValueError('Invalid version string: %r' % version_string)
+
+        major, minor, patch, prerelease, build = match.groups()
+
+        if _has_leading_zero(major):
+            raise ValueError("Invalid leading zero in major: %r" % version_string)
+        if _has_leading_zero(minor):
+            raise ValueError("Invalid leading zero in minor: %r" % version_string)
+        if _has_leading_zero(patch):
+            raise ValueError("Invalid leading zero in patch: %r" % version_string)
+
+        major = int(major)
+        minor = cls._coerce(minor, partial)
+        patch = cls._coerce(patch, partial)
+
+        if prerelease is None:
+            if partial and (build is None):
+                # No build info, strip here
+                return (major, minor, patch, None, None)
+            else:
+                prerelease = ()
+        elif prerelease == '':
+            prerelease = ()
+        else:
+            prerelease = tuple(prerelease.split('.'))
+            cls._validate_identifiers(prerelease, allow_leading_zeroes=False)
+
+        if build is None:
+            if partial:
+                build = None
+            else:
+                build = ()
+        elif build == '':
+            build = ()
+        else:
+            build = tuple(build.split('.'))
+            cls._validate_identifiers(build, allow_leading_zeroes=True)
+
+        return (major, minor, patch, prerelease, build)
+
+    @classmethod
+    def _validate_identifiers(cls, identifiers, allow_leading_zeroes=False):
+        for item in identifiers:
+            if not item:
+                raise ValueError(
+                    "Invalid empty identifier %r in %r"
+                    % (item, '.'.join(identifiers))
+                )
+
+            if item[0] == '0' and item.isdigit() and item != '0' and not allow_leading_zeroes:
+                raise ValueError("Invalid leading zero in identifier %r" % item)
+
+    @classmethod
+    def _validate_kwargs(cls, major, minor, patch, prerelease, build, partial):
+        if (
+                major != int(major)
+                or minor != cls._coerce(minor, partial)
+                or patch != cls._coerce(patch, partial)
+                or prerelease is None and not partial
+                or build is None and not partial
+        ):
+            raise ValueError(
+                "Invalid kwargs to Version(major=%r, minor=%r, patch=%r, "
+                "prerelease=%r, build=%r, partial=%r" % (
+                    major, minor, patch, prerelease, build, partial
+                ))
+        if prerelease is not None:
+            cls._validate_identifiers(prerelease, allow_leading_zeroes=False)
+        if build is not None:
+            cls._validate_identifiers(build, allow_leading_zeroes=True)
+
+    def __iter__(self):
+        return iter((self.major, self.minor, self.patch, self.prerelease, self.build))
+
+    def __str__(self):
+        version = '%d' % self.major
+        if self.minor is not None:
+            version = '%s.%d' % (version, self.minor)
+        if self.patch is not None:
+            version = '%s.%d' % (version, self.patch)
+
+        if self.prerelease or (self.partial and self.prerelease == () and self.build is None):
+            version = '%s-%s' % (version, '.'.join(self.prerelease))
+        if self.build or (self.partial and self.build == ()):
+            version = '%s+%s' % (version, '.'.join(self.build))
+        return version
+
+    def __repr__(self):
+        return '%s(%r%s)' % (
+            self.__class__.__name__,
+            str(self),
+            ', partial=True' if self.partial else '',
+        )
+
+    def __hash__(self):
+        # We don't include 'partial', since this is strictly equivalent to having
+        # at least a field being `None`.
+        return hash((self.major, self.minor, self.patch, self.prerelease, self.build))
+
+    def _build_precedence_key(self, with_build=False):
+        """Build a precedence key.
+
+        The "build" component should only be used when sorting an iterable
+        of versions.
+        """
+        if self.prerelease:
+            prerelease_key = tuple(
+                NumericIdentifier(part) if part.isdigit() else AlphaIdentifier(part)
+                for part in self.prerelease
+            )
+        else:
+            prerelease_key = (
+                MaxIdentifier(),
+            )
+
+        if not with_build:
+            return (
+                self.major,
+                self.minor,
+                self.patch,
+                prerelease_key,
+            )
+
+        build_key = tuple(
+            NumericIdentifier(part) if part.isdigit() else AlphaIdentifier(part)
+            for part in self.build or ()
+        )
+
+        return (
+            self.major,
+            self.minor,
+            self.patch,
+            prerelease_key,
+            build_key,
+        )
+
+    @property
+    def precedence_key(self):
+        return self._sort_precedence_key
+
+    def __cmp__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        if self < other:
+            return -1
+        elif self > other:
+            return 1
+        elif self == other:
+            return 0
+        else:
+            return NotImplemented
+
+    def __eq__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        return (
+            self.major == other.major
+            and self.minor == other.minor
+            and self.patch == other.patch
+            and (self.prerelease or ()) == (other.prerelease or ())
+            and (self.build or ()) == (other.build or ())
+        )
+
+    def __ne__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        return tuple(self) != tuple(other)
+
+    def __lt__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        return self._cmp_precedence_key < other._cmp_precedence_key
+
+    def __le__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        return self._cmp_precedence_key <= other._cmp_precedence_key
+
+    def __gt__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        return self._cmp_precedence_key > other._cmp_precedence_key
+
+    def __ge__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+        return self._cmp_precedence_key >= other._cmp_precedence_key
+
+
+class SpecItem(object):
+    """A requirement specification."""
+
+    KIND_ANY = '*'
+    KIND_LT = '<'
+    KIND_LTE = '<='
+    KIND_EQUAL = '=='
+    KIND_SHORTEQ = '='
+    KIND_EMPTY = ''
+    KIND_GTE = '>='
+    KIND_GT = '>'
+    KIND_NEQ = '!='
+    KIND_CARET = '^'
+    KIND_TILDE = '~'
+    KIND_COMPATIBLE = '~='
+
+    # Map a kind alias to its full version
+    KIND_ALIASES = {
+        KIND_SHORTEQ: KIND_EQUAL,
+        KIND_EMPTY: KIND_EQUAL,
+    }
+
+    re_spec = re.compile(r'^(<|<=||=|==|>=|>|!=|\^|~|~=)(\d.*)$')
+
+    def __init__(self, requirement_string, _warn=True):
+        if _warn:
+            warnings.warn(
+                "The `SpecItem` class will be removed in 3.0.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+        kind, spec = self.parse(requirement_string)
+        self.kind = kind
+        self.spec = spec
+        self._clause = Spec(requirement_string).clause
+
+    @classmethod
+    def parse(cls, requirement_string):
+        if not requirement_string:
+            raise ValueError("Invalid empty requirement specification: %r" % requirement_string)
+
+        # Special case: the 'any' version spec.
+        if requirement_string == '*':
+            return (cls.KIND_ANY, '')
+
+        match = cls.re_spec.match(requirement_string)
+        if not match:
+            raise ValueError("Invalid requirement specification: %r" % requirement_string)
+
+        kind, version = match.groups()
+        if kind in cls.KIND_ALIASES:
+            kind = cls.KIND_ALIASES[kind]
+
+        spec = Version(version, partial=True)
+        if spec.build is not None and kind not in (cls.KIND_EQUAL, cls.KIND_NEQ):
+            raise ValueError(
+                "Invalid requirement specification %r: build numbers have no ordering."
+                % requirement_string
+            )
+        return (kind, spec)
+
+    @classmethod
+    def from_matcher(cls, matcher):
+        if matcher == Always():
+            return cls('*', _warn=False)
+        elif matcher == Never():
+            return cls('<0.0.0-', _warn=False)
+        elif isinstance(matcher, Range):
+            return cls('%s%s' % (matcher.operator, matcher.target), _warn=False)
+
+    def match(self, version):
+        return self._clause.match(version)
+
+    def __str__(self):
+        return '%s%s' % (self.kind, self.spec)
+
+    def __repr__(self):
+        return '' % (self.kind, self.spec)
+
+    def __eq__(self, other):
+        if not isinstance(other, SpecItem):
+            return NotImplemented
+        return self.kind == other.kind and self.spec == other.spec
+
+    def __hash__(self):
+        return hash((self.kind, self.spec))
+
+
+def compare(v1, v2):
+    return Version(v1).__cmp__(Version(v2))
+
+
+def match(spec, version):
+    return Spec(spec).match(Version(version))
+
+
+def validate(version_string):
+    """Validates a version string againt the SemVer specification."""
+    try:
+        Version.parse(version_string)
+        return True
+    except ValueError:
+        return False
+
+
+DEFAULT_SYNTAX = 'simple'
+
+
+class BaseSpec(object):
+    """A specification of compatible versions.
+
+    Usage:
+    >>> Spec('>=1.0.0', syntax='npm')
+
+    A version matches a specification if it matches any
+    of the clauses of that specification.
+
+    Internally, a Spec is AnyOf(
+        AllOf(Matcher, Matcher, Matcher),
+        AllOf(...),
+    )
+    """
+    SYNTAXES = {}
+
+    @classmethod
+    def register_syntax(cls, subclass):
+        syntax = subclass.SYNTAX
+        if syntax is None:
+            raise ValueError("A Spec needs its SYNTAX field to be set.")
+        elif syntax in cls.SYNTAXES:
+            raise ValueError(
+                "Duplicate syntax for %s: %r, %r"
+                % (syntax, cls.SYNTAXES[syntax], subclass)
+            )
+        cls.SYNTAXES[syntax] = subclass
+        return subclass
+
+    def __init__(self, expression):
+        super(BaseSpec, self).__init__()
+        self.expression = expression
+        self.clause = self._parse_to_clause(expression)
+
+    @classmethod
+    def parse(cls, expression, syntax=DEFAULT_SYNTAX):
+        """Convert a syntax-specific expression into a BaseSpec instance."""
+        return cls.SYNTAXES[syntax](expression)
+
+    @classmethod
+    def _parse_to_clause(cls, expression):
+        """Converts an expression to a clause."""
+        raise NotImplementedError()
+
+    def filter(self, versions):
+        """Filter an iterable of versions satisfying the Spec."""
+        for version in versions:
+            if self.match(version):
+                yield version
+
+    def match(self, version):
+        """Check whether a Version satisfies the Spec."""
+        return self.clause.match(version)
+
+    def select(self, versions):
+        """Select the best compatible version among an iterable of options."""
+        options = list(self.filter(versions))
+        if options:
+            return max(options)
+        return None
+
+    def __contains__(self, version):
+        """Whether `version in self`."""
+        if isinstance(version, Version):
+            return self.match(version)
+        return False
+
+    def __eq__(self, other):
+        if not isinstance(other, self.__class__):
+            return NotImplemented
+
+        return self.clause == other.clause
+
+    def __hash__(self):
+        return hash(self.clause)
+
+    def __str__(self):
+        return self.expression
+
+    def __repr__(self):
+        return '<%s: %r>' % (self.__class__.__name__, self.expression)
+
+
+class Clause(object):
+    __slots__ = []
+
+    def match(self, version):
+        raise NotImplementedError()
+
+    def __and__(self, other):
+        raise NotImplementedError()
+
+    def __or__(self, other):
+        raise NotImplementedError()
+
+    def __eq__(self, other):
+        raise NotImplementedError()
+
+    def prettyprint(self, indent='\t'):
+        """Pretty-print the clause.
+        """
+        return '\n'.join(self._pretty()).replace('\t', indent)
+
+    def _pretty(self):
+        """Actual pretty-printing logic.
+
+        Yields:
+            A list of string. Indentation is performed with \t.
+        """
+        yield repr(self)
+
+    def __ne__(self, other):
+        return not self == other
+
+    def simplify(self):
+        return self
+
+
+class AnyOf(Clause):
+    __slots__ = ['clauses']
+
+    def __init__(self, *clauses):
+        super(AnyOf, self).__init__()
+        self.clauses = frozenset(clauses)
+
+    def match(self, version):
+        return any(c.match(version) for c in self.clauses)
+
+    def simplify(self):
+        subclauses = set()
+        for clause in self.clauses:
+            simplified = clause.simplify()
+            if isinstance(simplified, AnyOf):
+                subclauses |= simplified.clauses
+            elif simplified == Never():
+                continue
+            else:
+                subclauses.add(simplified)
+        if len(subclauses) == 1:
+            return subclauses.pop()
+        return AnyOf(*subclauses)
+
+    def __hash__(self):
+        return hash((AnyOf, self.clauses))
+
+    def __iter__(self):
+        return iter(self.clauses)
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__) and self.clauses == other.clauses
+
+    def __and__(self, other):
+        if isinstance(other, AllOf):
+            return other & self
+        elif isinstance(other, Matcher) or isinstance(other, AnyOf):
+            return AllOf(self, other)
+        else:
+            return NotImplemented
+
+    def __or__(self, other):
+        if isinstance(other, AnyOf):
+            clauses = list(self.clauses | other.clauses)
+        elif isinstance(other, Matcher) or isinstance(other, AllOf):
+            clauses = list(self.clauses | set([other]))
+        else:
+            return NotImplemented
+        return AnyOf(*clauses)
+
+    def __repr__(self):
+        return 'AnyOf(%s)' % ', '.join(sorted(repr(c) for c in self.clauses))
+
+    def _pretty(self):
+        yield 'AnyOF('
+        for clause in self.clauses:
+            lines = list(clause._pretty())
+            for line in lines[:-1]:
+                yield '\t' + line
+            yield '\t' + lines[-1] + ','
+        yield ')'
+
+
+class AllOf(Clause):
+    __slots__ = ['clauses']
+
+    def __init__(self, *clauses):
+        super(AllOf, self).__init__()
+        self.clauses = frozenset(clauses)
+
+    def match(self, version):
+        return all(clause.match(version) for clause in self.clauses)
+
+    def simplify(self):
+        subclauses = set()
+        for clause in self.clauses:
+            simplified = clause.simplify()
+            if isinstance(simplified, AllOf):
+                subclauses |= simplified.clauses
+            elif simplified == Always():
+                continue
+            else:
+                subclauses.add(simplified)
+        if len(subclauses) == 1:
+            return subclauses.pop()
+        return AllOf(*subclauses)
+
+    def __hash__(self):
+        return hash((AllOf, self.clauses))
+
+    def __iter__(self):
+        return iter(self.clauses)
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__) and self.clauses == other.clauses
+
+    def __and__(self, other):
+        if isinstance(other, Matcher) or isinstance(other, AnyOf):
+            clauses = list(self.clauses | set([other]))
+        elif isinstance(other, AllOf):
+            clauses = list(self.clauses | other.clauses)
+        else:
+            return NotImplemented
+        return AllOf(*clauses)
+
+    def __or__(self, other):
+        if isinstance(other, AnyOf):
+            return other | self
+        elif isinstance(other, Matcher):
+            return AnyOf(self, AllOf(other))
+        elif isinstance(other, AllOf):
+            return AnyOf(self, other)
+        else:
+            return NotImplemented
+
+    def __repr__(self):
+        return 'AllOf(%s)' % ', '.join(sorted(repr(c) for c in self.clauses))
+
+    def _pretty(self):
+        yield 'AllOF('
+        for clause in self.clauses:
+            lines = list(clause._pretty())
+            for line in lines[:-1]:
+                yield '\t' + line
+            yield '\t' + lines[-1] + ','
+        yield ')'
+
+
+class Matcher(Clause):
+    __slots__ = []
+
+    def __and__(self, other):
+        if isinstance(other, AllOf):
+            return other & self
+        elif isinstance(other, Matcher) or isinstance(other, AnyOf):
+            return AllOf(self, other)
+        else:
+            return NotImplemented
+
+    def __or__(self, other):
+        if isinstance(other, AnyOf):
+            return other | self
+        elif isinstance(other, Matcher) or isinstance(other, AllOf):
+            return AnyOf(self, other)
+        else:
+            return NotImplemented
+
+
+class Never(Matcher):
+    __slots__ = []
+
+    def match(self, version):
+        return False
+
+    def __hash__(self):
+        return hash((Never,))
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__)
+
+    def __and__(self, other):
+        return self
+
+    def __or__(self, other):
+        return other
+
+    def __repr__(self):
+        return 'Never()'
+
+
+class Always(Matcher):
+    __slots__ = []
+
+    def match(self, version):
+        return True
+
+    def __hash__(self):
+        return hash((Always,))
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__)
+
+    def __and__(self, other):
+        return other
+
+    def __or__(self, other):
+        return self
+
+    def __repr__(self):
+        return 'Always()'
+
+
+class Range(Matcher):
+    OP_EQ = '=='
+    OP_GT = '>'
+    OP_GTE = '>='
+    OP_LT = '<'
+    OP_LTE = '<='
+    OP_NEQ = '!='
+
+    # <1.2.3 matches 1.2.3-a1
+    PRERELEASE_ALWAYS = 'always'
+    # <1.2.3 does not match 1.2.3-a1
+    PRERELEASE_NATURAL = 'natural'
+    # 1.2.3-a1 is only considered if target == 1.2.3-xxx
+    PRERELEASE_SAMEPATCH = 'same-patch'
+
+    # 1.2.3 matches 1.2.3+*
+    BUILD_IMPLICIT = 'implicit'
+    # 1.2.3 matches only 1.2.3, not 1.2.3+4
+    BUILD_STRICT = 'strict'
+
+    __slots__ = ['operator', 'target', 'prerelease_policy', 'build_policy']
+
+    def __init__(self, operator, target, prerelease_policy=PRERELEASE_NATURAL, build_policy=BUILD_IMPLICIT):
+        super(Range, self).__init__()
+        if target.build and operator not in (self.OP_EQ, self.OP_NEQ):
+            raise ValueError(
+                "Invalid range %s%s: build numbers have no ordering."
+                % (operator, target))
+        self.operator = operator
+        self.target = target
+        self.prerelease_policy = prerelease_policy
+        self.build_policy = self.BUILD_STRICT if target.build else build_policy
+
+    def match(self, version):
+        if self.build_policy != self.BUILD_STRICT:
+            version = version.truncate('prerelease')
+
+        if version.prerelease:
+            same_patch = self.target.truncate() == version.truncate()
+
+            if self.prerelease_policy == self.PRERELEASE_SAMEPATCH and not same_patch:
+                return False
+
+        if self.operator == self.OP_EQ:
+            if self.build_policy == self.BUILD_STRICT:
+                return (
+                    self.target.truncate('prerelease') == version.truncate('prerelease')
+                    and version.build == self.target.build
+                )
+            return version == self.target
+        elif self.operator == self.OP_GT:
+            return version > self.target
+        elif self.operator == self.OP_GTE:
+            return version >= self.target
+        elif self.operator == self.OP_LT:
+            if (
+                version.prerelease
+                and self.prerelease_policy == self.PRERELEASE_NATURAL
+                and version.truncate() == self.target.truncate()
+                and not self.target.prerelease
+            ):
+                return False
+            return version < self.target
+        elif self.operator == self.OP_LTE:
+            return version <= self.target
+        else:
+            assert self.operator == self.OP_NEQ
+            if self.build_policy == self.BUILD_STRICT:
+                return not (
+                    self.target.truncate('prerelease') == version.truncate('prerelease')
+                    and version.build == self.target.build
+                )
+
+            if (
+                version.prerelease
+                and self.prerelease_policy == self.PRERELEASE_NATURAL
+                and version.truncate() == self.target.truncate()
+                and not self.target.prerelease
+            ):
+                return False
+            return version != self.target
+
+    def __hash__(self):
+        return hash((Range, self.operator, self.target, self.prerelease_policy))
+
+    def __eq__(self, other):
+        return (
+            isinstance(other, self.__class__)
+            and self.operator == other.operator
+            and self.target == other.target
+            and self.prerelease_policy == other.prerelease_policy
+        )
+
+    def __str__(self):
+        return '%s%s' % (self.operator, self.target)
+
+    def __repr__(self):
+        policy_part = (
+            '' if self.prerelease_policy == self.PRERELEASE_NATURAL
+            else ', prerelease_policy=%r' % self.prerelease_policy
+        ) + (
+            '' if self.build_policy == self.BUILD_IMPLICIT
+            else ', build_policy=%r' % self.build_policy
+        )
+        return 'Range(%r, %r%s)' % (
+            self.operator,
+            self.target,
+            policy_part,
+        )
+
+
+@BaseSpec.register_syntax
+class SimpleSpec(BaseSpec):
+
+    SYNTAX = 'simple'
+
+    @classmethod
+    def _parse_to_clause(cls, expression):
+        return cls.Parser.parse(expression)
+
+    class Parser:
+        NUMBER = r'\*|0|[1-9][0-9]*'
+        NAIVE_SPEC = re.compile(r"""^
+            (?P<|<=||=|==|>=|>|!=|\^|~|~=)
+            (?P{nb})(?:\.(?P{nb})(?:\.(?P{nb}))?)?
+            (?:-(?P[a-z0-9A-Z.-]*))?
+            (?:\+(?P[a-z0-9A-Z.-]*))?
+            $
+            """.format(nb=NUMBER),
+            re.VERBOSE,
+        )
+
+        @classmethod
+        def parse(cls, expression):
+            blocks = expression.split(',')
+            clause = Always()
+            for block in blocks:
+                if not cls.NAIVE_SPEC.match(block):
+                    raise ValueError("Invalid simple block %r" % block)
+                clause &= cls.parse_block(block)
+
+            return clause
+
+        PREFIX_CARET = '^'
+        PREFIX_TILDE = '~'
+        PREFIX_COMPATIBLE = '~='
+        PREFIX_EQ = '=='
+        PREFIX_NEQ = '!='
+        PREFIX_GT = '>'
+        PREFIX_GTE = '>='
+        PREFIX_LT = '<'
+        PREFIX_LTE = '<='
+
+        PREFIX_ALIASES = {
+            '=': PREFIX_EQ,
+            '': PREFIX_EQ,
+        }
+
+        EMPTY_VALUES = ['*', 'x', 'X', None]
+
+        @classmethod
+        def parse_block(cls, expr):
+            if not cls.NAIVE_SPEC.match(expr):
+                raise ValueError("Invalid simple spec component: %r" % expr)
+            prefix, major_t, minor_t, patch_t, prerel, build = cls.NAIVE_SPEC.match(expr).groups()
+            prefix = cls.PREFIX_ALIASES.get(prefix, prefix)
+
+            major = None if major_t in cls.EMPTY_VALUES else int(major_t)
+            minor = None if minor_t in cls.EMPTY_VALUES else int(minor_t)
+            patch = None if patch_t in cls.EMPTY_VALUES else int(patch_t)
+
+            if major is None:  # '*'
+                target = Version(major=0, minor=0, patch=0)
+                if prefix not in (cls.PREFIX_EQ, cls.PREFIX_GTE):
+                    raise ValueError("Invalid simple spec: %r" % expr)
+            elif minor is None:
+                target = Version(major=major, minor=0, patch=0)
+            elif patch is None:
+                target = Version(major=major, minor=minor, patch=0)
+            else:
+                target = Version(
+                    major=major,
+                    minor=minor,
+                    patch=patch,
+                    prerelease=prerel.split('.') if prerel else (),
+                    build=build.split('.') if build else (),
+                )
+
+            if (major is None or minor is None or patch is None) and (prerel or build):
+                raise ValueError("Invalid simple spec: %r" % expr)
+
+            if build is not None and prefix not in (cls.PREFIX_EQ, cls.PREFIX_NEQ):
+                raise ValueError("Invalid simple spec: %r" % expr)
+
+            if prefix == cls.PREFIX_CARET:
+                # Accept anything with the same most-significant digit
+                if target.major:
+                    high = target.next_major()
+                elif target.minor:
+                    high = target.next_minor()
+                else:
+                    high = target.next_patch()
+                return Range(Range.OP_GTE, target) & Range(Range.OP_LT, high)
+
+            elif prefix == cls.PREFIX_TILDE:
+                assert major is not None
+                # Accept any higher patch in the same minor
+                # Might go higher if the initial version was a partial
+                if minor is None:
+                    high = target.next_major()
+                else:
+                    high = target.next_minor()
+                return Range(Range.OP_GTE, target) & Range(Range.OP_LT, high)
+
+            elif prefix == cls.PREFIX_COMPATIBLE:
+                assert major is not None
+                # ~1 is 1.0.0..2.0.0; ~=2.2 is 2.2.0..3.0.0; ~=1.4.5 is 1.4.5..1.5.0
+                if minor is None or patch is None:
+                    # We got a partial version
+                    high = target.next_major()
+                else:
+                    high = target.next_minor()
+                return Range(Range.OP_GTE, target) & Range(Range.OP_LT, high)
+
+            elif prefix == cls.PREFIX_EQ:
+                if major is None:
+                    return Range(Range.OP_GTE, target)
+                elif minor is None:
+                    return Range(Range.OP_GTE, target) & Range(Range.OP_LT, target.next_major())
+                elif patch is None:
+                    return Range(Range.OP_GTE, target) & Range(Range.OP_LT, target.next_minor())
+                elif build == '':
+                    return Range(Range.OP_EQ, target, build_policy=Range.BUILD_STRICT)
+                else:
+                    return Range(Range.OP_EQ, target)
+
+            elif prefix == cls.PREFIX_NEQ:
+                assert major is not None
+                if minor is None:
+                    # !=1.x => <1.0.0 || >=2.0.0
+                    return Range(Range.OP_LT, target) | Range(Range.OP_GTE, target.next_major())
+                elif patch is None:
+                    # !=1.2.x => <1.2.0 || >=1.3.0
+                    return Range(Range.OP_LT, target) | Range(Range.OP_GTE, target.next_minor())
+                elif prerel == '':
+                    # !=1.2.3-
+                    return Range(Range.OP_NEQ, target, prerelease_policy=Range.PRERELEASE_ALWAYS)
+                elif build == '':
+                    # !=1.2.3+ or !=1.2.3-a2+
+                    return Range(Range.OP_NEQ, target, build_policy=Range.BUILD_STRICT)
+                else:
+                    return Range(Range.OP_NEQ, target)
+
+            elif prefix == cls.PREFIX_GT:
+                assert major is not None
+                if minor is None:
+                    # >1.x => >=2.0
+                    return Range(Range.OP_GTE, target.next_major())
+                elif patch is None:
+                    return Range(Range.OP_GTE, target.next_minor())
+                else:
+                    return Range(Range.OP_GT, target)
+
+            elif prefix == cls.PREFIX_GTE:
+                return Range(Range.OP_GTE, target)
+
+            elif prefix == cls.PREFIX_LT:
+                assert major is not None
+                if prerel == '':
+                    # <1.2.3-
+                    return Range(Range.OP_LT, target, prerelease_policy=Range.PRERELEASE_ALWAYS)
+                return Range(Range.OP_LT, target)
+
+            else:
+                assert prefix == cls.PREFIX_LTE
+                assert major is not None
+                if minor is None:
+                    # <=1.x => <2.0
+                    return Range(Range.OP_LT, target.next_major())
+                elif patch is None:
+                    return Range(Range.OP_LT, target.next_minor())
+                else:
+                    return Range(Range.OP_LTE, target)
+
+
+class LegacySpec(SimpleSpec):
+    def __init__(self, *expressions):
+        warnings.warn(
+            "The Spec() class will be removed in 3.1; use SimpleSpec() instead.",
+            PendingDeprecationWarning,
+            stacklevel=2,
+        )
+
+        if len(expressions) > 1:
+            warnings.warn(
+                "Passing 2+ arguments to SimpleSpec will be removed in 3.0; concatenate them with ',' instead.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+        expression = ','.join(expressions)
+        super(LegacySpec, self).__init__(expression)
+
+    @property
+    def specs(self):
+        return list(self)
+
+    def __iter__(self):
+        warnings.warn(
+            "Iterating over the components of a SimpleSpec object will be removed in 3.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        try:
+            clauses = list(self.clause)
+        except TypeError:  # Not an iterable
+            clauses = [self.clause]
+        for clause in clauses:
+            yield SpecItem.from_matcher(clause)
+
+
+Spec = LegacySpec
+
+
+@BaseSpec.register_syntax
+class NpmSpec(BaseSpec):
+    SYNTAX = 'npm'
+
+    @classmethod
+    def _parse_to_clause(cls, expression):
+        return cls.Parser.parse(expression)
+
+    class Parser:
+        JOINER = '||'
+        HYPHEN = ' - '
+
+        NUMBER = r'x|X|\*|0|[1-9][0-9]*'
+        PART = r'[a-zA-Z0-9.-]*'
+        NPM_SPEC_BLOCK = re.compile(r"""
+            ^(?:v)?                     # Strip optional initial v
+            (?P<|<=|>=|>|=|\^|~|)   # Operator, can be empty
+            (?P{nb})(?:\.(?P{nb})(?:\.(?P{nb}))?)?
+            (?:-(?P{part}))?    # Optional re-release
+            (?:\+(?P{part}))?    # Optional build
+            $""".format(nb=NUMBER, part=PART),
+            re.VERBOSE,
+        )
+
+        @classmethod
+        def range(cls, operator, target):
+            return Range(operator, target, prerelease_policy=Range.PRERELEASE_SAMEPATCH)
+
+        @classmethod
+        def parse(cls, expression):
+            result = Never()
+            groups = expression.split(cls.JOINER)
+            for group in groups:
+                group = group.strip()
+                if not group:
+                    group = '>=0.0.0'
+
+                subclauses = []
+                if cls.HYPHEN in group:
+                    low, high = group.split(cls.HYPHEN, 2)
+                    subclauses = cls.parse_simple('>=' + low) + cls.parse_simple('<=' + high)
+
+                else:
+                    blocks = group.split(' ')
+                    for block in blocks:
+                        if not cls.NPM_SPEC_BLOCK.match(block):
+                            raise ValueError("Invalid NPM block in %r: %r" % (expression, block))
+
+                        subclauses.extend(cls.parse_simple(block))
+
+                prerelease_clauses = []
+                non_prerel_clauses = []
+                for clause in subclauses:
+                    if clause.target.prerelease:
+                        if clause.operator in (Range.OP_GT, Range.OP_GTE):
+                            prerelease_clauses.append(Range(
+                                operator=Range.OP_LT,
+                                target=Version(
+                                    major=clause.target.major,
+                                    minor=clause.target.minor,
+                                    patch=clause.target.patch + 1,
+                                ),
+                                prerelease_policy=Range.PRERELEASE_ALWAYS,
+                            ))
+                        elif clause.operator in (Range.OP_LT, Range.OP_LTE):
+                            prerelease_clauses.append(Range(
+                                operator=Range.OP_GTE,
+                                target=Version(
+                                    major=clause.target.major,
+                                    minor=clause.target.minor,
+                                    patch=0,
+                                    prerelease=(),
+                                ),
+                                prerelease_policy=Range.PRERELEASE_ALWAYS,
+                            ))
+                        prerelease_clauses.append(clause)
+                        non_prerel_clauses.append(cls.range(
+                            operator=clause.operator,
+                            target=clause.target.truncate(),
+                        ))
+                    else:
+                        non_prerel_clauses.append(clause)
+                if prerelease_clauses:
+                    result |= AllOf(*prerelease_clauses)
+                result |= AllOf(*non_prerel_clauses)
+
+            return result
+
+        PREFIX_CARET = '^'
+        PREFIX_TILDE = '~'
+        PREFIX_EQ = '='
+        PREFIX_GT = '>'
+        PREFIX_GTE = '>='
+        PREFIX_LT = '<'
+        PREFIX_LTE = '<='
+
+        PREFIX_ALIASES = {
+            '': PREFIX_EQ,
+        }
+
+        PREFIX_TO_OPERATOR = {
+            PREFIX_EQ: Range.OP_EQ,
+            PREFIX_LT: Range.OP_LT,
+            PREFIX_LTE: Range.OP_LTE,
+            PREFIX_GTE: Range.OP_GTE,
+            PREFIX_GT: Range.OP_GT,
+        }
+
+        EMPTY_VALUES = ['*', 'x', 'X', None]
+
+        @classmethod
+        def parse_simple(cls, simple):
+            match = cls.NPM_SPEC_BLOCK.match(simple)
+
+            prefix, major_t, minor_t, patch_t, prerel, build = match.groups()
+
+            prefix = cls.PREFIX_ALIASES.get(prefix, prefix)
+            major = None if major_t in cls.EMPTY_VALUES else int(major_t)
+            minor = None if minor_t in cls.EMPTY_VALUES else int(minor_t)
+            patch = None if patch_t in cls.EMPTY_VALUES else int(patch_t)
+
+            if build is not None and prefix not in [cls.PREFIX_EQ]:
+                # Ignore the 'build' part when not comparing to a specific part.
+                build = None
+
+            if major is None:  # '*', 'x', 'X'
+                target = Version(major=0, minor=0, patch=0)
+                if prefix not in [cls.PREFIX_EQ, cls.PREFIX_GTE]:
+                    raise ValueError("Invalid expression %r" % simple)
+                prefix = cls.PREFIX_GTE
+            elif minor is None:
+                target = Version(major=major, minor=0, patch=0)
+            elif patch is None:
+                target = Version(major=major, minor=minor, patch=0)
+            else:
+                target = Version(
+                    major=major,
+                    minor=minor,
+                    patch=patch,
+                    prerelease=prerel.split('.') if prerel else (),
+                    build=build.split('.') if build else (),
+                )
+
+            if (major is None or minor is None or patch is None) and (prerel or build):
+                raise ValueError("Invalid NPM spec: %r" % simple)
+
+            if prefix == cls.PREFIX_CARET:
+                if target.major:  # ^1.2.4 => >=1.2.4 <2.0.0 ; ^1.x => >=1.0.0 <2.0.0
+                    high = target.truncate().next_major()
+                elif target.minor:  # ^0.1.2 => >=0.1.2 <0.2.0
+                    high = target.truncate().next_minor()
+                elif minor is None:  # ^0.x => >=0.0.0 <1.0.0
+                    high = target.truncate().next_major()
+                elif patch is None:  # ^0.2.x => >=0.2.0 <0.3.0
+                    high = target.truncate().next_minor()
+                else:  # ^0.0.1 => >=0.0.1 <0.0.2
+                    high = target.truncate().next_patch()
+                return [cls.range(Range.OP_GTE, target), cls.range(Range.OP_LT, high)]
+
+            elif prefix == cls.PREFIX_TILDE:
+                assert major is not None
+                if minor is None:  # ~1.x => >=1.0.0 <2.0.0
+                    high = target.next_major()
+                else:  # ~1.2.x => >=1.2.0 <1.3.0; ~1.2.3 => >=1.2.3 <1.3.0
+                    high = target.next_minor()
+                return [cls.range(Range.OP_GTE, target), cls.range(Range.OP_LT, high)]
+
+            elif prefix == cls.PREFIX_EQ:
+                if major is None:
+                    return [cls.range(Range.OP_GTE, target)]
+                elif minor is None:
+                    return [cls.range(Range.OP_GTE, target), cls.range(Range.OP_LT, target.next_major())]
+                elif patch is None:
+                    return [cls.range(Range.OP_GTE, target), cls.range(Range.OP_LT, target.next_minor())]
+                else:
+                    return [cls.range(Range.OP_EQ, target)]
+
+            elif prefix == cls.PREFIX_GT:
+                assert major is not None
+                if minor is None:  # >1.x
+                    return [cls.range(Range.OP_GTE, target.next_major())]
+                elif patch is None:  # >1.2.x => >=1.3.0
+                    return [cls.range(Range.OP_GTE, target.next_minor())]
+                else:
+                    return [cls.range(Range.OP_GT, target)]
+
+            elif prefix == cls.PREFIX_GTE:
+                return [cls.range(Range.OP_GTE, target)]
+
+            elif prefix == cls.PREFIX_LT:
+                assert major is not None
+                return [cls.range(Range.OP_LT, target)]
+
+            else:
+                assert prefix == cls.PREFIX_LTE
+                assert major is not None
+                if minor is None:  # <=1.x => <2.0.0
+                    return [cls.range(Range.OP_LT, target.next_major())]
+                elif patch is None:  # <=1.2.x => <1.3.0
+                    return [cls.range(Range.OP_LT, target.next_minor())]
+                else:
+                    return [cls.range(Range.OP_LTE, target)]
diff --git a/lib/python3.11/site-packages/semantic_version/django_fields.py b/lib/python3.11/site-packages/semantic_version/django_fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5bd7eb2340cfedad7ac387869ce20bdb053f112
--- /dev/null
+++ b/lib/python3.11/site-packages/semantic_version/django_fields.py
@@ -0,0 +1,107 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+import warnings
+
+import django
+from django.db import models
+
+if django.VERSION >= (3, 0):
+    # See https://docs.djangoproject.com/en/dev/releases/3.0/#features-deprecated-in-3-0
+    from django.utils.translation import gettext_lazy as _
+else:
+    from django.utils.translation import ugettext_lazy as _
+
+from . import base
+
+
+class SemVerField(models.CharField):
+
+    def __init__(self, *args, **kwargs):
+        kwargs.setdefault('max_length', 200)
+        super(SemVerField, self).__init__(*args, **kwargs)
+
+    def from_db_value(self, value, expression, connection, *args):
+        """Convert from the database format.
+
+        This should be the inverse of self.get_prep_value()
+        """
+        return self.to_python(value)
+
+    def get_prep_value(self, obj):
+        return None if obj is None else str(obj)
+
+    def get_db_prep_value(self, value, connection, prepared=False):
+        if not prepared:
+            value = self.get_prep_value(value)
+        return value
+
+    def value_to_string(self, obj):
+        value = self.to_python(self.value_from_object(obj))
+        return str(value)
+
+    def run_validators(self, value):
+        return super(SemVerField, self).run_validators(str(value))
+
+
+class VersionField(SemVerField):
+    default_error_messages = {
+        'invalid': _("Enter a valid version number in X.Y.Z format."),
+    }
+    description = _("Version")
+
+    def __init__(self, *args, **kwargs):
+        self.partial = kwargs.pop('partial', False)
+        if self.partial:
+            warnings.warn(
+                "Use of `partial=True` will be removed in 3.0.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+        self.coerce = kwargs.pop('coerce', False)
+        super(VersionField, self).__init__(*args, **kwargs)
+
+    def deconstruct(self):
+        """Handle django.db.migrations."""
+        name, path, args, kwargs = super(VersionField, self).deconstruct()
+        kwargs['partial'] = self.partial
+        kwargs['coerce'] = self.coerce
+        return name, path, args, kwargs
+
+    def to_python(self, value):
+        """Converts any value to a base.Version field."""
+        if value is None or value == '':
+            return value
+        if isinstance(value, base.Version):
+            return value
+        if self.coerce:
+            return base.Version.coerce(value, partial=self.partial)
+        else:
+            return base.Version(value, partial=self.partial)
+
+
+class SpecField(SemVerField):
+    default_error_messages = {
+        'invalid': _("Enter a valid version number spec list in ==X.Y.Z,>=A.B.C format."),
+    }
+    description = _("Version specification list")
+
+    def __init__(self, *args, **kwargs):
+        self.syntax = kwargs.pop('syntax', base.DEFAULT_SYNTAX)
+        super(SpecField, self).__init__(*args, **kwargs)
+
+    def deconstruct(self):
+        """Handle django.db.migrations."""
+        name, path, args, kwargs = super(SpecField, self).deconstruct()
+        if self.syntax != base.DEFAULT_SYNTAX:
+            kwargs['syntax'] = self.syntax
+        return name, path, args, kwargs
+
+    def to_python(self, value):
+        """Converts any value to a base.Spec field."""
+        if value is None or value == '':
+            return value
+        if isinstance(value, base.BaseSpec):
+            return value
+        return base.BaseSpec.parse(value, syntax=self.syntax)
diff --git a/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/INSTALLER b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/METADATA b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..de114be88c5daed96d52425ac9e553866395e25c
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/METADATA
@@ -0,0 +1,251 @@
+Metadata-Version: 2.4
+Name: sentencepiece
+Version: 0.2.1
+Summary: Unsupervised text tokenizer and detokenizer.
+Author-email: Taku Kudo 
+Project-URL: Homepage, https://github.com/google/sentencepiece
+Classifier: Programming Language :: Python :: 3
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Science/Research
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
+Classifier: Topic :: Text Processing :: Linguistic
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.9
+Description-Content-Type: text/markdown
+Provides-Extra: test
+Requires-Dist: pytest; extra == "test"
+Provides-Extra: testpaths
+Requires-Dist: test; extra == "testpaths"
+
+# SentencePiece Python Wrapper
+
+Python wrapper for SentencePiece. This API will offer the encoding, decoding and training of Sentencepiece.
+
+## Build and Install SentencePiece
+
+For Linux (x64/i686), macOS, and Windows(win32/x64/arm64) environment, you can simply use pip command to install SentencePiece python module.
+
+```
+% pip install sentencepiece
+```
+
+Before building SentencePiece from source on Linux, ensure that the following dependencies are installed.
+
+```
+% sudo apt update
+% sudo apt install -y cmake pkg-config libsentencepiece-dev
+```
+
+To build and install the Python wrapper from source, try the following commands to build and install wheel package.
+
+```
+% git clone https://github.com/google/sentencepiece.git
+% cd sentencepiece
+% mkdir build
+% cd build
+% cmake .. -DSPM_ENABLE_SHARED=OFF -DCMAKE_INSTALL_PREFIX=./root -DSPM_DISABLE_EMBEDDED_DATA=ON
+% make install
+% cd ../python
+% python setup.py bdist_wheel
+% pip install dist/sentencepiece*.whl
+```
+
+If you don’t have write permission to the global site-packages directory or don’t want to install into it, please try:
+
+```
+% python setup.py install --user
+```
+
+For Windows users who want to build from source, you can build and install the Python wrapper using Visual Studio. First, you need to install the `pwsh.exe` (Powershell 7). Use `winget install --id Microsoft.Powershell --source winget` to install directly. Then open the `Developer PowerShell for VS 2022`, and execute the following commands.
+
+```
+git clone https://github.com/google/sentencepiece.git
+cd sentencepiece
+mkdir build
+cd build
+cmake .. -DSPM_ENABLE_SHARED=OFF -DCMAKE_INSTALL_PREFIX=".\root" -DSPM_DISABLE_EMBEDDED_DATA=ON
+cmake --build . --config Release --target install
+cd ../python
+pip install wheel
+python setup.py bdist_wheel
+Get-ChildItem .\dist\sentencepiece*.whl | ForEach-Object { pip install $_.FullName }
+```
+
+## Usage
+
+See [this google colab page](https://github.com/google/sentencepiece/blob/master/python/sentencepiece_python_module_example.ipynb) to run sentencepiece interactively.
+
+### Segmentation
+
+```
+% python
+>>> import sentencepiece as spm
+>>> sp = spm.SentencePieceProcessor(model_file='test/test_model.model')
+
+>>> sp.encode('This is a test')
+[284, 47, 11, 4, 15, 400]
+
+>>> sp.encode(['This is a test', 'Hello world'], out_type=int)
+[[284, 47, 11, 4, 15, 400], [151, 88, 21, 887]]
+
+>>> sp.encode_as_ids(['This is a test', 'Hello world'])
+[[284, 47, 11, 4, 15, 400], [151, 88, 21, 887]]
+
+>>> sp.encode('This is a test', out_type=str)
+['▁This', '▁is', '▁a', '▁', 't', 'est']
+
+>>> sp.encode(['This is a test', 'Hello world'], out_type=str)
+[['▁This', '▁is', '▁a', '▁', 't', 'est'], ['▁He', 'll', 'o', '▁world']]
+
+>>> sp.encode_as_pieces(['This is a test', 'Hello world'])
+[['▁This', '▁is', '▁a', '▁', 't', 'est'], ['▁He', 'll', 'o', '▁world']]
+
+>>> proto = sp.encode('This is a test', out_type='immutable_proto')
+>>> for n in proto.pieces:
+...     print('piece="{}" surface="{}" id={} begin={} end={}'.format(n.piece, n.surface, n.id, n.begin, n.end))
+...
+piece="▁This" surface="This" id=284 begin=0 end=4
+piece="▁is" surface=" is" id=47 begin=4 end=7
+piece="▁a" surface=" a" id=11 begin=7 end=9
+piece="▁" surface=" " id=4 begin=9 end=10
+piece="t" surface="t" id=15 begin=10 end=11
+piece="est" surface="est" id=400 begin=11 end=14
+
+>>> [[x.id for x in proto.pieces], [x.piece for x in proto.pieces], [x.begin for x in proto.pieces], [x.end for x in proto.pieces]]
+[[284, 47, 11, 4, 15, 400], ['▁This', '▁is', '▁a', '▁', 't', 'est'], [0, 4, 7, 9, 10, 11], [4, 7, 9, 10, 11, 14]]
+
+>>> proto2 = sp.encode_as_immutable_proto('This is a test')
+>>> proto2 == proto
+True
+
+>>> for _ in range(10):
+...     sp.encode('This is a test', out_type=str, enable_sampling=True, alpha=0.1, nbest_size=-1)
+...
+['▁', 'This', '▁', 'is', '▁a', '▁', 't', 'e', 'st']
+['▁T', 'h', 'i', 's', '▁is', '▁a', '▁', 'te', 's', 't']
+['▁T', 'h', 'is', '▁', 'is', '▁', 'a', '▁', 't', 'est']
+['▁', 'This', '▁is', '▁', 'a', '▁', 't', 'e', 'st']
+['▁', 'This', '▁', 'is', '▁', 'a', '▁', 't', 'e', 's', 't']
+['▁This', '▁is', '▁a', '▁', 'te', 's', 't']
+['▁This', '▁is', '▁', 'a', '▁', 't', 'e', 'st']
+['▁', 'T', 'h', 'is', '▁', 'is', '▁', 'a', '▁', 'te', 'st']
+['▁', 'This', '▁', 'i', 's', '▁a', '▁', 't', 'e', 'st']
+['▁This', '▁', 'is', '▁a', '▁', 't', 'est']
+
+>> sp.nbest_encode('This is a test', nbest_size=5, out_type=str)
+[['▁This', '▁is', '▁a', '▁', 't', 'est'],
+['▁This', '▁is', '▁a', '▁', 'te', 'st'],
+['▁This', '▁is', '▁a', '▁', 'te', 's', 't'],
+['▁This', '▁is', '▁a', '▁', 't', 'e', 'st'],
+['▁This', '▁is', '▁a', '▁', 't', 'es', 't']]
+
+>>> sp.sample_encode_and_score('This is a test', num_samples=5, alpha=0.1, out_type=str, wor=True)
+[(['▁This', '▁', 'i', 's', '▁a', '▁', 'te', 's', 't'], -3.043105125427246),
+(['▁This', '▁', 'i', 's', '▁a', '▁', 'te', 'st'], -2.8475849628448486),
+(['▁', 'This', '▁is', '▁', 'a', '▁', 'te', 'st'], -3.043248176574707),
+(['▁', 'This', '▁is', '▁a', '▁', 't', 'e', 'st'], -2.87727689743042),
+(['▁', 'This', '▁', 'i', 's', '▁', 'a', '▁', 't', 'est'], -3.6284031867980957)]
+
+>>> sp.decode([284, 47, 11, 4, 15, 400])
+'This is a test'
+
+>>> sp.decode([[284, 47, 11, 4, 15, 400], [151, 88, 21, 887]])
+['This is a test', 'Hello world']
+
+>>> proto = sp.decode([284, 47, 11, 4, 15, 400], out_type='immutable_proto')
+>>> proto.text
+'This is a test'
+
+>>> sp.decode(['▁', 'This', '▁', 'is', '▁a', '▁', 't', 'e', 'st'])
+'This is a test'
+
+>>> sp.decode([['▁This', '▁is', '▁a', '▁', 't', 'est'], ['▁He', 'll', 'o', '▁world']])
+['This is a test', 'Hello world']
+
+>>> sp.get_piece_size()
+1000
+
+>>> sp.id_to_piece(2)
+''
+
+>>> sp.id_to_piece([2, 3, 4])
+['', '\r', '▁']
+
+>>> sp.piece_to_id('')
+1
+
+>>> sp.piece_to_id(['', '\r', '▁'])
+[2, 3, 4]
+
+>>> len(sp)
+1000
+
+>>> sp['']
+2
+```
+
+### Model Training
+
+Training is performed by passing parameters of [spm_train](https://github.com/google/sentencepiece#train-sentencepiece-model) to SentencePieceTrainer.train() function.
+
+```
+>>> import sentencepiece as spm
+>>> spm.SentencePieceTrainer.train(input='test/botchan.txt', model_prefix='m', vocab_size=1000, user_defined_symbols=['foo', 'bar'])
+sentencepiece_trainer.cc(73) LOG(INFO) Starts training with :
+trainer_spec {
+  input: test/botchan.txt
+  .. snip
+unigram_model_trainer.cc(500) LOG(INFO) EM sub_iter=1 size=1188 obj=10.2839 num_tokens=32182 num_tokens/piece=27.0892
+unigram_model_trainer.cc(500) LOG(INFO) EM sub_iter=0 size=1100 obj=10.4269 num_tokens=33001 num_tokens/piece=30.0009
+unigram_model_trainer.cc(500) LOG(INFO) EM sub_iter=1 size=1100 obj=10.4069 num_tokens=33002 num_tokens/piece=30.0018
+trainer_interface.cc(595) LOG(INFO) Saving model: m.model
+trainer_interface.cc(619) LOG(INFO) Saving vocabs: m.vocab
+>>>
+```
+
+### Training without local filesystem
+
+Sentencepiece trainer can receive any iterable object to feed training sentences. You can also pass a file object (instance with write() method) to emit the output model to any devices. These features are useful to run sentencepiece on environment that have limited access to the local file system (e.g., Google colab.)
+
+```
+import urllib.request
+import io
+import sentencepiece as spm
+
+# Loads model from URL as iterator and stores the model to BytesIO.
+model = io.BytesIO()
+with urllib.request.urlopen(
+    'https://raw.githubusercontent.com/google/sentencepiece/master/data/botchan.txt'
+) as response:
+  spm.SentencePieceTrainer.train(
+      sentence_iterator=response, model_writer=model, vocab_size=1000)
+
+# Serialize the model as file.
+# with open('out.model', 'wb') as f:
+#   f.write(model.getvalue())
+
+# Directly load the model from serialized model.
+sp = spm.SentencePieceProcessor(model_proto=model.getvalue())
+print(sp.encode('this is test'))
+```
+
+### Free Threading support
+Experimental support for no-GIL/Free-Threading has been introduced since v0.2.1. For more details, please refer to [this page](https://py-free-threading.github.io.).
+This operates similarly to how [NumPy](https://numpy.org/devdocs/reference/thread_safety.html#free-threaded-python) handles it.
+
+The C++ library's const and static methods, e.g., encode(), decode() and train(), are designed to work in a non-GIL environment.
+However, non-const methods, e.g., load(), may have potential data race issues, so please ensure you implement appropriate locks beforehand.
+
+While this limitation might be removed in the future, please note that it's not a simple fix, as it would require additional shared locks in C++.
diff --git a/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/RECORD b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..5912ce9e1829c66097b6854ebab62a693997c8f8
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/RECORD
@@ -0,0 +1,20 @@
+sentencepiece-0.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+sentencepiece-0.2.1.dist-info/METADATA,sha256=zgounFmc0GCnvD3_sYvlz8PV8pNTPj7k6HDq7wpVAP0,10003
+sentencepiece-0.2.1.dist-info/RECORD,,
+sentencepiece-0.2.1.dist-info/WHEEL,sha256=3daP3VhxT_uXQ4g9qxjrsHJLh9a9x1Dc522TvcSo1E0,152
+sentencepiece-0.2.1.dist-info/top_level.txt,sha256=NIXVKmsq-xdZ5KROMHHV0gkLA3fvbNTb1g1KtgiYFOk,130
+sentencepiece/__init__.py,sha256=NQT0kP3jkjEmRRIyK_jsKCug6L9zQi2vIPTWQin8E2w,49422
+sentencepiece/__pycache__/__init__.cpython-311.pyc,,
+sentencepiece/__pycache__/_version.cpython-311.pyc,,
+sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-311.pyc,,
+sentencepiece/__pycache__/sentencepiece_pb2.cpython-311.pyc,,
+sentencepiece/_sentencepiece.cpython-311-x86_64-linux-gnu.so,sha256=_3ZvKBo6qXcdNrDlmC_B1PF4769Q6OeCW5RaxKMw7-w,2001816
+sentencepiece/_version.py,sha256=PmcQ2PI2oP8irnLtJLJby2YfW6sBvLAmL-VpABzTqwc,22
+sentencepiece/package_data/nfkc.bin,sha256=UvEQKP-KffPgCdlKi2pU1KihcTLvtMzByaCkHkMr2R4,240008
+sentencepiece/package_data/nfkc_cf.bin,sha256=YIM-wRIBRGZZw1ScGDsY8CTEAHYozGs6TpGuAHaXuCY,247028
+sentencepiece/package_data/nmt_nfkc.bin,sha256=eTcsQTicK5spvBcQF6tUAONS3r1oawJnCkK-xwkBUHQ,240007
+sentencepiece/package_data/nmt_nfkc_cf.bin,sha256=IsKSx29QN5XzDIXXnTCn9XL_9PSeADktLWD0-T6UGh4,247027
+sentencepiece/sentencepiece.i,sha256=Hfv8AHFOJEfDfElVYIhoz29W7rV1VJ0Z13aP7S7ck6M,72647
+sentencepiece/sentencepiece_model_pb2.py,sha256=LawEwmdUiIU1T9HcYu-rNEVTFcwAh9i-qavMMsg9riE,6257
+sentencepiece/sentencepiece_pb2.py,sha256=_ZgnXOkpoScMXbJ-8BMKn2Q97BbMOH9Hz-L7JFMcJro,1753
+sentencepiece/sentencepiece_wrap.cxx,sha256=XlbUFs7s48i3i_nhka9U_b41Xpv_eeSD9U_uxO742Y0,381494
diff --git a/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/WHEEL b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..877b63ad81f31e9e52588701b631478d58f56658
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: false
+Tag: cp311-cp311-manylinux_2_27_x86_64
+Tag: cp311-cp311-manylinux_2_28_x86_64
+
diff --git a/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/top_level.txt b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6a66f9441436eaa6d7b2d87d1af197d980e727b0
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece-0.2.1.dist-info/top_level.txt
@@ -0,0 +1,5 @@
+sentencepiece
+sentencepiece/__init__
+sentencepiece/_version
+sentencepiece/sentencepiece_model_pb2
+sentencepiece/sentencepiece_pb2
diff --git a/lib/python3.11/site-packages/sentencepiece/__init__.py b/lib/python3.11/site-packages/sentencepiece/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02379dd36dad021a82d4b3a85ad1598f01184758
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece/__init__.py
@@ -0,0 +1,1230 @@
+# This file was automatically generated by SWIG (https://www.swig.org).
+# Version 4.3.0
+#
+# Do not make changes to this file unless you know what you are doing - modify
+# the SWIG interface file instead.
+
+from sys import version_info as _swig_python_version_info
+# Import the low-level C/C++ module
+if __package__ or "." in __name__:
+    from . import _sentencepiece
+else:
+    import _sentencepiece
+
+try:
+    import builtins as __builtin__
+except ImportError:
+    import __builtin__
+
+def _swig_repr(self):
+    try:
+        strthis = "proxy of " + self.this.__repr__()
+    except __builtin__.Exception:
+        strthis = ""
+    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
+
+
+def _swig_setattr_nondynamic_instance_variable(set):
+    def set_instance_attr(self, name, value):
+        if name == "this":
+            set(self, name, value)
+        elif name == "thisown":
+            self.this.own(value)
+        elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
+            set(self, name, value)
+        else:
+            raise AttributeError("You cannot add instance attributes to %s" % self)
+    return set_instance_attr
+
+
+def _swig_setattr_nondynamic_class_variable(set):
+    def set_class_attr(cls, name, value):
+        if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
+            set(cls, name, value)
+        else:
+            raise AttributeError("You cannot add class attributes to %s" % cls)
+    return set_class_attr
+
+
+def _swig_add_metaclass(metaclass):
+    """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
+    def wrapper(cls):
+        return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
+    return wrapper
+
+
+class _SwigNonDynamicMeta(type):
+    """Meta class to enforce nondynamic attributes (no new attributes) for a class"""
+    __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
+
+
+class ImmutableSentencePieceText_ImmutableSentencePiece(object):
+    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
+    __repr__ = _swig_repr
+
+    def __init__(self):
+        _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece_swiginit(self, _sentencepiece.new_ImmutableSentencePieceText_ImmutableSentencePiece())
+    __swig_destroy__ = _sentencepiece.delete_ImmutableSentencePieceText_ImmutableSentencePiece
+
+    def _piece(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__piece(self)
+
+    def _surface(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__surface(self)
+
+    def _id(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__id(self)
+
+    def _begin(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__begin(self)
+
+    def _end(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__end(self)
+
+    def _surface_as_bytes(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes(self)
+
+    def _piece_as_bytes(self):
+        return _sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes(self)
+
+    piece = property(_piece)
+    piece_as_bytes = property(_piece_as_bytes)
+    surface = property(_surface)
+    surface_as_bytes = property(_surface_as_bytes)
+    id = property(_id)
+    begin = property(_begin)
+    end = property(_end)
+
+    def __str__(self):
+      return ('piece: \"{}\"\n'
+              'id: {}\n'
+              'surface: \"{}\"\n'
+              'begin: {}\n'
+              'end: {}\n').format(self.piece, self.id, self.surface,
+                                  self.begin, self.end)
+
+    def __eq__(self, other):
+      return self.piece == other.piece and self.id == other.id and self.surface == other.surface and self.begin == other.begin and self.end == other.end
+
+    def __hash__(self):
+      return hash(str(self))
+
+    __repr__ = __str__
+
+
+# Register ImmutableSentencePieceText_ImmutableSentencePiece in _sentencepiece:
+_sentencepiece.ImmutableSentencePieceText_ImmutableSentencePiece_swigregister(ImmutableSentencePieceText_ImmutableSentencePiece)
+class ImmutableSentencePieceText(object):
+    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
+    __repr__ = _swig_repr
+
+    def __init__(self):
+        _sentencepiece.ImmutableSentencePieceText_swiginit(self, _sentencepiece.new_ImmutableSentencePieceText())
+    __swig_destroy__ = _sentencepiece.delete_ImmutableSentencePieceText
+
+    def _pieces_size(self):
+        return _sentencepiece.ImmutableSentencePieceText__pieces_size(self)
+
+    def _pieces(self, index):
+        return _sentencepiece.ImmutableSentencePieceText__pieces(self, index)
+
+    def _text(self):
+        return _sentencepiece.ImmutableSentencePieceText__text(self)
+
+    def _score(self):
+        return _sentencepiece.ImmutableSentencePieceText__score(self)
+
+    def SerializeAsString(self):
+        return _sentencepiece.ImmutableSentencePieceText_SerializeAsString(self)
+
+    def _text_as_bytes(self):
+        return _sentencepiece.ImmutableSentencePieceText__text_as_bytes(self)
+
+    text = property(_text)
+    text_as_bytes = property(_text_as_bytes)
+    score = property(_score)
+
+    class ImmutableSentencePieceIterator:
+      def __init__(self, proto):
+        self.proto = proto
+        self.len = self.proto._pieces_size()
+
+      def __len__(self):
+        return self.len
+
+      def __getitem__(self, index):
+        if isinstance(index, slice):
+          return [self.proto._pieces(i) for i in range(self.len)][index.start:index.stop:index.step]
+        if index < 0:
+          index = index + self.len
+        if index < 0 or index >= self.len:
+          raise IndexError('piece index is out of range')
+        return self.proto._pieces(index)
+
+      def __str__(self):
+        return '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self])
+
+      __repr__ = __str__
+
+    @property
+    def pieces(self):
+      return ImmutableSentencePieceText.ImmutableSentencePieceIterator(self)
+
+    def __eq__(self, other):
+      return self.SerializeAsString() == other.SerializeAsString()
+
+    def __hash__(self):
+      return hash(self.SerializeAsString())
+
+    def __str__(self):
+      return ('text: \"{}\"\n'
+              'score: {}\n'
+              '{}').format(self.text, self.score,
+                           '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self.pieces]))
+
+    __repr__ = __str__
+
+
+# Register ImmutableSentencePieceText in _sentencepiece:
+_sentencepiece.ImmutableSentencePieceText_swigregister(ImmutableSentencePieceText)
+class ImmutableNBestSentencePieceText(object):
+    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
+    __repr__ = _swig_repr
+
+    def __init__(self):
+        _sentencepiece.ImmutableNBestSentencePieceText_swiginit(self, _sentencepiece.new_ImmutableNBestSentencePieceText())
+    __swig_destroy__ = _sentencepiece.delete_ImmutableNBestSentencePieceText
+
+    def _nbests_size(self):
+        return _sentencepiece.ImmutableNBestSentencePieceText__nbests_size(self)
+
+    def _nbests(self, index):
+        return _sentencepiece.ImmutableNBestSentencePieceText__nbests(self, index)
+
+    def SerializeAsString(self):
+        return _sentencepiece.ImmutableNBestSentencePieceText_SerializeAsString(self)
+
+    class ImmutableSentencePieceTextIterator:
+      def __init__(self, proto):
+        self.proto = proto
+        self.len = self.proto._nbests_size()
+
+      def __len__(self):
+        return self.len
+
+      def __getitem__(self, index):
+        if isinstance(index, slice):
+          return [self.proto._nbests(i) for i in range(self.len)][index.start:index.stop:index.step]
+        if index < 0:
+          index = index + self.len
+        if index < 0 or index >= self.len:
+          raise IndexError('nbests index is out of range')
+        return self.proto._nbests(index)
+
+      def __str__(self):
+        return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self])
+
+      __repr__ = __str__
+
+    @property
+    def nbests(self):
+      return ImmutableNBestSentencePieceText.ImmutableSentencePieceTextIterator(self)
+
+    def __eq__(self, other):
+      return self.SerializeAsString() == other.SerializeAsString()
+
+    def __hash__(self):
+      return hash(self.SerializeAsString())
+
+    def __str__(self):
+      return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self.nbests])
+
+    __repr__ = __str__
+
+
+# Register ImmutableNBestSentencePieceText in _sentencepiece:
+_sentencepiece.ImmutableNBestSentencePieceText_swigregister(ImmutableNBestSentencePieceText)
+class SentencePieceProcessor(object):
+    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
+    __repr__ = _swig_repr
+
+    def __init__(self):
+        _sentencepiece.SentencePieceProcessor_swiginit(self, _sentencepiece.new_SentencePieceProcessor())
+    __swig_destroy__ = _sentencepiece.delete_SentencePieceProcessor
+
+    def LoadFromSerializedProto(self, serialized):
+        return _sentencepiece.SentencePieceProcessor_LoadFromSerializedProto(self, serialized)
+
+    def SetEncodeExtraOptions(self, extra_option):
+        return _sentencepiece.SentencePieceProcessor_SetEncodeExtraOptions(self, extra_option)
+
+    def SetDecodeExtraOptions(self, extra_option):
+        return _sentencepiece.SentencePieceProcessor_SetDecodeExtraOptions(self, extra_option)
+
+    def SetVocabulary(self, valid_vocab):
+        return _sentencepiece.SentencePieceProcessor_SetVocabulary(self, valid_vocab)
+
+    def ResetVocabulary(self):
+        return _sentencepiece.SentencePieceProcessor_ResetVocabulary(self)
+
+    def LoadVocabulary(self, filename, threshold):
+        return _sentencepiece.SentencePieceProcessor_LoadVocabulary(self, filename, threshold)
+
+    def CalculateEntropy(self, *args):
+        return _sentencepiece.SentencePieceProcessor_CalculateEntropy(self, *args)
+
+    def GetPieceSize(self):
+        return _sentencepiece.SentencePieceProcessor_GetPieceSize(self)
+
+    def PieceToId(self, piece):
+        return _sentencepiece.SentencePieceProcessor_PieceToId(self, piece)
+
+    def IdToPiece(self, id):
+        return _sentencepiece.SentencePieceProcessor_IdToPiece(self, id)
+
+    def GetScore(self, id):
+        return _sentencepiece.SentencePieceProcessor_GetScore(self, id)
+
+    def IsUnknown(self, id):
+        return _sentencepiece.SentencePieceProcessor_IsUnknown(self, id)
+
+    def IsControl(self, id):
+        return _sentencepiece.SentencePieceProcessor_IsControl(self, id)
+
+    def IsUnused(self, id):
+        return _sentencepiece.SentencePieceProcessor_IsUnused(self, id)
+
+    def IsByte(self, id):
+        return _sentencepiece.SentencePieceProcessor_IsByte(self, id)
+
+    def unk_id(self):
+        return _sentencepiece.SentencePieceProcessor_unk_id(self)
+
+    def bos_id(self):
+        return _sentencepiece.SentencePieceProcessor_bos_id(self)
+
+    def eos_id(self):
+        return _sentencepiece.SentencePieceProcessor_eos_id(self)
+
+    def pad_id(self):
+        return _sentencepiece.SentencePieceProcessor_pad_id(self)
+
+    def serialized_model_proto(self):
+        return _sentencepiece.SentencePieceProcessor_serialized_model_proto(self)
+
+    def LoadFromFile(self, arg):
+        return _sentencepiece.SentencePieceProcessor_LoadFromFile(self, arg)
+
+    def _EncodeAsIds(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsIds(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsPieces(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsPieces(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsSerializedProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsSerializedProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsImmutableProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsImmutableProto(self, text, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsIdsBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsIdsBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsPiecesBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsPiecesBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsSerializedProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsSerializedProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _EncodeAsImmutableProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__EncodeAsImmutableProtoBatch(self, ins, num_threads, enable_sampling, nbest_size, alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _DecodeIds(self, ids):
+        return _sentencepiece.SentencePieceProcessor__DecodeIds(self, ids)
+
+    def _DecodeIdsAsBytes(self, ids):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsAsBytes(self, ids)
+
+    def _DecodePieces(self, pieces):
+        return _sentencepiece.SentencePieceProcessor__DecodePieces(self, pieces)
+
+    def _DecodeIdsAsSerializedProto(self, ids):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsAsSerializedProto(self, ids)
+
+    def _DecodePiecesAsSerializedProto(self, pieces):
+        return _sentencepiece.SentencePieceProcessor__DecodePiecesAsSerializedProto(self, pieces)
+
+    def _DecodeIdsAsImmutableProto(self, ids):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsAsImmutableProto(self, ids)
+
+    def _DecodePiecesAsImmutableProto(self, pieces):
+        return _sentencepiece.SentencePieceProcessor__DecodePiecesAsImmutableProto(self, pieces)
+
+    def _DecodeIdsBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsBatch(self, ins, num_threads)
+
+    def _DecodeIdsAsBytesBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsAsBytesBatch(self, ins, num_threads)
+
+    def _DecodeIdsAsSerializedProtoBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch(self, ins, num_threads)
+
+    def _DecodeIdsAsImmutableProtoBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch(self, ins, num_threads)
+
+    def _DecodePiecesBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodePiecesBatch(self, ins, num_threads)
+
+    def _DecodePiecesAsSerializedProtoBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch(self, ins, num_threads)
+
+    def _DecodePiecesAsImmutableProtoBatch(self, ins, num_threads):
+        return _sentencepiece.SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch(self, ins, num_threads)
+
+    def _NBestEncodeAsIds(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__NBestEncodeAsIds(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _NBestEncodeAsPieces(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__NBestEncodeAsPieces(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _NBestEncodeAsSerializedProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__NBestEncodeAsSerializedProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _NBestEncodeAsImmutableProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__NBestEncodeAsImmutableProto(self, text, nbest_size, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _SampleEncodeAndScoreAsIds(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsIds(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _SampleEncodeAndScoreAsPieces(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsPieces(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _SampleEncodeAndScoreAsSerializedProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _SampleEncodeAndScoreAsImmutableProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece):
+        return _sentencepiece.SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto(self, text, num_samples, alpha, wor, include_best, add_bos, add_eos, reverse, emit_unk_piece)
+
+    def _Normalize(self, text):
+        return _sentencepiece.SentencePieceProcessor__Normalize(self, text)
+
+    def _NormalizeWithOffsets(self, text):
+        return _sentencepiece.SentencePieceProcessor__NormalizeWithOffsets(self, text)
+
+    def _CalculateEntropy(self, text, alpha):
+        return _sentencepiece.SentencePieceProcessor__CalculateEntropy(self, text, alpha)
+
+    def _CalculateEntropyBatch(self, ins, alpha, num_threads):
+        return _sentencepiece.SentencePieceProcessor__CalculateEntropyBatch(self, ins, alpha, num_threads)
+
+    def _OverrideNormalizerSpec(self, args):
+        return _sentencepiece.SentencePieceProcessor__OverrideNormalizerSpec(self, args)
+
+    def Init(self,
+             model_file=None,
+             model_proto=None,
+             out_type=int,
+             add_bos=False,
+             add_eos=False,
+             reverse=False,
+             emit_unk_piece=False,
+             enable_sampling=False,
+             nbest_size=-1,
+             alpha=0.1,
+             num_threads=-1):
+      """Initialzie sentencepieceProcessor.
+
+      Args:
+        model_file: The sentencepiece model file path.
+        model_proto: The sentencepiece model serialized proto.
+        out_type: output type. int or str.
+        add_bos: Add  to the result (Default = false)
+        add_eos: Add  to the result (Default = false) / is added after
+          reversing (if enabled).
+        reverse: Reverses the tokenized sequence (Default = false)
+        emit_unk_piece: Emits the unk literal string (Default = false)
+        nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout.
+                    nbest_size = {0,1}: No sampling is performed.
+                    nbest_size > 1: samples from the nbest_size results.
+                    nbest_size < 0: assuming that nbest_size is infinite and samples
+                      from the all hypothesis (lattice) using
+                      forward-filtering-and-backward-sampling algorithm.
+        alpha: Soothing parameter for unigram sampling, and dropout probability of
+               merge operations for BPE-dropout.
+        num_threads: number of threads in batch processing (Default = -1, auto-detected)
+      """
+
+      _sentencepiece_processor_init_native(self)
+      self._out_type = out_type
+      self._add_bos = add_bos
+      self._add_eos = add_eos
+      self._reverse = reverse
+      self._emit_unk_piece = emit_unk_piece
+      self._enable_sampling = enable_sampling
+      self._nbest_size = nbest_size
+      self._alpha = alpha
+      self._num_threads = num_threads
+      if model_file or model_proto:
+        self.Load(model_file=model_file, model_proto=model_proto)
+
+
+    def Encode(self,
+               input,
+               out_type=None,
+               add_bos=None,
+               add_eos=None,
+               reverse=None,
+               emit_unk_piece=None,
+               enable_sampling=None,
+               nbest_size=None,
+               alpha=None,
+               num_threads=None):
+      """Encode text input to segmented ids or tokens.
+
+        Args:
+        input: input string. accepsts list of string.
+        out_type: output type. int or str.
+        add_bos: Add  to the result (Default = false)
+        add_eos: Add  to the result (Default = false) / is added after
+                 reversing (if enabled).
+        reverse: Reverses the tokenized sequence (Default = false)
+        emit_unk_piece: Emits the unk literal string (Default = false)
+        nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout.
+                    nbest_size = {0,1}: No sampling is performed.
+                    nbest_size > 1: samples from the nbest_size results.
+                    nbest_size < 0: assuming that nbest_size is infinite and samples
+                    from the all hypothesis (lattice) using
+                    forward-filtering-and-backward-sampling algorithm.
+        alpha: Soothing parameter for unigram sampling, and merge probability for
+               BPE-dropout (probablity 'p' in BPE-dropout paper).
+        num_threads: the number of threads used in the batch processing (Default = -1).
+      """
+
+      if out_type is None:
+        out_type = self._out_type
+      if add_bos is None:
+        add_bos = self._add_bos
+      if add_eos is None:
+        add_eos = self._add_eos
+      if reverse is None:
+        reverse = self._reverse
+      if emit_unk_piece is None:
+        emit_unk_piece = self._emit_unk_piece
+      if enable_sampling is None:
+        enable_sampling = self._enable_sampling
+      if nbest_size is None:
+        nbest_size = self._nbest_size
+      if alpha is None:
+        alpha = self._alpha
+      if num_threads is None:
+        num_threads = self._num_threads
+
+      if enable_sampling == True and (nbest_size is None or nbest_size == 0 or
+                                      nbest_size == 1 or alpha is None):
+        raise RuntimeError(
+            'When enable_sampling is True, We must specify "nbest_size > 1" or "nbest_size = -1", '
+            'and "alpha". "nbest_size" is enabled only on unigram mode ignored in BPE-dropout. '
+            'when "nbest_size = -1" , this method samples from all candidates on the lattice '
+            'instead of nbest segmentations.'
+        )
+
+      if num_threads is None or type(num_threads) is not int:
+        raise RuntimeError('num_threads must be int')
+
+      if type(input) is list:
+        if out_type is int:
+          return self._EncodeAsIdsBatch(input, num_threads, enable_sampling, nbest_size,
+                                        alpha, add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type is str:
+          return self._EncodeAsPiecesBatch(input, num_threads, enable_sampling, nbest_size,
+                                           alpha, add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type == 'serialized_proto' or out_type == 'proto':
+          return self._EncodeAsSerializedProtoBatch(input, num_threads, enable_sampling, nbest_size,
+                                                    alpha, add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type == 'immutable_proto':
+          return self._EncodeAsImmutableProtoBatch(input, num_threads, enable_sampling, nbest_size,
+                                                   alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+      if out_type is int:
+        return self._EncodeAsIds(input, enable_sampling, nbest_size,
+                                 alpha, add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type is str:
+        return self._EncodeAsPieces(input, enable_sampling, nbest_size,
+                                    alpha, add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type == 'serialized_proto' or out_type == 'proto':
+        return self._EncodeAsSerializedProto(input, enable_sampling, nbest_size,
+                                             alpha, add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type == 'immutable_proto':
+        return self._EncodeAsImmutableProto(input, enable_sampling, nbest_size,
+                                            alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+      raise RuntimeError('unknown out_type={}'.format(out_type))
+      return None
+
+
+    def EncodeAsPieces(self, input, **kwargs):
+      return self.Encode(input=input, out_type=str, **kwargs)
+
+
+    def EncodeAsIds(self, input, **kwargs):
+      return self.Encode(input=input, out_type=int, **kwargs)
+
+
+    def EncodeAsSerializedProto(self, input, **kwargs):
+      return self.Encode(input=input, out_type='serialized_proto', **kwargs)
+
+
+    def EncodeAsImmutableProto(self, input, **kwargs):
+      return self.Encode(input=input, out_type='immutable_proto', **kwargs)
+
+
+    def SampleEncodeAsPieces(self, input, nbest_size=None, alpha=None, **kwargs):
+      return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                         out_type=str, enable_sampling=True, **kwargs)
+
+
+    def SampleEncodeAsIds(self, input, nbest_size=None, alpha=None,**kwargs):
+      return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                         out_type=int, enable_sampling=True, **kwargs)
+
+
+    def SampleEncodeAsSerializedProto(self, input, nbest_size=None, alpha=None, **kwargs):
+      return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                         out_type='serialized_proto', enable_sampling=True, **kwargs)
+
+
+    def SampleEncodeAsImmutableProto(self, input, nbest_size=None, alpha=None, **kwargs):
+      return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                         out_type='immutable_proto', enable_sampling=True, **kwargs)
+
+
+    def NBestEncode(self,
+                    input,
+                    out_type=None,
+                    add_bos=None,
+                    add_eos=None,
+                    reverse=None,
+                    emit_unk_piece=None,
+                    nbest_size=None):
+      """NBestEncode text input to segmented ids or tokens.
+
+        Args:
+        input: input string. accepsts list of string.
+        out_type: output type. int or str.
+        add_bos: Add  to the result (Default = false)
+        add_eos: Add  to the result (Default = false) / is added after reversing (if enabled).
+        reverse: Reverses the tokenized sequence (Default = false)
+        emit_unk_piece: Emits the unk literal string (Default = false)
+        nbest_size: nbest size
+      """
+
+      if out_type is None:
+        out_type = self._out_type
+      if add_bos is None:
+        add_bos = self._add_bos
+      if add_eos is None:
+        add_eos = self._add_eos
+      if reverse is None:
+        reverse = self._reverse
+      if emit_unk_piece is None:
+        emit_unk_piece = self._emit_unk_piece
+      if nbest_size is None:
+        nbest_size = self._nbest_size
+
+      if nbest_size <= 0:
+        nbest_size=1
+
+      def _encode(text):
+        if out_type is int:
+          return self._NBestEncodeAsIds(text, nbest_size,
+                                        add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type is str:
+          return self._NBestEncodeAsPieces(text, nbest_size,
+                                           add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type == 'serialized_proto' or out_type == 'proto':
+          return self._NBestEncodeAsSerializedProto(text, nbest_size,
+                                                    add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type == 'immutable_proto':
+          return self._NBestEncodeAsImmutableProto(text, nbest_size,
+                                                   add_bos, add_eos, reverse, emit_unk_piece)
+
+        raise RuntimeError('unknown out_type')
+
+      if type(input) is list:
+        return [_encode(n) for n in input]
+
+      return _encode(input)
+
+
+    def NBestEncodeAsPieces(self, input, nbest_size=None, **kwargs):
+      return self.NBestEncode(input=input, nbest_size=nbest_size,
+                              out_type=str, **kwargs)
+
+
+    def NBestEncodeAsIds(self, input, nbest_size=None, **kwargs):
+      return self.NBestEncode(input=input, nbest_size=nbest_size,
+                              out_type=int, **kwargs)
+
+
+    def NBestEncodeAsSerializedProto(self, input, nbest_size=None, **kwargs):
+      return self.NBestEncode(input=input, nbest_size=nbest_size,
+                              out_type='serialized_proto', **kwargs)
+
+
+    def NBestEncodeAsImmutableProto(self, input, nbest_size=None, **kwargs):
+      return self.NBestEncode(input=input, nbest_size=nbest_size,
+                              out_type='immutable_proto', **kwargs)
+
+
+    def SampleEncodeAndScore(self,
+                             input,
+                             out_type=None,
+                             add_bos=None,
+                             add_eos=None,
+                             reverse=None,
+                             emit_unk_piece=None,
+                             num_samples=None,
+                             alpha=None,
+                             wor=None,
+                             include_best=None):
+      """SampleEncodeAndScore text input to segmented ids or tokens.
+
+        Args:
+        input: input string. accepsts list of string.
+        out_type: output type. int or str or 'serialized_proto' or 'immutable_proto'
+        add_bos: Add  to the result (Default = false)
+        add_eos: Add  to the result (Default = false) / is added after reversing (if enabled).
+        reverse: Reverses the tokenized sequence (Default = false)
+        emit_unk_piece: Emits the unk literal string (Default = false)
+        num_samples: How many samples to return (Default = 1)
+        alpha: inverse temperature for sampling
+        wor: whether to sample without replacement (Default = false)
+        include_best: whether to include the best tokenization, requires wor=True (Default = false)
+      """
+
+      if out_type is None:
+        out_type = self._out_type
+      if add_bos is None:
+        add_bos = self._add_bos
+      if add_eos is None:
+        add_eos = self._add_eos
+      if reverse is None:
+        reverse = self._reverse
+      if emit_unk_piece is None:
+        emit_unk_piece = self._emit_unk_piece
+      if num_samples is None:
+        num_samples = 1
+      if alpha is None:
+        alpha = 1.
+      if wor is None:
+        wor = False
+      if include_best is None:
+        include_best = False
+
+      if num_samples <= 0:
+        raise RuntimeError('num_examples must be positive')
+
+      if include_best and not wor:
+        raise RuntimeError('When include_best is True, We must specify "wor = True".')
+
+
+      def _encode(text):
+        if out_type is int:
+          return self._SampleEncodeAndScoreAsIds(text, num_samples, alpha, wor, include_best,
+                                                 add_bos, add_eos, reverse, emit_unk_piece)
+        if out_type is str:
+          return self._SampleEncodeAndScoreAsPieces(text, num_samples, alpha, wor, include_best,
+                                                    add_bos, add_eos, reverse, emit_unk_piece)
+
+        if out_type == 'serialized_proto' or out_type == 'proto':
+          return self._SampleEncodeAndScoreAsSerializedProto(text, num_samples, alpha, wor, include_best,
+                                                             add_bos, add_eos, reverse, emit_unk_piece)
+
+        if out_type == 'immutable_proto':
+          return self._SampleEncodeAndScoreAsImmutableProto(text, num_samples, alpha, wor, include_best,
+                                                            add_bos, add_eos, reverse, emit_unk_piece)
+
+        raise RuntimeError('unknown output type')
+
+
+      if type(input) is list:
+        return [_encode(n) for n in input]
+
+      return _encode(input)
+
+
+    def SampleEncodeAndScoreAsPieces(self, input, num_samples=None, alpha=None, **kwargs):
+      return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                       out_type=str, **kwargs)
+
+
+    def SampleEncodeAndScoreAsIds(self, input, num_samples=None, alpha=None, **kwargs):
+      return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                       out_type=int, **kwargs)
+
+
+    def SampleEncodeAndScoreAsSerializedProto(self, input, num_samples=None, alpha=None, **kwargs):
+      return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                       out_type='serialized_proto', **kwargs)
+
+
+    def SampleEncodeAndScoreAsImmutableProto(self, input, num_samples=None, alpha=None, **kwargs):
+      return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                       out_type='immutable_proto', **kwargs)
+
+
+    def Decode(self, input, out_type=str, num_threads=None):
+      """Decode processed id or token sequences.
+
+      Args:
+        out_type: output type. str, bytes or 'serialized_proto' or 'immutable_proto' (Default = str)
+        num_threads: the number of threads used in the batch processing (Default = -1).
+      """
+
+      if num_threads is None:
+        num_threads = self._num_threads
+
+      if num_threads is None or type(num_threads) is not int:
+        raise RuntimeError('num_threads must be int')
+
+      if not input:
+        return ''
+
+      if out_type is str:
+        if type(input) is int:
+          return self._DecodeIds([input])
+        if type(input) is str:
+          return self._DecodePieces([input])
+
+        if type(input) is list:
+          if len(input) == 0 or type(input[0]) is int:
+            return self._DecodeIds(input)
+          if type(input[0]) is str:
+            return self._DecodePieces(input)
+
+          if type(input[0]) is list:
+            if len(input[0]) == 0 or type(input[0][0]) is int:
+             return self._DecodeIdsBatch(input, num_threads)
+            if type(input[0][0]) is str:
+             return self._DecodePiecesBatch(input, num_threads)
+
+      if out_type is bytes:
+        if type(input) is int:
+          return self._DecodeIdsAsBytes([input])
+        if type(input) is str:
+          return self._DecodePieces([input])
+
+        if type(input) is list:
+          if len(input) == 0 or type(input[0]) is int:
+            return self._DecodeIdsAsBytes(input)
+          if type(input[0]) is str:
+            return self._DecodePieces(input)
+
+          if type(input[0]) is list:
+            if len(input[0]) == 0 or type(input[0][0]) is int:
+             return self._DecodeIdsAsBytesBatch(input, num_threads)
+            if type(input[0][0]) is str:
+             return self._DecodePiecesBatch(input, num_threads)
+
+      if out_type == 'serialized_proto':
+        if type(input) is int:
+          return self._DecodeIdsAsSerializedProto([input])
+        if type(input) is str:
+          return self._DecodePiecesAsSerializedProto([input])
+
+        if type(input) is list:
+          if len(input) == 0 or type(input[0]) is int:
+            return self._DecodeIdsAsSerializedProto(input)
+          if type(input[0]) is str:
+            return self._DecodePiecesAsSerializedProto(input)
+
+          if type(input[0]) is list:
+            if len(input[0]) == 0 or type(input[0][0]) is int:
+             return self._DecodeIdsAsSerializedProtoBatch(input, num_threads)
+            if type(input[0][0]) is str:
+             return self._DecodePiecesAsSerializedProtoBatch(input, num_threads)
+
+
+      if out_type == 'immutable_proto':
+        if type(input) is int:
+          return self._DecodeIdsAsImmutableProto([input])
+        if type(input) is str:
+          return self._DecodePiecesAsImmutableProto([input])
+
+        if type(input) is list:
+          if len(input) == 0 or type(input[0]) is int:
+            return self._DecodeIdsAsImmutableProto(input)
+          if type(input[0]) is str:
+            return self._DecodePiecesAsImmutableProto(input)
+
+          if type(input[0]) is list:
+            if len(input[0]) == 0 or type(input[0][0]) is int:
+             return self._DecodeIdsAsImmutableProtoBatch(input, num_threads)
+            if type(input[0][0]) is str:
+             return self._DecodePiecesAsImmutableProtoBatch(input, num_threads)
+
+
+      raise RuntimeError('unknown output or input type')
+      return None
+
+
+    def DecodePieces(self, input, out_type=str, **kwargs):
+      return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+    def DecodeIds(self, input, out_type=str, **kwargs):
+      return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+    def DecodePiecesAsSerializedProto(self, input, out_type='serialized_proto', **kwargs):
+      return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+    def DecodeIdsAsSerializedProto(self, input, out_type='serialized_proto', **kwargs):
+      return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+    def DecodePiecesAsImmutableProto(self, input, out_type='immutable_proto', **kwargs):
+      return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+    def DecodeIdsAsImmutableProto(self, input, out_type='immutable_proto', **kwargs):
+      return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+    def CalculateEntropy(self, input, alpha, num_threads=None):
+      """Calculate sentence entropy"""
+      if type(input) is list:
+        if num_threads is None:
+          num_threads = self._num_threads
+        if num_threads is None or type(num_threads) is not int:
+          raise RuntimeError('num_threads must be int')
+        return self._CalculateEntropyBatch(input, alpha, num_threads)
+
+      return self._CalculateEntropy(input, alpha)
+
+
+    def Normalize(self, input, with_offsets=None):
+      def _normalize(text):
+        if with_offsets:
+          return self._NormalizeWithOffsets(text)
+        return self._Normalize(text)
+
+      if type(input) is list:
+        return [_normalize(x) for x in input]
+      return _normalize(input)
+
+    def OverrideNormalizerSpec(self, **kwargs):
+      new_kwargs = {}
+      for key, value in kwargs.items():
+        new_kwargs[key] = str(value)
+      return self._OverrideNormalizerSpec(new_kwargs)
+
+
+    def piece_size(self):
+      return self.GetPieceSize()
+
+
+    def vocab_size(self):
+      return self.GetPieceSize()
+
+
+    def __getstate__(self):
+      return self.serialized_model_proto()
+
+
+    def __setstate__(self, serialized_model_proto):
+      self.__init__()
+      self.LoadFromSerializedProto(serialized_model_proto)
+
+
+    def __len__(self):
+      return self.GetPieceSize()
+
+
+    def __getitem__(self, piece):
+      return self.PieceToId(piece)
+
+
+    def Load(self, model_file=None, model_proto=None):
+      """Overwride SentencePieceProcessor.Load to support both model_file and model_proto.
+
+      Args:
+        model_file: The sentencepiece model file path.
+        model_proto: The sentencepiece model serialized proto. Either `model_file`
+          or `model_proto` must be set.
+      """
+      if model_file and model_proto:
+        raise RuntimeError('model_file and model_proto must be exclusive.')
+      if model_proto:
+        return self.LoadFromSerializedProto(model_proto)
+      return self.LoadFromFile(model_file)
+
+
+# Register SentencePieceProcessor in _sentencepiece:
+_sentencepiece.SentencePieceProcessor_swigregister(SentencePieceProcessor)
+
+def SetRandomGeneratorSeed(seed):
+    return _sentencepiece.SetRandomGeneratorSeed(seed)
+
+def SetMinLogLevel(v):
+    return _sentencepiece.SetMinLogLevel(v)
+class SentencePieceTrainer(object):
+    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
+
+    def __init__(self, *args, **kwargs):
+        raise AttributeError("No constructor defined")
+    __repr__ = _swig_repr
+
+    @staticmethod
+    def _TrainFromString(arg):
+        return _sentencepiece.SentencePieceTrainer__TrainFromString(arg)
+
+    @staticmethod
+    def _TrainFromMap(args):
+        return _sentencepiece.SentencePieceTrainer__TrainFromMap(args)
+
+    @staticmethod
+    def _TrainFromMap2(args, iter):
+        return _sentencepiece.SentencePieceTrainer__TrainFromMap2(args, iter)
+
+    @staticmethod
+    def _TrainFromMap3(args):
+        return _sentencepiece.SentencePieceTrainer__TrainFromMap3(args)
+
+    @staticmethod
+    def _TrainFromMap4(args, iter):
+        return _sentencepiece.SentencePieceTrainer__TrainFromMap4(args, iter)
+
+    @staticmethod
+    def _Train(arg=None, **kwargs):
+      """Train Sentencepiece model. Accept both kwargs and legacy string arg."""
+      if arg is not None and type(arg) is str:
+        return SentencePieceTrainer._TrainFromString(arg)
+
+      def _encode(value):
+        """Encode value to CSV.."""
+        if type(value) is list:
+          if sys.version_info[0] == 3:
+            f = StringIO()
+          else:
+            f = BytesIO()
+          writer = csv.writer(f, lineterminator='')
+          writer.writerow([str(v) for v in value])
+          return f.getvalue()
+        else:
+          return str(value)
+
+      sentence_iterator = None
+      model_writer = None
+      new_kwargs = {}
+      for key, value in kwargs.items():
+        if key in ['sentence_iterator', 'sentence_reader']:
+          sentence_iterator = value
+        elif key in ['model_writer']:
+          model_writer = value
+        else:
+          new_kwargs[key] = _encode(value)
+
+      if model_writer:
+        if sentence_iterator:
+          model_proto = SentencePieceTrainer._TrainFromMap4(new_kwargs,
+                                                           sentence_iterator)
+        else:
+          model_proto = SentencePieceTrainer._TrainFromMap3(new_kwargs)
+        model_writer.write(model_proto)
+      else:
+        if sentence_iterator:
+          return SentencePieceTrainer._TrainFromMap2(new_kwargs, sentence_iterator)
+        else:
+          return SentencePieceTrainer._TrainFromMap(new_kwargs)
+
+      return None
+
+    @staticmethod
+    def Train(arg=None, logstream=None, **kwargs):
+      with _LogStream(ostream=logstream):
+        SentencePieceTrainer._Train(arg=arg, **kwargs)
+
+
+# Register SentencePieceTrainer in _sentencepiece:
+_sentencepiece.SentencePieceTrainer_swigregister(SentencePieceTrainer)
+class SentencePieceNormalizer(object):
+    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
+    __repr__ = _swig_repr
+
+    def __init__(self):
+        _sentencepiece.SentencePieceNormalizer_swiginit(self, _sentencepiece.new_SentencePieceNormalizer())
+    __swig_destroy__ = _sentencepiece.delete_SentencePieceNormalizer
+
+    def LoadFromSerializedProto(self, serialized):
+        return _sentencepiece.SentencePieceNormalizer_LoadFromSerializedProto(self, serialized)
+
+    def LoadFromRuleTSV(self, filename):
+        return _sentencepiece.SentencePieceNormalizer_LoadFromRuleTSV(self, filename)
+
+    def LoadFromRuleName(self, name):
+        return _sentencepiece.SentencePieceNormalizer_LoadFromRuleName(self, name)
+
+    def serialized_model_proto(self):
+        return _sentencepiece.SentencePieceNormalizer_serialized_model_proto(self)
+
+    def LoadFromFile(self, arg):
+        return _sentencepiece.SentencePieceNormalizer_LoadFromFile(self, arg)
+
+    def _Normalize(self, text):
+        return _sentencepiece.SentencePieceNormalizer__Normalize(self, text)
+
+    def _NormalizeWithOffsets(self, text):
+        return _sentencepiece.SentencePieceNormalizer__NormalizeWithOffsets(self, text)
+
+    def _SetProtoField(self, name, value):
+        return _sentencepiece.SentencePieceNormalizer__SetProtoField(self, name, value)
+
+    def Init(self,
+             model_file=None,
+             model_proto=None,
+             rule_tsv=None,
+             rule_name=None,
+             add_dummy_prefix=False,
+             escape_whitespaces=False,
+             remove_extra_whitespaces=False):
+      """Initialzie sentencePieceNormalizer.
+
+      Args:
+        model_file: The sentencepiece model file path.
+        model_proto: The sentencepiece model serialized proto.
+        rule_tsv: The normalization rule file in TSV format.
+        rule_name: Pre-defined normalization name.
+        add_dummy_prefix: add dummy prefix.
+        escape_whitespaces: escape whitespaces.
+        remove_extra_whitespaces: remove extra whitespaces.
+      """
+
+      _sentencepiece_normalizer_init_native(self)
+
+      if model_file:
+        status = self.LoadFromFile(model_file)
+      elif model_proto:
+        status = self.LoadFromSerializedProto(model_proto)
+      elif rule_tsv:
+        status = self.LoadFromRuleTSV(rule_tsv)
+      elif rule_name:
+        status = self.LoadFromRuleName(rule_name)
+      else:
+        raise RuntimeError('no model is specified')
+
+      if status:
+        self._SetProtoField('add_dummy_prefix', add_dummy_prefix)
+        self._SetProtoField('escape_whitespaces', escape_whitespaces)
+        self._SetProtoField('remove_extra_whitespaces', remove_extra_whitespaces)
+
+    def Normalize(self, input, with_offsets=None):
+      def _normalize(text):
+        if with_offsets:
+          return self._NormalizeWithOffsets(text)
+        return self._Normalize(text)
+
+      if type(input) is list:
+        return [_normalize(x) for x in input]
+      return _normalize(input)
+
+
+    def __getstate__(self):
+      return self.serialized_model_proto()
+
+
+    def __setstate__(self, serialized_model_proto):
+      self.__init__()
+      self.LoadFromSerializedProto(serialized_model_proto)
+
+
+# Register SentencePieceNormalizer in _sentencepiece:
+_sentencepiece.SentencePieceNormalizer_swigregister(SentencePieceNormalizer)
+
+def SetDataDir(data_dir):
+    return _sentencepiece.SetDataDir(data_dir)
+
+
+import re
+import csv
+import sys
+import os
+import importlib.resources
+from io import StringIO
+from io import BytesIO
+
+
+def _add_snake_case(classname):
+  """Added snake_cased method from CammelCased method."""
+
+  snake_map = {}
+  for k, v in classname.__dict__.items():
+    if re.match(r'^[A-Z]+', k):
+      snake = re.sub(r'(?= v.piece_size()):
+      raise IndexError('piece id is out of range.')
+    return func(v, n)
+
+  def _batched_func(self, arg):
+    if type(arg) is list:
+      return [_func(self, n) for n in arg]
+    else:
+      return _func(self, arg)
+
+  setattr(classname, name, _batched_func)
+
+
+_sentencepiece_processor_init_native = SentencePieceProcessor.__init__
+_sentencepiece_normalizer_init_native = SentencePieceNormalizer.__init__
+setattr(SentencePieceProcessor, '__init__', SentencePieceProcessor.Init)
+setattr(SentencePieceNormalizer, '__init__', SentencePieceNormalizer.Init)
+
+SentencePieceProcessor.Tokenize = SentencePieceProcessor.Encode
+SentencePieceProcessor.Detokenize = SentencePieceProcessor.Decode
+
+for m in [
+    'PieceToId', 'IdToPiece', 'GetScore', 'IsUnknown', 'IsControl', 'IsUnused',
+    'IsByte'
+]:
+  _batchnize(SentencePieceProcessor, m)
+
+_add_snake_case(SentencePieceProcessor)
+_add_snake_case(SentencePieceTrainer)
+_add_snake_case(SentencePieceNormalizer)
+set_random_generator_seed = SetRandomGeneratorSeed
+set_min_log_level = SetMinLogLevel
+
+from ._version import __version__
+
+SetDataDir(os.path.join(str(importlib.resources.files('sentencepiece')), 'package_data'))
+
+class _LogStream(object):
+  def __init__(self, ostream=None):
+    self.ostream = ostream
+    if self.ostream is not None:
+      self.orig_stream_fileno = sys.stderr.fileno()
+
+  def __enter__(self):
+    if self.ostream is not None:
+      self.orig_stream_dup = os.dup(self.orig_stream_fileno)
+      os.dup2(self.ostream.fileno(), self.orig_stream_fileno)
+
+  def __exit__(self, type, value, traceback):
+    if self.ostream is not None:
+      os.close(self.orig_stream_fileno)
+      os.dup2(self.orig_stream_dup, self.orig_stream_fileno)
+      os.close(self.orig_stream_dup)
+      self.ostream.close()
+
+
diff --git a/lib/python3.11/site-packages/sentencepiece/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/sentencepiece/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55e5c4140b4d843419cf281086341a5708fd8c4f
Binary files /dev/null and b/lib/python3.11/site-packages/sentencepiece/__pycache__/__init__.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sentencepiece/__pycache__/_version.cpython-311.pyc b/lib/python3.11/site-packages/sentencepiece/__pycache__/_version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e2ba0d55f9c2d6246a0d85672acd996e72b8a7f
Binary files /dev/null and b/lib/python3.11/site-packages/sentencepiece/__pycache__/_version.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-311.pyc b/lib/python3.11/site-packages/sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de38abc5970fef60849130c4e906e90f47113ae3
Binary files /dev/null and b/lib/python3.11/site-packages/sentencepiece/__pycache__/sentencepiece_model_pb2.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sentencepiece/__pycache__/sentencepiece_pb2.cpython-311.pyc b/lib/python3.11/site-packages/sentencepiece/__pycache__/sentencepiece_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..549dc9bf2f3ac35ca1e96764dece277cd0092226
Binary files /dev/null and b/lib/python3.11/site-packages/sentencepiece/__pycache__/sentencepiece_pb2.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sentencepiece/_version.py b/lib/python3.11/site-packages/sentencepiece/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc79d63d5430b972ac6ec1c4bfea9af80922da4d
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece/_version.py
@@ -0,0 +1 @@
+__version__ = '0.2.1'
diff --git a/lib/python3.11/site-packages/sentencepiece/sentencepiece.i b/lib/python3.11/site-packages/sentencepiece/sentencepiece.i
new file mode 100644
index 0000000000000000000000000000000000000000..20944ea1ea2ade6d4a1b2debf4e90aa8e16d91d6
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece/sentencepiece.i
@@ -0,0 +1,2013 @@
+%module sentencepiece
+%include exception.i
+
+%{
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace {
+PyObject* kUnicodeInput = reinterpret_cast(0x1);
+PyObject* kByteInput = reinterpret_cast(0x2);
+
+using BytesArray = std::vector;
+
+inline void ReleaseResultObject(PyObject *obj) {
+  if (obj != nullptr && obj != kUnicodeInput && obj != kByteInput) {
+    Py_XDECREF(obj);
+  }
+}
+
+class PyInputString {
+ public:
+  explicit PyInputString(PyObject* obj) {
+    if (PyUnicode_Check(obj)) {
+      str_ = const_cast(PyUnicode_AsUTF8AndSize(obj, &size_));
+      input_type_ = kUnicodeInput;
+    } else if (PyBytes_Check(obj)) {
+      PyBytes_AsStringAndSize(obj, &str_, &size_);
+      input_type_ = kByteInput;
+    } else {
+      str_ = nullptr;
+    }
+  }
+  absl::string_view str() const { return absl::string_view(data(), size()); }
+  const char* data() const { return str_; }
+  Py_ssize_t size() const { return size_; }
+  bool IsAvalable() const { return str_ != nullptr; }
+  PyObject *input_type() const { return input_type_; }
+
+  static bool IsUnicode(PyObject *resultobj) {
+    return (resultobj == nullptr || resultobj == kUnicodeInput);
+  }
+
+ private:
+  PyObject* input_type_ = nullptr;
+  char* str_ = nullptr;
+  Py_ssize_t size_ = 0;
+};
+
+PyObject* MakePyOutputString(const std::string& output,
+                             PyObject *resultobj) {
+  if (PyInputString::IsUnicode(resultobj)) {
+    return PyUnicode_FromStringAndSize(output.data(), output.size());
+  }
+  return PyBytes_FromStringAndSize(output.data(), output.size());
+}
+
+PyObject* MakePyOutputBytes(const sentencepiece::util::bytes& output) {
+  return PyBytes_FromStringAndSize(output.data(), output.size());
+}
+
+int ToSwigError(sentencepiece::util::StatusCode code) {
+  switch (code) {
+    case sentencepiece::util::StatusCode::kNotFound:
+      return SWIG_IOError;
+    case sentencepiece::util::StatusCode::kOutOfRange:
+      return SWIG_IndexError;
+    case sentencepiece::util::StatusCode::kInvalidArgument:
+      return SWIG_SyntaxError;
+    default:
+      return SWIG_RuntimeError;
+  }
+  return SWIG_RuntimeError;
+}
+
+class PySentenceIterator : public sentencepiece::SentenceIterator {
+  public:
+  PySentenceIterator(PyObject *iter) : iter_(iter) {
+    item_ = PyIter_Next(iter_);
+    CopyValue();
+  }
+
+  ~PySentenceIterator() {
+   // Py_XDECREF(iter_);
+  }
+
+  bool done() const override {
+    return item_ == nullptr;
+  }
+
+  void Next() override {
+    item_ = PyIter_Next(iter_);
+    CopyValue();
+  }
+
+  const std::string &value() const override {
+    return value_;
+  }
+
+  sentencepiece::util::Status status() const override {
+    return status_;
+  }
+
+  private:
+   void CopyValue() {
+     if (item_ == nullptr) return;
+     const PyInputString ustring(item_);
+     if (ustring.IsAvalable()) {
+       const char *data = ustring.data();
+       size_t size = ustring.size();
+       while (size > 0) {
+         if (data[size - 1] == '\r' || data[size - 1] == '\n')
+           --size;
+         else
+           break;
+       }
+       value_.assign(data, size);
+     } else {
+       status_ = sentencepiece::util::Status(sentencepiece::util::StatusCode::kInternal,
+                                             "Not a string.");
+     }
+     Py_XDECREF(item_);
+   }
+   PyObject *iter_ = nullptr;
+   PyObject *item_ = nullptr;
+   std::string value_;
+   sentencepiece::util::Status status_;
+};
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       std::vector *ids,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (!add_bos && !add_eos && !reverse) return;
+  if (reverse) std::reverse(ids->begin(), ids->end());
+  if (add_bos) ids->insert(ids->begin(), sp.bos_id());
+  if (add_eos) ids->push_back(sp.eos_id());
+}
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       std::vector *pieces,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (!add_bos && !add_eos && !reverse && !emit_unk_piece) return;
+  if (reverse) std::reverse(pieces->begin(), pieces->end());
+  if (add_bos) pieces->insert(pieces->begin(), sp.IdToPiece(sp.bos_id()));
+  if (add_eos) pieces->push_back(sp.IdToPiece(sp.eos_id()));
+  if (emit_unk_piece) {
+    const auto &unk = sp.IdToPiece(sp.unk_id());
+    for (auto &piece : *pieces) {
+      const int id = sp.PieceToId(piece);
+      if (id == sp.unk_id()) {
+        piece = unk;
+      }
+    }
+  }
+}
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       sentencepiece::util::bytes *proto,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (add_bos || add_eos || reverse || emit_unk_piece) {
+    throw sentencepiece::util::Status(
+        sentencepiece::util::StatusCode::kUnimplemented,
+        "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API");
+  }
+}
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       sentencepiece::ImmutableSentencePieceText *proto,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (add_bos || add_eos || reverse || emit_unk_piece) {
+    throw sentencepiece::util::Status(
+        sentencepiece::util::StatusCode::kUnimplemented,
+        "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API");
+  }
+}
+
+inline void CheckIds(const std::vector &ids, int num_pieces) {
+  for (int id : ids) {
+    if (id < 0 || id >= num_pieces) {
+      throw sentencepiece::util::Status(
+          sentencepiece::util::StatusCode::kOutOfRange,
+          "piece id is out of range.");
+    }
+  }
+}
+
+inline void CheckIds(const std::vector &ids, int num_pieces) {}
+
+inline void CheckIdsBatch(const std::vector> &ids, int num_pieces) {
+  for (const auto &v : ids) CheckIds(v, num_pieces);
+}
+
+template 
+inline void ConvertToUnicodeSpans(T *proto) {}
+
+template <>
+inline void ConvertToUnicodeSpans(sentencepiece::ImmutableSentencePieceText *proto) {
+  proto->ConvertToUnicodeSpans();
+}
+
+template <>
+inline void ConvertToUnicodeSpans(sentencepiece::ImmutableNBestSentencePieceText *proto) {
+  proto->ConvertToUnicodeSpans();
+}
+
+class ThreadPool {
+ public:
+  explicit ThreadPool(size_t request_size) :
+    request_size_(request_size) {}
+
+  virtual ~ThreadPool() {
+    for (auto &task : tasks_) {
+      task.join();
+    }
+  }
+
+  void Schedule(std::function closure) {
+    static constexpr size_t kMinThreadSize = 2;
+    if (request_size_ < kMinThreadSize) {
+      closure();
+    } else {
+      tasks_.emplace_back(closure);
+    }
+  }
+
+ private:
+  size_t request_size_ = 0;
+  std::vector tasks_;
+};
+
+template 
+inline void InitNumThreads(const std::vector &ins, int *num_threads) {
+  if (*num_threads < 0) {
+    *num_threads = std::thread::hardware_concurrency();
+  }
+  *num_threads = std::max(1,
+                               std::min({*num_threads,
+                                     static_cast(ins.size()), 256}));
+}
+
+#define DEFINE_ENCODE_BATCH_FUNC_IMPL(FuncName, InType, OutType)        \
+  std::vector outs(ins.size());                                \
+  InitNumThreads(ins, &num_threads);                                    \
+  {                                                                     \
+    ThreadPool pool(ins.size());                                        \
+    std::atomic index = 0;                                      \
+    for (int n = 0;  n < num_threads; ++n) {                            \
+      pool.Schedule([&]() {                                             \
+          size_t i = 0;                                                 \
+          while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \
+            auto out = enable_sampling ?                                \
+                       self->Sample##FuncName(ins[i],                   \
+                                              nbest_size, alpha) :      \
+                       self->FuncName(ins[i]);                          \
+            RewriteIds(*self, &out, add_bos, add_eos, reverse,          \
+                       emit_unk_piece);                                 \
+            ConvertToUnicodeSpans(&out);                                \
+            outs[i] = std::move(out);                                   \
+          }                                                             \
+        });                                                             \
+    }                                                                   \
+  }                                                                     \
+  return outs;
+
+#define DEFINE_DECODE_BATCH_FUNC_IMPL(FuncName, InType, OutType)        \
+  std::vector outs(ins.size());                                \
+  InitNumThreads(ins, &num_threads);                                    \
+  {                                                                     \
+    std::atomic index = 0;                                      \
+    ThreadPool pool(ins.size());                                        \
+    for (int n = 0;  n < num_threads; ++n) {                            \
+      pool.Schedule([&]() {                                             \
+          size_t i = 0;                                                 \
+          while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \
+            auto out = self->FuncName(ins[i]);                          \
+            ConvertToUnicodeSpans(&out);                                \
+            outs[i] = std::move(out);                                   \
+          }                                                             \
+        });                                                             \
+    }                                                                   \
+  }                                                                     \
+  return outs;
+
+}  // namespace
+%}
+
+%init %{
+#ifdef Py_GIL_DISABLED
+  PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
+#endif
+%}
+
+%exception {
+  try {
+    $action
+    ReleaseResultObject(resultobj);
+  }
+  catch (const sentencepiece::util::Status &status) {
+    SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+  }
+}
+
+%apply unsigned int { uint32_t }
+
+%ignore sentencepiece::util::Status;
+%ignore sentencepiece::util::StatusCode;
+%ignore absl::string_view;
+%ignore std::string_view;
+%ignore sentencepiece::SentencePieceText;
+%ignore sentencepiece::NormalizerSpec;
+%ignore sentencepiece::TrainerSpec;
+%ignore sentencepiece::SentencePieceProcessor::status;
+%ignore sentencepiece::ImmutableSentencePieceText::mutable_proto;
+%ignore sentencepiece::ImmutableSentencePieceText::pieces() const;
+%ignore sentencepiece::ImmutableSentencePieceText::ConvertToUnicodeSpans;
+%ignore sentencepiece::ImmutableNBestSentencePieceText::mutable_proto;
+%ignore sentencepiece::ImmutableNBestSentencePieceText::nbests() const;
+%ignore sentencepiece::ImmutableNBestSentencePieceText::ConvertToUnicodeSpans;
+
+%ignore sentencepiece::SentencePieceProcessor::Encode;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncode;
+%ignore sentencepiece::SentencePieceProcessor::NBestEncode;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScore;
+%ignore sentencepiece::SentencePieceProcessor::Decode;
+
+%ignore sentencepiece::SentencePieceProcessor::EncodeAsPieces;
+%ignore sentencepiece::SentencePieceProcessor::EncodeAsIds;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsIds;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsPieces;
+%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsIds;
+%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsPieces;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsIds;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsPieces;
+%ignore sentencepiece::SentencePieceProcessor::DecodeIds;
+%ignore sentencepiece::SentencePieceProcessor::DecodePieces;
+
+%ignore sentencepiece::SentencePieceProcessor::EncodeAsSerializedProto;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsSerializedProto;
+%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsSerializedProto;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsSerializedProto;
+%ignore sentencepiece::SentencePieceProcessor::DecodePiecesAsSerializedProto;
+%ignore sentencepiece::SentencePieceProcessor::DecodeIdsAsSerializedProto;
+
+%ignore sentencepiece::SentencePieceProcessor::EncodeAsImmutableProto;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAsImmutableProto;
+%ignore sentencepiece::SentencePieceProcessor::NBestEncodeAsImmutableProto;
+%ignore sentencepiece::SentencePieceProcessor::SampleEncodeAndScoreAsImmutableProto;
+%ignore sentencepiece::SentencePieceProcessor::DecodePiecesAsImmutableProto;
+%ignore sentencepiece::SentencePieceProcessor::DecodeIdsAsImmutableProto;
+
+%ignore sentencepiece::SentencePieceProcessor::Normalize;
+%ignore sentencepiece::SentencePieceProcessor::NormalizeWithOffsets;
+
+%ignore sentencepiece::SentencePieceProcessor::model_proto;
+%ignore sentencepiece::SentencePieceProcessor::mutable_normalizer_spec;
+%ignore sentencepiece::SentencePieceProcessor::Load;
+%ignore sentencepiece::SentencePieceProcessor::LoadOrDie;
+%ignore sentencepiece::SentencePieceProcessor::SetModel;
+%ignore sentencepiece::SentencePieceProcessor::SetNormalizer;
+%ignore sentencepiece::pretokenizer::PretokenizerForTrainingInterface;
+%ignore sentencepiece::SentenceIterator;
+%ignore sentencepiece::ConvertToUnicodeSpans;
+%ignore sentencepiece::SentencePieceTrainer::Train;
+%ignore sentencepiece::SentencePieceTrainer::GetNormalizerSpec;
+%ignore sentencepiece::SentencePieceTrainer::PopulateNormalizerSpec;
+%ignore sentencepiece::SentencePieceTrainer::MergeSpecsFromArgs;
+%ignore sentencepiece::SentencePieceTrainer::SetProtoField;
+%ignore sentencepiece::SentencePieceTrainer::PopulateModelTypeFromString;
+%ignore sentencepiece::SentencePieceTrainer::PieceProcecssor;
+%ignore sentencepiece::SentencePieceTrainer::SetPretokenizerForTraining;
+%ignore sentencepiece::SentencePieceTrainer::GetPretokenizerForTraining;
+%ignore sentencepiece::SentencePieceTrainer::SetDataDir;
+%ignore sentencepiece::ConvertToUnicodeAlignment;
+
+%ignore sentencepiece::SentencePieceNormalizer::Load;
+%ignore sentencepiece::SentencePieceNormalizer::Normalize;
+%ignore sentencepiece::SentencePieceNormalizer::mutable_normalizer_spec;
+
+%ignore sentencepiece::io::LoadModelProto;
+%ignore sentencepiece::io::SaveModelProto;
+
+%extend sentencepiece::SentencePieceProcessor {
+  sentencepiece::util::Status LoadFromFile(absl::string_view arg) {
+    return $self->Load(arg);
+  }
+
+  /////////////////////////////////////////////////////////////////////////////
+  // EncodeAs* (Single request)
+  std::vector _EncodeAsIds(absl::string_view text,
+                                bool enable_sampling,
+                                int nbest_size, float alpha,
+                                bool add_bos, bool add_eos, bool reverse,
+                                bool emit_unk_piece) const {
+    auto ids = enable_sampling ?
+               $self->SampleEncodeAsIds(text, nbest_size, alpha) :
+               $self->EncodeAsIds(text);
+    RewriteIds(*$self, &ids, add_bos, add_eos, reverse, emit_unk_piece);
+    return ids;
+  }
+
+  std::vector _EncodeAsPieces(absl::string_view text,
+                                           bool enable_sampling,
+                                           int nbest_size, float alpha,
+                                           bool add_bos, bool add_eos, bool reverse,
+                                           bool emit_unk_piece) const {
+    auto pieces = enable_sampling ?
+                  $self->SampleEncodeAsPieces(text, nbest_size, alpha) :
+                  $self->EncodeAsPieces(text);
+    RewriteIds(*$self, &pieces, add_bos, add_eos, reverse, emit_unk_piece);
+    return pieces;
+  }
+
+  sentencepiece::util::bytes _EncodeAsSerializedProto(absl::string_view text,
+                                                      bool enable_sampling,
+                                                      int nbest_size, float alpha,
+                                                      bool add_bos, bool add_eos, bool reverse,
+                                                      bool emit_unk_piece) const {
+    auto proto = enable_sampling ?
+                 $self->SampleEncodeAsSerializedProto(text, nbest_size, alpha) :
+                 $self->EncodeAsSerializedProto(text);
+    RewriteIds(*$self, &proto, add_bos, add_eos, reverse, emit_unk_piece);
+    return proto;
+  }
+
+  sentencepiece::ImmutableSentencePieceText
+      _EncodeAsImmutableProto(absl::string_view text,
+                              bool enable_sampling,
+                              int nbest_size, float alpha,
+                              bool add_bos, bool add_eos, bool reverse,
+                              bool emit_unk_piece) const {
+    auto proto = enable_sampling ?
+                 $self->SampleEncodeAsImmutableProto(text, nbest_size, alpha) :
+                 $self->EncodeAsImmutableProto(text);
+    proto.ConvertToUnicodeSpans();
+    RewriteIds(*$self, &proto, add_bos, add_eos, reverse, emit_unk_piece);
+    return proto;
+  }
+
+  /////////////////////////////////////////////////////////////////////////////
+  // EncodeAs* (Batch request)
+  std::vector> _EncodeAsIdsBatch(
+      const std::vector &ins, int num_threads,
+      bool enable_sampling, int nbest_size, float alpha,
+      bool add_bos, bool add_eos, bool reverse,
+      bool emit_unk_piece) const {
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsIds,
+                                  absl::string_view, std::vector);
+  }
+
+  std::vector> _EncodeAsPiecesBatch(
+      const std::vector &ins, int num_threads,
+      bool enable_sampling, int nbest_size, float alpha,
+      bool add_bos, bool add_eos, bool reverse,
+      bool emit_unk_piece) const {
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsPieces,
+                                  absl::string_view, std::vector);
+  }
+
+  BytesArray _EncodeAsSerializedProtoBatch(
+      const std::vector &ins, int num_threads,
+      bool enable_sampling, int nbest_size, float alpha,
+      bool add_bos, bool add_eos, bool reverse,
+      bool emit_unk_piece) const {
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsSerializedProto,
+                                  absl::string_view,
+                                  sentencepiece::util::bytes);
+  }
+
+  std::vector
+      _EncodeAsImmutableProtoBatch(
+      const std::vector &ins, int num_threads,
+      bool enable_sampling, int nbest_size, float alpha,
+      bool add_bos, bool add_eos, bool reverse,
+      bool emit_unk_piece) const {
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsImmutableProto,
+                                  absl::string_view,
+                                  sentencepiece::ImmutableSentencePieceText);
+  }
+
+  /////////////////////////////////////////////////////////////////////////////
+  // DecodeAs* (Single request)
+  std::string _DecodeIds(const std::vector &ids) const {
+    CheckIds(ids, $self->GetPieceSize());
+    return $self->DecodeIds(ids);
+  }
+
+  sentencepiece::util::bytes _DecodeIdsAsBytes(const std::vector &ids) const {
+    CheckIds(ids, $self->GetPieceSize());
+    return $self->DecodeIds(ids);
+  }
+
+  std::string _DecodePieces(const std::vector &pieces) const {
+    return $self->DecodePieces(pieces);
+  }
+
+  sentencepiece::util::bytes _DecodeIdsAsSerializedProto(
+      const std::vector &ids) const {
+    CheckIds(ids, $self->GetPieceSize());
+    return $self->DecodeIdsAsSerializedProto(ids);
+  }
+
+  sentencepiece::util::bytes _DecodePiecesAsSerializedProto(
+      const std::vector &pieces) const {
+    CheckIds(pieces, $self->GetPieceSize());
+    return $self->DecodePiecesAsSerializedProto(pieces);
+  }
+
+  sentencepiece::ImmutableSentencePieceText _DecodeIdsAsImmutableProto(
+      const std::vector &ids) const {
+    CheckIds(ids, $self->GetPieceSize());
+    auto proto = $self->DecodeIdsAsImmutableProto(ids);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+
+  sentencepiece::ImmutableSentencePieceText _DecodePiecesAsImmutableProto(
+      const std::vector &pieces) const {
+    CheckIds(pieces, $self->GetPieceSize());
+    auto proto= $self->DecodePiecesAsImmutableProto(pieces);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+
+  /////////////////////////////////////////////////////////////////////////////
+  // DecodeAs* (Batch request)
+  std::vector _DecodeIdsBatch(
+      const std::vector> &ins, int num_threads) const {
+    CheckIdsBatch(ins, $self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string);
+  }
+
+  BytesArray _DecodeIdsAsBytesBatch(
+      const std::vector> &ins, int num_threads) const {
+    CheckIdsBatch(ins, $self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string);
+  }
+
+  BytesArray _DecodeIdsAsSerializedProtoBatch(
+      const std::vector> &ins, int num_threads) const {
+    CheckIdsBatch(ins, $self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsSerializedProto, int,
+                                  sentencepiece::util::bytes);
+  }
+
+  std::vector
+      _DecodeIdsAsImmutableProtoBatch(
+          const std::vector> &ins, int num_threads) const {
+    CheckIdsBatch(ins, $self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsImmutableProto, int,
+                                  sentencepiece::ImmutableSentencePieceText);
+  }
+
+  std::vector _DecodePiecesBatch(
+      const std::vector> &ins, int num_threads) const {
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePieces, std::string, std::string);
+  }
+
+  BytesArray _DecodePiecesAsSerializedProtoBatch(
+      const std::vector> &ins, int num_threads) const {
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsSerializedProto, std::string,
+                                  sentencepiece::util::bytes);
+  }
+
+  std::vector
+      _DecodePiecesAsImmutableProtoBatch(
+          const std::vector> &ins, int num_threads) const {
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsImmutableProto, std::string,
+                                  sentencepiece::ImmutableSentencePieceText);
+  }
+
+  ////////////////////////////////////////////////////////////////////////////
+  // NBestEncodeAs* (Single request)
+  std::vector>
+      _NBestEncodeAsIds(absl::string_view text,
+                        int nbest_size,
+                        bool add_bos, bool add_eos, bool reverse,
+                        bool emit_unk_piece) const {
+    auto idss = $self->NBestEncodeAsIds(text, nbest_size);
+    for (auto &ids : idss) {
+      RewriteIds(*$self, &ids, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return idss;
+  }
+
+  std::vector>
+      _NBestEncodeAsPieces(absl::string_view text,
+                           int nbest_size,
+                           bool add_bos, bool add_eos, bool reverse,
+                           bool emit_unk_piece) const {
+    auto piecess = $self->NBestEncodeAsPieces(text, nbest_size);
+    for (auto &pieces : piecess) {
+      RewriteIds(*$self, &pieces, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return piecess;
+  }
+
+  sentencepiece::util::bytes
+      _NBestEncodeAsSerializedProto(absl::string_view text,
+                                    int nbest_size,
+                                    bool add_bos, bool add_eos, bool reverse,
+                                    bool emit_unk_piece) const {
+    RewriteIds(*$self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    return $self->NBestEncodeAsSerializedProto(text, nbest_size);
+  }
+
+  sentencepiece::ImmutableNBestSentencePieceText
+      _NBestEncodeAsImmutableProto(absl::string_view text,
+                                   int nbest_size,
+                                   bool add_bos, bool add_eos, bool reverse,
+                                   bool emit_unk_piece) const {
+    RewriteIds(*$self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    auto proto = $self->NBestEncodeAsImmutableProto(text, nbest_size);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+
+
+  /////////////////////////////////////////////////////////////////////////////
+  // SampleEncodeAndScoreAs* (Single request)
+  std::vector, float>>
+      _SampleEncodeAndScoreAsIds(absl::string_view text,
+                                 int num_samples, float alpha, bool wor,
+                                 bool include_best,
+                                 bool add_bos, bool add_eos, bool reverse,
+                                 bool emit_unk_piece) const {
+    auto idss = $self->SampleEncodeAndScoreAsIds(text, num_samples,
+                                                 alpha, wor, include_best);
+    for (auto &ids : idss) {
+      RewriteIds(*$self, &ids.first, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return idss;
+  }
+
+  std::vector, float>>
+      _SampleEncodeAndScoreAsPieces(absl::string_view text,
+                                    int num_samples, float alpha, bool wor,
+                                    bool include_best,
+                                    bool add_bos, bool add_eos, bool reverse,
+                                    bool emit_unk_piece) const {
+    auto piecess = $self->SampleEncodeAndScoreAsPieces(text, num_samples,
+                                                       alpha, wor, include_best);
+    for (auto &pieces : piecess) {
+      RewriteIds(*$self, &pieces.first, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return piecess;
+  }
+
+  sentencepiece::util::bytes
+      _SampleEncodeAndScoreAsSerializedProto(absl::string_view text,
+                                             int num_samples, float alpha, bool wor,
+                                             bool include_best,
+                                             bool add_bos, bool add_eos, bool reverse,
+                                             bool emit_unk_piece) const {
+    RewriteIds(*$self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    return $self->SampleEncodeAndScoreAsSerializedProto(text, num_samples,
+                                                        alpha, wor, include_best);
+  }
+
+  sentencepiece::ImmutableNBestSentencePieceText
+      _SampleEncodeAndScoreAsImmutableProto(absl::string_view text,
+                                            int num_samples, float alpha, bool wor,
+                                            bool include_best,
+                                            bool add_bos, bool add_eos, bool reverse,
+                                            bool emit_unk_piece) const {
+    RewriteIds(*$self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    auto proto = $self->SampleEncodeAndScoreAsImmutableProto(text, num_samples,
+                                                       alpha, wor, include_best);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+
+  // Normalize
+  std::string _Normalize(absl::string_view text) {
+    return $self->Normalize(text);
+  }
+
+  std::pair> _NormalizeWithOffsets(absl::string_view text) {
+    std::pair> result;
+    $self->Normalize(text, &result.first, &result.second).IgnoreError();
+    return result;
+  }
+
+  // Calculate Entropy
+  float _CalculateEntropy(absl::string_view text, float alpha)  {
+    return $self->CalculateEntropy(text, alpha);
+  }
+
+  std::vector _CalculateEntropyBatch(const std::vector &ins,
+                                            float alpha, int num_threads)  {
+    std::vector outs(ins.size());
+    InitNumThreads(ins, &num_threads);
+    {
+      ThreadPool pool(ins.size());
+      std::atomic index = 0;
+      for (int n = 0;  n < num_threads; ++n) {
+        pool.Schedule([&]() {
+           size_t i = 0;
+           while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) {
+             outs[i] = self->CalculateEntropy(ins[i], alpha);
+           }
+         });
+      }
+    }
+    return outs;
+  }
+
+  // override normalizer_spec
+  sentencepiece::util::Status _OverrideNormalizerSpec(
+      const std::unordered_map &args) {
+    sentencepiece::util::Status status;
+    for (const auto &[key, value] : args) {
+      status = sentencepiece::SentencePieceTrainer::SetProtoField(
+          key, value,
+          $self->mutable_normalizer_spec());
+      if (!status.ok()) return status;
+    }
+    return status;
+  }
+
+%pythoncode {
+  def Init(self,
+           model_file=None,
+           model_proto=None,
+           out_type=int,
+           add_bos=False,
+           add_eos=False,
+           reverse=False,
+           emit_unk_piece=False,
+           enable_sampling=False,
+           nbest_size=-1,
+           alpha=0.1,
+           num_threads=-1):
+    """Initialzie sentencepieceProcessor.
+
+    Args:
+      model_file: The sentencepiece model file path.
+      model_proto: The sentencepiece model serialized proto.
+      out_type: output type. int or str.
+      add_bos: Add  to the result (Default = false)
+      add_eos: Add  to the result (Default = false) / is added after
+        reversing (if enabled).
+      reverse: Reverses the tokenized sequence (Default = false)
+      emit_unk_piece: Emits the unk literal string (Default = false)
+      nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout.
+                  nbest_size = {0,1}: No sampling is performed.
+                  nbest_size > 1: samples from the nbest_size results.
+                  nbest_size < 0: assuming that nbest_size is infinite and samples
+                    from the all hypothesis (lattice) using
+                    forward-filtering-and-backward-sampling algorithm.
+      alpha: Soothing parameter for unigram sampling, and dropout probability of
+             merge operations for BPE-dropout.
+      num_threads: number of threads in batch processing (Default = -1, auto-detected)
+    """
+
+    _sentencepiece_processor_init_native(self)
+    self._out_type = out_type
+    self._add_bos = add_bos
+    self._add_eos = add_eos
+    self._reverse = reverse
+    self._emit_unk_piece = emit_unk_piece
+    self._enable_sampling = enable_sampling
+    self._nbest_size = nbest_size
+    self._alpha = alpha
+    self._num_threads = num_threads
+    if model_file or model_proto:
+      self.Load(model_file=model_file, model_proto=model_proto)
+
+
+  def Encode(self,
+             input,
+             out_type=None,
+             add_bos=None,
+             add_eos=None,
+             reverse=None,
+             emit_unk_piece=None,
+             enable_sampling=None,
+             nbest_size=None,
+             alpha=None,
+             num_threads=None):
+    """Encode text input to segmented ids or tokens.
+
+      Args:
+      input: input string. accepsts list of string.
+      out_type: output type. int or str.
+      add_bos: Add  to the result (Default = false)
+      add_eos: Add  to the result (Default = false) / is added after
+               reversing (if enabled).
+      reverse: Reverses the tokenized sequence (Default = false)
+      emit_unk_piece: Emits the unk literal string (Default = false)
+      nbest_size: sampling parameters for unigram. Invalid in BPE-Dropout.
+                  nbest_size = {0,1}: No sampling is performed.
+                  nbest_size > 1: samples from the nbest_size results.
+                  nbest_size < 0: assuming that nbest_size is infinite and samples
+                  from the all hypothesis (lattice) using
+                  forward-filtering-and-backward-sampling algorithm.
+      alpha: Soothing parameter for unigram sampling, and merge probability for
+             BPE-dropout (probablity 'p' in BPE-dropout paper).
+      num_threads: the number of threads used in the batch processing (Default = -1).
+    """
+
+    if out_type is None:
+      out_type = self._out_type
+    if add_bos is None:
+      add_bos = self._add_bos
+    if add_eos is None:
+      add_eos = self._add_eos
+    if reverse is None:
+      reverse = self._reverse
+    if emit_unk_piece is None:
+      emit_unk_piece = self._emit_unk_piece
+    if enable_sampling is None:
+      enable_sampling = self._enable_sampling
+    if nbest_size is None:
+      nbest_size = self._nbest_size
+    if alpha is None:
+      alpha = self._alpha
+    if num_threads is None:
+      num_threads = self._num_threads
+
+    if enable_sampling == True and (nbest_size is None or nbest_size == 0 or
+                                    nbest_size == 1 or alpha is None):
+      raise RuntimeError(
+          'When enable_sampling is True, We must specify "nbest_size > 1" or "nbest_size = -1", '
+          'and "alpha". "nbest_size" is enabled only on unigram mode ignored in BPE-dropout. '
+          'when "nbest_size = -1" , this method samples from all candidates on the lattice '
+          'instead of nbest segmentations.'
+      )
+
+    if num_threads is None or type(num_threads) is not int:
+      raise RuntimeError('num_threads must be int')
+
+    if type(input) is list:
+      if out_type is int:
+        return self._EncodeAsIdsBatch(input, num_threads, enable_sampling, nbest_size,
+                                      alpha, add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type is str:
+        return self._EncodeAsPiecesBatch(input, num_threads, enable_sampling, nbest_size,
+                                         alpha, add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type == 'serialized_proto' or out_type == 'proto':
+        return self._EncodeAsSerializedProtoBatch(input, num_threads, enable_sampling, nbest_size,
+                                                  alpha, add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type == 'immutable_proto':
+        return self._EncodeAsImmutableProtoBatch(input, num_threads, enable_sampling, nbest_size,
+                                                 alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    if out_type is int:
+      return self._EncodeAsIds(input, enable_sampling, nbest_size,
+                               alpha, add_bos, add_eos, reverse, emit_unk_piece)
+    if out_type is str:
+      return self._EncodeAsPieces(input, enable_sampling, nbest_size,
+                                  alpha, add_bos, add_eos, reverse, emit_unk_piece)
+    if out_type == 'serialized_proto' or out_type == 'proto':
+      return self._EncodeAsSerializedProto(input, enable_sampling, nbest_size,
+                                           alpha, add_bos, add_eos, reverse, emit_unk_piece)
+    if out_type == 'immutable_proto':
+      return self._EncodeAsImmutableProto(input, enable_sampling, nbest_size,
+                                          alpha, add_bos, add_eos, reverse, emit_unk_piece)
+
+    raise RuntimeError('unknown out_type={}'.format(out_type))
+    return None
+
+
+  def EncodeAsPieces(self, input, **kwargs):
+    return self.Encode(input=input, out_type=str, **kwargs)
+
+
+  def EncodeAsIds(self, input, **kwargs):
+    return self.Encode(input=input, out_type=int, **kwargs)
+
+
+  def EncodeAsSerializedProto(self, input, **kwargs):
+    return self.Encode(input=input, out_type='serialized_proto', **kwargs)
+
+
+  def EncodeAsImmutableProto(self, input, **kwargs):
+    return self.Encode(input=input, out_type='immutable_proto', **kwargs)
+
+
+  def SampleEncodeAsPieces(self, input, nbest_size=None, alpha=None, **kwargs):
+    return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                       out_type=str, enable_sampling=True, **kwargs)
+
+
+  def SampleEncodeAsIds(self, input, nbest_size=None, alpha=None,**kwargs):
+    return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                       out_type=int, enable_sampling=True, **kwargs)
+
+
+  def SampleEncodeAsSerializedProto(self, input, nbest_size=None, alpha=None, **kwargs):
+    return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                       out_type='serialized_proto', enable_sampling=True, **kwargs)
+
+
+  def SampleEncodeAsImmutableProto(self, input, nbest_size=None, alpha=None, **kwargs):
+    return self.Encode(input=input, nbest_size=nbest_size, alpha=alpha,
+                       out_type='immutable_proto', enable_sampling=True, **kwargs)
+
+
+  def NBestEncode(self,
+                  input,
+                  out_type=None,
+                  add_bos=None,
+                  add_eos=None,
+                  reverse=None,
+                  emit_unk_piece=None,
+                  nbest_size=None):
+    """NBestEncode text input to segmented ids or tokens.
+
+      Args:
+      input: input string. accepsts list of string.
+      out_type: output type. int or str.
+      add_bos: Add  to the result (Default = false)
+      add_eos: Add  to the result (Default = false) / is added after reversing (if enabled).
+      reverse: Reverses the tokenized sequence (Default = false)
+      emit_unk_piece: Emits the unk literal string (Default = false)
+      nbest_size: nbest size
+    """
+
+    if out_type is None:
+      out_type = self._out_type
+    if add_bos is None:
+      add_bos = self._add_bos
+    if add_eos is None:
+      add_eos = self._add_eos
+    if reverse is None:
+      reverse = self._reverse
+    if emit_unk_piece is None:
+      emit_unk_piece = self._emit_unk_piece
+    if nbest_size is None:
+      nbest_size = self._nbest_size
+
+    if nbest_size <= 0:
+      nbest_size=1
+
+    def _encode(text):
+      if out_type is int:
+        return self._NBestEncodeAsIds(text, nbest_size,
+                                      add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type is str:
+        return self._NBestEncodeAsPieces(text, nbest_size,
+                                         add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type == 'serialized_proto' or out_type == 'proto':
+        return self._NBestEncodeAsSerializedProto(text, nbest_size,
+                                                  add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type == 'immutable_proto':
+        return self._NBestEncodeAsImmutableProto(text, nbest_size,
+                                                 add_bos, add_eos, reverse, emit_unk_piece)
+
+      raise RuntimeError('unknown out_type')
+
+    if type(input) is list:
+      return [_encode(n) for n in input]
+
+    return _encode(input)
+
+
+  def NBestEncodeAsPieces(self, input, nbest_size=None, **kwargs):
+    return self.NBestEncode(input=input, nbest_size=nbest_size,
+                            out_type=str, **kwargs)
+
+
+  def NBestEncodeAsIds(self, input, nbest_size=None, **kwargs):
+    return self.NBestEncode(input=input, nbest_size=nbest_size,
+                            out_type=int, **kwargs)
+
+
+  def NBestEncodeAsSerializedProto(self, input, nbest_size=None, **kwargs):
+    return self.NBestEncode(input=input, nbest_size=nbest_size,
+                            out_type='serialized_proto', **kwargs)
+
+
+  def NBestEncodeAsImmutableProto(self, input, nbest_size=None, **kwargs):
+    return self.NBestEncode(input=input, nbest_size=nbest_size,
+                            out_type='immutable_proto', **kwargs)
+
+
+  def SampleEncodeAndScore(self,
+                           input,
+                           out_type=None,
+                           add_bos=None,
+                           add_eos=None,
+                           reverse=None,
+                           emit_unk_piece=None,
+                           num_samples=None,
+                           alpha=None,
+                           wor=None,
+                           include_best=None):
+    """SampleEncodeAndScore text input to segmented ids or tokens.
+
+      Args:
+      input: input string. accepsts list of string.
+      out_type: output type. int or str or 'serialized_proto' or 'immutable_proto'
+      add_bos: Add  to the result (Default = false)
+      add_eos: Add  to the result (Default = false) / is added after reversing (if enabled).
+      reverse: Reverses the tokenized sequence (Default = false)
+      emit_unk_piece: Emits the unk literal string (Default = false)
+      num_samples: How many samples to return (Default = 1)
+      alpha: inverse temperature for sampling
+      wor: whether to sample without replacement (Default = false)
+      include_best: whether to include the best tokenization, requires wor=True (Default = false)
+    """
+
+    if out_type is None:
+      out_type = self._out_type
+    if add_bos is None:
+      add_bos = self._add_bos
+    if add_eos is None:
+      add_eos = self._add_eos
+    if reverse is None:
+      reverse = self._reverse
+    if emit_unk_piece is None:
+      emit_unk_piece = self._emit_unk_piece
+    if num_samples is None:
+      num_samples = 1
+    if alpha is None:
+      alpha = 1.
+    if wor is None:
+      wor = False
+    if include_best is None:
+      include_best = False
+
+    if num_samples <= 0:
+      raise RuntimeError('num_examples must be positive')
+
+    if include_best and not wor:
+      raise RuntimeError('When include_best is True, We must specify "wor = True".')
+
+
+    def _encode(text):
+      if out_type is int:
+        return self._SampleEncodeAndScoreAsIds(text, num_samples, alpha, wor, include_best,
+                                               add_bos, add_eos, reverse, emit_unk_piece)
+      if out_type is str:
+        return self._SampleEncodeAndScoreAsPieces(text, num_samples, alpha, wor, include_best,
+                                                  add_bos, add_eos, reverse, emit_unk_piece)
+
+      if out_type == 'serialized_proto' or out_type == 'proto':
+        return self._SampleEncodeAndScoreAsSerializedProto(text, num_samples, alpha, wor, include_best,
+                                                           add_bos, add_eos, reverse, emit_unk_piece)
+
+      if out_type == 'immutable_proto':
+        return self._SampleEncodeAndScoreAsImmutableProto(text, num_samples, alpha, wor, include_best,
+                                                          add_bos, add_eos, reverse, emit_unk_piece)
+
+      raise RuntimeError('unknown output type')
+
+
+    if type(input) is list:
+      return [_encode(n) for n in input]
+
+    return _encode(input)
+
+
+  def SampleEncodeAndScoreAsPieces(self, input, num_samples=None, alpha=None, **kwargs):
+    return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                     out_type=str, **kwargs)
+
+
+  def SampleEncodeAndScoreAsIds(self, input, num_samples=None, alpha=None, **kwargs):
+    return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                     out_type=int, **kwargs)
+
+
+  def SampleEncodeAndScoreAsSerializedProto(self, input, num_samples=None, alpha=None, **kwargs):
+    return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                     out_type='serialized_proto', **kwargs)
+
+
+  def SampleEncodeAndScoreAsImmutableProto(self, input, num_samples=None, alpha=None, **kwargs):
+    return self.SampleEncodeAndScore(input=input, num_samples=num_samples, alpha=alpha,
+                                     out_type='immutable_proto', **kwargs)
+
+
+  def Decode(self, input, out_type=str, num_threads=None):
+    """Decode processed id or token sequences.
+
+    Args:
+      out_type: output type. str, bytes or 'serialized_proto' or 'immutable_proto' (Default = str)
+      num_threads: the number of threads used in the batch processing (Default = -1).
+    """
+
+    if num_threads is None:
+      num_threads = self._num_threads
+
+    if num_threads is None or type(num_threads) is not int:
+      raise RuntimeError('num_threads must be int')
+
+    if not input:
+      return ''
+
+    if out_type is str:
+      if type(input) is int:
+        return self._DecodeIds([input])
+      if type(input) is str:
+        return self._DecodePieces([input])
+
+      if type(input) is list:
+        if len(input) == 0 or type(input[0]) is int:
+          return self._DecodeIds(input)
+        if type(input[0]) is str:
+          return self._DecodePieces(input)
+
+        if type(input[0]) is list:
+          if len(input[0]) == 0 or type(input[0][0]) is int:
+           return self._DecodeIdsBatch(input, num_threads)
+          if type(input[0][0]) is str:
+           return self._DecodePiecesBatch(input, num_threads)
+
+    if out_type is bytes:
+      if type(input) is int:
+        return self._DecodeIdsAsBytes([input])
+      if type(input) is str:
+        return self._DecodePieces([input])
+
+      if type(input) is list:
+        if len(input) == 0 or type(input[0]) is int:
+          return self._DecodeIdsAsBytes(input)
+        if type(input[0]) is str:
+          return self._DecodePieces(input)
+
+        if type(input[0]) is list:
+          if len(input[0]) == 0 or type(input[0][0]) is int:
+           return self._DecodeIdsAsBytesBatch(input, num_threads)
+          if type(input[0][0]) is str:
+           return self._DecodePiecesBatch(input, num_threads)
+
+    if out_type == 'serialized_proto':
+      if type(input) is int:
+        return self._DecodeIdsAsSerializedProto([input])
+      if type(input) is str:
+        return self._DecodePiecesAsSerializedProto([input])
+
+      if type(input) is list:
+        if len(input) == 0 or type(input[0]) is int:
+          return self._DecodeIdsAsSerializedProto(input)
+        if type(input[0]) is str:
+          return self._DecodePiecesAsSerializedProto(input)
+
+        if type(input[0]) is list:
+          if len(input[0]) == 0 or type(input[0][0]) is int:
+           return self._DecodeIdsAsSerializedProtoBatch(input, num_threads)
+          if type(input[0][0]) is str:
+           return self._DecodePiecesAsSerializedProtoBatch(input, num_threads)
+
+
+    if out_type == 'immutable_proto':
+      if type(input) is int:
+        return self._DecodeIdsAsImmutableProto([input])
+      if type(input) is str:
+        return self._DecodePiecesAsImmutableProto([input])
+
+      if type(input) is list:
+        if len(input) == 0 or type(input[0]) is int:
+          return self._DecodeIdsAsImmutableProto(input)
+        if type(input[0]) is str:
+          return self._DecodePiecesAsImmutableProto(input)
+
+        if type(input[0]) is list:
+          if len(input[0]) == 0 or type(input[0][0]) is int:
+           return self._DecodeIdsAsImmutableProtoBatch(input, num_threads)
+          if type(input[0][0]) is str:
+           return self._DecodePiecesAsImmutableProtoBatch(input, num_threads)
+
+
+    raise RuntimeError('unknown output or input type')
+    return None
+
+
+  def DecodePieces(self, input, out_type=str, **kwargs):
+    return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+  def DecodeIds(self, input, out_type=str, **kwargs):
+    return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+  def DecodePiecesAsSerializedProto(self, input, out_type='serialized_proto', **kwargs):
+    return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+  def DecodeIdsAsSerializedProto(self, input, out_type='serialized_proto', **kwargs):
+    return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+  def DecodePiecesAsImmutableProto(self, input, out_type='immutable_proto', **kwargs):
+    return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+  def DecodeIdsAsImmutableProto(self, input, out_type='immutable_proto', **kwargs):
+    return self.Decode(input=input, out_type=out_type, **kwargs)
+
+
+  def CalculateEntropy(self, input, alpha, num_threads=None):
+    """Calculate sentence entropy"""
+    if type(input) is list:
+      if num_threads is None:
+        num_threads = self._num_threads
+      if num_threads is None or type(num_threads) is not int:
+        raise RuntimeError('num_threads must be int')
+      return self._CalculateEntropyBatch(input, alpha, num_threads)
+
+    return self._CalculateEntropy(input, alpha)
+
+
+  def Normalize(self, input, with_offsets=None):
+    def _normalize(text):
+      if with_offsets:
+        return self._NormalizeWithOffsets(text)
+      return self._Normalize(text)
+
+    if type(input) is list:
+      return [_normalize(x) for x in input]
+    return _normalize(input)
+
+  def OverrideNormalizerSpec(self, **kwargs):
+    new_kwargs = {}
+    for key, value in kwargs.items():
+      new_kwargs[key] = str(value)
+    return self._OverrideNormalizerSpec(new_kwargs)
+
+
+  def piece_size(self):
+    return self.GetPieceSize()
+
+
+  def vocab_size(self):
+    return self.GetPieceSize()
+
+
+  def __getstate__(self):
+    return self.serialized_model_proto()
+
+
+  def __setstate__(self, serialized_model_proto):
+    self.__init__()
+    self.LoadFromSerializedProto(serialized_model_proto)
+
+
+  def __len__(self):
+    return self.GetPieceSize()
+
+
+  def __getitem__(self, piece):
+    return self.PieceToId(piece)
+
+
+  def Load(self, model_file=None, model_proto=None):
+    """Overwride SentencePieceProcessor.Load to support both model_file and model_proto.
+
+    Args:
+      model_file: The sentencepiece model file path.
+      model_proto: The sentencepiece model serialized proto. Either `model_file`
+        or `model_proto` must be set.
+    """
+    if model_file and model_proto:
+      raise RuntimeError('model_file and model_proto must be exclusive.')
+    if model_proto:
+      return self.LoadFromSerializedProto(model_proto)
+    return self.LoadFromFile(model_file)
+}
+}
+
+%extend sentencepiece::SentencePieceTrainer {
+  static void _TrainFromString(absl::string_view arg) {
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(arg);
+    if (!_status.ok()) throw _status;
+    return;
+  }
+
+  static void _TrainFromMap(const std::unordered_map &args) {
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args);
+    if (!_status.ok()) throw _status;
+    return;
+  }
+
+  static void _TrainFromMap2(const std::unordered_map &args,
+                            SentenceIterator *iter) {
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter);
+    if (!_status.ok()) throw _status;
+    return;
+  }
+
+  static sentencepiece::util::bytes _TrainFromMap3(const std::unordered_map &args) {
+    sentencepiece::util::bytes model_proto;
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args, nullptr, &model_proto);
+    if (!_status.ok()) throw _status;
+    return model_proto;
+  }
+
+  static sentencepiece::util::bytes _TrainFromMap4(const std::unordered_map &args,
+                                                  SentenceIterator *iter) {
+    sentencepiece::util::bytes model_proto;
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter, &model_proto);
+    if (!_status.ok()) throw _status;
+    return model_proto;
+  }
+
+%pythoncode {
+  @staticmethod
+  def _Train(arg=None, **kwargs):
+    """Train Sentencepiece model. Accept both kwargs and legacy string arg."""
+    if arg is not None and type(arg) is str:
+      return SentencePieceTrainer._TrainFromString(arg)
+
+    def _encode(value):
+      """Encode value to CSV.."""
+      if type(value) is list:
+        if sys.version_info[0] == 3:
+          f = StringIO()
+        else:
+          f = BytesIO()
+        writer = csv.writer(f, lineterminator='')
+        writer.writerow([str(v) for v in value])
+        return f.getvalue()
+      else:
+        return str(value)
+
+    sentence_iterator = None
+    model_writer = None
+    new_kwargs = {}
+    for key, value in kwargs.items():
+      if key in ['sentence_iterator', 'sentence_reader']:
+        sentence_iterator = value
+      elif key in ['model_writer']:
+        model_writer = value
+      else:
+        new_kwargs[key] = _encode(value)
+
+    if model_writer:
+      if sentence_iterator:
+        model_proto = SentencePieceTrainer._TrainFromMap4(new_kwargs,
+                                                         sentence_iterator)
+      else:
+        model_proto = SentencePieceTrainer._TrainFromMap3(new_kwargs)
+      model_writer.write(model_proto)
+    else:
+      if sentence_iterator:
+        return SentencePieceTrainer._TrainFromMap2(new_kwargs, sentence_iterator)
+      else:
+        return SentencePieceTrainer._TrainFromMap(new_kwargs)
+
+    return None
+
+  @staticmethod
+  def Train(arg=None, logstream=None, **kwargs):
+    with _LogStream(ostream=logstream):
+      SentencePieceTrainer._Train(arg=arg, **kwargs)
+}
+}
+
+%extend sentencepiece::SentencePieceNormalizer {
+  sentencepiece::util::Status LoadFromFile(absl::string_view arg) {
+    return $self->Load(arg);
+  }
+
+  std::string _Normalize(absl::string_view text) {
+    std::string result;
+    const auto _status = $self->Normalize(text, &result);
+    if (!_status.ok()) throw _status;
+    return result;
+  }
+
+  std::pair> _NormalizeWithOffsets(absl::string_view text) {
+    std::pair> result;
+    const auto _status = $self->Normalize(text, &result.first, &result.second);
+    if (!_status.ok()) throw _status;
+    return result;
+  }
+
+  void _SetProtoField(absl::string_view name, bool value) {
+    sentencepiece::SentencePieceTrainer::SetProtoField(
+        name,
+        value ? "1" : "0",
+        $self->mutable_normalizer_spec()).IgnoreError();
+  }
+
+%pythoncode %{
+  def Init(self,
+           model_file=None,
+           model_proto=None,
+           rule_tsv=None,
+           rule_name=None,
+           add_dummy_prefix=False,
+           escape_whitespaces=False,
+           remove_extra_whitespaces=False):
+    """Initialzie sentencePieceNormalizer.
+
+    Args:
+      model_file: The sentencepiece model file path.
+      model_proto: The sentencepiece model serialized proto.
+      rule_tsv: The normalization rule file in TSV format.
+      rule_name: Pre-defined normalization name.
+      add_dummy_prefix: add dummy prefix.
+      escape_whitespaces: escape whitespaces.
+      remove_extra_whitespaces: remove extra whitespaces.
+    """
+
+    _sentencepiece_normalizer_init_native(self)
+
+    if model_file:
+      status = self.LoadFromFile(model_file)
+    elif model_proto:
+      status = self.LoadFromSerializedProto(model_proto)
+    elif rule_tsv:
+      status = self.LoadFromRuleTSV(rule_tsv)
+    elif rule_name:
+      status = self.LoadFromRuleName(rule_name)
+    else:
+      raise RuntimeError('no model is specified')
+
+    if status:
+      self._SetProtoField('add_dummy_prefix', add_dummy_prefix)
+      self._SetProtoField('escape_whitespaces', escape_whitespaces)
+      self._SetProtoField('remove_extra_whitespaces', remove_extra_whitespaces)
+
+  def Normalize(self, input, with_offsets=None):
+    def _normalize(text):
+      if with_offsets:
+        return self._NormalizeWithOffsets(text)
+      return self._Normalize(text)
+
+    if type(input) is list:
+      return [_normalize(x) for x in input]
+    return _normalize(input)
+
+
+  def __getstate__(self):
+    return self.serialized_model_proto()
+
+
+  def __setstate__(self, serialized_model_proto):
+    self.__init__()
+    self.LoadFromSerializedProto(serialized_model_proto)
+%}
+}
+
+%extend sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece {
+  const sentencepiece::util::bytes& _surface_as_bytes() const {
+    return $self->surface();
+  }
+
+  const sentencepiece::util::bytes& _piece_as_bytes() const {
+    return $self->piece();
+  }
+
+  %rename(_piece) piece;
+  %rename(_piece_as_bytes) piece_as_bytes;
+  %rename(_id) id;
+  %rename(_surface) surface;
+  %rename(_surface_as_bytes) surface_as_bytes;
+  %rename(_begin) begin;
+  %rename(_end) end;
+
+  %pythoncode %{
+    piece = property(_piece)
+    piece_as_bytes = property(_piece_as_bytes)
+    surface = property(_surface)
+    surface_as_bytes = property(_surface_as_bytes)
+    id = property(_id)
+    begin = property(_begin)
+    end = property(_end)
+
+    def __str__(self):
+      return ('piece: \"{}\"\n'
+              'id: {}\n'
+              'surface: \"{}\"\n'
+              'begin: {}\n'
+              'end: {}\n').format(self.piece, self.id, self.surface,
+                                  self.begin, self.end)
+
+    def __eq__(self, other):
+      return self.piece == other.piece and self.id == other.id and self.surface == other.surface and self.begin == other.begin and self.end == other.end
+
+    def __hash__(self):
+      return hash(str(self))
+
+    __repr__ = __str__
+  %}
+}
+
+%extend sentencepiece::ImmutableSentencePieceText {
+  const sentencepiece::util::bytes& _text_as_bytes() const {
+    return $self->text();
+  }
+
+  %rename(_text) text;
+  %rename(_text_as_bytes) text_as_bytes;
+  %rename(_score) score;
+  %rename(_pieces) pieces;
+  %rename(_pieces_size) pieces_size;
+
+  %pythoncode %{
+    text = property(_text)
+    text_as_bytes = property(_text_as_bytes)
+    score = property(_score)
+
+    class ImmutableSentencePieceIterator:
+      def __init__(self, proto):
+        self.proto = proto
+        self.len = self.proto._pieces_size()
+
+      def __len__(self):
+        return self.len
+
+      def __getitem__(self, index):
+        if isinstance(index, slice):
+          return [self.proto._pieces(i) for i in range(self.len)][index.start:index.stop:index.step]
+        if index < 0:
+          index = index + self.len
+        if index < 0 or index >= self.len:
+          raise IndexError('piece index is out of range')
+        return self.proto._pieces(index)
+
+      def __str__(self):
+        return '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self])
+
+      __repr__ = __str__
+
+    @property
+    def pieces(self):
+      return ImmutableSentencePieceText.ImmutableSentencePieceIterator(self)
+
+    def __eq__(self, other):
+      return self.SerializeAsString() == other.SerializeAsString()
+
+    def __hash__(self):
+      return hash(self.SerializeAsString())
+
+    def __str__(self):
+      return ('text: \"{}\"\n'
+              'score: {}\n'
+              '{}').format(self.text, self.score,
+                           '\n'.join(['pieces {{\n{}}}'.format(str(x)) for x in self.pieces]))
+
+    __repr__ = __str__
+  %}
+}
+
+%extend sentencepiece::ImmutableNBestSentencePieceText {
+  %rename(_nbests) nbests;
+  %rename(_nbests_size) nbests_size;
+
+  %pythoncode %{
+    class ImmutableSentencePieceTextIterator:
+      def __init__(self, proto):
+        self.proto = proto
+        self.len = self.proto._nbests_size()
+
+      def __len__(self):
+        return self.len
+
+      def __getitem__(self, index):
+        if isinstance(index, slice):
+          return [self.proto._nbests(i) for i in range(self.len)][index.start:index.stop:index.step]
+        if index < 0:
+          index = index + self.len
+        if index < 0 or index >= self.len:
+          raise IndexError('nbests index is out of range')
+        return self.proto._nbests(index)
+
+      def __str__(self):
+        return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self])
+
+      __repr__ = __str__
+
+    @property
+    def nbests(self):
+      return ImmutableNBestSentencePieceText.ImmutableSentencePieceTextIterator(self)
+
+    def __eq__(self, other):
+      return self.SerializeAsString() == other.SerializeAsString()
+
+    def __hash__(self):
+      return hash(self.SerializeAsString())
+
+    def __str__(self):
+      return '\n'.join(['nbests {{\n{}}}'.format(str(x)) for x in self.nbests])
+
+    __repr__ = __str__
+  %}
+}
+
+%typemap(out) std::vector {
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyList_SET_ITEM($result, i, PyInt_FromLong(static_cast($1[i])));
+  }
+}
+
+%typemap(out) std::vector {
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyList_SET_ITEM($result, i, PyFloat_FromDouble(static_cast($1[i])));
+  }
+}
+
+%typemap(out) std::vector> {
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyObject *obj = PyList_New($1[i].size());
+    for (size_t j = 0; j < $1[i].size(); ++j) {
+      PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast($1[i][j])));
+    }
+    PyList_SET_ITEM($result, i, obj);
+  }
+}
+
+%typemap(out) std::vector {
+  PyObject *input_type = resultobj;
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyList_SET_ITEM($result, i, MakePyOutputString($1[i], input_type));
+  }
+}
+
+%typemap(out) BytesArray {
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyList_SET_ITEM($result, i, MakePyOutputBytes($1[i]));
+  }
+}
+
+%typemap(out) std::vector> {
+  PyObject *input_type = resultobj;
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyObject *obj = PyList_New($1[i].size());
+    for (size_t j = 0; j < $1[i].size(); ++j) {
+      PyList_SET_ITEM(obj, j, MakePyOutputString($1[i][j], input_type));
+    }
+    PyList_SET_ITEM($result, i, obj);
+  }
+}
+
+%typemap(out) sentencepiece::util::bytes {
+  $result = MakePyOutputBytes($1);
+}
+
+%typemap(out) const sentencepiece::util::bytes& {
+  $result = MakePyOutputBytes(*$1);
+}
+
+%typemap(out) std::string {
+  PyObject *input_type = resultobj;
+  $result = MakePyOutputString($1, input_type);
+}
+
+%typemap(out) const std::string& {
+  PyObject *input_type = resultobj;
+  $result = MakePyOutputString(*$1, input_type);
+}
+
+%typemap(out) sentencepiece::util::Status {
+  if (!$1.ok()) {
+    SWIG_exception(ToSwigError($1.code()), $1.ToString().c_str());
+  }
+  $result = SWIG_From_bool($1.ok());}
+
+
+%typemap(in) const std::string & {
+  const PyInputString ustring($input);
+  if (!ustring.IsAvalable()) {
+    PyErr_SetString(PyExc_TypeError, "not a string");
+    SWIG_fail;
+  }
+  resultobj = ustring.input_type();
+  $1 = new std::string(ustring.data(), ustring.size());
+}
+
+%typemap(typecheck) absl::string_view = char *;
+
+%typemap(in) absl::string_view {
+  const PyInputString ustring($input);
+  if (!ustring.IsAvalable()) {
+    PyErr_SetString(PyExc_TypeError, "not a string");
+    SWIG_fail;
+  }
+  resultobj = ustring.input_type();
+  $1 = ustring.str();
+}
+
+%typemap(in) const std::vector& {
+  std::vector *out = nullptr;
+  if (PyList_Check($input)) {
+    const size_t size = PyList_Size($input);
+    out = new std::vector(size);
+    for (size_t i = 0; i < size; ++i) {
+      const PyInputString ustring(PyList_GetItem($input, i));
+      if (ustring.IsAvalable()) {
+        (*out)[i] = ustring.str();
+      } else {
+        PyErr_SetString(PyExc_TypeError, "list must contain strings");
+        SWIG_fail;
+      }
+      resultobj = ustring.input_type();
+    }
+  } else {
+    PyErr_SetString(PyExc_TypeError, "not a list");
+    SWIG_fail;
+  }
+  $1 = out;
+}
+
+%typemap(in) const std::vector& {
+  std::vector *out = nullptr;
+  if (PyList_Check($input)) {
+    const size_t size = PyList_Size($input);
+    out = new std::vector(size);
+    for (size_t i = 0; i < size; ++i) {
+      PyObject *o = PyList_GetItem($input, i);
+      if (PyInt_Check(o)) {
+        (*out)[i] = static_cast(PyInt_AsLong(o));
+      } else {
+        PyErr_SetString(PyExc_TypeError,"list must contain integers");
+        SWIG_fail;
+      }
+    }
+  } else {
+    PyErr_SetString(PyExc_TypeError,"not a list");
+    SWIG_fail;
+  }
+  $1 = out;
+}
+
+%typemap(in) const std::vector>& {
+  std::vector> *out = nullptr;
+  if (PyList_Check($input)) {
+    const size_t size = PyList_Size($input);
+    out = new std::vector>(size);
+    for (size_t i = 0; i < size; ++i) {
+      PyObject *o = PyList_GetItem($input, i);
+      if (PyList_Check(o)) {
+        const size_t size2 = PyList_Size(o);
+        (*out)[i].resize(size2);
+        for (size_t j = 0; j < size2; ++j) {
+          const PyInputString ustring(PyList_GetItem(o, j));
+          if (ustring.IsAvalable()) {
+            (*out)[i][j] = ustring.str();
+          } else {
+            PyErr_SetString(PyExc_TypeError,"list must contain integers");
+            SWIG_fail;
+          }
+          resultobj = ustring.input_type();
+        }
+      } else {
+        PyErr_SetString(PyExc_TypeError,"not a list");
+        SWIG_fail;
+      }
+    }
+  } else {
+    PyErr_SetString(PyExc_TypeError,"not a list");
+    SWIG_fail;
+  }
+  $1 = out;
+}
+
+%typemap(in) const std::vector>& {
+  std::vector> *out = nullptr;
+  if (PyList_Check($input)) {
+    const size_t size = PyList_Size($input);
+    out = new std::vector>(size);
+    for (size_t i = 0; i < size; ++i) {
+      PyObject *o = PyList_GetItem($input, i);
+      if (PyList_Check(o)) {
+        const size_t size2 = PyList_Size(o);
+        (*out)[i].resize(size2);
+        for (size_t j = 0; j < size2; ++j) {
+          PyObject *o2 = PyList_GetItem(o, j);
+          if (PyInt_Check(o2)) {
+            (*out)[i][j] = static_cast(PyInt_AsLong(o2));
+          } else {
+            PyErr_SetString(PyExc_TypeError, "list must contain strings");
+            SWIG_fail;
+          }
+        }
+      } else {
+        PyErr_SetString(PyExc_TypeError, "not a list");
+        SWIG_fail;
+      }
+    }
+  } else {
+    PyErr_SetString(PyExc_TypeError,"not a list");
+    SWIG_fail;
+  }
+  $1 = out;
+}
+
+%typemap(in) const std::unordered_map & {
+  std::unordered_map *out = nullptr;
+  if (PyDict_Check($input)) {
+    PyObject *key, *value;
+    Py_ssize_t pos = 0;
+    out = new std::unordered_map;
+    while (PyDict_Next($input, &pos, &key, &value)) {
+      const PyInputString key_ustring(key);
+      const PyInputString value_ustring(value);
+      if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) {
+        out->emplace(std::string(key_ustring.data(), key_ustring.size()),
+                     std::string(value_ustring.data(), value_ustring.size()));
+      } else {
+        PyErr_SetString(PyExc_TypeError, "map must contain strings.");
+        SWIG_fail;
+      }
+      resultobj = key_ustring.input_type();
+    }
+  } else {
+    PyErr_SetString(PyExc_TypeError, "not a dictionary");
+    SWIG_fail;
+  }
+  $1 = out;
+}
+
+%typemap(out) std::vector, float>> {
+  PyObject *input_type = resultobj;
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyObject *obj = PyList_New($1[i].first.size());
+    for (size_t j = 0; j < $1[i].first.size(); ++j) {
+      PyList_SET_ITEM(obj, j, MakePyOutputString($1[i].first[j], input_type));
+    }
+    PyList_SET_ITEM($result, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast($1[i].second))));
+  }
+}
+
+%typemap(out) std::vector, float>> {
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyObject *obj = PyList_New($1[i].first.size());
+    for (size_t j = 0; j < $1[i].first.size(); ++j) {
+      PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast($1[i].first[j])));
+    }
+    PyList_SET_ITEM($result, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast($1[i].second))));
+  }
+}
+
+%typemap(out) std::vector {
+  $result = PyList_New($1.size());
+  for (size_t i = 0; i < $1.size(); ++i) {
+    PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText($1.at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0);
+    PyList_SET_ITEM($result, i, obj);
+  }
+}
+
+// Types for normalized string and offset
+%typemap(out) std::pair> {
+  PyObject *input_type = resultobj;
+  if (PyInputString::IsUnicode(input_type)) {
+    sentencepiece::ConvertToUnicodeAlignment(arg2, $1.first, &$1.second);
+  }
+  PyObject *obj = PyList_New($1.second.size());
+  for (size_t i = 0; i < $1.second.size(); ++i) {
+    PyList_SET_ITEM(obj, i, PyInt_FromLong(static_cast($1.second[i])));
+  }
+  $result = PyTuple_Pack(2, MakePyOutputString($1.first, input_type), obj);
+}
+
+%typemap(in) sentencepiece::SentenceIterator * {
+  sentencepiece::SentenceIterator *out = nullptr;
+  if (PyIter_Check($input)) {
+    out = new PySentenceIterator($input);
+  } else {
+    PyErr_SetString(PyExc_TypeError, "not a iterator");
+    SWIG_fail;
+  }
+  $1 = out;
+}
+
+%typemap(freearg) const std::string& {
+  delete $1;
+}
+
+%typemap(freearg) const std::vector& {
+  delete $1;
+}
+
+%typemap(freearg) const std::vector& {
+  delete $1;
+}
+
+%typemap(freearg) const std::vector>& {
+  delete $1;
+}
+
+%typemap(freearg) const std::vector& {
+  delete $1;
+}
+
+%typemap(freearg) const std::vector& {
+  delete $1;
+}
+
+%typemap(freearg) const std::vector>& {
+  delete $1;
+}
+
+%typemap(freearg) const std::unordered_map & {
+  delete $1;
+}
+
+%typemap(freearg) sentencepiece::SentenceIterator * {
+  delete $1;
+}
+
+%typemap(freearg) sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece {
+  delete $1;
+}
+
+%typemap(freearg) sentencepiece::ImmutableSentencePieceText {
+  delete $1;
+}
+
+%typemap(freearg) sentencepiece::ImmutableNBestSentencePieceText {
+  delete $1;
+}
+
+%include 
+%include 
+
+%pythoncode %{
+
+import re
+import csv
+import sys
+import os
+import importlib.resources
+from io import StringIO
+from io import BytesIO
+
+
+def _add_snake_case(classname):
+  """Added snake_cased method from CammelCased method."""
+
+  snake_map = {}
+  for k, v in classname.__dict__.items():
+    if re.match(r'^[A-Z]+', k):
+      snake = re.sub(r'(?= v.piece_size()):
+      raise IndexError('piece id is out of range.')
+    return func(v, n)
+
+  def _batched_func(self, arg):
+    if type(arg) is list:
+      return [_func(self, n) for n in arg]
+    else:
+      return _func(self, arg)
+
+  setattr(classname, name, _batched_func)
+
+
+_sentencepiece_processor_init_native = SentencePieceProcessor.__init__
+_sentencepiece_normalizer_init_native = SentencePieceNormalizer.__init__
+setattr(SentencePieceProcessor, '__init__', SentencePieceProcessor.Init)
+setattr(SentencePieceNormalizer, '__init__', SentencePieceNormalizer.Init)
+
+SentencePieceProcessor.Tokenize = SentencePieceProcessor.Encode
+SentencePieceProcessor.Detokenize = SentencePieceProcessor.Decode
+
+for m in [
+    'PieceToId', 'IdToPiece', 'GetScore', 'IsUnknown', 'IsControl', 'IsUnused',
+    'IsByte'
+]:
+  _batchnize(SentencePieceProcessor, m)
+
+_add_snake_case(SentencePieceProcessor)
+_add_snake_case(SentencePieceTrainer)
+_add_snake_case(SentencePieceNormalizer)
+set_random_generator_seed = SetRandomGeneratorSeed
+set_min_log_level = SetMinLogLevel
+
+from ._version import __version__
+
+SetDataDir(os.path.join(str(importlib.resources.files('sentencepiece')), 'package_data'))
+
+class _LogStream(object):
+  def __init__(self, ostream=None):
+    self.ostream = ostream
+    if self.ostream is not None:
+      self.orig_stream_fileno = sys.stderr.fileno()
+
+  def __enter__(self):
+    if self.ostream is not None:
+      self.orig_stream_dup = os.dup(self.orig_stream_fileno)
+      os.dup2(self.ostream.fileno(), self.orig_stream_fileno)
+
+  def __exit__(self, type, value, traceback):
+    if self.ostream is not None:
+      os.close(self.orig_stream_fileno)
+      os.dup2(self.orig_stream_dup, self.orig_stream_fileno)
+      os.close(self.orig_stream_dup)
+      self.ostream.close()
+%}
diff --git a/lib/python3.11/site-packages/sentencepiece/sentencepiece_model_pb2.py b/lib/python3.11/site-packages/sentencepiece/sentencepiece_model_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b07107d69de178e107544a29bb4d0280b5482241
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece/sentencepiece_model_pb2.py
@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler.  DO NOT EDIT!
+# source: sentencepiece_model.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18  \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18. \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+  DESCRIPTOR._options = None
+  DESCRIPTOR._serialized_options = b'H\003'
+  _TRAINERSPEC.fields_by_name['mining_sentence_size']._options = None
+  _TRAINERSPEC.fields_by_name['mining_sentence_size']._serialized_options = b'\030\001'
+  _TRAINERSPEC.fields_by_name['training_sentence_size']._options = None
+  _TRAINERSPEC.fields_by_name['training_sentence_size']._serialized_options = b'\030\001'
+  _TRAINERSPEC._serialized_start=45
+  _TRAINERSPEC._serialized_end=1581
+  _TRAINERSPEC_MODELTYPE._serialized_start=1517
+  _TRAINERSPEC_MODELTYPE._serialized_end=1570
+  _NORMALIZERSPEC._serialized_start=1584
+  _NORMALIZERSPEC._serialized_end=1793
+  _SELFTESTDATA._serialized_start=1795
+  _SELFTESTDATA._serialized_end=1916
+  _SELFTESTDATA_SAMPLE._serialized_start=1864
+  _SELFTESTDATA_SAMPLE._serialized_end=1905
+  _MODELPROTO._serialized_start=1919
+  _MODELPROTO._serialized_end=2429
+  _MODELPROTO_SENTENCEPIECE._serialized_start=2208
+  _MODELPROTO_SENTENCEPIECE._serialized_end=2418
+  _MODELPROTO_SENTENCEPIECE_TYPE._serialized_start=2323
+  _MODELPROTO_SENTENCEPIECE_TYPE._serialized_end=2407
+# @@protoc_insertion_point(module_scope)
diff --git a/lib/python3.11/site-packages/sentencepiece/sentencepiece_pb2.py b/lib/python3.11/site-packages/sentencepiece/sentencepiece_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..840cfd2143a47d8a972008bd946a8dd271aa0a0f
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece/sentencepiece_pb2.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler.  DO NOT EDIT!
+# source: sentencepiece.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13sentencepiece.proto\x12\rsentencepiece\"\xdf\x01\n\x11SentencePieceText\x12\x0c\n\x04text\x18\x01 \x01(\t\x12>\n\x06pieces\x18\x02 \x03(\x0b\x32..sentencepiece.SentencePieceText.SentencePiece\x12\r\n\x05score\x18\x03 \x01(\x02\x1a\x62\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\r\x12\x0f\n\x07surface\x18\x03 \x01(\t\x12\r\n\x05\x62\x65gin\x18\x04 \x01(\r\x12\x0b\n\x03\x65nd\x18\x05 \x01(\r*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"J\n\x16NBestSentencePieceText\x12\x30\n\x06nbests\x18\x01 \x03(\x0b\x32 .sentencepiece.SentencePieceTextB\x02H\x03')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+  DESCRIPTOR._options = None
+  DESCRIPTOR._serialized_options = b'H\003'
+  _SENTENCEPIECETEXT._serialized_start=39
+  _SENTENCEPIECETEXT._serialized_end=262
+  _SENTENCEPIECETEXT_SENTENCEPIECE._serialized_start=153
+  _SENTENCEPIECETEXT_SENTENCEPIECE._serialized_end=251
+  _NBESTSENTENCEPIECETEXT._serialized_start=264
+  _NBESTSENTENCEPIECETEXT._serialized_end=338
+# @@protoc_insertion_point(module_scope)
diff --git a/lib/python3.11/site-packages/sentencepiece/sentencepiece_wrap.cxx b/lib/python3.11/site-packages/sentencepiece/sentencepiece_wrap.cxx
new file mode 100644
index 0000000000000000000000000000000000000000..e6c3d659469e6cbe9c7bab2d8349fa289cd758b1
--- /dev/null
+++ b/lib/python3.11/site-packages/sentencepiece/sentencepiece_wrap.cxx
@@ -0,0 +1,10628 @@
+/* ----------------------------------------------------------------------------
+ * This file was automatically generated by SWIG (https://www.swig.org).
+ * Version 4.3.0
+ *
+ * Do not make changes to this file unless you know what you are doing - modify
+ * the SWIG interface file instead.
+ * ----------------------------------------------------------------------------- */
+
+
+#define SWIG_VERSION 0x040300
+#define SWIGPYTHON
+#define SWIG_PYTHON_DIRECTOR_NO_VTABLE
+
+#define SWIG_name    "_sentencepiece"
+/* -----------------------------------------------------------------------------
+ *  This section contains generic SWIG labels for method/variable
+ *  declarations/attributes, and other compiler dependent labels.
+ * ----------------------------------------------------------------------------- */
+
+/* template workaround for compilers that cannot correctly implement the C++ standard */
+#ifndef SWIGTEMPLATEDISAMBIGUATOR
+# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# elif defined(__HP_aCC)
+/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
+/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# else
+#  define SWIGTEMPLATEDISAMBIGUATOR
+# endif
+#endif
+
+/* inline attribute */
+#ifndef SWIGINLINE
+# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
+#   define SWIGINLINE inline
+# else
+#   define SWIGINLINE
+# endif
+#endif
+
+/* attribute recognised by some compilers to avoid 'unused' warnings */
+#ifndef SWIGUNUSED
+# if defined(__GNUC__)
+#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+#     define SWIGUNUSED __attribute__ ((__unused__))
+#   else
+#     define SWIGUNUSED
+#   endif
+# elif defined(__ICC)
+#   define SWIGUNUSED __attribute__ ((__unused__))
+# else
+#   define SWIGUNUSED
+# endif
+#endif
+
+#ifndef SWIG_MSC_UNSUPPRESS_4505
+# if defined(_MSC_VER)
+#   pragma warning(disable : 4505) /* unreferenced local function has been removed */
+# endif
+#endif
+
+#ifndef SWIGUNUSEDPARM
+# ifdef __cplusplus
+#   define SWIGUNUSEDPARM(p)
+# else
+#   define SWIGUNUSEDPARM(p) p SWIGUNUSED
+# endif
+#endif
+
+/* internal SWIG method */
+#ifndef SWIGINTERN
+# define SWIGINTERN static SWIGUNUSED
+#endif
+
+/* internal inline SWIG method */
+#ifndef SWIGINTERNINLINE
+# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
+#endif
+
+/* exporting methods */
+#if defined(__GNUC__)
+#  if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+#    ifndef GCC_HASCLASSVISIBILITY
+#      define GCC_HASCLASSVISIBILITY
+#    endif
+#  endif
+#endif
+
+#ifndef SWIGEXPORT
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   if defined(STATIC_LINKED)
+#     define SWIGEXPORT
+#   else
+#     define SWIGEXPORT __declspec(dllexport)
+#   endif
+# else
+#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
+#     define SWIGEXPORT __attribute__ ((visibility("default")))
+#   else
+#     define SWIGEXPORT
+#   endif
+# endif
+#endif
+
+/* calling conventions for Windows */
+#ifndef SWIGSTDCALL
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   define SWIGSTDCALL __stdcall
+# else
+#   define SWIGSTDCALL
+# endif
+#endif
+
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
+#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
+# define _SCL_SECURE_NO_DEPRECATE
+#endif
+
+/* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */
+#if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES)
+# define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
+#endif
+
+/* Intel's compiler complains if a variable which was never initialised is
+ * cast to void, which is a common idiom which we use to indicate that we
+ * are aware a variable isn't used.  So we just silence that warning.
+ * See: https://github.com/swig/swig/issues/192 for more discussion.
+ */
+#ifdef __INTEL_COMPILER
+# pragma warning disable 592
+#endif
+
+#if defined(__cplusplus) && __cplusplus >=201103L
+# define SWIG_NULLPTR nullptr
+#else
+# define SWIG_NULLPTR NULL
+#endif 
+
+/* -----------------------------------------------------------------------------
+ * swigcompat.swg
+ *
+ * Macros to provide support compatibility with older C and C++ standards.
+ *
+ * Note that SWIG expects __cplusplus to be defined to the appropriate C++ standard.
+ * MSVC users are urged to check and examine the /Zc:__cplusplus compiler option.
+ * See https://learn.microsoft.com/en-us/cpp/build/reference/zc-cplusplus.
+ * ----------------------------------------------------------------------------- */
+
+/* C99 and C++11 should provide snprintf, but define SWIG_NO_SNPRINTF
+ * if you're missing it.
+ */
+#if ((defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) || \
+     (defined __cplusplus && __cplusplus >= 201103L) || \
+     defined SWIG_HAVE_SNPRINTF) && \
+    !defined SWIG_NO_SNPRINTF
+# define SWIG_snprintf(O,S,F,A) snprintf(O,S,F,A)
+# define SWIG_snprintf2(O,S,F,A,B) snprintf(O,S,F,A,B)
+#else
+/* Fallback versions ignore the buffer size, but most of our uses either have a
+ * fixed maximum possible size or dynamically allocate a buffer that's large
+ * enough.
+ */
+# define SWIG_snprintf(O,S,F,A) sprintf(O,F,A)
+# define SWIG_snprintf2(O,S,F,A,B) sprintf(O,F,A,B)
+#endif
+
+
+#if defined(__GNUC__) && defined(_WIN32) && !defined(SWIG_PYTHON_NO_HYPOT_WORKAROUND)
+/* Workaround for '::hypot' has not been declared', see https://bugs.python.org/issue11566 */
+# include 
+#endif
+
+#if !defined(PY_SSIZE_T_CLEAN) && !defined(SWIG_NO_PY_SSIZE_T_CLEAN)
+#define PY_SSIZE_T_CLEAN
+#endif
+
+#if __GNUC__ >= 7
+#pragma GCC diagnostic push
+#if defined(__cplusplus) && __cplusplus >=201703L
+#pragma GCC diagnostic ignored "-Wregister" /* For python-2.7 headers that use register */
+#endif
+#endif
+
+#if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG)
+/* Use debug wrappers with the Python release dll */
+
+#if defined(_MSC_VER) && _MSC_VER >= 1929
+/* Workaround compilation errors when redefining _DEBUG in MSVC 2019 version 16.10 and later
+ * See https://github.com/swig/swig/issues/2090 */
+# include 
+#endif
+
+# undef _DEBUG
+# include 
+# define _DEBUG 1
+#else
+# include 
+#endif
+
+#if !defined(SWIGPYTHON_BUILTIN) && PY_VERSION_HEX >= 0x03030000
+# define SWIG_HEAPTYPES
+
+/* Note: Currently this won't activate - it is in place ready for when the
+ * SWIGPYTHON_BUILTIN condition above gets removed. */
+# if PY_VERSION_HEX < 0x030c0000 && defined(SWIGPYTHON_BUILTIN)
+#  include 
+#  define Py_READONLY READONLY
+#  define Py_T_PYSSIZET T_PYSSIZET
+# endif
+#endif
+
+#if __GNUC__ >= 7
+#pragma GCC diagnostic pop
+#endif
+
+#include 
+#include 
+
+/* -----------------------------------------------------------------------------
+ * swigrun.swg
+ *
+ * This file contains generic C API SWIG runtime support for pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
+
+/* This should only be incremented when either the layout of swig_type_info changes,
+   or for whatever reason, the runtime changes incompatibly */
+#define SWIG_RUNTIME_VERSION "4"
+
+/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
+#ifdef SWIG_TYPE_TABLE
+# define SWIG_QUOTE_STRING(x) #x
+# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
+# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
+#else
+# define SWIG_TYPE_TABLE_NAME
+#endif
+
+/*
+  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
+  creating a static or dynamic library from the SWIG runtime code.
+  In 99.9% of the cases, SWIG just needs to declare them as 'static'.
+
+  But only do this if strictly necessary, ie, if you have problems
+  with your compiler or suchlike.
+*/
+
+#ifndef SWIGRUNTIME
+# define SWIGRUNTIME SWIGINTERN
+#endif
+
+#ifndef SWIGRUNTIMEINLINE
+# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
+#endif
+
+/*  Generic buffer size */
+#ifndef SWIG_BUFFER_SIZE
+# define SWIG_BUFFER_SIZE 1024
+#endif
+
+/* Flags for pointer conversions */
+#define SWIG_POINTER_DISOWN        0x1
+#define SWIG_CAST_NEW_MEMORY       0x2
+#define SWIG_POINTER_NO_NULL       0x4
+#define SWIG_POINTER_CLEAR         0x8
+#define SWIG_POINTER_RELEASE       (SWIG_POINTER_CLEAR | SWIG_POINTER_DISOWN)
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_OWN           0x1
+
+
+/*
+   Flags/methods for returning states.
+
+   The SWIG conversion methods, as ConvertPtr, return an integer
+   that tells if the conversion was successful or not. And if not,
+   an error code can be returned (see swigerrors.swg for the codes).
+
+   Use the following macros/flags to set or process the returning
+   states.
+
+   In old versions of SWIG, code such as the following was usually written:
+
+     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
+       // success code
+     } else {
+       //fail code
+     }
+
+   Now you can be more explicit:
+
+    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+    } else {
+      // fail code
+    }
+
+   which is the same really, but now you can also do
+
+    Type *ptr;
+    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+      if (SWIG_IsNewObj(res) {
+        ...
+	delete *ptr;
+      } else {
+        ...
+      }
+    } else {
+      // fail code
+    }
+
+   I.e., now SWIG_ConvertPtr can return new objects and you can
+   identify the case and take care of the deallocation. Of course that
+   also requires SWIG_ConvertPtr to return new result values, such as
+
+      int SWIG_ConvertPtr(obj, ptr,...) {
+        if () {
+          if () {
+            *ptr = ;
+            return SWIG_NEWOBJ;
+          } else {
+            *ptr = ;
+            return SWIG_OLDOBJ;
+          }
+        } else {
+          return SWIG_BADOBJ;
+        }
+      }
+
+   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
+   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
+   SWIG errors code.
+
+   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
+   allows returning the 'cast rank', for example, if you have this
+
+       int food(double)
+       int fooi(int);
+
+   and you call
+
+      food(1)   // cast rank '1'  (1 -> 1.0)
+      fooi(1)   // cast rank '0'
+
+   just use the SWIG_AddCast()/SWIG_CheckState()
+*/
+
+#define SWIG_OK                    (0)
+/* Runtime errors are < 0 */
+#define SWIG_ERROR                 (-1)
+/* Errors in range -1 to -99 are in swigerrors.swg (errors for all languages including those not using the runtime) */
+/* Errors in range -100 to -199 are language specific errors defined in *errors.swg */
+/* Errors < -200 are generic runtime specific errors */
+#define SWIG_ERROR_RELEASE_NOT_OWNED (-200)
+
+#define SWIG_IsOK(r)               (r >= 0)
+#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)
+
+/* The CastRankLimit says how many bits are used for the cast rank */
+#define SWIG_CASTRANKLIMIT         (1 << 8)
+/* The NewMask denotes the object was created (using new/malloc) */
+#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
+/* The TmpMask is for in/out typemaps that use temporary objects */
+#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
+/* Simple returning values */
+#define SWIG_BADOBJ                (SWIG_ERROR)
+#define SWIG_OLDOBJ                (SWIG_OK)
+#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
+#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
+/* Check, add and del object mask methods */
+#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
+#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
+#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
+#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
+#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
+#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
+
+/* Cast-Rank Mode */
+#if defined(SWIG_CASTRANK_MODE)
+#  ifndef SWIG_TypeRank
+#    define SWIG_TypeRank             unsigned long
+#  endif
+#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
+#    define SWIG_MAXCASTRANK          (2)
+#  endif
+#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
+#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
+SWIGINTERNINLINE int SWIG_AddCast(int r) {
+  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
+}
+SWIGINTERNINLINE int SWIG_CheckState(int r) {
+  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0;
+}
+#else /* no cast-rank mode */
+#  define SWIG_AddCast(r) (r)
+#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
+#endif
+
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void *(*swig_converter_func)(void *, int *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
+
+/* Structure to store information on one type */
+typedef struct swig_type_info {
+  const char             *name;			/* mangled name of this type */
+  const char             *str;			/* human readable name of this type */
+  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
+  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
+  void                   *clientdata;		/* language specific type data */
+  int                    owndata;		/* flag if the structure owns the clientdata */
+} swig_type_info;
+
+/* Structure to store a type and conversion function used for casting */
+typedef struct swig_cast_info {
+  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
+  swig_converter_func     converter;		/* function to cast the void pointers */
+  struct swig_cast_info  *next;			/* pointer to next cast in linked list */
+  struct swig_cast_info  *prev;			/* pointer to the previous cast */
+} swig_cast_info;
+
+/* Structure used to store module information
+ * Each module generates one structure like this, and the runtime collects
+ * all of these structures and stores them in a circularly linked list.*/
+typedef struct swig_module_info {
+  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
+  size_t                 size;		        /* Number of types in this module */
+  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
+  swig_type_info         **type_initial;	/* Array of initially generated type structures */
+  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
+  void                    *clientdata;		/* Language specific module data */
+} swig_module_info;
+
+/*
+  Compare two type names skipping the space characters, therefore
+  "char*" == "char *" and "Class" == "Class", etc.
+
+  Return 0 when the two name types are equivalent, as in
+  strncmp, but skipping ' '.
+*/
+SWIGRUNTIME int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+		  const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
+  }
+  return (int)((l1 - f1) - (l2 - f2));
+}
+
+/*
+  Check type equivalence in a name list like ||...
+  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
+*/
+SWIGRUNTIME int
+SWIG_TypeCmp(const char *nb, const char *tb) {
+  int equiv = 1;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (equiv != 0 && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = SWIG_TypeNameComp(nb, ne, tb, te);
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+/*
+  Check type equivalence in a name list like ||...
+  Return 0 if not equal, 1 if equal
+*/
+SWIGRUNTIME int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0;
+}
+
+/*
+  Check the typename
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheck(const char *c, swig_type_info *ty) {
+  if (ty) {
+    swig_cast_info *iter = ty->cast;
+    while (iter) {
+      if (strcmp(iter->type->name, c) == 0) {
+        if (iter == ty->cast)
+          return iter;
+        /* Move iter to the top of the linked list */
+        iter->prev->next = iter->next;
+        if (iter->next)
+          iter->next->prev = iter->prev;
+        iter->next = ty->cast;
+        iter->prev = 0;
+        if (ty->cast) ty->cast->prev = iter;
+        ty->cast = iter;
+        return iter;
+      }
+      iter = iter->next;
+    }
+  }
+  return 0;
+}
+
+/*
+  Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) {
+  if (ty) {
+    swig_cast_info *iter = ty->cast;
+    while (iter) {
+      if (iter->type == from) {
+        if (iter == ty->cast)
+          return iter;
+        /* Move iter to the top of the linked list */
+        iter->prev->next = iter->next;
+        if (iter->next)
+          iter->next->prev = iter->prev;
+        iter->next = ty->cast;
+        iter->prev = 0;
+        if (ty->cast) ty->cast->prev = iter;
+        ty->cast = iter;
+        return iter;
+      }
+      iter = iter->next;
+    }
+  }
+  return 0;
+}
+
+/*
+  Cast a pointer up an inheritance hierarchy
+*/
+SWIGRUNTIMEINLINE void *
+SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {
+  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);
+}
+
+/*
+   Dynamic pointer casting. Down an inheritance hierarchy
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
+  swig_type_info *lastty = ty;
+  if (!ty || !ty->dcast) return ty;
+  while (ty && (ty->dcast)) {
+    ty = (*ty->dcast)(ptr);
+    if (ty) lastty = ty;
+  }
+  return lastty;
+}
+
+/*
+  Return the name associated with this type
+*/
+SWIGRUNTIMEINLINE const char *
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
+
+/*
+  Return the pretty name associated with this type,
+  that is an unmangled type name in a form presentable to the user.
+*/
+SWIGRUNTIME const char *
+SWIG_TypePrettyName(const swig_type_info *type) {
+  /* The "str" field contains the equivalent pretty names of the
+     type, separated by vertical-bar characters.  Choose the last
+     name. It should be the most specific; a fully resolved name
+     but not necessarily with default template parameters expanded. */
+  if (!type) return NULL;
+  if (type->str != NULL) {
+    const char *last_name = type->str;
+    const char *s;
+    for (s = type->str; *s; s++)
+      if (*s == '|') last_name = s+1;
+    return last_name;
+  }
+  else
+    return type->name;
+}
+
+/*
+   Set the clientdata field for a type
+*/
+SWIGRUNTIME void
+SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
+  swig_cast_info *cast = ti->cast;
+  /* if (ti->clientdata == clientdata) return; */
+  ti->clientdata = clientdata;
+
+  while (cast) {
+    if (!cast->converter) {
+      swig_type_info *tc = cast->type;
+      if (!tc->clientdata) {
+	SWIG_TypeClientData(tc, clientdata);
+      }
+    }
+    cast = cast->next;
+  }
+}
+SWIGRUNTIME void
+SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
+  SWIG_TypeClientData(ti, clientdata);
+  ti->owndata = 1;
+}
+
+/*
+  Search for a swig_type_info structure only by mangled name
+  Search is a O(log #types)
+
+  We start searching at module start, and finish searching when start == end.
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_MangledTypeQueryModule(swig_module_info *start,
+                            swig_module_info *end,
+		            const char *name) {
+  swig_module_info *iter = start;
+  do {
+    if (iter->size) {
+      size_t l = 0;
+      size_t r = iter->size - 1;
+      do {
+	/* since l+r >= 0, we can (>> 1) instead (/ 2) */
+	size_t i = (l + r) >> 1;
+	const char *iname = iter->types[i]->name;
+	if (iname) {
+	  int compare = strcmp(name, iname);
+	  if (compare == 0) {
+	    return iter->types[i];
+	  } else if (compare < 0) {
+	    if (i) {
+	      r = i - 1;
+	    } else {
+	      break;
+	    }
+	  } else if (compare > 0) {
+	    l = i + 1;
+	  }
+	} else {
+	  break; /* should never happen */
+	}
+      } while (l <= r);
+    }
+    iter = iter->next;
+  } while (iter != end);
+  return 0;
+}
+
+/*
+  Search for a swig_type_info structure for either a mangled name or a human readable name.
+  It first searches the mangled names of the types, which is a O(log #types)
+  If a type is not found it then searches the human readable names, which is O(#types).
+
+  We start searching at module start, and finish searching when start == end.
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeQueryModule(swig_module_info *start,
+                     swig_module_info *end,
+		     const char *name) {
+  /* STEP 1: Search the name field using binary search */
+  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
+  if (ret) {
+    return ret;
+  } else {
+    /* STEP 2: If the type hasn't been found, do a complete search
+       of the str field (the human readable name) */
+    swig_module_info *iter = start;
+    do {
+      size_t i = 0;
+      for (; i < iter->size; ++i) {
+	if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
+	  return iter->types[i];
+      }
+      iter = iter->next;
+    } while (iter != end);
+  }
+
+  /* neither found a match */
+  return 0;
+}
+
+/*
+   Pack binary data into a string
+*/
+SWIGRUNTIME char *
+SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static const char hex[17] = "0123456789abcdef";
+  const unsigned char *u = (unsigned char *) ptr;
+  const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    unsigned char uu = *u;
+    *(c++) = hex[(uu & 0xf0) >> 4];
+    *(c++) = hex[uu & 0xf];
+  }
+  return c;
+}
+
+/*
+   Unpack binary data from a string
+*/
+SWIGRUNTIME const char *
+SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  unsigned char *u = (unsigned char *) ptr;
+  const unsigned char *eu = u + sz;
+  for (; u != eu; ++u) {
+    char d = *(c++);
+    unsigned char uu;
+    if ((d >= '0') && (d <= '9'))
+      uu = (unsigned char)((d - '0') << 4);
+    else if ((d >= 'a') && (d <= 'f'))
+      uu = (unsigned char)((d - ('a'-10)) << 4);
+    else
+      return (char *) 0;
+    d = *(c++);
+    if ((d >= '0') && (d <= '9'))
+      uu |= (unsigned char)(d - '0');
+    else if ((d >= 'a') && (d <= 'f'))
+      uu |= (unsigned char)(d - ('a'-10));
+    else
+      return (char *) 0;
+    *u = uu;
+  }
+  return c;
+}
+
+/*
+   Pack 'void *' into a string buffer.
+*/
+SWIGRUNTIME char *
+SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+  char *r = buff;
+  if ((2*sizeof(void *) + 2) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,&ptr,sizeof(void *));
+  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
+  strcpy(r,name);
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      *ptr = (void *) 0;
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sizeof(void *));
+}
+
+SWIGRUNTIME char *
+SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+  char *r = buff;
+  size_t lname = (name ? strlen(name) : 0);
+  if ((2*sz + 2 + lname) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  if (lname) {
+    strncpy(r,name,lname+1);
+  } else {
+    *r = 0;
+  }
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      memset(ptr,0,sz);
+      return name;
+    } else {
+      return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sz);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/* SWIG Errors applicable to all language modules, values are reserved from -1 to -99 */
+#define  SWIG_UnknownError    	   -1
+#define  SWIG_IOError        	   -2
+#define  SWIG_RuntimeError   	   -3
+#define  SWIG_IndexError     	   -4
+#define  SWIG_TypeError      	   -5
+#define  SWIG_DivisionByZero 	   -6
+#define  SWIG_OverflowError  	   -7
+#define  SWIG_SyntaxError    	   -8
+#define  SWIG_ValueError     	   -9
+#define  SWIG_SystemError    	   -10
+#define  SWIG_AttributeError 	   -11
+#define  SWIG_MemoryError    	   -12
+#define  SWIG_NullReferenceError   -13
+
+
+/* Compatibility macros for Python 3 */
+#if PY_VERSION_HEX >= 0x03000000
+
+#define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type)
+#define PyInt_Check(x) PyLong_Check(x)
+#define PyInt_AsLong(x) PyLong_AsLong(x)
+#define PyInt_FromLong(x) PyLong_FromLong(x)
+#define PyInt_FromSize_t(x) PyLong_FromSize_t(x)
+#define PyString_Check(name) PyBytes_Check(name)
+#define PyString_FromString(x) PyUnicode_FromString(x)
+#define PyString_Format(fmt, args)  PyUnicode_Format(fmt, args)
+#define PyString_AsString(str) PyBytes_AsString(str)
+#define PyString_Size(str) PyBytes_Size(str)	
+#define PyString_InternFromString(key) PyUnicode_InternFromString(key)
+#define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE
+#define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x)
+
+#endif
+
+/* SWIG APIs for compatibility of both Python 2 & 3 */
+
+#if PY_VERSION_HEX >= 0x03000000
+#  define SWIG_Python_str_FromFormat PyUnicode_FromFormat
+#else
+#  define SWIG_Python_str_FromFormat PyString_FromFormat
+#endif
+
+
+/* Wrapper around PyUnicode_AsUTF8AndSize - call Py_XDECREF on the returned pbytes when finished with the returned string */
+SWIGINTERN const char *
+SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes)
+{
+#if PY_VERSION_HEX >= 0x03030000
+# if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
+  *pbytes = NULL;
+  return PyUnicode_AsUTF8AndSize(str, psize);
+# else
+  const char *chars;
+  *pbytes = PyUnicode_AsUTF8String(str);
+  chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL;
+  if (chars && psize)
+    *psize = PyBytes_Size(*pbytes);
+  return chars;
+# endif
+#else
+  char *chars = NULL;
+  *pbytes = NULL;
+  PyString_AsStringAndSize(str, &chars, psize);
+  return chars;
+#endif
+}
+
+SWIGINTERN PyObject*
+SWIG_Python_str_FromChar(const char *c)
+{
+#if PY_VERSION_HEX >= 0x03000000
+  return PyUnicode_FromString(c); 
+#else
+  return PyString_FromString(c);
+#endif
+}
+
+/* SWIGPY_USE_CAPSULE is no longer used within SWIG itself, but some user interface files check for it. */
+# define SWIGPY_USE_CAPSULE
+#ifdef SWIGPYTHON_BUILTIN
+# define SWIGPY_CAPSULE_ATTR_NAME "type_pointer_capsule_builtin" SWIG_TYPE_TABLE_NAME
+#else
+# define SWIGPY_CAPSULE_ATTR_NAME "type_pointer_capsule" SWIG_TYPE_TABLE_NAME
+#endif
+# define SWIGPY_CAPSULE_NAME ("swig_runtime_data" SWIG_RUNTIME_VERSION "." SWIGPY_CAPSULE_ATTR_NAME)
+
+#if PY_VERSION_HEX < 0x03020000
+#define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type)
+#define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name)
+#define Py_hash_t long
+#endif
+
+#ifdef Py_LIMITED_API
+# define PyTuple_GET_ITEM PyTuple_GetItem
+/* Note that PyTuple_SetItem() has different semantics from PyTuple_SET_ITEM as it decref's the original tuple item, so in general they cannot be used
+  interchangeably. However in SWIG-generated code PyTuple_SET_ITEM is only used with newly initialized tuples without any items and for them this does work. */
+# define PyTuple_SET_ITEM PyTuple_SetItem
+# define PyTuple_GET_SIZE PyTuple_Size
+# define PyCFunction_GET_FLAGS PyCFunction_GetFlags
+# define PyCFunction_GET_FUNCTION PyCFunction_GetFunction
+# define PyCFunction_GET_SELF PyCFunction_GetSelf
+# define PyList_GET_ITEM PyList_GetItem
+# define PyList_SET_ITEM PyList_SetItem
+# define PySliceObject PyObject
+#endif
+
+/* Increment and Decrement wrappers - for portability when using the stable abi and for performance otherwise */
+#ifdef Py_LIMITED_API
+# define SWIG_Py_INCREF Py_IncRef
+# define SWIG_Py_XINCREF Py_IncRef
+# define SWIG_Py_DECREF Py_DecRef
+# define SWIG_Py_XDECREF Py_DecRef
+#else
+# define SWIG_Py_INCREF Py_INCREF
+# define SWIG_Py_XINCREF Py_XINCREF
+# define SWIG_Py_DECREF Py_DECREF
+# define SWIG_Py_XDECREF Py_XDECREF
+#endif
+
+/* -----------------------------------------------------------------------------
+ * error manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIME PyObject*
+SWIG_Python_ErrorType(int code) {
+  PyObject* type = 0;
+  switch(code) {
+  case SWIG_MemoryError:
+    type = PyExc_MemoryError;
+    break;
+  case SWIG_IOError:
+    type = PyExc_IOError;
+    break;
+  case SWIG_RuntimeError:
+    type = PyExc_RuntimeError;
+    break;
+  case SWIG_IndexError:
+    type = PyExc_IndexError;
+    break;
+  case SWIG_TypeError:
+    type = PyExc_TypeError;
+    break;
+  case SWIG_DivisionByZero:
+    type = PyExc_ZeroDivisionError;
+    break;
+  case SWIG_OverflowError:
+    type = PyExc_OverflowError;
+    break;
+  case SWIG_SyntaxError:
+    type = PyExc_SyntaxError;
+    break;
+  case SWIG_ValueError:
+    type = PyExc_ValueError;
+    break;
+  case SWIG_SystemError:
+    type = PyExc_SystemError;
+    break;
+  case SWIG_AttributeError:
+    type = PyExc_AttributeError;
+    break;
+  case SWIG_NullReferenceError:
+    type = PyExc_TypeError;
+    break;
+  default:
+    type = PyExc_RuntimeError;
+  }
+  return type;
+}
+
+
+SWIGRUNTIME void
+SWIG_Python_AddErrorMsg(const char* mesg)
+{
+  PyObject *type = 0;
+  PyObject *value = 0;
+  PyObject *traceback = 0;
+
+  if (PyErr_Occurred())
+    PyErr_Fetch(&type, &value, &traceback);
+  if (value) {
+    PyObject *old_str = PyObject_Str(value);
+    PyObject *bytes = NULL;
+    const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes);
+    PyErr_Clear();
+    SWIG_Py_XINCREF(type);
+    if (tmp)
+      PyErr_Format(type, "%s %s", tmp, mesg);
+    else
+      PyErr_Format(type, "%s", mesg);
+    SWIG_Py_XDECREF(bytes);
+    SWIG_Py_DECREF(old_str);
+    SWIG_Py_DECREF(value);
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, mesg);
+  }
+}
+
+SWIGRUNTIME int
+SWIG_Python_TypeErrorOccurred(PyObject *obj)
+{
+  PyObject *error;
+  if (obj)
+    return 0;
+  error = PyErr_Occurred();
+  return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError);
+}
+
+SWIGRUNTIME void
+SWIG_Python_RaiseOrModifyTypeError(const char *message)
+{
+  if (SWIG_Python_TypeErrorOccurred(NULL)) {
+    /* Use existing TypeError to preserve stacktrace and enhance with given message */
+    PyObject *newvalue;
+    PyObject *type = NULL, *value = NULL, *traceback = NULL;
+    PyErr_Fetch(&type, &value, &traceback);
+#if PY_VERSION_HEX >= 0x03000000
+    newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message);
+#else
+    newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message);
+#endif
+    if (newvalue) {
+      SWIG_Py_XDECREF(value);
+      PyErr_Restore(type, newvalue, traceback);
+    } else {
+      PyErr_Restore(type, value, traceback);
+    }
+  } else {
+    /* Raise TypeError using given message */
+    PyErr_SetString(PyExc_TypeError, message);
+  }
+}
+
+#if defined(SWIG_PYTHON_NO_THREADS)
+#  if defined(SWIG_PYTHON_THREADS)
+#    undef SWIG_PYTHON_THREADS
+#  endif
+#endif
+#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */
+#  if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL)
+#    define SWIG_PYTHON_USE_GIL
+#  endif
+#  if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */
+#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)
+#      if PY_VERSION_HEX < 0x03070000
+#        define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads()
+#      else
+#        define SWIG_PYTHON_INITIALIZE_THREADS
+#      endif
+#    endif
+#    ifdef __cplusplus /* C++ code */
+       class SWIG_Python_Thread_Block {
+         bool status;
+         PyGILState_STATE state;
+       public:
+         void end() { if (status) { PyGILState_Release(state); status = false;} }
+         SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {}
+         ~SWIG_Python_Thread_Block() { end(); }
+       };
+       class SWIG_Python_Thread_Allow {
+         bool status;
+         PyThreadState *save;
+       public:
+         void end() { if (status) { status = false; PyEval_RestoreThread(save); }}
+         SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {}
+         ~SWIG_Python_Thread_Allow() { end(); }
+       };
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   SWIG_Python_Thread_Block _swig_thread_block
+#      define SWIG_PYTHON_THREAD_END_BLOCK     _swig_thread_block.end()
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   SWIG_Python_Thread_Allow _swig_thread_allow
+#      define SWIG_PYTHON_THREAD_END_ALLOW     _swig_thread_allow.end()
+#    else /* C code */
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   PyGILState_STATE _swig_thread_block = PyGILState_Ensure()
+#      define SWIG_PYTHON_THREAD_END_BLOCK     PyGILState_Release(_swig_thread_block)
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   PyThreadState *_swig_thread_allow = PyEval_SaveThread()
+#      define SWIG_PYTHON_THREAD_END_ALLOW     PyEval_RestoreThread(_swig_thread_allow)
+#    endif
+#  else /* Old thread way, not implemented, user must provide it */
+#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)
+#      define SWIG_PYTHON_INITIALIZE_THREADS
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK)
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_END_BLOCK)
+#      define SWIG_PYTHON_THREAD_END_BLOCK
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW)
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_END_ALLOW)
+#      define SWIG_PYTHON_THREAD_END_ALLOW
+#    endif
+#  endif
+#else /* No thread support */
+#  define SWIG_PYTHON_INITIALIZE_THREADS
+#  define SWIG_PYTHON_THREAD_BEGIN_BLOCK
+#  define SWIG_PYTHON_THREAD_END_BLOCK
+#  define SWIG_PYTHON_THREAD_BEGIN_ALLOW
+#  define SWIG_PYTHON_THREAD_END_ALLOW
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Python API portion that goes into the runtime
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Constant declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Constant Types */
+#define SWIG_PY_POINTER 4
+#define SWIG_PY_BINARY  5
+
+/* Constant information structure */
+typedef struct swig_const_info {
+  int type;
+  const char *name;
+  long lvalue;
+  double dvalue;
+  void   *pvalue;
+  swig_type_info **ptype;
+} swig_const_info;
+
+#ifdef __cplusplus
+}
+#endif
+
+
+/* -----------------------------------------------------------------------------
+ * pyrun.swg
+ *
+ * This file contains the runtime support for Python modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ *
+ * ----------------------------------------------------------------------------- */
+
+#if PY_VERSION_HEX < 0x02070000 /* 2.7.0 */
+# error "This version of SWIG only supports Python >= 2.7"
+#endif
+
+#if PY_VERSION_HEX >= 0x03000000 && PY_VERSION_HEX < 0x03030000
+# error "This version of SWIG only supports Python 3 >= 3.3"
+#endif
+
+/* Common SWIG API */
+
+/* for raw pointers */
+#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)
+
+#ifdef SWIGPYTHON_BUILTIN
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(self, ptr, type, flags)
+#else
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(NULL, ptr, type, flags)
+#endif
+
+#define SWIG_InternalNewPointerObj(ptr, type, flags)	SWIG_Python_NewPointerObj(NULL, ptr, type, flags)
+
+#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) 
+#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)
+#define swig_owntype                                    int
+
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
+
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)
+
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(NULL, ptr, type, 0)
+
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
+
+
+/* Runtime API */
+
+#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule(clientdata)
+#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)
+#define SWIG_NewClientData(obj)                         SwigPyClientData_New(obj)
+
+#define SWIG_SetErrorObj                                SWIG_Python_SetErrorObj                            
+#define SWIG_SetErrorMsg                        	SWIG_Python_SetErrorMsg				   
+#define SWIG_ErrorType(code)                    	SWIG_Python_ErrorType(code)                        
+#define SWIG_Error(code, msg)            		SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) 
+#define SWIG_fail                        		goto fail					   
+
+
+/* Runtime API implementation */
+
+/* Error manipulation */
+
+SWIGINTERN void 
+SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) {
+  SWIG_PYTHON_THREAD_BEGIN_BLOCK; 
+  PyErr_SetObject(errtype, obj);
+  SWIG_Py_DECREF(obj);
+  SWIG_PYTHON_THREAD_END_BLOCK;
+}
+
+SWIGINTERN void 
+SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) {
+  SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+  PyErr_SetString(errtype, msg);
+  SWIG_PYTHON_THREAD_END_BLOCK;
+}
+
+#define SWIG_Python_Raise(obj, type, desc)  SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj)
+
+/* Set a constant value */
+
+#if defined(SWIGPYTHON_BUILTIN)
+
+SWIGINTERN void
+SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) {
+  PyObject *s = PyString_InternFromString(key);
+  PyList_Append(seq, s);
+  SWIG_Py_DECREF(s);
+}
+
+SWIGINTERN void
+SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) {   
+  PyDict_SetItemString(d, name, obj);
+  SWIG_Py_DECREF(obj);
+  if (public_interface)
+    SwigPyBuiltin_AddPublicSymbol(public_interface, name);
+}
+
+#else
+
+SWIGINTERN void
+SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) {   
+  PyDict_SetItemString(d, name, obj);
+  SWIG_Py_DECREF(obj);
+}
+
+#endif
+
+/* Append a value to the result obj */
+
+SWIGINTERN PyObject*
+SWIG_Python_AppendOutput(PyObject* result, PyObject* obj, int is_void) {
+  if (!result) {
+    result = obj;
+  } else if (result == Py_None && is_void) {
+    SWIG_Py_DECREF(result);
+    result = obj;
+  } else {
+    if (!PyList_Check(result)) {
+      PyObject *o2 = result;
+      result = PyList_New(1);
+      if (result) {
+        PyList_SET_ITEM(result, 0, o2);
+      } else {
+        SWIG_Py_DECREF(obj);
+        return o2;
+      }
+    }
+    PyList_Append(result,obj);
+    SWIG_Py_DECREF(obj);
+  }
+  return result;
+}
+
+/* Unpack the argument tuple */
+
+SWIGINTERN Py_ssize_t
+SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs)
+{
+  if (!args) {
+    if (!min && !max) {
+      return 1;
+    } else {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", 
+		   name, (min == max ? "" : "at least "), (int)min);
+      return 0;
+    }
+  }  
+  if (!PyTuple_Check(args)) {
+    if (min <= 1 && max >= 1) {
+      Py_ssize_t i;
+      objs[0] = args;
+      for (i = 1; i < max; ++i) {
+	objs[i] = 0;
+      }
+      return 2;
+    }
+    PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple");
+    return 0;
+  } else {
+    Py_ssize_t l = PyTuple_GET_SIZE(args);
+    if (l < min) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+		   name, (min == max ? "" : "at least "), (int)min, (int)l);
+      return 0;
+    } else if (l > max) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+		   name, (min == max ? "" : "at most "), (int)max, (int)l);
+      return 0;
+    } else {
+      Py_ssize_t i;
+      for (i = 0; i < l; ++i) {
+	objs[i] = PyTuple_GET_ITEM(args, i);
+      }
+      for (; l < max; ++l) {
+	objs[l] = 0;
+      }
+      return i + 1;
+    }    
+  }
+}
+
+SWIGINTERN int
+SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) {
+  int no_kwargs = 1;
+  if (kwargs) {
+    assert(PyDict_Check(kwargs));
+    if (PyDict_Size(kwargs) > 0) {
+      PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name);
+      no_kwargs = 0;
+    }
+  }
+  return no_kwargs;
+}
+
+/* A functor is a function object with one single object argument */
+#define SWIG_Python_CallFunctor(functor, obj)	        PyObject_CallFunctionObjArgs(functor, obj, NULL);
+
+/*
+  Helper for static pointer initialization for both C and C++ code, for example
+  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);
+*/
+#ifdef __cplusplus
+#define SWIG_STATIC_POINTER(var)  var
+#else
+#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Python-specific SWIG API */
+#define SWIG_newvarlink()                             SWIG_Python_newvarlink()
+#define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)
+#define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)
+ 
+/* -----------------------------------------------------------------------------
+ * global variable support code.
+ * ----------------------------------------------------------------------------- */
+ 
+typedef struct swig_globalvar {   
+  char       *name;                  /* Name of global variable */
+  PyObject *(*get_attr)(void);       /* Return the current value */
+  int       (*set_attr)(PyObject *); /* Set the value */
+  struct swig_globalvar *next;
+} swig_globalvar;
+
+typedef struct swig_varlinkobject {
+  PyObject_HEAD
+  swig_globalvar *vars;
+} swig_varlinkobject;
+
+SWIGINTERN PyObject *
+swig_varlink_repr(PyObject *SWIGUNUSEDPARM(v)) {
+#if PY_VERSION_HEX >= 0x03000000
+  return PyUnicode_InternFromString("");
+#else
+  return PyString_FromString("");
+#endif
+}
+
+SWIGINTERN PyObject *
+swig_varlink_str(PyObject *o) {
+  swig_varlinkobject *v = (swig_varlinkobject *) o;
+#if PY_VERSION_HEX >= 0x03000000
+  PyObject *str = PyUnicode_InternFromString("(");
+  PyObject *tail;
+  PyObject *joined;
+  swig_globalvar *var;
+  for (var = v->vars; var; var=var->next) {
+    tail = PyUnicode_FromString(var->name);
+    joined = PyUnicode_Concat(str, tail);
+    SWIG_Py_DECREF(str);
+    SWIG_Py_DECREF(tail);
+    str = joined;
+    if (var->next) {
+        tail = PyUnicode_InternFromString(", ");
+        joined = PyUnicode_Concat(str, tail);
+        SWIG_Py_DECREF(str);
+        SWIG_Py_DECREF(tail);
+        str = joined;
+    }
+  }
+  tail = PyUnicode_InternFromString(")");
+  joined = PyUnicode_Concat(str, tail);
+  SWIG_Py_DECREF(str);
+  SWIG_Py_DECREF(tail);
+  str = joined;
+#else
+  PyObject *str = PyString_FromString("(");
+  swig_globalvar *var;
+  for (var = v->vars; var; var=var->next) {
+    PyString_ConcatAndDel(&str,PyString_FromString(var->name));
+    if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", "));
+  }
+  PyString_ConcatAndDel(&str,PyString_FromString(")"));
+#endif
+  return str;
+}
+
+SWIGINTERN void
+swig_varlink_dealloc(PyObject *o) {
+  swig_varlinkobject *v = (swig_varlinkobject *) o;
+  swig_globalvar *var = v->vars;
+  while (var) {
+    swig_globalvar *n = var->next;
+    free(var->name);
+    free(var);
+    var = n;
+  }
+}
+
+SWIGINTERN PyObject *
+swig_varlink_getattr(PyObject *o, char *n) {
+  swig_varlinkobject *v = (swig_varlinkobject *) o;
+  PyObject *res = NULL;
+  swig_globalvar *var = v->vars;
+  while (var) {
+    if (strcmp(var->name,n) == 0) {
+      res = (*var->get_attr)();
+      break;
+    }
+    var = var->next;
+  }
+  if (res == NULL && !PyErr_Occurred()) {
+    PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n);
+  }
+  return res;
+}
+
+SWIGINTERN int
+swig_varlink_setattr(PyObject *o, char *n, PyObject *p) {
+  swig_varlinkobject *v = (swig_varlinkobject *) o;
+  int res = 1;
+  swig_globalvar *var = v->vars;
+  while (var) {
+    if (strcmp(var->name,n) == 0) {
+      res = (*var->set_attr)(p);
+      break;
+    }
+    var = var->next;
+  }
+  if (res == 1 && !PyErr_Occurred()) {
+    PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n);
+  }
+  return res;
+}
+
+SWIGINTERN PyTypeObject*
+swig_varlink_type(void) {
+  static char varlink__doc__[] = "Swig var link object";
+#ifndef SWIG_HEAPTYPES
+  static PyTypeObject varlink_type;
+  static int type_init = 0;
+  if (!type_init) {
+    const PyTypeObject tmp = {
+#if PY_VERSION_HEX >= 0x03000000
+      PyVarObject_HEAD_INIT(NULL, 0)
+#else
+      PyObject_HEAD_INIT(NULL)
+      0,                                  /* ob_size */
+#endif
+      "swigvarlink",                      /* tp_name */
+      sizeof(swig_varlinkobject),         /* tp_basicsize */
+      0,                                  /* tp_itemsize */
+      (destructor) swig_varlink_dealloc,  /* tp_dealloc */
+#if PY_VERSION_HEX < 0x030800b4
+      (printfunc)0,                       /* tp_print */
+#else
+      (Py_ssize_t)0,                      /* tp_vectorcall_offset */
+#endif
+      (getattrfunc) swig_varlink_getattr, /* tp_getattr */
+      (setattrfunc) swig_varlink_setattr, /* tp_setattr */
+      0,                                  /* tp_compare */
+      (reprfunc) swig_varlink_repr,       /* tp_repr */
+      0,                                  /* tp_as_number */
+      0,                                  /* tp_as_sequence */
+      0,                                  /* tp_as_mapping */
+      0,                                  /* tp_hash */
+      0,                                  /* tp_call */
+      (reprfunc) swig_varlink_str,        /* tp_str */
+      0,                                  /* tp_getattro */
+      0,                                  /* tp_setattro */
+      0,                                  /* tp_as_buffer */
+      0,                                  /* tp_flags */
+      varlink__doc__,                     /* tp_doc */
+      0,                                  /* tp_traverse */
+      0,                                  /* tp_clear */
+      0,                                  /* tp_richcompare */
+      0,                                  /* tp_weaklistoffset */
+      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+      0,                                  /* tp_del */
+      0,                                  /* tp_version_tag */
+#if PY_VERSION_HEX >= 0x03040000
+      0,                                  /* tp_finalize */
+#endif
+#if PY_VERSION_HEX >= 0x03080000
+      0,                                  /* tp_vectorcall */
+#endif
+#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)
+      0,                                  /* tp_print */
+#endif
+#if PY_VERSION_HEX >= 0x030c0000
+      0,                                  /* tp_watched */
+#endif
+#if PY_VERSION_HEX >= 0x030d00a4
+      0,                                  /* tp_versions_used */
+#endif
+#ifdef COUNT_ALLOCS
+      0,                                  /* tp_allocs */
+      0,                                  /* tp_frees */
+      0,                                  /* tp_maxalloc */
+      0,                                  /* tp_prev */
+      0                                   /* tp_next */
+#endif
+    };
+    varlink_type = tmp;
+    type_init = 1;
+    if (PyType_Ready(&varlink_type) < 0)
+      return NULL;
+  }
+  return &varlink_type;
+#else
+  PyType_Slot slots[] = {
+    { Py_tp_dealloc, (void *)swig_varlink_dealloc },
+    { Py_tp_repr, (void *)swig_varlink_repr },
+    { Py_tp_getattr, (void *)swig_varlink_getattr },
+    { Py_tp_setattr, (void *)swig_varlink_setattr },
+    { Py_tp_str, (void *)swig_varlink_str },
+    { Py_tp_doc, (void *)varlink__doc__ },
+    { 0, NULL }
+  };
+  PyType_Spec spec = {
+    "swigvarlink",
+    sizeof(swig_varlinkobject),
+    0,
+    Py_TPFLAGS_DEFAULT,
+    slots
+  };
+  return (PyTypeObject *)PyType_FromSpec(&spec);
+#endif
+}
+
+/* Create a variable linking object for use later */
+SWIGINTERN PyObject *
+SWIG_Python_newvarlink(void) {
+  swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type());
+  if (result) {
+    result->vars = 0;
+  }
+  return ((PyObject*) result);
+}
+
+SWIGINTERN void 
+SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
+  swig_varlinkobject *v = (swig_varlinkobject *) p;
+  swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
+  if (gv) {
+    size_t size = strlen(name)+1;
+    gv->name = (char *)malloc(size);
+    if (gv->name) {
+      memcpy(gv->name, name, size);
+      gv->get_attr = get_attr;
+      gv->set_attr = set_attr;
+      gv->next = v->vars;
+    }
+  }
+  v->vars = gv;
+}
+
+
+static PyObject *Swig_Globals_global = NULL;
+  
+SWIGINTERN PyObject *
+SWIG_globals(void) {
+  if (Swig_Globals_global == NULL) {
+    Swig_Globals_global = SWIG_newvarlink();
+  }
+  return Swig_Globals_global;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Pointer declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)
+#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)
+
+#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)
+
+#define SWIG_BUILTIN_TP_INIT	    (SWIG_POINTER_OWN << 2)
+#define SWIG_BUILTIN_INIT	    (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* The python void return value */
+
+SWIGRUNTIMEINLINE PyObject * 
+SWIG_Py_Void(void)
+{
+  PyObject *none = Py_None;
+  SWIG_Py_INCREF(none);
+  return none;
+}
+
+/* SwigPyClientData */
+
+typedef struct {
+  PyObject *klass;
+  PyObject *newraw;
+  PyObject *newargs;
+  PyObject *destroy;
+  int delargs;
+  int implicitconv;
+  PyTypeObject *pytype;
+} SwigPyClientData;
+
+SWIGRUNTIMEINLINE int 
+SWIG_Python_CheckImplicit(swig_type_info *ty)
+{
+  SwigPyClientData *data = (SwigPyClientData *)ty->clientdata;
+  int fail = data ? data->implicitconv : 0;
+  if (fail)
+    PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors.");
+  return fail;
+}
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_ExceptionType(swig_type_info *desc) {
+  SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0;
+  PyObject *klass = data ? data->klass : 0;
+  return (klass ? klass : PyExc_RuntimeError);
+}
+
+
+SWIGRUNTIME SwigPyClientData * 
+SwigPyClientData_New(PyObject* obj)
+{
+  if (!obj) {
+    return 0;
+  } else {
+    SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData));
+    /* the klass element */
+    data->klass = obj;
+    SWIG_Py_INCREF(data->klass);
+    /* the newraw method and newargs arguments used to create a new raw instance */
+    if (PyClass_Check(obj)) {
+      data->newraw = 0;
+      SWIG_Py_INCREF(obj);
+      data->newargs = obj;
+    } else {
+      data->newraw = PyObject_GetAttrString(data->klass, "__new__");
+      if (data->newraw) {
+        data->newargs = PyTuple_New(1);
+        if (data->newargs) {
+          SWIG_Py_INCREF(obj);
+          PyTuple_SET_ITEM(data->newargs, 0, obj);
+        } else {
+          SWIG_Py_DECREF(data->newraw);
+          SWIG_Py_DECREF(data->klass);
+          free(data);
+          return 0;
+        }
+      } else {
+        SWIG_Py_INCREF(obj);
+        data->newargs = obj;
+      }
+    }
+    /* the destroy method, aka as the C++ delete method */
+    data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__");
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      data->destroy = 0;
+    }
+    if (data->destroy) {
+      data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O);
+    } else {
+      data->delargs = 0;
+    }
+    data->implicitconv = 0;
+    data->pytype = 0;
+    return data;
+  }
+}
+
+SWIGRUNTIME void 
+SwigPyClientData_Del(SwigPyClientData *data)
+{
+  SWIG_Py_XDECREF(data->klass);
+  SWIG_Py_XDECREF(data->newraw);
+  SWIG_Py_XDECREF(data->newargs);
+  SWIG_Py_XDECREF(data->destroy);
+  free(data);
+}
+
+/* =============== SwigPyObject =====================*/
+
+typedef struct {
+  PyObject_HEAD
+  void *ptr;
+  swig_type_info *ty;
+  int own;
+  PyObject *next;
+#ifdef SWIGPYTHON_BUILTIN
+  PyObject *dict;
+#endif
+} SwigPyObject;
+
+
+#ifdef SWIGPYTHON_BUILTIN
+
+SWIGRUNTIME PyObject *
+SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args))
+{
+  SwigPyObject *sobj = (SwigPyObject *)v;
+
+  if (!sobj->dict)
+    sobj->dict = PyDict_New();
+
+  SWIG_Py_XINCREF(sobj->dict);
+  return sobj->dict;
+}
+
+#endif
+
+SWIGRUNTIME PyObject *
+SwigPyObject_long(SwigPyObject *v)
+{
+  return PyLong_FromVoidPtr(v->ptr);
+}
+
+SWIGRUNTIME PyObject *
+SwigPyObject_format(const char* fmt, SwigPyObject *v)
+{
+  PyObject *res = NULL;
+  PyObject *args = PyTuple_New(1);
+  if (args) {
+    PyObject *val = SwigPyObject_long(v);
+    if (val) {
+      PyObject *ofmt;
+      PyTuple_SET_ITEM(args, 0, val);
+      ofmt = SWIG_Python_str_FromChar(fmt);
+      if (ofmt) {
+#if PY_VERSION_HEX >= 0x03000000
+        res = PyUnicode_Format(ofmt,args);
+#else
+        res = PyString_Format(ofmt,args);
+#endif
+        SWIG_Py_DECREF(ofmt);
+      }
+    }
+    SWIG_Py_DECREF(args);
+  }
+  return res;
+}
+
+SWIGRUNTIME PyObject *
+SwigPyObject_oct(SwigPyObject *v)
+{
+  return SwigPyObject_format("%o",v);
+}
+
+SWIGRUNTIME PyObject *
+SwigPyObject_hex(SwigPyObject *v)
+{
+  return SwigPyObject_format("%x",v);
+}
+
+SWIGRUNTIME PyObject *
+SwigPyObject_repr(SwigPyObject *v)
+{
+  const char *name = SWIG_TypePrettyName(v->ty);
+  PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v);
+  if (repr && v->next) {
+    PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next);
+    if (nrep) {
+# if PY_VERSION_HEX >= 0x03000000
+      PyObject *joined = PyUnicode_Concat(repr, nrep);
+      SWIG_Py_DECREF(repr);
+      SWIG_Py_DECREF(nrep);
+      repr = joined;
+# else
+      PyString_ConcatAndDel(&repr,nrep);
+# endif
+    } else {
+      SWIG_Py_DECREF(repr);
+      repr = NULL;
+    }
+  }
+  return repr;
+}
+
+/* We need a version taking two PyObject* parameters so it's a valid
+ * PyCFunction to use in swigobject_methods[]. */
+SWIGRUNTIME PyObject *
+SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args))
+{
+  return SwigPyObject_repr((SwigPyObject*)v);
+}
+
+SWIGRUNTIME int
+SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w)
+{
+  void *i = v->ptr;
+  void *j = w->ptr;
+  return (i < j) ? -1 : ((i > j) ? 1 : 0);
+}
+
+/* Added for Python 3.x, would it also be useful for Python 2.x? */
+SWIGRUNTIME PyObject*
+SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op)
+{
+  PyObject* res = NULL;
+  if (!PyErr_Occurred()) {
+    if (op != Py_EQ && op != Py_NE) {
+      SWIG_Py_INCREF(Py_NotImplemented);
+      return Py_NotImplemented;
+    }
+    res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0);
+  }
+  return res;  
+}
+
+
+SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void);
+
+#ifdef SWIGPYTHON_BUILTIN
+static swig_type_info *SwigPyObject_stype = 0;
+SWIGRUNTIME PyTypeObject*
+SwigPyObject_type(void) {
+    SwigPyClientData *cd;
+    assert(SwigPyObject_stype);
+    cd = (SwigPyClientData*) SwigPyObject_stype->clientdata;
+    assert(cd);
+    assert(cd->pytype);
+    return cd->pytype;
+}
+#else
+SWIGRUNTIME PyTypeObject*
+SwigPyObject_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce();
+  return type;
+}
+#endif
+
+SWIGRUNTIMEINLINE int
+SwigPyObject_Check(PyObject *op) {
+  PyTypeObject *target_tp = SwigPyObject_type();
+  PyTypeObject *op_type = Py_TYPE(op);
+#ifdef SWIGPYTHON_BUILTIN
+  if (PyType_IsSubtype(op_type, target_tp))
+    return 1;
+  return (strcmp(op_type->tp_name, "SwigPyObject") == 0);
+#else
+# ifdef Py_LIMITED_API
+  int cmp;
+  PyObject *tp_name;
+#endif
+  if (op_type == target_tp)
+    return 1;
+# ifdef Py_LIMITED_API
+  tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__");
+  if (!tp_name)
+    return 0;
+  cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject");
+  SWIG_Py_DECREF(tp_name);
+  return cmp == 0;
+# else
+  return (strcmp(op_type->tp_name, "SwigPyObject") == 0);
+# endif
+#endif
+}
+
+SWIGRUNTIME PyObject *
+SwigPyObject_New(void *ptr, swig_type_info *ty, int own);
+
+static PyObject* Swig_Capsule_global = NULL;
+
+SWIGRUNTIME void
+SwigPyObject_dealloc(PyObject *v)
+{
+  SwigPyObject *sobj = (SwigPyObject *) v;
+  PyObject *next = sobj->next;
+  if (sobj->own == SWIG_POINTER_OWN) {
+    swig_type_info *ty = sobj->ty;
+    SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0;
+    PyObject *destroy = data ? data->destroy : 0;
+    if (destroy) {
+      /* destroy is always a VARARGS method */
+      PyObject *res;
+
+      /* PyObject_CallFunction() has the potential to silently drop
+         the active exception.  In cases of unnamed temporary
+         variable or where we just finished iterating over a generator
+         StopIteration will be active right now, and this needs to
+         remain true upon return from SwigPyObject_dealloc.  So save
+         and restore. */
+      
+      PyObject *type = NULL, *value = NULL, *traceback = NULL;
+      PyErr_Fetch(&type, &value, &traceback);
+
+      if (data->delargs) {
+        /* we need to create a temporary object to carry the destroy operation */
+        PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0);
+        if (tmp) {
+          res = SWIG_Python_CallFunctor(destroy, tmp);
+        } else {
+          res = 0;
+        }
+        SWIG_Py_XDECREF(tmp);
+      } else {
+        PyCFunction meth = PyCFunction_GET_FUNCTION(destroy);
+        PyObject *mself = PyCFunction_GET_SELF(destroy);
+        res = ((*meth)(mself, v));
+      }
+      if (!res)
+        PyErr_WriteUnraisable(destroy);
+
+      PyErr_Restore(type, value, traceback);
+
+      SWIG_Py_XDECREF(res);
+    } 
+#if !defined(SWIG_PYTHON_SILENT_MEMLEAK)
+    else {
+      const char *name = SWIG_TypePrettyName(ty);
+      printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown"));
+    }
+#endif
+    SWIG_Py_XDECREF(Swig_Capsule_global);
+  }
+  SWIG_Py_XDECREF(next);
+#ifdef SWIGPYTHON_BUILTIN
+  SWIG_Py_XDECREF(sobj->dict);
+#endif
+  PyObject_Free(v);
+}
+
+SWIGRUNTIME PyObject* 
+SwigPyObject_append(PyObject* v, PyObject* next)
+{
+  SwigPyObject *sobj = (SwigPyObject *) v;
+  if (!SwigPyObject_Check(next)) {
+    PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject");
+    return NULL;
+  }
+  ((SwigPyObject *)next)->next = sobj->next;
+  sobj->next = next;
+  SWIG_Py_INCREF(next);
+  return SWIG_Py_Void();
+}
+
+SWIGRUNTIME PyObject* 
+SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+{
+  SwigPyObject *sobj = (SwigPyObject *) v;
+  if (sobj->next) {    
+    SWIG_Py_INCREF(sobj->next);
+    return sobj->next;
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+
+SWIGINTERN PyObject*
+SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+{
+  SwigPyObject *sobj = (SwigPyObject *)v;
+  sobj->own = 0;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+{
+  SwigPyObject *sobj = (SwigPyObject *)v;
+  sobj->own = SWIG_POINTER_OWN;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+SwigPyObject_own(PyObject *v, PyObject *args)
+{
+  PyObject *val = 0;
+  if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) {
+    return NULL;
+  } else {
+    SwigPyObject *sobj = (SwigPyObject *)v;
+    PyObject *obj = PyBool_FromLong(sobj->own);
+    if (val) {
+      if (PyObject_IsTrue(val)) {
+        SWIG_Py_DECREF(SwigPyObject_acquire(v,args));
+      } else {
+        SWIG_Py_DECREF(SwigPyObject_disown(v,args));
+      }
+    } 
+    return obj;
+  }
+}
+
+static PyMethodDef
+swigobject_methods[] = {
+  {"disown",  SwigPyObject_disown,  METH_NOARGS,  "releases ownership of the pointer"},
+  {"acquire", SwigPyObject_acquire, METH_NOARGS,  "acquires ownership of the pointer"},
+  {"own",     SwigPyObject_own,     METH_VARARGS, "returns/sets ownership of the pointer"},
+  {"append",  SwigPyObject_append,  METH_O,       "appends another 'this' object"},
+  {"next",    SwigPyObject_next,    METH_NOARGS,  "returns the next 'this' object"},
+  {"__repr__",SwigPyObject_repr2,   METH_NOARGS,  "returns object representation"},
+  {0, 0, 0, 0}  
+};
+
+SWIGRUNTIME PyTypeObject*
+SwigPyObject_TypeOnce(void) {
+  static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer";
+#ifndef SWIG_HEAPTYPES
+  static PyNumberMethods SwigPyObject_as_number = {
+    (binaryfunc)0, /*nb_add*/
+    (binaryfunc)0, /*nb_subtract*/
+    (binaryfunc)0, /*nb_multiply*/
+    /* nb_divide removed in Python 3 */
+#if PY_VERSION_HEX < 0x03000000
+    (binaryfunc)0, /*nb_divide*/
+#endif
+    (binaryfunc)0, /*nb_remainder*/
+    (binaryfunc)0, /*nb_divmod*/
+    (ternaryfunc)0,/*nb_power*/
+    (unaryfunc)0,  /*nb_negative*/
+    (unaryfunc)0,  /*nb_positive*/
+    (unaryfunc)0,  /*nb_absolute*/
+    (inquiry)0,    /*nb_nonzero*/
+    0,		   /*nb_invert*/
+    0,		   /*nb_lshift*/
+    0,		   /*nb_rshift*/
+    0,		   /*nb_and*/
+    0,		   /*nb_xor*/
+    0,		   /*nb_or*/
+#if PY_VERSION_HEX < 0x03000000
+    0,   /*nb_coerce*/
+#endif
+    (unaryfunc)SwigPyObject_long, /*nb_int*/
+#if PY_VERSION_HEX < 0x03000000
+    (unaryfunc)SwigPyObject_long, /*nb_long*/
+#else
+    0, /*nb_reserved*/
+#endif
+    (unaryfunc)0,                 /*nb_float*/
+#if PY_VERSION_HEX < 0x03000000
+    (unaryfunc)SwigPyObject_oct,  /*nb_oct*/
+    (unaryfunc)SwigPyObject_hex,  /*nb_hex*/
+#endif
+#if PY_VERSION_HEX >= 0x03050000 /* 3.5 */
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */
+#elif PY_VERSION_HEX >= 0x03000000 /* 3.0 */
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */
+#else
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */
+#endif
+  };
+
+  static PyTypeObject swigpyobject_type;
+  static int type_init = 0;
+  if (!type_init) {
+    const PyTypeObject tmp = {
+#if PY_VERSION_HEX >= 0x03000000
+      PyVarObject_HEAD_INIT(NULL, 0)
+#else
+      PyObject_HEAD_INIT(NULL)
+      0,                                    /* ob_size */
+#endif
+      "SwigPyObject",                       /* tp_name */
+      sizeof(SwigPyObject),                 /* tp_basicsize */
+      0,                                    /* tp_itemsize */
+      (destructor)SwigPyObject_dealloc,     /* tp_dealloc */
+#if PY_VERSION_HEX < 0x030800b4
+      (printfunc)0,                         /* tp_print */
+#else
+      (Py_ssize_t)0,                        /* tp_vectorcall_offset */
+#endif
+      (getattrfunc)0,                       /* tp_getattr */
+      (setattrfunc)0,                       /* tp_setattr */
+#if PY_VERSION_HEX >= 0x03000000
+      0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */
+#else
+      (cmpfunc)SwigPyObject_compare,        /* tp_compare */
+#endif
+      (reprfunc)SwigPyObject_repr,          /* tp_repr */
+      &SwigPyObject_as_number,              /* tp_as_number */
+      0,                                    /* tp_as_sequence */
+      0,                                    /* tp_as_mapping */
+      (hashfunc)0,                          /* tp_hash */
+      (ternaryfunc)0,                       /* tp_call */
+      0,                                    /* tp_str */
+      PyObject_GenericGetAttr,              /* tp_getattro */
+      0,                                    /* tp_setattro */
+      0,                                    /* tp_as_buffer */
+      Py_TPFLAGS_DEFAULT,                   /* tp_flags */
+      swigobject_doc,                       /* tp_doc */
+      0,                                    /* tp_traverse */
+      0,                                    /* tp_clear */
+      (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */
+      0,                                    /* tp_weaklistoffset */
+      0,                                    /* tp_iter */
+      0,                                    /* tp_iternext */
+      swigobject_methods,                   /* tp_methods */
+      0,                                    /* tp_members */
+      0,                                    /* tp_getset */
+      0,                                    /* tp_base */
+      0,                                    /* tp_dict */
+      0,                                    /* tp_descr_get */
+      0,                                    /* tp_descr_set */
+      0,                                    /* tp_dictoffset */
+      0,                                    /* tp_init */
+      0,                                    /* tp_alloc */
+      0,                                    /* tp_new */
+      0,                                    /* tp_free */
+      0,                                    /* tp_is_gc */
+      0,                                    /* tp_bases */
+      0,                                    /* tp_mro */
+      0,                                    /* tp_cache */
+      0,                                    /* tp_subclasses */
+      0,                                    /* tp_weaklist */
+      0,                                    /* tp_del */
+      0,                                    /* tp_version_tag */
+#if PY_VERSION_HEX >= 0x03040000
+      0,                                    /* tp_finalize */
+#endif
+#if PY_VERSION_HEX >= 0x03080000
+      0,                                    /* tp_vectorcall */
+#endif
+#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)
+      0,                                    /* tp_print */
+#endif
+#if PY_VERSION_HEX >= 0x030c0000
+      0,                                    /* tp_watched */
+#endif
+#if PY_VERSION_HEX >= 0x030d00a4
+      0,                                    /* tp_versions_used */
+#endif
+#ifdef COUNT_ALLOCS
+      0,                                    /* tp_allocs */
+      0,                                    /* tp_frees */
+      0,                                    /* tp_maxalloc */
+      0,                                    /* tp_prev */
+      0                                     /* tp_next */
+#endif
+    };
+    swigpyobject_type = tmp;
+    type_init = 1;
+    if (PyType_Ready(&swigpyobject_type) != 0)
+      return NULL;
+  }
+  return &swigpyobject_type;
+#else
+  PyType_Slot slots[] = {
+    { Py_tp_dealloc, (void *)SwigPyObject_dealloc },
+    { Py_tp_repr, (void *)SwigPyObject_repr },
+    { Py_tp_getattro, (void *)PyObject_GenericGetAttr },
+    { Py_tp_doc, (void *)swigobject_doc },
+    { Py_tp_richcompare, (void *)SwigPyObject_richcompare },
+    { Py_tp_methods, (void *)swigobject_methods },
+    { Py_nb_int, (void *)SwigPyObject_long },
+    { 0, NULL }
+  };
+  PyType_Spec spec = {
+    "SwigPyObject",
+    sizeof(SwigPyObject),
+    0,
+    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
+    slots
+  };
+  return (PyTypeObject *)PyType_FromSpec(&spec);
+#endif
+}
+
+SWIGRUNTIME PyObject *
+SwigPyObject_New(void *ptr, swig_type_info *ty, int own)
+{
+  SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type());
+  if (sobj) {
+    sobj->ptr  = ptr;
+    sobj->ty   = ty;
+    sobj->own  = own;
+    sobj->next = 0;
+#ifdef SWIGPYTHON_BUILTIN
+    sobj->dict = 0;
+#endif
+    if (own == SWIG_POINTER_OWN) {
+      /* Obtain a reference to the Python capsule wrapping the module information, so that the
+       * module information is correctly destroyed after all SWIG python objects have been freed
+       * by the GC (and corresponding destructors invoked) */
+      SWIG_Py_XINCREF(Swig_Capsule_global);
+    }
+  }
+  return (PyObject *)sobj;
+}
+
+/* -----------------------------------------------------------------------------
+ * Implements a simple Swig Packed type, and use it instead of string
+ * ----------------------------------------------------------------------------- */
+
+typedef struct {
+  PyObject_HEAD
+  void *pack;
+  swig_type_info *ty;
+  size_t size;
+} SwigPyPacked;
+
+SWIGRUNTIME PyObject *
+SwigPyPacked_repr(SwigPyPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    return SWIG_Python_str_FromFormat("", result, v->ty->name);
+  } else {
+    return SWIG_Python_str_FromFormat("", v->ty->name);
+  }  
+}
+
+SWIGRUNTIME PyObject *
+SwigPyPacked_str(SwigPyPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
+    return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name);
+  } else {
+    return SWIG_Python_str_FromChar(v->ty->name);
+  }  
+}
+
+SWIGRUNTIME int
+SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w)
+{
+  size_t i = v->size;
+  size_t j = w->size;
+  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
+  return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2*v->size);
+}
+
+SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void);
+
+SWIGRUNTIME PyTypeObject*
+SwigPyPacked_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+SwigPyPacked_Check(PyObject *op) {
+#ifdef Py_LIMITED_API
+  int cmp;
+  PyObject *tp_name;
+#endif
+  PyTypeObject* op_type = Py_TYPE(op);
+  if (op_type == SwigPyPacked_TypeOnce())
+    return 1;
+#ifdef Py_LIMITED_API
+  tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__");
+  if (!tp_name)
+    return 0;
+  cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked");
+  SWIG_Py_DECREF(tp_name);
+  return cmp == 0;
+#else
+  return (strcmp(op_type->tp_name, "SwigPyPacked") == 0);
+#endif
+}
+
+SWIGRUNTIME void
+SwigPyPacked_dealloc(PyObject *v)
+{
+  if (SwigPyPacked_Check(v)) {
+    SwigPyPacked *sobj = (SwigPyPacked *) v;
+    free(sobj->pack);
+  }
+  PyObject_Free(v);
+}
+
+SWIGRUNTIME PyTypeObject*
+SwigPyPacked_TypeOnce(void) {
+  static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer";
+#ifndef SWIG_HEAPTYPES
+  static PyTypeObject swigpypacked_type;
+  static int type_init = 0;
+  if (!type_init) {
+    const PyTypeObject tmp = {
+#if PY_VERSION_HEX>=0x03000000
+      PyVarObject_HEAD_INIT(NULL, 0)
+#else
+      PyObject_HEAD_INIT(NULL)
+      0,                                    /* ob_size */
+#endif
+      "SwigPyPacked",                       /* tp_name */
+      sizeof(SwigPyPacked),                 /* tp_basicsize */
+      0,                                    /* tp_itemsize */
+      (destructor)SwigPyPacked_dealloc,     /* tp_dealloc */
+#if PY_VERSION_HEX < 0x030800b4
+      (printfunc)0,                         /* tp_print */
+#else
+      (Py_ssize_t)0,                        /* tp_vectorcall_offset */
+#endif
+      (getattrfunc)0,                       /* tp_getattr */
+      (setattrfunc)0,                       /* tp_setattr */
+#if PY_VERSION_HEX>=0x03000000
+      0, /* tp_reserved in 3.0.1 */
+#else
+      (cmpfunc)SwigPyPacked_compare,        /* tp_compare */
+#endif
+      (reprfunc)SwigPyPacked_repr,          /* tp_repr */
+      0,                                    /* tp_as_number */
+      0,                                    /* tp_as_sequence */
+      0,                                    /* tp_as_mapping */
+      (hashfunc)0,                          /* tp_hash */
+      (ternaryfunc)0,                       /* tp_call */
+      (reprfunc)SwigPyPacked_str,           /* tp_str */
+      PyObject_GenericGetAttr,              /* tp_getattro */
+      0,                                    /* tp_setattro */
+      0,                                    /* tp_as_buffer */
+      Py_TPFLAGS_DEFAULT,                   /* tp_flags */
+      swigpacked_doc,                       /* tp_doc */
+      0,                                    /* tp_traverse */
+      0,                                    /* tp_clear */
+      0,                                    /* tp_richcompare */
+      0,                                    /* tp_weaklistoffset */
+      0,                                    /* tp_iter */
+      0,                                    /* tp_iternext */
+      0,                                    /* tp_methods */
+      0,                                    /* tp_members */
+      0,                                    /* tp_getset */
+      0,                                    /* tp_base */
+      0,                                    /* tp_dict */
+      0,                                    /* tp_descr_get */
+      0,                                    /* tp_descr_set */
+      0,                                    /* tp_dictoffset */
+      0,                                    /* tp_init */
+      0,                                    /* tp_alloc */
+      0,                                    /* tp_new */
+      0,                                    /* tp_free */
+      0,                                    /* tp_is_gc */
+      0,                                    /* tp_bases */
+      0,                                    /* tp_mro */
+      0,                                    /* tp_cache */
+      0,                                    /* tp_subclasses */
+      0,                                    /* tp_weaklist */
+      0,                                    /* tp_del */
+      0,                                    /* tp_version_tag */
+#if PY_VERSION_HEX >= 0x03040000
+      0,                                    /* tp_finalize */
+#endif
+#if PY_VERSION_HEX >= 0x03080000
+      0,                                    /* tp_vectorcall */
+#endif
+#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)
+      0,                                    /* tp_print */
+#endif
+#if PY_VERSION_HEX >= 0x030c0000
+      0,                                    /* tp_watched */
+#endif
+#if PY_VERSION_HEX >= 0x030d00a4
+      0,                                    /* tp_versions_used */
+#endif
+#ifdef COUNT_ALLOCS
+      0,                                    /* tp_allocs */
+      0,                                    /* tp_frees */
+      0,                                    /* tp_maxalloc */
+      0,                                    /* tp_prev */
+      0                                     /* tp_next */
+#endif
+    };
+    swigpypacked_type = tmp;
+    type_init = 1;
+    if (PyType_Ready(&swigpypacked_type) != 0)
+      return NULL;
+  }
+  return &swigpypacked_type;
+#else
+  PyType_Slot slots[] = {
+    { Py_tp_dealloc, (void *)SwigPyPacked_dealloc },
+    { Py_tp_repr, (void *)SwigPyPacked_repr },
+    { Py_tp_str, (void *)SwigPyPacked_str },
+    { Py_tp_getattro, (void *)PyObject_GenericGetAttr },
+    { Py_tp_doc, (void *)swigpacked_doc },
+    { 0, NULL }
+  };
+  PyType_Spec spec = {
+    "SwigPyPacked",
+    sizeof(SwigPyPacked),
+    0,
+    Py_TPFLAGS_DEFAULT,
+    slots
+  };
+  return (PyTypeObject *)PyType_FromSpec(&spec);
+#endif
+}
+
+SWIGRUNTIME PyObject *
+SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty)
+{
+  SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type());
+  if (sobj) {
+    void *pack = malloc(size);
+    if (pack) {
+      memcpy(pack, ptr, size);
+      sobj->pack = pack;
+      sobj->ty   = ty;
+      sobj->size = size;
+    } else {
+      PyObject_Free((PyObject *)sobj);
+      sobj = 0;
+    }
+  }
+  return (PyObject *) sobj;
+}
+
+SWIGRUNTIME swig_type_info *
+SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
+{
+  if (SwigPyPacked_Check(obj)) {
+    SwigPyPacked *sobj = (SwigPyPacked *)obj;
+    if (sobj->size != size) return 0;
+    memcpy(ptr, sobj->pack, size);
+    return sobj->ty;
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+static PyObject *Swig_This_global = NULL;
+
+SWIGRUNTIME PyObject *
+SWIG_This(void)
+{
+  if (Swig_This_global == NULL)
+    Swig_This_global = SWIG_Python_str_FromChar("this");
+  return Swig_This_global;
+}
+
+/* #define SWIG_PYTHON_SLOW_GETSET_THIS */
+
+/* TODO: I don't know how to implement the fast getset in Python 3 right now */
+#if PY_VERSION_HEX>=0x03000000
+#define SWIG_PYTHON_SLOW_GETSET_THIS 
+#endif
+
+SWIGRUNTIME SwigPyObject *
+SWIG_Python_GetSwigThis(PyObject *pyobj) 
+{
+  PyObject *obj;
+
+  if (SwigPyObject_Check(pyobj))
+    return (SwigPyObject *) pyobj;
+
+#ifdef SWIGPYTHON_BUILTIN
+  (void)obj;
+# ifdef PyWeakref_CheckProxy
+  if (PyWeakref_CheckProxy(pyobj)) {
+#if PY_VERSION_HEX >= 0x030d0000
+    PyWeakref_GetRef(pyobj, &pyobj);
+    Py_DECREF(pyobj);
+#else
+    pyobj = PyWeakref_GET_OBJECT(pyobj);
+#endif
+    if (pyobj && SwigPyObject_Check(pyobj))
+      return (SwigPyObject*) pyobj;
+  }
+# endif
+  return NULL;
+#else
+
+  obj = 0;
+
+#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+  if (PyInstance_Check(pyobj)) {
+    obj = _PyInstance_Lookup(pyobj, SWIG_This());      
+  } else {
+    PyObject **dictptr = _PyObject_GetDictPtr(pyobj);
+    if (dictptr != NULL) {
+      PyObject *dict = *dictptr;
+      obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0;
+    } else {
+#ifdef PyWeakref_CheckProxy
+      if (PyWeakref_CheckProxy(pyobj)) {
+	PyObject *wobj = PyWeakref_GET_OBJECT(pyobj);
+	return wobj ? SWIG_Python_GetSwigThis(wobj) : 0;
+      }
+#endif
+      obj = PyObject_GetAttr(pyobj,SWIG_This());
+      if (obj) {
+	SWIG_Py_DECREF(obj);
+      } else {
+	if (PyErr_Occurred()) PyErr_Clear();
+	return 0;
+      }
+    }
+  }
+#else
+  obj = PyObject_GetAttr(pyobj,SWIG_This());
+  if (obj) {
+    SWIG_Py_DECREF(obj);
+  } else {
+    if (PyErr_Occurred()) PyErr_Clear();
+    return 0;
+  }
+#endif
+  if (obj && !SwigPyObject_Check(obj)) {
+    /* a PyObject is called 'this', try to get the 'real this'
+       SwigPyObject from it */ 
+    return SWIG_Python_GetSwigThis(obj);
+  }
+  return (SwigPyObject *)obj;
+#endif
+}
+
+/* Acquire a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_AcquirePtr(PyObject *obj, int own) {
+  if (own == SWIG_POINTER_OWN) {
+    SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj);
+    if (sobj) {
+      int oldown = sobj->own;
+      sobj->own = own;
+      return oldown;
+    }
+  }
+  return 0;
+}
+
+/* Convert a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {
+  int res;
+  SwigPyObject *sobj;
+  int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0;
+
+  if (!obj)
+    return SWIG_ERROR;
+  if (obj == Py_None && !implicit_conv) {
+    if (ptr)
+      *ptr = 0;
+    return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK;
+  }
+
+  res = SWIG_ERROR;
+
+  sobj = SWIG_Python_GetSwigThis(obj);
+  if (own)
+    *own = 0;
+  while (sobj) {
+    void *vptr = sobj->ptr;
+    if (ty) {
+      swig_type_info *to = sobj->ty;
+      if (to == ty) {
+        /* no type cast needed */
+        if (ptr) *ptr = vptr;
+        break;
+      } else {
+        swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+        if (!tc) {
+          sobj = (SwigPyObject *)sobj->next;
+        } else {
+          if (ptr) {
+            int newmemory = 0;
+            *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
+            if (newmemory == SWIG_CAST_NEW_MEMORY) {
+              assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */
+              if (own)
+                *own = *own | SWIG_CAST_NEW_MEMORY;
+            }
+          }
+          break;
+        }
+      }
+    } else {
+      if (ptr) *ptr = vptr;
+      break;
+    }
+  }
+  if (sobj) {
+    if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) {
+      res = SWIG_ERROR_RELEASE_NOT_OWNED;
+    } else {
+      if (own)
+        *own = *own | sobj->own;
+      if (flags & SWIG_POINTER_DISOWN) {
+        sobj->own = 0;
+      }
+      if (flags & SWIG_POINTER_CLEAR) {
+        sobj->ptr = 0;
+      }
+      res = SWIG_OK;
+    }
+  } else {
+    if (implicit_conv) {
+      SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0;
+      if (data && !data->implicitconv) {
+        PyObject *klass = data->klass;
+        if (klass) {
+          PyObject *impconv;
+          data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/
+          impconv = SWIG_Python_CallFunctor(klass, obj);
+          data->implicitconv = 0;
+          if (PyErr_Occurred()) {
+            PyErr_Clear();
+            impconv = 0;
+          }
+          if (impconv) {
+            SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv);
+            if (iobj) {
+              void *vptr;
+              res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0);
+              if (SWIG_IsOK(res)) {
+                if (ptr) {
+                  *ptr = vptr;
+                  /* transfer the ownership to 'ptr' */
+                  iobj->own = 0;
+                  res = SWIG_AddCast(res);
+                  res = SWIG_AddNewMask(res);
+                } else {
+                  res = SWIG_AddCast(res);		    
+                }
+              }
+            }
+            SWIG_Py_DECREF(impconv);
+          }
+        }
+      }
+      if (!SWIG_IsOK(res) && obj == Py_None) {
+        if (ptr)
+          *ptr = 0;
+        if (PyErr_Occurred())
+          PyErr_Clear();
+        res = SWIG_OK;
+      }
+    }
+  }
+  return res;
+}
+
+/* Convert a function ptr value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {
+  if (!PyCFunction_Check(obj)) {
+    return SWIG_ConvertPtr(obj, ptr, ty, 0);
+  } else {
+    void *vptr = 0;
+    swig_cast_info *tc;
+
+    /* here we get the method pointer for callbacks */
+#ifndef Py_LIMITED_API
+    const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
+#else
+    PyObject* pystr_doc = PyObject_GetAttrString(obj, "__doc__");
+    PyObject *bytes = NULL;
+    const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0;
+#endif
+    const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0;
+    if (desc)
+      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;
+#ifdef Py_LIMITED_API
+    SWIG_Py_XDECREF(bytes);
+    SWIG_Py_XDECREF(pystr_doc);
+#endif
+    if (!desc)
+      return SWIG_ERROR;
+    tc = SWIG_TypeCheck(desc,ty);
+    if (tc) {
+      int newmemory = 0;
+      *ptr = SWIG_TypeCast(tc,vptr,&newmemory);
+      assert(!newmemory); /* newmemory handling not yet implemented */
+    } else {
+      return SWIG_ERROR;
+    }
+    return SWIG_OK;
+  }
+}
+
+/* Convert a packed pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {
+  swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz);
+  if (!to) return SWIG_ERROR;
+  if (ty) {
+    if (to != ty) {
+      /* check type cast? */
+      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+      if (!tc) return SWIG_ERROR;
+    }
+  }
+  return SWIG_OK;
+}  
+
+/* -----------------------------------------------------------------------------
+ * Create a new pointer object
+ * ----------------------------------------------------------------------------- */
+
+/*
+  Create a new instance object, without calling __init__, and set the
+  'this' attribute.
+*/
+
+SWIGRUNTIME PyObject* 
+SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this)
+{
+  PyObject *inst = 0;
+  PyObject *newraw = data->newraw;
+  if (newraw) {
+    inst = PyObject_Call(newraw, data->newargs, NULL);
+    if (inst) {
+#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+      PyObject **dictptr = _PyObject_GetDictPtr(inst);
+      if (dictptr != NULL) {
+        PyObject *dict = *dictptr;
+        if (dict == NULL) {
+          dict = PyDict_New();
+          *dictptr = dict;
+        }
+        if (dict) {
+          PyDict_SetItem(dict, SWIG_This(), swig_this);
+        } else{
+          SWIG_Py_DECREF(inst);
+          inst = 0;
+        }
+      }
+#else
+      if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) {
+        SWIG_Py_DECREF(inst);
+        inst = 0;
+      }
+#endif
+    }
+  } else {
+#if PY_VERSION_HEX >= 0x03000000
+    PyObject *empty_args = PyTuple_New(0);
+    if (empty_args) {
+      PyObject *empty_kwargs = PyDict_New();
+      if (empty_kwargs) {
+#ifndef Py_LIMITED_API
+        newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new;
+#else
+        newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new);
+#endif
+        inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs);
+        SWIG_Py_DECREF(empty_kwargs);
+        if (inst) {
+          if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) {
+            SWIG_Py_DECREF(inst);
+            inst = 0;
+          } else {
+            PyType_Modified(Py_TYPE(inst));
+          }
+        }
+      }
+      SWIG_Py_DECREF(empty_args);
+    }
+#else
+    PyObject *dict = PyDict_New();
+    if (dict) {
+      PyDict_SetItem(dict, SWIG_This(), swig_this);
+      inst = PyInstance_NewRaw(data->newargs, dict);
+      SWIG_Py_DECREF(dict);
+    }
+#endif
+  }
+  return inst;
+}
+
+SWIGRUNTIME int
+SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this)
+{
+#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+  PyObject **dictptr = _PyObject_GetDictPtr(inst);
+  if (dictptr != NULL) {
+    PyObject *dict = *dictptr;
+    if (dict == NULL) {
+      dict = PyDict_New();
+      *dictptr = dict;
+    }
+    if (dict) {
+      return PyDict_SetItem(dict, SWIG_This(), swig_this);
+    } else{
+      return -1;
+    }
+  }
+#endif
+  return PyObject_SetAttr(inst, SWIG_This(), swig_this);
+} 
+
+
+SWIGINTERN PyObject *
+SWIG_Python_InitShadowInstance(PyObject *args) {
+  PyObject *obj[2];
+  if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) {
+    return NULL;
+  } else {
+    SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]);
+    if (sthis) {
+      SWIG_Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1]));
+    } else {
+      if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0)
+        return NULL;
+    }
+    return SWIG_Py_Void();
+  }
+}
+
+/* Create a new pointer object */
+
+SWIGRUNTIME PyObject *
+SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) {
+  SwigPyClientData *clientdata;
+  PyObject * robj;
+  int own;
+
+  if (!ptr)
+    return SWIG_Py_Void();
+
+  clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0;
+  own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;
+  if (clientdata && clientdata->pytype) {
+    SwigPyObject *newobj;
+    if (flags & SWIG_BUILTIN_TP_INIT) {
+      newobj = (SwigPyObject*) self;
+      if (newobj->ptr) {
+#ifndef Py_LIMITED_API
+        allocfunc alloc = clientdata->pytype->tp_alloc;
+#else
+        allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc);
+#endif
+        PyObject *next_self = alloc(clientdata->pytype, 0);
+        while (newobj->next)
+	  newobj = (SwigPyObject *) newobj->next;
+        newobj->next = next_self;
+        newobj = (SwigPyObject *)next_self;
+#ifdef SWIGPYTHON_BUILTIN
+        newobj->dict = 0;
+#endif
+      }
+    } else {
+      newobj = PyObject_New(SwigPyObject, clientdata->pytype);
+#ifdef SWIGPYTHON_BUILTIN
+      if (newobj) {
+        newobj->dict = 0;
+      }
+#endif
+    }
+    if (newobj) {
+      newobj->ptr = ptr;
+      newobj->ty = type;
+      newobj->own = own;
+      newobj->next = 0;
+      return (PyObject*) newobj;
+    }
+    return SWIG_Py_Void();
+  }
+
+  assert(!(flags & SWIG_BUILTIN_TP_INIT));
+
+  robj = SwigPyObject_New(ptr, type, own);
+  if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {
+    PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);
+    SWIG_Py_DECREF(robj);
+    robj = inst;
+  }
+  return robj;
+}
+
+/* Create a new packed object */
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Get type list 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_LINK_RUNTIME
+void *SWIG_ReturnGlobalTypeList(void *);
+#endif
+
+static PyObject *Swig_TypeCache_global = NULL;
+
+/* The python cached type query */
+SWIGRUNTIME PyObject *
+SWIG_Python_TypeCache(void) {
+  if (Swig_TypeCache_global == NULL) {
+    Swig_TypeCache_global = PyDict_New();
+  }
+  return Swig_TypeCache_global;
+}
+
+SWIGRUNTIME swig_module_info *
+SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) {
+#ifdef SWIG_LINK_RUNTIME
+  static void *type_pointer = (void *)0;
+  /* first check if module already created */
+  if (!type_pointer) {
+    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
+  }
+#else
+  void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0);
+  if (PyErr_Occurred()) {
+    PyErr_Clear();
+    type_pointer = (void *)0;
+  }
+#endif
+  return (swig_module_info *) type_pointer;
+}
+
+
+static int interpreter_counter = 0; /* how many (sub-)interpreters are using swig_module's types */
+
+SWIGRUNTIME void
+SWIG_Python_DestroyModule(PyObject *obj)
+{
+  swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME);
+  swig_type_info **types = swig_module->types;
+  size_t i;
+  if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */
+    return;
+  for (i =0; i < swig_module->size; ++i) {
+    swig_type_info *ty = types[i];
+    if (ty->owndata) {
+      SwigPyClientData *data = (SwigPyClientData *) ty->clientdata;
+      ty->clientdata = 0;
+      if (data) SwigPyClientData_Del(data);
+    }
+  }
+  SWIG_Py_DECREF(SWIG_This());
+  Swig_This_global = NULL;
+  SWIG_Py_DECREF(SWIG_globals());
+  Swig_Globals_global = NULL;
+  SWIG_Py_DECREF(SWIG_Python_TypeCache());
+  Swig_TypeCache_global = NULL;
+  Swig_Capsule_global = NULL;
+}
+
+SWIGRUNTIME void
+SWIG_Python_SetModule(swig_module_info *swig_module) {
+#if PY_VERSION_HEX >= 0x03000000
+ /* Add a dummy module object into sys.modules */
+  PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION);
+#else
+  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */
+  PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table);
+#endif
+  PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule);
+  if (pointer && module) {
+    if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) {
+      ++interpreter_counter;
+      Swig_Capsule_global = pointer;
+    } else {
+      SWIG_Py_DECREF(pointer);
+    }
+  } else {
+    SWIG_Py_XDECREF(pointer);
+  }
+}
+
+SWIGRUNTIME swig_type_info *
+SWIG_Python_TypeQuery(const char *type)
+{
+  PyObject *cache = SWIG_Python_TypeCache();
+  PyObject *key = SWIG_Python_str_FromChar(type); 
+  PyObject *obj = PyDict_GetItem(cache, key);
+  swig_type_info *descriptor;
+  if (obj) {
+    descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL);
+  } else {
+    swig_module_info *swig_module = SWIG_GetModule(0);
+    descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type);
+    if (descriptor) {
+      obj = PyCapsule_New((void*) descriptor, NULL, NULL);
+      if (obj) {
+        PyDict_SetItem(cache, key, obj);
+        SWIG_Py_DECREF(obj);
+      }
+    }
+  }
+  SWIG_Py_DECREF(key);
+  return descriptor;
+}
+
+/* 
+   For backward compatibility only
+*/
+#define SWIG_POINTER_EXCEPTION  0
+#define SWIG_arg_fail(arg)      SWIG_Python_ArgFail(arg)
+#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)
+
+SWIGRUNTIME int
+SWIG_Python_AddErrMesg(const char* mesg, int infront)
+{  
+  if (PyErr_Occurred()) {
+    PyObject *type = 0;
+    PyObject *value = 0;
+    PyObject *traceback = 0;
+    PyErr_Fetch(&type, &value, &traceback);
+    if (value) {
+      PyObject *old_str = PyObject_Str(value);
+      PyObject *bytes = NULL;
+      const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes);
+      const char *errmesg = tmp ? tmp : "Invalid error message";
+      SWIG_Py_XINCREF(type);
+      PyErr_Clear();
+      if (infront) {
+	PyErr_Format(type, "%s %s", mesg, errmesg);
+      } else {
+	PyErr_Format(type, "%s %s", errmesg, mesg);
+      }
+      SWIG_Py_XDECREF(bytes);
+      SWIG_Py_DECREF(old_str);
+    }
+    return 1;
+  } else {
+    return 0;
+  }
+}
+  
+SWIGRUNTIME int
+SWIG_Python_ArgFail(int argnum)
+{
+  if (PyErr_Occurred()) {
+    /* add information about failing argument */
+    char mesg[256];
+    PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum);
+    return SWIG_Python_AddErrMesg(mesg, 1);
+  } else {
+    return 0;
+  }
+}
+
+SWIGRUNTIMEINLINE const char *
+SwigPyObject_GetDesc(PyObject *self)
+{
+  SwigPyObject *v = (SwigPyObject *)self;
+  swig_type_info *ty = v ? v->ty : 0;
+  return ty ? ty->str : "";
+}
+
+SWIGRUNTIME void
+SWIG_Python_TypeError(const char *type, PyObject *obj)
+{
+  (void) obj;
+  if (type) {
+#if defined(SWIG_COBJECT_TYPES)
+    if (obj && SwigPyObject_Check(obj)) {
+      const char *otype = (const char *) SwigPyObject_GetDesc(obj);
+      if (otype) {
+	PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received",
+		     type, otype);
+	return;
+      }
+    } else 
+#endif      
+    {
+#ifndef Py_LIMITED_API
+      /* tp_name is not accessible */
+      const char *otype = (obj ? obj->ob_type->tp_name : 0); 
+      if (otype) {
+	PyObject *str = PyObject_Str(obj);
+	PyObject *bytes = NULL;
+	const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0;
+	if (cstr) {
+	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
+		       type, otype, cstr);
+	} else {
+	  PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
+		       type, otype);
+	}
+	SWIG_Py_XDECREF(bytes);
+	SWIG_Py_XDECREF(str);
+	return;
+      }
+#endif
+    }   
+    PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
+  } else {
+    PyErr_Format(PyExc_TypeError, "unexpected type is received");
+  }
+}
+
+
+/* Convert a pointer value, signal an exception on a type mismatch */
+SWIGRUNTIME void *
+SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) {
+  void *result;
+  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
+    PyErr_Clear();
+  }
+  return result;
+}
+
+#ifdef SWIGPYTHON_BUILTIN
+SWIGRUNTIME int
+SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) {
+  PyTypeObject *tp = obj->ob_type;
+  PyObject *descr;
+  PyObject *encoded_name;
+  descrsetfunc f;
+  int res = -1;
+
+# ifdef Py_USING_UNICODE
+  if (PyString_Check(name)) {
+    name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL);
+    if (!name)
+      return -1;
+  } else if (!PyUnicode_Check(name))
+# else
+  if (!PyString_Check(name))
+# endif
+  {
+    PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name);
+    return -1;
+  } else {
+    SWIG_Py_INCREF(name);
+  }
+
+  if (!tp->tp_dict) {
+    if (PyType_Ready(tp) != 0)
+      goto done;
+  }
+
+  descr = _PyType_Lookup(tp, name);
+  f = NULL;
+  if (descr != NULL)
+    f = descr->ob_type->tp_descr_set;
+  if (!f) {
+    if (PyString_Check(name)) {
+      encoded_name = name;
+      SWIG_Py_INCREF(name);
+    } else {
+      encoded_name = PyUnicode_AsUTF8String(name);
+      if (!encoded_name)
+        goto done;
+    }
+    PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name));
+    SWIG_Py_DECREF(encoded_name);
+  } else {
+    res = f(descr, obj, value);
+  }
+  
+  done:
+  SWIG_Py_DECREF(name);
+  return res;
+}
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) 
+
+#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) 
+
+
+
+  #define SWIG_exception(code, msg) do { SWIG_Error(code, msg); SWIG_fail;; } while(0) 
+
+
+/* -------- TYPES TABLE (BEGIN) -------- */
+
+#define SWIGTYPE_p_char swig_types[0]
+#define SWIGTYPE_p_float swig_types[1]
+#define SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText swig_types[2]
+#define SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText swig_types[3]
+#define SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece swig_types[4]
+#define SWIGTYPE_p_sentencepiece__SentenceIterator swig_types[5]
+#define SWIGTYPE_p_sentencepiece__SentencePieceNormalizer swig_types[6]
+#define SWIGTYPE_p_sentencepiece__SentencePieceProcessor swig_types[7]
+#define SWIGTYPE_p_sentencepiece__SentencePieceTrainer swig_types[8]
+#define SWIGTYPE_p_std__string swig_types[9]
+#define SWIGTYPE_p_std__unordered_mapT_std__string_std__string_t swig_types[10]
+#define SWIGTYPE_p_std__vectorT_absl__string_view_t swig_types[11]
+#define SWIGTYPE_p_std__vectorT_int_t swig_types[12]
+#define SWIGTYPE_p_std__vectorT_std__vectorT_absl__string_view_t_t swig_types[13]
+#define SWIGTYPE_p_std__vectorT_std__vectorT_int_t_t swig_types[14]
+static swig_type_info *swig_types[16];
+static swig_module_info swig_module = {swig_types, 15, 0, 0, 0, 0};
+#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
+#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
+
+/* -------- TYPES TABLE (END) -------- */
+
+#ifdef SWIG_TypeQuery
+# undef SWIG_TypeQuery
+#endif
+#define SWIG_TypeQuery SWIG_Python_TypeQuery
+
+/*-----------------------------------------------
+              @(target):= _sentencepiece.so
+  ------------------------------------------------*/
+#if PY_VERSION_HEX >= 0x03000000
+#  define SWIG_init    PyInit__sentencepiece
+
+#else
+#  define SWIG_init    init_sentencepiece
+
+#endif
+
+#ifdef __cplusplus
+#include 
+/* SwigValueWrapper is described in swig.swg */
+template class SwigValueWrapper {
+  struct SwigSmartPointer {
+    T *ptr;
+    SwigSmartPointer(T *p) : ptr(p) { }
+    ~SwigSmartPointer() { delete ptr; }
+    SwigSmartPointer& operator=(SwigSmartPointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
+    void reset(T *p) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = p; }
+  } pointer;
+  SwigValueWrapper& operator=(const SwigValueWrapper& rhs);
+  SwigValueWrapper(const SwigValueWrapper& rhs);
+public:
+  SwigValueWrapper() : pointer(0) { }
+  SwigValueWrapper& operator=(const T& t) { SwigSmartPointer tmp(new T(t)); pointer = tmp; return *this; }
+#if __cplusplus >=201103L
+  SwigValueWrapper& operator=(T&& t) { SwigSmartPointer tmp(new T(std::move(t))); pointer = tmp; return *this; }
+  operator T&&() const { return std::move(*pointer.ptr); }
+#else
+  operator T&() const { return *pointer.ptr; }
+#endif
+  T *operator&() const { return pointer.ptr; }
+  static void reset(SwigValueWrapper& t, T *p) { t.pointer.reset(p); }
+};
+
+/*
+ * SwigValueInit() is a generic initialisation solution as the following approach:
+ * 
+ *       T c_result = T();
+ * 
+ * doesn't compile for all types for example:
+ * 
+ *       unsigned int c_result = unsigned int();
+ */
+template  T SwigValueInit() {
+  return T();
+}
+
+#if __cplusplus >=201103L
+# define SWIG_STD_MOVE(OBJ) std::move(OBJ)
+#else
+# define SWIG_STD_MOVE(OBJ) OBJ
+#endif
+
+#endif
+
+
+#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) 
+#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) 
+
+
+#include 
+
+
+namespace swig {
+  class SwigPtr_PyObject {
+  protected:
+    PyObject *_obj;
+
+  public:
+    SwigPtr_PyObject() :_obj(0)
+    {
+    }
+
+    SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj)
+    {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+      SWIG_Py_XINCREF(_obj);
+      SWIG_PYTHON_THREAD_END_BLOCK;
+    }
+    
+    SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj)
+    {
+      if (initial_ref) {
+        SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+        SWIG_Py_XINCREF(_obj);
+        SWIG_PYTHON_THREAD_END_BLOCK;
+      }
+    }
+    
+    SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) 
+    {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+      SWIG_Py_XINCREF(item._obj);
+      SWIG_Py_XDECREF(_obj);
+      _obj = item._obj;
+      SWIG_PYTHON_THREAD_END_BLOCK;
+      return *this;      
+    }
+    
+    ~SwigPtr_PyObject() 
+    {
+      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+      SWIG_Py_XDECREF(_obj);
+      SWIG_PYTHON_THREAD_END_BLOCK;
+    }
+    
+    operator PyObject *() const
+    {
+      return _obj;
+    }
+
+    PyObject *operator->() const
+    {
+      return _obj;
+    }
+  };
+}
+
+
+namespace swig {
+  struct SwigVar_PyObject : SwigPtr_PyObject {
+    SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { }
+    
+    SwigVar_PyObject & operator = (PyObject* obj)
+    {
+      SWIG_Py_XDECREF(_obj);
+      _obj = obj;
+      return *this;      
+    }
+  };
+}
+
+
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace {
+PyObject* kUnicodeInput = reinterpret_cast(0x1);
+PyObject* kByteInput = reinterpret_cast(0x2);
+
+using BytesArray = std::vector;
+
+inline void ReleaseResultObject(PyObject *obj) {
+  if (obj != nullptr && obj != kUnicodeInput && obj != kByteInput) {
+    Py_XDECREF(obj);
+  }
+}
+
+class PyInputString {
+ public:
+  explicit PyInputString(PyObject* obj) {
+    if (PyUnicode_Check(obj)) {
+      str_ = const_cast(PyUnicode_AsUTF8AndSize(obj, &size_));
+      input_type_ = kUnicodeInput;
+    } else if (PyBytes_Check(obj)) {
+      PyBytes_AsStringAndSize(obj, &str_, &size_);
+      input_type_ = kByteInput;
+    } else {
+      str_ = nullptr;
+    }
+  }
+  absl::string_view str() const { return absl::string_view(data(), size()); }
+  const char* data() const { return str_; }
+  Py_ssize_t size() const { return size_; }
+  bool IsAvalable() const { return str_ != nullptr; }
+  PyObject *input_type() const { return input_type_; }
+
+  static bool IsUnicode(PyObject *resultobj) {
+    return (resultobj == nullptr || resultobj == kUnicodeInput);
+  }
+
+ private:
+  PyObject* input_type_ = nullptr;
+  char* str_ = nullptr;
+  Py_ssize_t size_ = 0;
+};
+
+PyObject* MakePyOutputString(const std::string& output,
+                             PyObject *resultobj) {
+  if (PyInputString::IsUnicode(resultobj)) {
+    return PyUnicode_FromStringAndSize(output.data(), output.size());
+  }
+  return PyBytes_FromStringAndSize(output.data(), output.size());
+}
+
+PyObject* MakePyOutputBytes(const sentencepiece::util::bytes& output) {
+  return PyBytes_FromStringAndSize(output.data(), output.size());
+}
+
+int ToSwigError(sentencepiece::util::StatusCode code) {
+  switch (code) {
+    case sentencepiece::util::StatusCode::kNotFound:
+      return SWIG_IOError;
+    case sentencepiece::util::StatusCode::kOutOfRange:
+      return SWIG_IndexError;
+    case sentencepiece::util::StatusCode::kInvalidArgument:
+      return SWIG_SyntaxError;
+    default:
+      return SWIG_RuntimeError;
+  }
+  return SWIG_RuntimeError;
+}
+
+class PySentenceIterator : public sentencepiece::SentenceIterator {
+  public:
+  PySentenceIterator(PyObject *iter) : iter_(iter) {
+    item_ = PyIter_Next(iter_);
+    CopyValue();
+  }
+
+  ~PySentenceIterator() {
+   // Py_XDECREF(iter_);
+  }
+
+  bool done() const override {
+    return item_ == nullptr;
+  }
+
+  void Next() override {
+    item_ = PyIter_Next(iter_);
+    CopyValue();
+  }
+
+  const std::string &value() const override {
+    return value_;
+  }
+
+  sentencepiece::util::Status status() const override {
+    return status_;
+  }
+
+  private:
+   void CopyValue() {
+     if (item_ == nullptr) return;
+     const PyInputString ustring(item_);
+     if (ustring.IsAvalable()) {
+       const char *data = ustring.data();
+       size_t size = ustring.size();
+       while (size > 0) {
+         if (data[size - 1] == '\r' || data[size - 1] == '\n')
+           --size;
+         else
+           break;
+       }
+       value_.assign(data, size);
+     } else {
+       status_ = sentencepiece::util::Status(sentencepiece::util::StatusCode::kInternal,
+                                             "Not a string.");
+     }
+     Py_XDECREF(item_);
+   }
+   PyObject *iter_ = nullptr;
+   PyObject *item_ = nullptr;
+   std::string value_;
+   sentencepiece::util::Status status_;
+};
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       std::vector *ids,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (!add_bos && !add_eos && !reverse) return;
+  if (reverse) std::reverse(ids->begin(), ids->end());
+  if (add_bos) ids->insert(ids->begin(), sp.bos_id());
+  if (add_eos) ids->push_back(sp.eos_id());
+}
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       std::vector *pieces,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (!add_bos && !add_eos && !reverse && !emit_unk_piece) return;
+  if (reverse) std::reverse(pieces->begin(), pieces->end());
+  if (add_bos) pieces->insert(pieces->begin(), sp.IdToPiece(sp.bos_id()));
+  if (add_eos) pieces->push_back(sp.IdToPiece(sp.eos_id()));
+  if (emit_unk_piece) {
+    const auto &unk = sp.IdToPiece(sp.unk_id());
+    for (auto &piece : *pieces) {
+      const int id = sp.PieceToId(piece);
+      if (id == sp.unk_id()) {
+        piece = unk;
+      }
+    }
+  }
+}
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       sentencepiece::util::bytes *proto,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (add_bos || add_eos || reverse || emit_unk_piece) {
+    throw sentencepiece::util::Status(
+        sentencepiece::util::StatusCode::kUnimplemented,
+        "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API");
+  }
+}
+
+inline void RewriteIds(const sentencepiece::SentencePieceProcessor &sp,
+                       sentencepiece::ImmutableSentencePieceText *proto,
+                       bool add_bos, bool add_eos, bool reverse, bool emit_unk_piece) {
+  if (add_bos || add_eos || reverse || emit_unk_piece) {
+    throw sentencepiece::util::Status(
+        sentencepiece::util::StatusCode::kUnimplemented,
+        "add_bos, add_eos, reverse, and emit_unk_piece is not supported in proto API");
+  }
+}
+
+inline void CheckIds(const std::vector &ids, int num_pieces) {
+  for (int id : ids) {
+    if (id < 0 || id >= num_pieces) {
+      throw sentencepiece::util::Status(
+          sentencepiece::util::StatusCode::kOutOfRange,
+          "piece id is out of range.");
+    }
+  }
+}
+
+inline void CheckIds(const std::vector &ids, int num_pieces) {}
+
+inline void CheckIdsBatch(const std::vector> &ids, int num_pieces) {
+  for (const auto &v : ids) CheckIds(v, num_pieces);
+}
+
+template 
+inline void ConvertToUnicodeSpans(T *proto) {}
+
+template <>
+inline void ConvertToUnicodeSpans(sentencepiece::ImmutableSentencePieceText *proto) {
+  proto->ConvertToUnicodeSpans();
+}
+
+template <>
+inline void ConvertToUnicodeSpans(sentencepiece::ImmutableNBestSentencePieceText *proto) {
+  proto->ConvertToUnicodeSpans();
+}
+
+class ThreadPool {
+ public:
+  explicit ThreadPool(size_t request_size) :
+    request_size_(request_size) {}
+
+  virtual ~ThreadPool() {
+    for (auto &task : tasks_) {
+      task.join();
+    }
+  }
+
+  void Schedule(std::function closure) {
+    static constexpr size_t kMinThreadSize = 2;
+    if (request_size_ < kMinThreadSize) {
+      closure();
+    } else {
+      tasks_.emplace_back(closure);
+    }
+  }
+
+ private:
+  size_t request_size_ = 0;
+  std::vector tasks_;
+};
+
+template 
+inline void InitNumThreads(const std::vector &ins, int *num_threads) {
+  if (*num_threads < 0) {
+    *num_threads = std::thread::hardware_concurrency();
+  }
+  *num_threads = std::max(1,
+                               std::min({*num_threads,
+                                     static_cast(ins.size()), 256}));
+}
+
+#define DEFINE_ENCODE_BATCH_FUNC_IMPL(FuncName, InType, OutType)        \
+  std::vector outs(ins.size());                                \
+  InitNumThreads(ins, &num_threads);                                    \
+  {                                                                     \
+    ThreadPool pool(ins.size());                                        \
+    std::atomic index = 0;                                      \
+    for (int n = 0;  n < num_threads; ++n) {                            \
+      pool.Schedule([&]() {                                             \
+          size_t i = 0;                                                 \
+          while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \
+            auto out = enable_sampling ?                                \
+                       self->Sample##FuncName(ins[i],                   \
+                                              nbest_size, alpha) :      \
+                       self->FuncName(ins[i]);                          \
+            RewriteIds(*self, &out, add_bos, add_eos, reverse,          \
+                       emit_unk_piece);                                 \
+            ConvertToUnicodeSpans(&out);                                \
+            outs[i] = std::move(out);                                   \
+          }                                                             \
+        });                                                             \
+    }                                                                   \
+  }                                                                     \
+  return outs;
+
+#define DEFINE_DECODE_BATCH_FUNC_IMPL(FuncName, InType, OutType)        \
+  std::vector outs(ins.size());                                \
+  InitNumThreads(ins, &num_threads);                                    \
+  {                                                                     \
+    std::atomic index = 0;                                      \
+    ThreadPool pool(ins.size());                                        \
+    for (int n = 0;  n < num_threads; ++n) {                            \
+      pool.Schedule([&]() {                                             \
+          size_t i = 0;                                                 \
+          while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) { \
+            auto out = self->FuncName(ins[i]);                          \
+            ConvertToUnicodeSpans(&out);                                \
+            outs[i] = std::move(out);                                   \
+          }                                                             \
+        });                                                             \
+    }                                                                   \
+  }                                                                     \
+  return outs;
+
+}  // namespace
+
+
+SWIGINTERNINLINE PyObject*
+  SWIG_From_unsigned_SS_int  (unsigned int value)
+{
+  return PyInt_FromSize_t((size_t) value);
+}
+
+SWIGINTERN sentencepiece::util::bytes const &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes(sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *self){
+    return self->surface();
+  }
+SWIGINTERN sentencepiece::util::bytes const &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes(sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *self){
+    return self->piece();
+  }
+
+  #define SWIG_From_long   PyInt_FromLong 
+
+
+SWIGINTERNINLINE PyObject* 
+SWIG_From_unsigned_SS_long  (unsigned long value)
+{
+  return (value > LONG_MAX) ?
+    PyLong_FromUnsignedLong(value) : PyInt_FromLong(static_cast< long >(value));
+}
+
+
+#include 
+#if !defined(SWIG_NO_LLONG_MAX)
+# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)
+#   define LLONG_MAX __LONG_LONG_MAX__
+#   define LLONG_MIN (-LLONG_MAX - 1LL)
+#   define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
+# endif
+#endif
+
+
+#if defined(LLONG_MAX) && !defined(SWIG_LONG_LONG_AVAILABLE)
+#  define SWIG_LONG_LONG_AVAILABLE
+#endif
+
+
+#ifdef SWIG_LONG_LONG_AVAILABLE
+SWIGINTERNINLINE PyObject* 
+SWIG_From_unsigned_SS_long_SS_long  (unsigned long long value)
+{
+  return (value > LONG_MAX) ?
+    PyLong_FromUnsignedLongLong(value) : PyInt_FromLong(static_cast< long >(value));
+}
+#endif
+
+
+SWIGINTERNINLINE PyObject *
+SWIG_From_size_t  (size_t value)
+{    
+#ifdef SWIG_LONG_LONG_AVAILABLE
+  if (sizeof(size_t) <= sizeof(unsigned long)) {
+#endif
+    return SWIG_From_unsigned_SS_long  (static_cast< unsigned long >(value));
+#ifdef SWIG_LONG_LONG_AVAILABLE
+  } else {
+    /* assume sizeof(size_t) <= sizeof(unsigned long long) */
+    return SWIG_From_unsigned_SS_long_SS_long  (static_cast< unsigned long long >(value));
+  }
+#endif
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_double (PyObject *obj, double *val)
+{
+  int res = SWIG_TypeError;
+  if (PyFloat_Check(obj)) {
+    if (val) *val = PyFloat_AsDouble(obj);
+    return SWIG_OK;
+#if PY_VERSION_HEX < 0x03000000
+  } else if (PyInt_Check(obj)) {
+    if (val) *val = (double) PyInt_AsLong(obj);
+    return SWIG_OK;
+#endif
+  } else if (PyLong_Check(obj)) {
+    double v = PyLong_AsDouble(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    double d = PyFloat_AsDouble(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = d;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      long v = PyLong_AsLong(obj);
+      if (!PyErr_Occurred()) {
+	if (val) *val = v;
+	return SWIG_AddCast(SWIG_AddCast(SWIG_OK));
+      } else {
+	PyErr_Clear();
+      }
+    }
+  }
+#endif
+  return res;
+}
+
+
+#include 
+
+
+#include 
+
+
+SWIGINTERNINLINE int
+SWIG_CanCastAsInteger(double *d, double min, double max) {
+  double x = *d;
+  if ((min <= x && x <= max)) {
+   double fx, cx, rd;
+   errno = 0;
+   fx = floor(x);
+   cx = ceil(x);
+   rd =  ((x - fx) < 0.5) ? fx : cx; /* simple rint */
+   if ((errno == EDOM) || (errno == ERANGE)) {
+     errno = 0;
+   } else {
+     double summ, reps, diff;
+     if (rd < x) {
+       diff = x - rd;
+     } else if (rd > x) {
+       diff = rd - x;
+     } else {
+       return 1;
+     }
+     summ = rd + x;
+     reps = diff/summ;
+     if (reps < 8*DBL_EPSILON) {
+       *d = rd;
+       return 1;
+     }
+   }
+  }
+  return 0;
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_long (PyObject *obj, long* val)
+{
+#if PY_VERSION_HEX < 0x03000000
+  if (PyInt_Check(obj)) {
+    if (val) *val = PyInt_AsLong(obj);
+    return SWIG_OK;
+  } else
+#endif
+  if (PyLong_Check(obj)) {
+    long v = PyLong_AsLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+      return SWIG_OverflowError;
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    long v = PyInt_AsLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));
+      // Largest double not larger than LONG_MAX (not portably calculated easily)
+      // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long)
+      // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0))
+      const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX;
+      // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) {
+	if (val) *val = (long)(d);
+	return res;
+      }
+    }
+  }
+#endif
+  return SWIG_TypeError;
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_int (PyObject * obj, int *val)
+{
+  long v;
+  int res = SWIG_AsVal_long (obj, &v);
+  if (SWIG_IsOK(res)) {
+    if ((v < INT_MIN || v > INT_MAX)) {
+      return SWIG_OverflowError;
+    } else {
+      if (val) *val = static_cast< int >(v);
+    }
+  }  
+  return res;
+}
+
+
+  #define SWIG_From_double   PyFloat_FromDouble 
+
+
+SWIGINTERNINLINE PyObject *
+SWIG_From_float  (float value)
+{    
+  return SWIG_From_double  (value);
+}
+
+SWIGINTERN sentencepiece::util::bytes const &sentencepiece_ImmutableSentencePieceText__text_as_bytes(sentencepiece::ImmutableSentencePieceText const *self){
+    return self->text();
+  }
+
+SWIGINTERN swig_type_info*
+SWIG_pchar_descriptor(void)
+{
+  static swig_type_info* info = 0;
+  if (!info) {
+    info = SWIG_TypeQuery("_p_char");
+  }
+  return info;
+}
+
+
+/* Return string from Python obj. NOTE: obj must remain in scope in order
+   to use the returned cptr (but only when alloc is set to SWIG_OLDOBJ) */
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc)
+{
+#if PY_VERSION_HEX>=0x03000000
+#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
+  if (PyBytes_Check(obj))
+#else
+  if (PyUnicode_Check(obj))
+#endif
+#else  
+  if (PyString_Check(obj))
+#endif
+  {
+    char *cstr; Py_ssize_t len;
+    PyObject *bytes = NULL;
+    int ret = SWIG_OK;
+    if (alloc)
+      *alloc = SWIG_OLDOBJ;
+#if PY_VERSION_HEX>=0x03000000 && defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
+    if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1)
+      return SWIG_TypeError;
+#else
+    cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes);
+    if (!cstr)
+      return SWIG_TypeError;
+    /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */
+    if (bytes && cptr) {
+      if (alloc) {
+        cstr = reinterpret_cast< char* >(memcpy(new char[len + 1], cstr, sizeof(char)*(len + 1)));
+        *alloc = SWIG_NEWOBJ;
+      } else {
+        /* alloc must be set in order to clean up allocated memory */
+        return SWIG_RuntimeError;
+      }
+    }
+#endif
+    if (cptr) *cptr = cstr;
+    if (psize) *psize = len + 1;
+    SWIG_Py_XDECREF(bytes);
+    return ret;
+  } else {
+#if defined(SWIG_PYTHON_2_UNICODE)
+#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
+#error "Cannot use both SWIG_PYTHON_2_UNICODE and SWIG_PYTHON_STRICT_BYTE_CHAR at once"
+#endif
+#if PY_VERSION_HEX<0x03000000
+    if (PyUnicode_Check(obj)) {
+      char *cstr; Py_ssize_t len;
+      if (!alloc && cptr) {
+        return SWIG_RuntimeError;
+      }
+      obj = PyUnicode_AsUTF8String(obj);
+      if (!obj)
+        return SWIG_TypeError;
+      if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) {
+        if (cptr) {
+          if (alloc) *alloc = SWIG_NEWOBJ;
+          *cptr = reinterpret_cast< char* >(memcpy(new char[len + 1], cstr, sizeof(char)*(len + 1)));
+        }
+        if (psize) *psize = len + 1;
+
+        SWIG_Py_XDECREF(obj);
+        return SWIG_OK;
+      } else {
+        SWIG_Py_XDECREF(obj);
+      }
+    }
+#endif
+#endif
+
+    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+    if (pchar_descriptor) {
+      void* vptr = 0;
+      if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {
+	if (cptr) *cptr = (char *) vptr;
+	if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0;
+	if (alloc) *alloc = SWIG_OLDOBJ;
+	return SWIG_OK;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+
+
+
+
+
+/* Getting isfinite working pre C99 across multiple platforms is non-trivial. Users can provide SWIG_isfinite on older platforms. */
+#ifndef SWIG_isfinite
+/* isfinite() is a macro for C99 */
+# if defined(isfinite)
+#  define SWIG_isfinite(X) (isfinite(X))
+# elif defined(__cplusplus) && __cplusplus >= 201103L
+/* Use a template so that this works whether isfinite() is std::isfinite() or
+ * in the global namespace.  The reality seems to vary between compiler
+ * versions.
+ *
+ * Make sure namespace std exists to avoid compiler warnings.
+ *
+ * extern "C++" is required as this fragment can end up inside an extern "C" { } block
+ */
+namespace std { }
+extern "C++" template
+inline int SWIG_isfinite_func(T x) {
+  using namespace std;
+  return isfinite(x);
+}
+#  define SWIG_isfinite(X) (SWIG_isfinite_func(X))
+# elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
+#  define SWIG_isfinite(X) (__builtin_isfinite(X))
+# elif defined(_MSC_VER)
+#  define SWIG_isfinite(X) (_finite(X))
+# elif defined(__sun) && defined(__SVR4)
+#  include 
+#  define SWIG_isfinite(X) (finite(X))
+# endif
+#endif
+
+
+/* Accept infinite as a valid float value unless we are unable to check if a value is finite */
+#ifdef SWIG_isfinite
+# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX) && SWIG_isfinite(X))
+#else
+# define SWIG_Float_Overflow_Check(X) ((X < -FLT_MAX || X > FLT_MAX))
+#endif
+
+
+SWIGINTERN int
+SWIG_AsVal_float (PyObject * obj, float *val)
+{
+  double v;
+  int res = SWIG_AsVal_double (obj, &v);
+  if (SWIG_IsOK(res)) {
+    if (SWIG_Float_Overflow_Check(v)) {
+      return SWIG_OverflowError;
+    } else {
+      if (val) *val = static_cast< float >(v);
+    }
+  }  
+  return res;
+}
+
+
+SWIGINTERNINLINE PyObject*
+  SWIG_From_int  (int value)
+{
+  return PyInt_FromLong((long) value);
+}
+
+
+SWIGINTERNINLINE PyObject*
+  SWIG_From_bool  (bool value)
+{
+  return PyBool_FromLong(value ? 1 : 0);
+}
+
+SWIGINTERN sentencepiece::util::Status sentencepiece_SentencePieceProcessor_LoadFromFile(sentencepiece::SentencePieceProcessor *self,absl::string_view arg){
+    return self->Load(arg);
+  }
+
+SWIGINTERN int
+SWIG_AsVal_bool (PyObject *obj, bool *val)
+{
+  int r;
+  if (!PyBool_Check(obj))
+    return SWIG_ERROR;
+  r = PyObject_IsTrue(obj);
+  if (r == -1)
+    return SWIG_ERROR;
+  if (val) *val = r ? true : false;
+  return SWIG_OK;
+}
+
+SWIGINTERN std::vector< int > sentencepiece_SentencePieceProcessor__EncodeAsIds(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto ids = enable_sampling ?
+               self->SampleEncodeAsIds(text, nbest_size, alpha) :
+               self->EncodeAsIds(text);
+    RewriteIds(*self, &ids, add_bos, add_eos, reverse, emit_unk_piece);
+    return ids;
+  }
+SWIGINTERN std::vector< std::string > sentencepiece_SentencePieceProcessor__EncodeAsPieces(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto pieces = enable_sampling ?
+                  self->SampleEncodeAsPieces(text, nbest_size, alpha) :
+                  self->EncodeAsPieces(text);
+    RewriteIds(*self, &pieces, add_bos, add_eos, reverse, emit_unk_piece);
+    return pieces;
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__EncodeAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto proto = enable_sampling ?
+                 self->SampleEncodeAsSerializedProto(text, nbest_size, alpha) :
+                 self->EncodeAsSerializedProto(text);
+    RewriteIds(*self, &proto, add_bos, add_eos, reverse, emit_unk_piece);
+    return proto;
+  }
+SWIGINTERN sentencepiece::ImmutableSentencePieceText sentencepiece_SentencePieceProcessor__EncodeAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto proto = enable_sampling ?
+                 self->SampleEncodeAsImmutableProto(text, nbest_size, alpha) :
+                 self->EncodeAsImmutableProto(text);
+    proto.ConvertToUnicodeSpans();
+    RewriteIds(*self, &proto, add_bos, add_eos, reverse, emit_unk_piece);
+    return proto;
+  }
+SWIGINTERN std::vector< std::vector< int > > sentencepiece_SentencePieceProcessor__EncodeAsIdsBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsIds,
+                                  absl::string_view, std::vector);
+  }
+SWIGINTERN std::vector< std::vector< std::string > > sentencepiece_SentencePieceProcessor__EncodeAsPiecesBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsPieces,
+                                  absl::string_view, std::vector);
+  }
+SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__EncodeAsSerializedProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsSerializedProto,
+                                  absl::string_view,
+                                  sentencepiece::util::bytes);
+  }
+SWIGINTERN std::vector< sentencepiece::ImmutableSentencePieceText > sentencepiece_SentencePieceProcessor__EncodeAsImmutableProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &ins,int num_threads,bool enable_sampling,int nbest_size,float alpha,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    DEFINE_ENCODE_BATCH_FUNC_IMPL(EncodeAsImmutableProto,
+                                  absl::string_view,
+                                  sentencepiece::ImmutableSentencePieceText);
+  }
+SWIGINTERN std::string sentencepiece_SentencePieceProcessor__DecodeIds(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){
+    CheckIds(ids, self->GetPieceSize());
+    return self->DecodeIds(ids);
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__DecodeIdsAsBytes(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){
+    CheckIds(ids, self->GetPieceSize());
+    return self->DecodeIds(ids);
+  }
+SWIGINTERN std::string sentencepiece_SentencePieceProcessor__DecodePieces(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &pieces){
+    return self->DecodePieces(pieces);
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){
+    CheckIds(ids, self->GetPieceSize());
+    return self->DecodeIdsAsSerializedProto(ids);
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &pieces){
+    CheckIds(pieces, self->GetPieceSize());
+    return self->DecodePiecesAsSerializedProto(pieces);
+  }
+SWIGINTERN sentencepiece::ImmutableSentencePieceText sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,std::vector< int > const &ids){
+    CheckIds(ids, self->GetPieceSize());
+    auto proto = self->DecodeIdsAsImmutableProto(ids);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+SWIGINTERN sentencepiece::ImmutableSentencePieceText sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,std::vector< absl::string_view > const &pieces){
+    CheckIds(pieces, self->GetPieceSize());
+    auto proto= self->DecodePiecesAsImmutableProto(pieces);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+SWIGINTERN std::vector< std::string > sentencepiece_SentencePieceProcessor__DecodeIdsBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){
+    CheckIdsBatch(ins, self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string);
+  }
+SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__DecodeIdsAsBytesBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){
+    CheckIdsBatch(ins, self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIds, int, std::string);
+  }
+SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){
+    CheckIdsBatch(ins, self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsSerializedProto, int,
+                                  sentencepiece::util::bytes);
+  }
+SWIGINTERN std::vector< sentencepiece::ImmutableSentencePieceText > sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< int > > const &ins,int num_threads){
+    CheckIdsBatch(ins, self->GetPieceSize());
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodeIdsAsImmutableProto, int,
+                                  sentencepiece::ImmutableSentencePieceText);
+  }
+SWIGINTERN std::vector< std::string > sentencepiece_SentencePieceProcessor__DecodePiecesBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< absl::string_view > > const &ins,int num_threads){
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePieces, std::string, std::string);
+  }
+SWIGINTERN BytesArray sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< absl::string_view > > const &ins,int num_threads){
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsSerializedProto, std::string,
+                                  sentencepiece::util::bytes);
+  }
+SWIGINTERN std::vector< sentencepiece::ImmutableSentencePieceText > sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch(sentencepiece::SentencePieceProcessor const *self,std::vector< std::vector< absl::string_view > > const &ins,int num_threads){
+    DEFINE_DECODE_BATCH_FUNC_IMPL(DecodePiecesAsImmutableProto, std::string,
+                                  sentencepiece::ImmutableSentencePieceText);
+  }
+SWIGINTERN std::vector< std::vector< int > > sentencepiece_SentencePieceProcessor__NBestEncodeAsIds(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto idss = self->NBestEncodeAsIds(text, nbest_size);
+    for (auto &ids : idss) {
+      RewriteIds(*self, &ids, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return idss;
+  }
+SWIGINTERN std::vector< std::vector< std::string > > sentencepiece_SentencePieceProcessor__NBestEncodeAsPieces(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto piecess = self->NBestEncodeAsPieces(text, nbest_size);
+    for (auto &pieces : piecess) {
+      RewriteIds(*self, &pieces, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return piecess;
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__NBestEncodeAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    RewriteIds(*self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    return self->NBestEncodeAsSerializedProto(text, nbest_size);
+  }
+SWIGINTERN sentencepiece::ImmutableNBestSentencePieceText sentencepiece_SentencePieceProcessor__NBestEncodeAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int nbest_size,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    RewriteIds(*self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    auto proto = self->NBestEncodeAsImmutableProto(text, nbest_size);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+SWIGINTERN std::vector< std::pair< std::vector< int >,float > > sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsIds(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto idss = self->SampleEncodeAndScoreAsIds(text, num_samples,
+                                                 alpha, wor, include_best);
+    for (auto &ids : idss) {
+      RewriteIds(*self, &ids.first, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return idss;
+  }
+SWIGINTERN std::vector< std::pair< std::vector< std::string >,float > > sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsPieces(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    auto piecess = self->SampleEncodeAndScoreAsPieces(text, num_samples,
+                                                       alpha, wor, include_best);
+    for (auto &pieces : piecess) {
+      RewriteIds(*self, &pieces.first, add_bos, add_eos, reverse, emit_unk_piece);
+    }
+    return piecess;
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    RewriteIds(*self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    return self->SampleEncodeAndScoreAsSerializedProto(text, num_samples,
+                                                        alpha, wor, include_best);
+  }
+SWIGINTERN sentencepiece::ImmutableNBestSentencePieceText sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto(sentencepiece::SentencePieceProcessor const *self,absl::string_view text,int num_samples,float alpha,bool wor,bool include_best,bool add_bos,bool add_eos,bool reverse,bool emit_unk_piece){
+    RewriteIds(*self, static_cast(nullptr),
+               add_bos, add_eos, reverse, emit_unk_piece);
+    auto proto = self->SampleEncodeAndScoreAsImmutableProto(text, num_samples,
+                                                       alpha, wor, include_best);
+    proto.ConvertToUnicodeSpans();
+    return proto;
+  }
+SWIGINTERN std::string sentencepiece_SentencePieceProcessor__Normalize(sentencepiece::SentencePieceProcessor *self,absl::string_view text){
+    return self->Normalize(text);
+  }
+SWIGINTERN std::pair< std::string,std::vector< size_t > > sentencepiece_SentencePieceProcessor__NormalizeWithOffsets(sentencepiece::SentencePieceProcessor *self,absl::string_view text){
+    std::pair> result;
+    self->Normalize(text, &result.first, &result.second).IgnoreError();
+    return result;
+  }
+SWIGINTERN float sentencepiece_SentencePieceProcessor__CalculateEntropy(sentencepiece::SentencePieceProcessor *self,absl::string_view text,float alpha){
+    return self->CalculateEntropy(text, alpha);
+  }
+SWIGINTERN std::vector< float > sentencepiece_SentencePieceProcessor__CalculateEntropyBatch(sentencepiece::SentencePieceProcessor *self,std::vector< absl::string_view > const &ins,float alpha,int num_threads){
+    std::vector outs(ins.size());
+    InitNumThreads(ins, &num_threads);
+    {
+      ThreadPool pool(ins.size());
+      std::atomic index = 0;
+      for (int n = 0;  n < num_threads; ++n) {
+        pool.Schedule([&]() {
+           size_t i = 0;
+           while ((i = std::atomic_fetch_add(&index, 1)) < outs.size()) {
+             outs[i] = self->CalculateEntropy(ins[i], alpha);
+           }
+         });
+      }
+    }
+    return outs;
+  }
+SWIGINTERN sentencepiece::util::Status sentencepiece_SentencePieceProcessor__OverrideNormalizerSpec(sentencepiece::SentencePieceProcessor *self,std::unordered_map< std::string,std::string > const &args){
+    sentencepiece::util::Status status;
+    for (const auto &[key, value] : args) {
+      status = sentencepiece::SentencePieceTrainer::SetProtoField(
+          key, value,
+          self->mutable_normalizer_spec());
+      if (!status.ok()) return status;
+    }
+    return status;
+  }
+
+SWIGINTERN int
+SWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) 
+{
+#if PY_VERSION_HEX < 0x03000000
+  if (PyInt_Check(obj)) {
+    long v = PyInt_AsLong(obj);
+    if (v >= 0) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }
+  } else
+#endif
+  if (PyLong_Check(obj)) {
+    unsigned long v = PyLong_AsUnsignedLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+      return SWIG_OverflowError;
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    unsigned long v = PyLong_AsUnsignedLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));
+      // Largest double not larger than ULONG_MAX (not portably calculated easily)
+      // Note that double(ULONG_MAX) is stored in a double rounded up by one (for 64-bit unsigned long)
+      // 0xfffffffffffff800ULL == (uint64_t)std::nextafter(double(__uint128_t(ULONG_MAX)+1), double(0))
+      const double ulong_max = sizeof(unsigned long) == 8 ? 0xfffffffffffff800ULL : ULONG_MAX;
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ulong_max)) {
+	if (val) *val = (unsigned long)(d);
+	return res;
+      }
+    }
+  }
+#endif
+  return SWIG_TypeError;
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_unsigned_SS_int (PyObject * obj, unsigned int *val)
+{
+  unsigned long v;
+  int res = SWIG_AsVal_unsigned_SS_long (obj, &v);
+  if (SWIG_IsOK(res)) {
+    if ((v > UINT_MAX)) {
+      return SWIG_OverflowError;
+    } else {
+      if (val) *val = static_cast< unsigned int >(v);
+    }
+  }  
+  return res;
+}
+
+SWIGINTERN void sentencepiece_SentencePieceTrainer__TrainFromString(absl::string_view arg){
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(arg);
+    if (!_status.ok()) throw _status;
+    return;
+  }
+SWIGINTERN void sentencepiece_SentencePieceTrainer__TrainFromMap(std::unordered_map< std::string,std::string > const &args){
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args);
+    if (!_status.ok()) throw _status;
+    return;
+  }
+SWIGINTERN void sentencepiece_SentencePieceTrainer__TrainFromMap2(std::unordered_map< std::string,std::string > const &args,sentencepiece::SentenceIterator *iter){
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter);
+    if (!_status.ok()) throw _status;
+    return;
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceTrainer__TrainFromMap3(std::unordered_map< std::string,std::string > const &args){
+    sentencepiece::util::bytes model_proto;
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args, nullptr, &model_proto);
+    if (!_status.ok()) throw _status;
+    return model_proto;
+  }
+SWIGINTERN sentencepiece::util::bytes sentencepiece_SentencePieceTrainer__TrainFromMap4(std::unordered_map< std::string,std::string > const &args,sentencepiece::SentenceIterator *iter){
+    sentencepiece::util::bytes model_proto;
+    const auto _status = sentencepiece::SentencePieceTrainer::Train(args, iter, &model_proto);
+    if (!_status.ok()) throw _status;
+    return model_proto;
+  }
+SWIGINTERN sentencepiece::util::Status sentencepiece_SentencePieceNormalizer_LoadFromFile(sentencepiece::SentencePieceNormalizer *self,absl::string_view arg){
+    return self->Load(arg);
+  }
+SWIGINTERN std::string sentencepiece_SentencePieceNormalizer__Normalize(sentencepiece::SentencePieceNormalizer *self,absl::string_view text){
+    std::string result;
+    const auto _status = self->Normalize(text, &result);
+    if (!_status.ok()) throw _status;
+    return result;
+  }
+SWIGINTERN std::pair< std::string,std::vector< size_t > > sentencepiece_SentencePieceNormalizer__NormalizeWithOffsets(sentencepiece::SentencePieceNormalizer *self,absl::string_view text){
+    std::pair> result;
+    const auto _status = self->Normalize(text, &result.first, &result.second);
+    if (!_status.ok()) throw _status;
+    return result;
+  }
+SWIGINTERN void sentencepiece_SentencePieceNormalizer__SetProtoField(sentencepiece::SentencePieceNormalizer *self,absl::string_view name,bool value){
+    sentencepiece::SentencePieceTrainer::SetProtoField(
+        name,
+        value ? "1" : "0",
+        self->mutable_normalizer_spec()).IgnoreError();
+  }
+#ifdef __cplusplus
+extern "C" {
+#endif
+SWIGINTERN PyObject *_wrap_new_ImmutableSentencePieceText_ImmutableSentencePiece(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *result = 0 ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "new_ImmutableSentencePieceText_ImmutableSentencePiece", 0, 0, 0)) SWIG_fail;
+  {
+    try {
+      result = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *)new sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_ImmutableSentencePieceText_ImmutableSentencePiece(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ImmutableSentencePieceText_ImmutableSentencePiece" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      delete arg1;
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  std::string *result = 0 ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__piece" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = (std::string *) &((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->piece();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(*result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  std::string *result = 0 ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__surface" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = (std::string *) &((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->surface();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(*result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__id(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  uint32_t result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__id" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->id();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__begin(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  uint32_t result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__begin" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->begin();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__end(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  uint32_t result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__end" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1)->end();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes *result = 0 ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = (sentencepiece::util::bytes *) &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(*result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *arg1 = (sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes *result = 0 ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece * >(argp1);
+  {
+    try {
+      result = (sentencepiece::util::bytes *) &sentencepiece_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes((sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece const *)arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(*result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *ImmutableSentencePieceText_ImmutableSentencePiece_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj = NULL;
+  if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *ImmutableSentencePieceText_ImmutableSentencePiece_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  return SWIG_Python_InitShadowInstance(args);
+}
+
+SWIGINTERN PyObject *_wrap_new_ImmutableSentencePieceText(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *result = 0 ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "new_ImmutableSentencePieceText", 0, 0, 0)) SWIG_fail;
+  {
+    try {
+      result = (sentencepiece::ImmutableSentencePieceText *)new sentencepiece::ImmutableSentencePieceText();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_ImmutableSentencePieceText(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ImmutableSentencePieceText" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  {
+    try {
+      delete arg1;
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__pieces_size(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  size_t result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__pieces_size" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableSentencePieceText const *)arg1)->pieces_size();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_size_t(static_cast< size_t >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__pieces(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "ImmutableSentencePieceText__pieces", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__pieces" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ImmutableSentencePieceText__pieces" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = ((sentencepiece::ImmutableSentencePieceText const *)arg1)->pieces(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__text(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  std::string *result = 0 ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__text" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  {
+    try {
+      result = (std::string *) &((sentencepiece::ImmutableSentencePieceText const *)arg1)->text();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(*result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__score(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  float result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__score" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  {
+    try {
+      result = (float)((sentencepiece::ImmutableSentencePieceText const *)arg1)->score();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_float(static_cast< float >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText_SerializeAsString(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText_SerializeAsString" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableSentencePieceText const *)arg1)->SerializeAsString();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableSentencePieceText__text_as_bytes(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableSentencePieceText *arg1 = (sentencepiece::ImmutableSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes *result = 0 ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableSentencePieceText__text_as_bytes" "', argument " "1"" of type '" "sentencepiece::ImmutableSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableSentencePieceText * >(argp1);
+  {
+    try {
+      result = (sentencepiece::util::bytes *) &sentencepiece_ImmutableSentencePieceText__text_as_bytes((sentencepiece::ImmutableSentencePieceText const *)arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(*result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *ImmutableSentencePieceText_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj = NULL;
+  if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *ImmutableSentencePieceText_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  return SWIG_Python_InitShadowInstance(args);
+}
+
+SWIGINTERN PyObject *_wrap_new_ImmutableNBestSentencePieceText(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableNBestSentencePieceText *result = 0 ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "new_ImmutableNBestSentencePieceText", 0, 0, 0)) SWIG_fail;
+  {
+    try {
+      result = (sentencepiece::ImmutableNBestSentencePieceText *)new sentencepiece::ImmutableNBestSentencePieceText();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_ImmutableNBestSentencePieceText(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ImmutableNBestSentencePieceText" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1);
+  {
+    try {
+      delete arg1;
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableNBestSentencePieceText__nbests_size(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  size_t result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableNBestSentencePieceText__nbests_size" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableNBestSentencePieceText const *)arg1)->nbests_size();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_size_t(static_cast< size_t >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableNBestSentencePieceText__nbests(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::ImmutableSentencePieceText result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "ImmutableNBestSentencePieceText__nbests", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableNBestSentencePieceText__nbests" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "ImmutableNBestSentencePieceText__nbests" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = ((sentencepiece::ImmutableNBestSentencePieceText const *)arg1)->nbests(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_ImmutableNBestSentencePieceText_SerializeAsString(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::ImmutableNBestSentencePieceText *arg1 = (sentencepiece::ImmutableNBestSentencePieceText *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImmutableNBestSentencePieceText_SerializeAsString" "', argument " "1"" of type '" "sentencepiece::ImmutableNBestSentencePieceText const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::ImmutableNBestSentencePieceText * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::ImmutableNBestSentencePieceText const *)arg1)->SerializeAsString();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *ImmutableNBestSentencePieceText_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj = NULL;
+  if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *ImmutableNBestSentencePieceText_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  return SWIG_Python_InitShadowInstance(args);
+}
+
+SWIGINTERN PyObject *_wrap_new_SentencePieceProcessor(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *result = 0 ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "new_SentencePieceProcessor", 0, 0, 0)) SWIG_fail;
+  {
+    try {
+      result = (sentencepiece::SentencePieceProcessor *)new sentencepiece::SentencePieceProcessor();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__SentencePieceProcessor, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_SentencePieceProcessor(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_SentencePieceProcessor" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      delete arg1;
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_LoadFromSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_LoadFromSerializedProto", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_LoadFromSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (arg1)->LoadFromSerializedProto(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_SetEncodeExtraOptions(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_SetEncodeExtraOptions", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_SetEncodeExtraOptions" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (arg1)->SetEncodeExtraOptions(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_SetDecodeExtraOptions(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_SetDecodeExtraOptions", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_SetDecodeExtraOptions" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (arg1)->SetDecodeExtraOptions(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_SetVocabulary(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_SetVocabulary", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_SetVocabulary" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = (arg1)->SetVocabulary((std::vector< absl::string_view > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_ResetVocabulary(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_ResetVocabulary" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = (arg1)->ResetVocabulary();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_LoadVocabulary(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_LoadVocabulary", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_LoadVocabulary" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor_LoadVocabulary" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = (arg1)->LoadVocabulary(SWIG_STD_MOVE(arg2),arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_CalculateEntropy__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  float arg3 ;
+  float *arg4 = (float *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  float val3 ;
+  int ecode3 = 0 ;
+  void *argp4 = 0 ;
+  int res4 = 0 ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if ((nobjs < 4) || (nobjs > 4)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "3"" of type '" "float""'");
+  } 
+  arg3 = static_cast< float >(val3);
+  res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_float, 0 |  0 );
+  if (!SWIG_IsOK(res4)) {
+    SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "4"" of type '" "float *""'"); 
+  }
+  arg4 = reinterpret_cast< float * >(argp4);
+  {
+    try {
+      result = ((sentencepiece::SentencePieceProcessor const *)arg1)->CalculateEntropy(SWIG_STD_MOVE(arg2),arg3,arg4);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_CalculateEntropy__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  float arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  float val3 ;
+  int ecode3 = 0 ;
+  float result;
+  
+  (void)self;
+  if ((nobjs < 3) || (nobjs > 3)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor_CalculateEntropy" "', argument " "3"" of type '" "float""'");
+  } 
+  arg3 = static_cast< float >(val3);
+  {
+    try {
+      result = (float)((sentencepiece::SentencePieceProcessor const *)arg1)->CalculateEntropy(SWIG_STD_MOVE(arg2),arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_float(static_cast< float >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_CalculateEntropy(PyObject *self, PyObject *args) {
+  Py_ssize_t argc;
+  PyObject *argv[5] = {
+    0
+  };
+  
+  if (!(argc = SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_CalculateEntropy", 0, 4, argv))) SWIG_fail;
+  --argc;
+  if (argc == 3) {
+    int _v = 0;
+    void *vptr = 0;
+    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0);
+    _v = SWIG_CheckState(res);
+    if (_v) {
+      int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0);
+      _v = SWIG_CheckState(res);
+      if (_v) {
+        {
+          int res = SWIG_AsVal_float(argv[2], NULL);
+          _v = SWIG_CheckState(res);
+        }
+        if (_v) {
+          return _wrap_SentencePieceProcessor_CalculateEntropy__SWIG_1(self, argc, argv);
+        }
+      }
+    }
+  }
+  if (argc == 4) {
+    int _v = 0;
+    void *vptr = 0;
+    int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0);
+    _v = SWIG_CheckState(res);
+    if (_v) {
+      int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0);
+      _v = SWIG_CheckState(res);
+      if (_v) {
+        {
+          int res = SWIG_AsVal_float(argv[2], NULL);
+          _v = SWIG_CheckState(res);
+        }
+        if (_v) {
+          void *vptr = 0;
+          int res = SWIG_ConvertPtr(argv[3], &vptr, SWIGTYPE_p_float, 0);
+          _v = SWIG_CheckState(res);
+          if (_v) {
+            return _wrap_SentencePieceProcessor_CalculateEntropy__SWIG_0(self, argc, argv);
+          }
+        }
+      }
+    }
+  }
+  
+fail:
+  SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'SentencePieceProcessor_CalculateEntropy'.\n"
+    "  Possible C/C++ prototypes are:\n"
+    "    sentencepiece::SentencePieceProcessor::CalculateEntropy(absl::string_view,float,float *) const\n"
+    "    sentencepiece::SentencePieceProcessor::CalculateEntropy(absl::string_view,float) const\n");
+  return 0;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_GetPieceSize(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  int result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_GetPieceSize" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->GetPieceSize();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_PieceToId(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  int result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_PieceToId", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_PieceToId" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->PieceToId(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IdToPiece(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::string *result = 0 ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IdToPiece", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IdToPiece" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IdToPiece" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = (std::string *) &((sentencepiece::SentencePieceProcessor const *)arg1)->IdToPiece(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(*result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_GetScore(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  float result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_GetScore", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_GetScore" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_GetScore" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = (float)((sentencepiece::SentencePieceProcessor const *)arg1)->GetScore(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_float(static_cast< float >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsUnknown(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  bool result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsUnknown", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsUnknown" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsUnknown" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsUnknown(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsControl(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  bool result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsControl", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsControl" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsControl" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsControl(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsUnused(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  bool result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsUnused", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsUnused" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsUnused" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsUnused(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_IsByte(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject *swig_obj[2] ;
+  bool result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_IsByte", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_IsByte" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  ecode2 = SWIG_AsVal_int(swig_obj[1], &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SentencePieceProcessor_IsByte" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  {
+    try {
+      result = (bool)((sentencepiece::SentencePieceProcessor const *)arg1)->IsByte(arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_unk_id(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  int result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_unk_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->unk_id();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_bos_id(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  int result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_bos_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->bos_id();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_eos_id(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  int result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_eos_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->eos_id();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_pad_id(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  int result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_pad_id" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = (int)((sentencepiece::SentencePieceProcessor const *)arg1)->pad_id();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_serialized_model_proto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_serialized_model_proto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::SentencePieceProcessor const *)arg1)->serialized_model_proto();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor_LoadFromFile(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor_LoadFromFile", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor_LoadFromFile" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor_LoadFromFile(arg1,SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsIds(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  bool arg3 ;
+  int arg4 ;
+  float arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  bool val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  float val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  PyObject *swig_obj[9] ;
+  std::vector< int > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsIds", 9, 9, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "3"" of type '" "bool""'");
+  } 
+  arg3 = static_cast< bool >(val3);
+  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = static_cast< int >(val4);
+  ecode5 = SWIG_AsVal_float(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "5"" of type '" "float""'");
+  } 
+  arg5 = static_cast< float >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsIds" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsIds((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, PyInt_FromLong(static_cast(result[i])));
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsPieces(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  bool arg3 ;
+  int arg4 ;
+  float arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  bool val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  float val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  PyObject *swig_obj[9] ;
+  std::vector< std::string > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsPieces", 9, 9, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "3"" of type '" "bool""'");
+  } 
+  arg3 = static_cast< bool >(val3);
+  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = static_cast< int >(val4);
+  ecode5 = SWIG_AsVal_float(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "5"" of type '" "float""'");
+  } 
+  arg5 = static_cast< float >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsPieces" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsPieces((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputString(result[i], input_type));
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  bool arg3 ;
+  int arg4 ;
+  float arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  bool val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  float val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  PyObject *swig_obj[9] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsSerializedProto", 9, 9, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "3"" of type '" "bool""'");
+  } 
+  arg3 = static_cast< bool >(val3);
+  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = static_cast< int >(val4);
+  ecode5 = SWIG_AsVal_float(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "5"" of type '" "float""'");
+  } 
+  arg5 = static_cast< float >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsSerializedProto" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsImmutableProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  bool arg3 ;
+  int arg4 ;
+  float arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  bool val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  float val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  PyObject *swig_obj[9] ;
+  sentencepiece::ImmutableSentencePieceText result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsImmutableProto", 9, 9, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "3"" of type '" "bool""'");
+  } 
+  arg3 = static_cast< bool >(val3);
+  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = static_cast< int >(val4);
+  ecode5 = SWIG_AsVal_float(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "5"" of type '" "float""'");
+  } 
+  arg5 = static_cast< float >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsImmutableProto" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsIdsBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  int arg3 ;
+  bool arg4 ;
+  int arg5 ;
+  float arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  int val5 ;
+  int ecode5 = 0 ;
+  float val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  std::vector< std::vector< int > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsIdsBatch", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "5"" of type '" "int""'");
+  } 
+  arg5 = static_cast< int >(val5);
+  ecode6 = SWIG_AsVal_float(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "6"" of type '" "float""'");
+  } 
+  arg6 = static_cast< float >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsIdsBatch" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsIdsBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = PyList_New(result[i].size());
+      for (size_t j = 0; j < result[i].size(); ++j) {
+        PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast(result[i][j])));
+      }
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsPiecesBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  int arg3 ;
+  bool arg4 ;
+  int arg5 ;
+  float arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  int val5 ;
+  int ecode5 = 0 ;
+  float val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  std::vector< std::vector< std::string > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsPiecesBatch", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "5"" of type '" "int""'");
+  } 
+  arg5 = static_cast< int >(val5);
+  ecode6 = SWIG_AsVal_float(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "6"" of type '" "float""'");
+  } 
+  arg6 = static_cast< float >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsPiecesBatch" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsPiecesBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = PyList_New(result[i].size());
+      for (size_t j = 0; j < result[i].size(); ++j) {
+        PyList_SET_ITEM(obj, j, MakePyOutputString(result[i][j], input_type));
+      }
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsSerializedProtoBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  int arg3 ;
+  bool arg4 ;
+  int arg5 ;
+  float arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  int val5 ;
+  int ecode5 = 0 ;
+  float val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  BytesArray result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsSerializedProtoBatch", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "5"" of type '" "int""'");
+  } 
+  arg5 = static_cast< int >(val5);
+  ecode6 = SWIG_AsVal_float(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "6"" of type '" "float""'");
+  } 
+  arg6 = static_cast< float >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsSerializedProtoBatch" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsSerializedProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i]));
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__EncodeAsImmutableProtoBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  int arg3 ;
+  bool arg4 ;
+  int arg5 ;
+  float arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  int val5 ;
+  int ecode5 = 0 ;
+  float val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  SwigValueWrapper< std::vector< sentencepiece::ImmutableSentencePieceText > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__EncodeAsImmutableProtoBatch", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_int(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "5"" of type '" "int""'");
+  } 
+  arg5 = static_cast< int >(val5);
+  ecode6 = SWIG_AsVal_float(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "6"" of type '" "float""'");
+  } 
+  arg6 = static_cast< float >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__EncodeAsImmutableProtoBatch" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__EncodeAsImmutableProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText((&result)->at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0);
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIds(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< int > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::string result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIds", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyInt_Check(o)) {
+          (*out)[i] = static_cast(PyInt_AsLong(o));
+        } else {
+          PyErr_SetString(PyExc_TypeError,"list must contain integers");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIds((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(result, input_type);
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsBytes(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< int > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsBytes", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsBytes" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyInt_Check(o)) {
+          (*out)[i] = static_cast(PyInt_AsLong(o));
+        } else {
+          PyErr_SetString(PyExc_TypeError,"list must contain integers");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsAsBytes((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePieces(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::string result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePieces", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodePieces((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(result, input_type);
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< int > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsSerializedProto", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyInt_Check(o)) {
+          (*out)[i] = static_cast(PyInt_AsLong(o));
+        } else {
+          PyErr_SetString(PyExc_TypeError,"list must contain integers");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsSerializedProto", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsImmutableProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< int > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::ImmutableSentencePieceText result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsImmutableProto", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyInt_Check(o)) {
+          (*out)[i] = static_cast(PyInt_AsLong(o));
+        } else {
+          PyErr_SetString(PyExc_TypeError,"list must contain integers");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< int > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN |  0 );
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsImmutableProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::ImmutableSentencePieceText result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsImmutableProto", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< absl::string_view > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN |  0 );
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< int > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  std::vector< std::string > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            PyObject *o2 = PyList_GetItem(o, j);
+            if (PyInt_Check(o2)) {
+              (*out)[i][j] = static_cast(PyInt_AsLong(o2));
+            } else {
+              PyErr_SetString(PyExc_TypeError, "list must contain strings");
+              SWIG_fail;
+            }
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError, "not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputString(result[i], input_type));
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsBytesBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< int > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  BytesArray result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsBytesBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsBytesBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            PyObject *o2 = PyList_GetItem(o, j);
+            if (PyInt_Check(o2)) {
+              (*out)[i][j] = static_cast(PyInt_AsLong(o2));
+            } else {
+              PyErr_SetString(PyExc_TypeError, "list must contain strings");
+              SWIG_fail;
+            }
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError, "not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsAsBytesBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsAsBytesBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i]));
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< int > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  BytesArray result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            PyObject *o2 = PyList_GetItem(o, j);
+            if (PyInt_Check(o2)) {
+              (*out)[i][j] = static_cast(PyInt_AsLong(o2));
+            } else {
+              PyErr_SetString(PyExc_TypeError, "list must contain strings");
+              SWIG_fail;
+            }
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError, "not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i]));
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< int > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  SwigValueWrapper< std::vector< sentencepiece::ImmutableSentencePieceText > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            PyObject *o2 = PyList_GetItem(o, j);
+            if (PyInt_Check(o2)) {
+              (*out)[i][j] = static_cast(PyInt_AsLong(o2));
+            } else {
+              PyErr_SetString(PyExc_TypeError, "list must contain strings");
+              SWIG_fail;
+            }
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError, "not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< int > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText((&result)->at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0);
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< absl::string_view > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  std::vector< std::string > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            const PyInputString ustring(PyList_GetItem(o, j));
+            if (ustring.IsAvalable()) {
+              (*out)[i][j] = ustring.str();
+            } else {
+              PyErr_SetString(PyExc_TypeError,"list must contain integers");
+              SWIG_fail;
+            }
+            resultobj = ustring.input_type();
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError,"not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodePiecesBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodePiecesBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< absl::string_view > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputString(result[i], input_type));
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< absl::string_view > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  BytesArray result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            const PyInputString ustring(PyList_GetItem(o, j));
+            if (ustring.IsAvalable()) {
+              (*out)[i][j] = ustring.str();
+            } else {
+              PyErr_SetString(PyExc_TypeError,"list must contain integers");
+              SWIG_fail;
+            }
+            resultobj = ustring.input_type();
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError,"not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< absl::string_view > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, MakePyOutputBytes(result[i]));
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< std::vector< absl::string_view > > *arg2 = 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  SwigValueWrapper< std::vector< sentencepiece::ImmutableSentencePieceText > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector> *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector>(size);
+      for (size_t i = 0; i < size; ++i) {
+        PyObject *o = PyList_GetItem(swig_obj[1], i);
+        if (PyList_Check(o)) {
+          const size_t size2 = PyList_Size(o);
+          (*out)[i].resize(size2);
+          for (size_t j = 0; j < size2; ++j) {
+            const PyInputString ustring(PyList_GetItem(o, j));
+            if (ustring.IsAvalable()) {
+              (*out)[i][j] = ustring.str();
+            } else {
+              PyErr_SetString(PyExc_TypeError,"list must contain integers");
+              SWIG_fail;
+            }
+            resultobj = ustring.input_type();
+          }
+        } else {
+          PyErr_SetString(PyExc_TypeError,"not a list");
+          SWIG_fail;
+        }
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError,"not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch((sentencepiece::SentencePieceProcessor const *)arg1,(std::vector< std::vector< absl::string_view > > const &)*arg2,arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = SWIG_NewPointerObj(new sentencepiece::ImmutableSentencePieceText((&result)->at(i)), SWIGTYPE_p_sentencepiece__ImmutableSentencePieceText, SWIG_POINTER_OWN | 0);
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsIds(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  bool arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  PyObject *swig_obj[7] ;
+  std::vector< std::vector< int > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsIds", 7, 7, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsIds" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__NBestEncodeAsIds((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = PyList_New(result[i].size());
+      for (size_t j = 0; j < result[i].size(); ++j) {
+        PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast(result[i][j])));
+      }
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsPieces(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  bool arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  PyObject *swig_obj[7] ;
+  std::vector< std::vector< std::string > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsPieces", 7, 7, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsPieces" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__NBestEncodeAsPieces((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = PyList_New(result[i].size());
+      for (size_t j = 0; j < result[i].size(); ++j) {
+        PyList_SET_ITEM(obj, j, MakePyOutputString(result[i][j], input_type));
+      }
+      PyList_SET_ITEM(resultobj, i, obj);
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  bool arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  PyObject *swig_obj[7] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsSerializedProto", 7, 7, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsSerializedProto" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__NBestEncodeAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NBestEncodeAsImmutableProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  bool arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  bool val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  PyObject *swig_obj[7] ;
+  sentencepiece::ImmutableNBestSentencePieceText result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NBestEncodeAsImmutableProto", 7, 7, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "4"" of type '" "bool""'");
+  } 
+  arg4 = static_cast< bool >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__NBestEncodeAsImmutableProto" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__NBestEncodeAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableNBestSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsIds(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  float arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  float val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  std::vector< std::pair< std::vector< int >,float > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsIds", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_float(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "4"" of type '" "float""'");
+  } 
+  arg4 = static_cast< float >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsIds" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsIds((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = PyList_New(result[i].first.size());
+      for (size_t j = 0; j < result[i].first.size(); ++j) {
+        PyList_SET_ITEM(obj, j, PyInt_FromLong(static_cast(result[i].first[j])));
+      }
+      PyList_SET_ITEM(resultobj, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast(result[i].second))));
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsPieces(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  float arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  float val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  std::vector< std::pair< std::vector< std::string >,float > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsPieces", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_float(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "4"" of type '" "float""'");
+  } 
+  arg4 = static_cast< float >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsPieces" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsPieces((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyObject *obj = PyList_New(result[i].first.size());
+      for (size_t j = 0; j < result[i].first.size(); ++j) {
+        PyList_SET_ITEM(obj, j, MakePyOutputString(result[i].first[j], input_type));
+      }
+      PyList_SET_ITEM(resultobj, i, PyTuple_Pack(2, obj, PyFloat_FromDouble(static_cast(result[i].second))));
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  float arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  float val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_float(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "4"" of type '" "float""'");
+  } 
+  arg4 = static_cast< float >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  int arg3 ;
+  float arg4 ;
+  bool arg5 ;
+  bool arg6 ;
+  bool arg7 ;
+  bool arg8 ;
+  bool arg9 ;
+  bool arg10 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  float val4 ;
+  int ecode4 = 0 ;
+  bool val5 ;
+  int ecode5 = 0 ;
+  bool val6 ;
+  int ecode6 = 0 ;
+  bool val7 ;
+  int ecode7 = 0 ;
+  bool val8 ;
+  int ecode8 = 0 ;
+  bool val9 ;
+  int ecode9 = 0 ;
+  bool val10 ;
+  int ecode10 = 0 ;
+  PyObject *swig_obj[10] ;
+  sentencepiece::ImmutableNBestSentencePieceText result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto", 10, 10, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_int(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_float(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "4"" of type '" "float""'");
+  } 
+  arg4 = static_cast< float >(val4);
+  ecode5 = SWIG_AsVal_bool(swig_obj[4], &val5);
+  if (!SWIG_IsOK(ecode5)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "5"" of type '" "bool""'");
+  } 
+  arg5 = static_cast< bool >(val5);
+  ecode6 = SWIG_AsVal_bool(swig_obj[5], &val6);
+  if (!SWIG_IsOK(ecode6)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "6"" of type '" "bool""'");
+  } 
+  arg6 = static_cast< bool >(val6);
+  ecode7 = SWIG_AsVal_bool(swig_obj[6], &val7);
+  if (!SWIG_IsOK(ecode7)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "7"" of type '" "bool""'");
+  } 
+  arg7 = static_cast< bool >(val7);
+  ecode8 = SWIG_AsVal_bool(swig_obj[7], &val8);
+  if (!SWIG_IsOK(ecode8)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "8"" of type '" "bool""'");
+  } 
+  arg8 = static_cast< bool >(val8);
+  ecode9 = SWIG_AsVal_bool(swig_obj[8], &val9);
+  if (!SWIG_IsOK(ecode9)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "9"" of type '" "bool""'");
+  } 
+  arg9 = static_cast< bool >(val9);
+  ecode10 = SWIG_AsVal_bool(swig_obj[9], &val10);
+  if (!SWIG_IsOK(ecode10)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto" "', argument " "10"" of type '" "bool""'");
+  } 
+  arg10 = static_cast< bool >(val10);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto((sentencepiece::SentencePieceProcessor const *)arg1,SWIG_STD_MOVE(arg2),arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj((new sentencepiece::ImmutableNBestSentencePieceText(result)), SWIGTYPE_p_sentencepiece__ImmutableNBestSentencePieceText, SWIG_POINTER_OWN |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__Normalize(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::string result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__Normalize", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__Normalize" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__Normalize(arg1,SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__NormalizeWithOffsets(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::pair< std::string,std::vector< size_t > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__NormalizeWithOffsets", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__NormalizeWithOffsets" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__NormalizeWithOffsets(arg1,SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    if (PyInputString::IsUnicode(input_type)) {
+      sentencepiece::ConvertToUnicodeAlignment(arg2, (&result)->first, &(&result)->second);
+    }
+    PyObject *obj = PyList_New((&result)->second.size());
+    for (size_t i = 0; i < (&result)->second.size(); ++i) {
+      PyList_SET_ITEM(obj, i, PyInt_FromLong(static_cast((&result)->second[i])));
+    }
+    resultobj = PyTuple_Pack(2, MakePyOutputString((&result)->first, input_type), obj);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__CalculateEntropy(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  absl::string_view arg2 ;
+  float arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  float val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  float result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__CalculateEntropy", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__CalculateEntropy" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__CalculateEntropy" "', argument " "3"" of type '" "float""'");
+  } 
+  arg3 = static_cast< float >(val3);
+  {
+    try {
+      result = (float)sentencepiece_SentencePieceProcessor__CalculateEntropy(arg1,SWIG_STD_MOVE(arg2),arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_From_float(static_cast< float >(result));
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__CalculateEntropyBatch(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::vector< absl::string_view > *arg2 = 0 ;
+  float arg3 ;
+  int arg4 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  float val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  PyObject *swig_obj[4] ;
+  std::vector< float > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__CalculateEntropyBatch", 4, 4, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__CalculateEntropyBatch" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::vector *out = nullptr;
+    if (PyList_Check(swig_obj[1])) {
+      const size_t size = PyList_Size(swig_obj[1]);
+      out = new std::vector(size);
+      for (size_t i = 0; i < size; ++i) {
+        const PyInputString ustring(PyList_GetItem(swig_obj[1], i));
+        if (ustring.IsAvalable()) {
+          (*out)[i] = ustring.str();
+        } else {
+          PyErr_SetString(PyExc_TypeError, "list must contain strings");
+          SWIG_fail;
+        }
+        resultobj = ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a list");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  ecode3 = SWIG_AsVal_float(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceProcessor__CalculateEntropyBatch" "', argument " "3"" of type '" "float""'");
+  } 
+  arg3 = static_cast< float >(val3);
+  ecode4 = SWIG_AsVal_int(swig_obj[3], &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "SentencePieceProcessor__CalculateEntropyBatch" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = static_cast< int >(val4);
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__CalculateEntropyBatch(arg1,(std::vector< absl::string_view > const &)*arg2,arg3,arg4);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = PyList_New((&result)->size());
+    for (size_t i = 0; i < (&result)->size(); ++i) {
+      PyList_SET_ITEM(resultobj, i, PyFloat_FromDouble(static_cast(result[i])));
+    }
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceProcessor__OverrideNormalizerSpec(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceProcessor *arg1 = (sentencepiece::SentencePieceProcessor *) 0 ;
+  std::unordered_map< std::string,std::string > *arg2 = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceProcessor__OverrideNormalizerSpec", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceProcessor, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceProcessor__OverrideNormalizerSpec" "', argument " "1"" of type '" "sentencepiece::SentencePieceProcessor *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceProcessor * >(argp1);
+  {
+    std::unordered_map *out = nullptr;
+    if (PyDict_Check(swig_obj[1])) {
+      PyObject *key, *value;
+      Py_ssize_t pos = 0;
+      out = new std::unordered_map;
+      while (PyDict_Next(swig_obj[1], &pos, &key, &value)) {
+        const PyInputString key_ustring(key);
+        const PyInputString value_ustring(value);
+        if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) {
+          out->emplace(std::string(key_ustring.data(), key_ustring.size()),
+            std::string(value_ustring.data(), value_ustring.size()));
+        } else {
+          PyErr_SetString(PyExc_TypeError, "map must contain strings.");
+          SWIG_fail;
+        }
+        resultobj = key_ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a dictionary");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceProcessor__OverrideNormalizerSpec(arg1,(std::unordered_map< std::string,std::string > const &)*arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *SentencePieceProcessor_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj = NULL;
+  if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__SentencePieceProcessor, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *SentencePieceProcessor_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  return SWIG_Python_InitShadowInstance(args);
+}
+
+SWIGINTERN PyObject *_wrap_SetRandomGeneratorSeed(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  unsigned int arg1 ;
+  unsigned int val1 ;
+  int ecode1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  ecode1 = SWIG_AsVal_unsigned_SS_int(swig_obj[0], &val1);
+  if (!SWIG_IsOK(ecode1)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "SetRandomGeneratorSeed" "', argument " "1"" of type '" "unsigned int""'");
+  } 
+  arg1 = static_cast< unsigned int >(val1);
+  {
+    try {
+      sentencepiece::SetRandomGeneratorSeed(arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SetMinLogLevel(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  int arg1 ;
+  int val1 ;
+  int ecode1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  ecode1 = SWIG_AsVal_int(swig_obj[0], &val1);
+  if (!SWIG_IsOK(ecode1)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "SetMinLogLevel" "', argument " "1"" of type '" "int""'");
+  } 
+  arg1 = static_cast< int >(val1);
+  {
+    try {
+      sentencepiece::SetMinLogLevel(arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromString(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  absl::string_view arg1 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  {
+    const PyInputString ustring(swig_obj[0]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg1 = ustring.str();
+  }
+  {
+    try {
+      sentencepiece_SentencePieceTrainer__TrainFromString(SWIG_STD_MOVE(arg1));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  std::unordered_map< std::string,std::string > *arg1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  {
+    std::unordered_map *out = nullptr;
+    if (PyDict_Check(swig_obj[0])) {
+      PyObject *key, *value;
+      Py_ssize_t pos = 0;
+      out = new std::unordered_map;
+      while (PyDict_Next(swig_obj[0], &pos, &key, &value)) {
+        const PyInputString key_ustring(key);
+        const PyInputString value_ustring(value);
+        if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) {
+          out->emplace(std::string(key_ustring.data(), key_ustring.size()),
+            std::string(value_ustring.data(), value_ustring.size()));
+        } else {
+          PyErr_SetString(PyExc_TypeError, "map must contain strings.");
+          SWIG_fail;
+        }
+        resultobj = key_ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a dictionary");
+      SWIG_fail;
+    }
+    arg1 = out;
+  }
+  {
+    try {
+      sentencepiece_SentencePieceTrainer__TrainFromMap((std::unordered_map< std::string,std::string > const &)*arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  {
+    delete arg1;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg1;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap2(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  std::unordered_map< std::string,std::string > *arg1 = 0 ;
+  sentencepiece::SentenceIterator *arg2 = (sentencepiece::SentenceIterator *) 0 ;
+  PyObject *swig_obj[2] ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceTrainer__TrainFromMap2", 2, 2, swig_obj)) SWIG_fail;
+  {
+    std::unordered_map *out = nullptr;
+    if (PyDict_Check(swig_obj[0])) {
+      PyObject *key, *value;
+      Py_ssize_t pos = 0;
+      out = new std::unordered_map;
+      while (PyDict_Next(swig_obj[0], &pos, &key, &value)) {
+        const PyInputString key_ustring(key);
+        const PyInputString value_ustring(value);
+        if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) {
+          out->emplace(std::string(key_ustring.data(), key_ustring.size()),
+            std::string(value_ustring.data(), value_ustring.size()));
+        } else {
+          PyErr_SetString(PyExc_TypeError, "map must contain strings.");
+          SWIG_fail;
+        }
+        resultobj = key_ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a dictionary");
+      SWIG_fail;
+    }
+    arg1 = out;
+  }
+  {
+    sentencepiece::SentenceIterator *out = nullptr;
+    if (PyIter_Check(swig_obj[1])) {
+      out = new PySentenceIterator(swig_obj[1]);
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a iterator");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      sentencepiece_SentencePieceTrainer__TrainFromMap2((std::unordered_map< std::string,std::string > const &)*arg1,arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  {
+    delete arg1;
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg1;
+  }
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap3(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  std::unordered_map< std::string,std::string > *arg1 = 0 ;
+  PyObject *swig_obj[1] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  {
+    std::unordered_map *out = nullptr;
+    if (PyDict_Check(swig_obj[0])) {
+      PyObject *key, *value;
+      Py_ssize_t pos = 0;
+      out = new std::unordered_map;
+      while (PyDict_Next(swig_obj[0], &pos, &key, &value)) {
+        const PyInputString key_ustring(key);
+        const PyInputString value_ustring(value);
+        if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) {
+          out->emplace(std::string(key_ustring.data(), key_ustring.size()),
+            std::string(value_ustring.data(), value_ustring.size()));
+        } else {
+          PyErr_SetString(PyExc_TypeError, "map must contain strings.");
+          SWIG_fail;
+        }
+        resultobj = key_ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a dictionary");
+      SWIG_fail;
+    }
+    arg1 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceTrainer__TrainFromMap3((std::unordered_map< std::string,std::string > const &)*arg1);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  {
+    delete arg1;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg1;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceTrainer__TrainFromMap4(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  std::unordered_map< std::string,std::string > *arg1 = 0 ;
+  sentencepiece::SentenceIterator *arg2 = (sentencepiece::SentenceIterator *) 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::bytes result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceTrainer__TrainFromMap4", 2, 2, swig_obj)) SWIG_fail;
+  {
+    std::unordered_map *out = nullptr;
+    if (PyDict_Check(swig_obj[0])) {
+      PyObject *key, *value;
+      Py_ssize_t pos = 0;
+      out = new std::unordered_map;
+      while (PyDict_Next(swig_obj[0], &pos, &key, &value)) {
+        const PyInputString key_ustring(key);
+        const PyInputString value_ustring(value);
+        if (key_ustring.IsAvalable() && value_ustring.IsAvalable()) {
+          out->emplace(std::string(key_ustring.data(), key_ustring.size()),
+            std::string(value_ustring.data(), value_ustring.size()));
+        } else {
+          PyErr_SetString(PyExc_TypeError, "map must contain strings.");
+          SWIG_fail;
+        }
+        resultobj = key_ustring.input_type();
+      }
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a dictionary");
+      SWIG_fail;
+    }
+    arg1 = out;
+  }
+  {
+    sentencepiece::SentenceIterator *out = nullptr;
+    if (PyIter_Check(swig_obj[1])) {
+      out = new PySentenceIterator(swig_obj[1]);
+    } else {
+      PyErr_SetString(PyExc_TypeError, "not a iterator");
+      SWIG_fail;
+    }
+    arg2 = out;
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceTrainer__TrainFromMap4((std::unordered_map< std::string,std::string > const &)*arg1,arg2);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    resultobj = MakePyOutputBytes(result);
+  }
+  {
+    delete arg1;
+  }
+  {
+    delete arg2;
+  }
+  return resultobj;
+fail:
+  {
+    delete arg1;
+  }
+  {
+    delete arg2;
+  }
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *SentencePieceTrainer_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj = NULL;
+  if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__SentencePieceTrainer, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_new_SentencePieceNormalizer(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *result = 0 ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "new_SentencePieceNormalizer", 0, 0, 0)) SWIG_fail;
+  {
+    try {
+      result = (sentencepiece::SentencePieceNormalizer *)new sentencepiece::SentencePieceNormalizer();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_delete_SentencePieceNormalizer(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_SentencePieceNormalizer" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    try {
+      delete arg1;
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromSerializedProto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromSerializedProto", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromSerializedProto" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (arg1)->LoadFromSerializedProto(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromRuleTSV(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromRuleTSV", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromRuleTSV" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (arg1)->LoadFromRuleTSV(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromRuleName(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromRuleName", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromRuleName" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = (arg1)->LoadFromRuleName(SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_serialized_model_proto(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[1] ;
+  std::string result;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_serialized_model_proto" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer const *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    try {
+      result = ((sentencepiece::SentencePieceNormalizer const *)arg1)->serialized_model_proto();
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer_LoadFromFile(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  sentencepiece::util::Status result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer_LoadFromFile", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer_LoadFromFile" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceNormalizer_LoadFromFile(arg1,SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    if (!(&result)->ok()) {
+      SWIG_exception(ToSwigError((&result)->code()), (&result)->ToString().c_str());
+    }
+    resultobj = SWIG_From_bool((&result)->ok());
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer__Normalize(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::string result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer__Normalize", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer__Normalize" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceNormalizer__Normalize(arg1,SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    resultobj = MakePyOutputString(result, input_type);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer__NormalizeWithOffsets(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject *swig_obj[2] ;
+  std::pair< std::string,std::vector< size_t > > result;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer__NormalizeWithOffsets", 2, 2, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer__NormalizeWithOffsets" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  {
+    try {
+      result = sentencepiece_SentencePieceNormalizer__NormalizeWithOffsets(arg1,SWIG_STD_MOVE(arg2));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  {
+    PyObject *input_type = resultobj;
+    if (PyInputString::IsUnicode(input_type)) {
+      sentencepiece::ConvertToUnicodeAlignment(arg2, (&result)->first, &(&result)->second);
+    }
+    PyObject *obj = PyList_New((&result)->second.size());
+    for (size_t i = 0; i < (&result)->second.size(); ++i) {
+      PyList_SET_ITEM(obj, i, PyInt_FromLong(static_cast((&result)->second[i])));
+    }
+    resultobj = PyTuple_Pack(2, MakePyOutputString((&result)->first, input_type), obj);
+  }
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *_wrap_SentencePieceNormalizer__SetProtoField(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  sentencepiece::SentencePieceNormalizer *arg1 = (sentencepiece::SentencePieceNormalizer *) 0 ;
+  absl::string_view arg2 ;
+  bool arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  bool val3 ;
+  int ecode3 = 0 ;
+  PyObject *swig_obj[3] ;
+  
+  (void)self;
+  if (!SWIG_Python_UnpackTuple(args, "SentencePieceNormalizer__SetProtoField", 3, 3, swig_obj)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SentencePieceNormalizer__SetProtoField" "', argument " "1"" of type '" "sentencepiece::SentencePieceNormalizer *""'"); 
+  }
+  arg1 = reinterpret_cast< sentencepiece::SentencePieceNormalizer * >(argp1);
+  {
+    const PyInputString ustring(swig_obj[1]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg2 = ustring.str();
+  }
+  ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "SentencePieceNormalizer__SetProtoField" "', argument " "3"" of type '" "bool""'");
+  } 
+  arg3 = static_cast< bool >(val3);
+  {
+    try {
+      sentencepiece_SentencePieceNormalizer__SetProtoField(arg1,SWIG_STD_MOVE(arg2),arg3);
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+SWIGINTERN PyObject *SentencePieceNormalizer_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj = NULL;
+  if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_sentencepiece__SentencePieceNormalizer, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *SentencePieceNormalizer_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  return SWIG_Python_InitShadowInstance(args);
+}
+
+SWIGINTERN PyObject *_wrap_SetDataDir(PyObject *self, PyObject *args) {
+  PyObject *resultobj = 0;
+  absl::string_view arg1 ;
+  PyObject *swig_obj[1] ;
+  
+  (void)self;
+  if (!args) SWIG_fail;
+  swig_obj[0] = args;
+  {
+    const PyInputString ustring(swig_obj[0]);
+    if (!ustring.IsAvalable()) {
+      PyErr_SetString(PyExc_TypeError, "not a string");
+      SWIG_fail;
+    }
+    resultobj = ustring.input_type();
+    arg1 = ustring.str();
+  }
+  {
+    try {
+      sentencepiece::SetDataDir(SWIG_STD_MOVE(arg1));
+      ReleaseResultObject(resultobj);
+    }
+    catch (const sentencepiece::util::Status &status) {
+      SWIG_exception(ToSwigError(status.code()), status.ToString().c_str());
+    }
+  }
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
+}
+
+
+static PyMethodDef SwigMethods[] = {
+	 { "new_ImmutableSentencePieceText_ImmutableSentencePiece", _wrap_new_ImmutableSentencePieceText_ImmutableSentencePiece, METH_NOARGS, NULL},
+	 { "delete_ImmutableSentencePieceText_ImmutableSentencePiece", _wrap_delete_ImmutableSentencePieceText_ImmutableSentencePiece, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__piece", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__surface", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__id", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__id, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__begin", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__begin, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__end", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__end, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__surface_as_bytes, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes", _wrap_ImmutableSentencePieceText_ImmutableSentencePiece__piece_as_bytes, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece_swigregister", ImmutableSentencePieceText_ImmutableSentencePiece_swigregister, METH_O, NULL},
+	 { "ImmutableSentencePieceText_ImmutableSentencePiece_swiginit", ImmutableSentencePieceText_ImmutableSentencePiece_swiginit, METH_VARARGS, NULL},
+	 { "new_ImmutableSentencePieceText", _wrap_new_ImmutableSentencePieceText, METH_NOARGS, NULL},
+	 { "delete_ImmutableSentencePieceText", _wrap_delete_ImmutableSentencePieceText, METH_O, NULL},
+	 { "ImmutableSentencePieceText__pieces_size", _wrap_ImmutableSentencePieceText__pieces_size, METH_O, NULL},
+	 { "ImmutableSentencePieceText__pieces", _wrap_ImmutableSentencePieceText__pieces, METH_VARARGS, NULL},
+	 { "ImmutableSentencePieceText__text", _wrap_ImmutableSentencePieceText__text, METH_O, NULL},
+	 { "ImmutableSentencePieceText__score", _wrap_ImmutableSentencePieceText__score, METH_O, NULL},
+	 { "ImmutableSentencePieceText_SerializeAsString", _wrap_ImmutableSentencePieceText_SerializeAsString, METH_O, NULL},
+	 { "ImmutableSentencePieceText__text_as_bytes", _wrap_ImmutableSentencePieceText__text_as_bytes, METH_O, NULL},
+	 { "ImmutableSentencePieceText_swigregister", ImmutableSentencePieceText_swigregister, METH_O, NULL},
+	 { "ImmutableSentencePieceText_swiginit", ImmutableSentencePieceText_swiginit, METH_VARARGS, NULL},
+	 { "new_ImmutableNBestSentencePieceText", _wrap_new_ImmutableNBestSentencePieceText, METH_NOARGS, NULL},
+	 { "delete_ImmutableNBestSentencePieceText", _wrap_delete_ImmutableNBestSentencePieceText, METH_O, NULL},
+	 { "ImmutableNBestSentencePieceText__nbests_size", _wrap_ImmutableNBestSentencePieceText__nbests_size, METH_O, NULL},
+	 { "ImmutableNBestSentencePieceText__nbests", _wrap_ImmutableNBestSentencePieceText__nbests, METH_VARARGS, NULL},
+	 { "ImmutableNBestSentencePieceText_SerializeAsString", _wrap_ImmutableNBestSentencePieceText_SerializeAsString, METH_O, NULL},
+	 { "ImmutableNBestSentencePieceText_swigregister", ImmutableNBestSentencePieceText_swigregister, METH_O, NULL},
+	 { "ImmutableNBestSentencePieceText_swiginit", ImmutableNBestSentencePieceText_swiginit, METH_VARARGS, NULL},
+	 { "new_SentencePieceProcessor", _wrap_new_SentencePieceProcessor, METH_NOARGS, NULL},
+	 { "delete_SentencePieceProcessor", _wrap_delete_SentencePieceProcessor, METH_O, NULL},
+	 { "SentencePieceProcessor_LoadFromSerializedProto", _wrap_SentencePieceProcessor_LoadFromSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_SetEncodeExtraOptions", _wrap_SentencePieceProcessor_SetEncodeExtraOptions, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_SetDecodeExtraOptions", _wrap_SentencePieceProcessor_SetDecodeExtraOptions, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_SetVocabulary", _wrap_SentencePieceProcessor_SetVocabulary, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_ResetVocabulary", _wrap_SentencePieceProcessor_ResetVocabulary, METH_O, NULL},
+	 { "SentencePieceProcessor_LoadVocabulary", _wrap_SentencePieceProcessor_LoadVocabulary, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_CalculateEntropy", _wrap_SentencePieceProcessor_CalculateEntropy, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_GetPieceSize", _wrap_SentencePieceProcessor_GetPieceSize, METH_O, NULL},
+	 { "SentencePieceProcessor_PieceToId", _wrap_SentencePieceProcessor_PieceToId, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_IdToPiece", _wrap_SentencePieceProcessor_IdToPiece, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_GetScore", _wrap_SentencePieceProcessor_GetScore, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_IsUnknown", _wrap_SentencePieceProcessor_IsUnknown, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_IsControl", _wrap_SentencePieceProcessor_IsControl, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_IsUnused", _wrap_SentencePieceProcessor_IsUnused, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_IsByte", _wrap_SentencePieceProcessor_IsByte, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_unk_id", _wrap_SentencePieceProcessor_unk_id, METH_O, NULL},
+	 { "SentencePieceProcessor_bos_id", _wrap_SentencePieceProcessor_bos_id, METH_O, NULL},
+	 { "SentencePieceProcessor_eos_id", _wrap_SentencePieceProcessor_eos_id, METH_O, NULL},
+	 { "SentencePieceProcessor_pad_id", _wrap_SentencePieceProcessor_pad_id, METH_O, NULL},
+	 { "SentencePieceProcessor_serialized_model_proto", _wrap_SentencePieceProcessor_serialized_model_proto, METH_O, NULL},
+	 { "SentencePieceProcessor_LoadFromFile", _wrap_SentencePieceProcessor_LoadFromFile, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsIds", _wrap_SentencePieceProcessor__EncodeAsIds, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsPieces", _wrap_SentencePieceProcessor__EncodeAsPieces, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsSerializedProto", _wrap_SentencePieceProcessor__EncodeAsSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsImmutableProto", _wrap_SentencePieceProcessor__EncodeAsImmutableProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsIdsBatch", _wrap_SentencePieceProcessor__EncodeAsIdsBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsPiecesBatch", _wrap_SentencePieceProcessor__EncodeAsPiecesBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsSerializedProtoBatch", _wrap_SentencePieceProcessor__EncodeAsSerializedProtoBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__EncodeAsImmutableProtoBatch", _wrap_SentencePieceProcessor__EncodeAsImmutableProtoBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIds", _wrap_SentencePieceProcessor__DecodeIds, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsAsBytes", _wrap_SentencePieceProcessor__DecodeIdsAsBytes, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodePieces", _wrap_SentencePieceProcessor__DecodePieces, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsAsSerializedProto", _wrap_SentencePieceProcessor__DecodeIdsAsSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodePiecesAsSerializedProto", _wrap_SentencePieceProcessor__DecodePiecesAsSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsAsImmutableProto", _wrap_SentencePieceProcessor__DecodeIdsAsImmutableProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodePiecesAsImmutableProto", _wrap_SentencePieceProcessor__DecodePiecesAsImmutableProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsBatch", _wrap_SentencePieceProcessor__DecodeIdsBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsAsBytesBatch", _wrap_SentencePieceProcessor__DecodeIdsAsBytesBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch", _wrap_SentencePieceProcessor__DecodeIdsAsSerializedProtoBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch", _wrap_SentencePieceProcessor__DecodeIdsAsImmutableProtoBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodePiecesBatch", _wrap_SentencePieceProcessor__DecodePiecesBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch", _wrap_SentencePieceProcessor__DecodePiecesAsSerializedProtoBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch", _wrap_SentencePieceProcessor__DecodePiecesAsImmutableProtoBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__NBestEncodeAsIds", _wrap_SentencePieceProcessor__NBestEncodeAsIds, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__NBestEncodeAsPieces", _wrap_SentencePieceProcessor__NBestEncodeAsPieces, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__NBestEncodeAsSerializedProto", _wrap_SentencePieceProcessor__NBestEncodeAsSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__NBestEncodeAsImmutableProto", _wrap_SentencePieceProcessor__NBestEncodeAsImmutableProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__SampleEncodeAndScoreAsIds", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsIds, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__SampleEncodeAndScoreAsPieces", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsPieces, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto", _wrap_SentencePieceProcessor__SampleEncodeAndScoreAsImmutableProto, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__Normalize", _wrap_SentencePieceProcessor__Normalize, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__NormalizeWithOffsets", _wrap_SentencePieceProcessor__NormalizeWithOffsets, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__CalculateEntropy", _wrap_SentencePieceProcessor__CalculateEntropy, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__CalculateEntropyBatch", _wrap_SentencePieceProcessor__CalculateEntropyBatch, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor__OverrideNormalizerSpec", _wrap_SentencePieceProcessor__OverrideNormalizerSpec, METH_VARARGS, NULL},
+	 { "SentencePieceProcessor_swigregister", SentencePieceProcessor_swigregister, METH_O, NULL},
+	 { "SentencePieceProcessor_swiginit", SentencePieceProcessor_swiginit, METH_VARARGS, NULL},
+	 { "SetRandomGeneratorSeed", _wrap_SetRandomGeneratorSeed, METH_O, NULL},
+	 { "SetMinLogLevel", _wrap_SetMinLogLevel, METH_O, NULL},
+	 { "SentencePieceTrainer__TrainFromString", _wrap_SentencePieceTrainer__TrainFromString, METH_O, NULL},
+	 { "SentencePieceTrainer__TrainFromMap", _wrap_SentencePieceTrainer__TrainFromMap, METH_O, NULL},
+	 { "SentencePieceTrainer__TrainFromMap2", _wrap_SentencePieceTrainer__TrainFromMap2, METH_VARARGS, NULL},
+	 { "SentencePieceTrainer__TrainFromMap3", _wrap_SentencePieceTrainer__TrainFromMap3, METH_O, NULL},
+	 { "SentencePieceTrainer__TrainFromMap4", _wrap_SentencePieceTrainer__TrainFromMap4, METH_VARARGS, NULL},
+	 { "SentencePieceTrainer_swigregister", SentencePieceTrainer_swigregister, METH_O, NULL},
+	 { "new_SentencePieceNormalizer", _wrap_new_SentencePieceNormalizer, METH_NOARGS, NULL},
+	 { "delete_SentencePieceNormalizer", _wrap_delete_SentencePieceNormalizer, METH_O, NULL},
+	 { "SentencePieceNormalizer_LoadFromSerializedProto", _wrap_SentencePieceNormalizer_LoadFromSerializedProto, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer_LoadFromRuleTSV", _wrap_SentencePieceNormalizer_LoadFromRuleTSV, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer_LoadFromRuleName", _wrap_SentencePieceNormalizer_LoadFromRuleName, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer_serialized_model_proto", _wrap_SentencePieceNormalizer_serialized_model_proto, METH_O, NULL},
+	 { "SentencePieceNormalizer_LoadFromFile", _wrap_SentencePieceNormalizer_LoadFromFile, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer__Normalize", _wrap_SentencePieceNormalizer__Normalize, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer__NormalizeWithOffsets", _wrap_SentencePieceNormalizer__NormalizeWithOffsets, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer__SetProtoField", _wrap_SentencePieceNormalizer__SetProtoField, METH_VARARGS, NULL},
+	 { "SentencePieceNormalizer_swigregister", SentencePieceNormalizer_swigregister, METH_O, NULL},
+	 { "SentencePieceNormalizer_swiginit", SentencePieceNormalizer_swiginit, METH_VARARGS, NULL},
+	 { "SetDataDir", _wrap_SetDataDir, METH_O, NULL},
+	 { NULL, NULL, 0, NULL }
+};
+
+
+/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
+
+static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_float = {"_p_float", "float *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__ImmutableNBestSentencePieceText = {"_p_sentencepiece__ImmutableNBestSentencePieceText", "sentencepiece::ImmutableNBestSentencePieceText *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__ImmutableSentencePieceText = {"_p_sentencepiece__ImmutableSentencePieceText", "sentencepiece::ImmutableSentencePieceText *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece = {"_p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece", "sentencepiece::ImmutableSentencePieceText_ImmutableSentencePiece *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__SentenceIterator = {"_p_sentencepiece__SentenceIterator", "sentencepiece::SentenceIterator *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__SentencePieceNormalizer = {"_p_sentencepiece__SentencePieceNormalizer", "sentencepiece::SentencePieceNormalizer *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__SentencePieceProcessor = {"_p_sentencepiece__SentencePieceProcessor", "sentencepiece::SentencePieceProcessor *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_sentencepiece__SentencePieceTrainer = {"_p_sentencepiece__SentencePieceTrainer", "sentencepiece::SentencePieceTrainer *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_std__string = {"_p_std__string", "sentencepiece::util::bytes *|std::string *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_std__unordered_mapT_std__string_std__string_t = {"_p_std__unordered_mapT_std__string_std__string_t", "std::unordered_map< std::string,std::string > *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_std__vectorT_absl__string_view_t = {"_p_std__vectorT_absl__string_view_t", "std::vector< absl::string_view > *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_std__vectorT_int_t = {"_p_std__vectorT_int_t", "std::vector< int > *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_std__vectorT_std__vectorT_absl__string_view_t_t = {"_p_std__vectorT_std__vectorT_absl__string_view_t_t", "std::vector< std::vector< absl::string_view > > *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_std__vectorT_std__vectorT_int_t_t = {"_p_std__vectorT_std__vectorT_int_t_t", "std::vector< std::vector< int > > *", 0, 0, (void*)0, 0};
+
+static swig_type_info *swig_type_initial[] = {
+  &_swigt__p_char,
+  &_swigt__p_float,
+  &_swigt__p_sentencepiece__ImmutableNBestSentencePieceText,
+  &_swigt__p_sentencepiece__ImmutableSentencePieceText,
+  &_swigt__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece,
+  &_swigt__p_sentencepiece__SentenceIterator,
+  &_swigt__p_sentencepiece__SentencePieceNormalizer,
+  &_swigt__p_sentencepiece__SentencePieceProcessor,
+  &_swigt__p_sentencepiece__SentencePieceTrainer,
+  &_swigt__p_std__string,
+  &_swigt__p_std__unordered_mapT_std__string_std__string_t,
+  &_swigt__p_std__vectorT_absl__string_view_t,
+  &_swigt__p_std__vectorT_int_t,
+  &_swigt__p_std__vectorT_std__vectorT_absl__string_view_t_t,
+  &_swigt__p_std__vectorT_std__vectorT_int_t_t,
+};
+
+static swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_float[] = {  {&_swigt__p_float, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__ImmutableNBestSentencePieceText[] = {  {&_swigt__p_sentencepiece__ImmutableNBestSentencePieceText, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__ImmutableSentencePieceText[] = {  {&_swigt__p_sentencepiece__ImmutableSentencePieceText, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece[] = {  {&_swigt__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__SentenceIterator[] = {  {&_swigt__p_sentencepiece__SentenceIterator, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__SentencePieceNormalizer[] = {  {&_swigt__p_sentencepiece__SentencePieceNormalizer, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__SentencePieceProcessor[] = {  {&_swigt__p_sentencepiece__SentencePieceProcessor, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_sentencepiece__SentencePieceTrainer[] = {  {&_swigt__p_sentencepiece__SentencePieceTrainer, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_std__string[] = {  {&_swigt__p_std__string, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_std__unordered_mapT_std__string_std__string_t[] = {  {&_swigt__p_std__unordered_mapT_std__string_std__string_t, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_std__vectorT_absl__string_view_t[] = {  {&_swigt__p_std__vectorT_absl__string_view_t, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_std__vectorT_int_t[] = {  {&_swigt__p_std__vectorT_int_t, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_std__vectorT_std__vectorT_absl__string_view_t_t[] = {  {&_swigt__p_std__vectorT_std__vectorT_absl__string_view_t_t, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_std__vectorT_std__vectorT_int_t_t[] = {  {&_swigt__p_std__vectorT_std__vectorT_int_t_t, 0, 0, 0},{0, 0, 0, 0}};
+
+static swig_cast_info *swig_cast_initial[] = {
+  _swigc__p_char,
+  _swigc__p_float,
+  _swigc__p_sentencepiece__ImmutableNBestSentencePieceText,
+  _swigc__p_sentencepiece__ImmutableSentencePieceText,
+  _swigc__p_sentencepiece__ImmutableSentencePieceText_ImmutableSentencePiece,
+  _swigc__p_sentencepiece__SentenceIterator,
+  _swigc__p_sentencepiece__SentencePieceNormalizer,
+  _swigc__p_sentencepiece__SentencePieceProcessor,
+  _swigc__p_sentencepiece__SentencePieceTrainer,
+  _swigc__p_std__string,
+  _swigc__p_std__unordered_mapT_std__string_std__string_t,
+  _swigc__p_std__vectorT_absl__string_view_t,
+  _swigc__p_std__vectorT_int_t,
+  _swigc__p_std__vectorT_std__vectorT_absl__string_view_t_t,
+  _swigc__p_std__vectorT_std__vectorT_int_t_t,
+};
+
+
+/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
+
+static swig_const_info swig_const_table[] = {
+{0, 0, 0, 0.0, 0, 0}};
+
+#ifdef __cplusplus
+}
+#endif
+/* -----------------------------------------------------------------------------
+ * Type initialization:
+ * This problem is tough by the requirement that no dynamic
+ * memory is used. Also, since swig_type_info structures store pointers to
+ * swig_cast_info structures and swig_cast_info structures store pointers back
+ * to swig_type_info structures, we need some lookup code at initialization.
+ * The idea is that swig generates all the structures that are needed.
+ * The runtime then collects these partially filled structures.
+ * The SWIG_InitializeModule function takes these initial arrays out of
+ * swig_module, and does all the lookup, filling in the swig_module.types
+ * array with the correct data and linking the correct swig_cast_info
+ * structures together.
+ *
+ * The generated swig_type_info structures are assigned statically to an initial
+ * array. We just loop through that array, and handle each type individually.
+ * First we lookup if this type has been already loaded, and if so, use the
+ * loaded structure instead of the generated one. Then we have to fill in the
+ * cast linked list. The cast data is initially stored in something like a
+ * two-dimensional array. Each row corresponds to a type (there are the same
+ * number of rows as there are in the swig_type_initial array). Each entry in
+ * a column is one of the swig_cast_info structures for that type.
+ * The cast_initial array is actually an array of arrays, because each row has
+ * a variable number of columns. So to actually build the cast linked list,
+ * we find the array of casts associated with the type, and loop through it
+ * adding the casts to the list. The one last trick we need to do is making
+ * sure the type pointer in the swig_cast_info struct is correct.
+ *
+ * First off, we lookup the cast->type name to see if it is already loaded.
+ * There are three cases to handle:
+ *  1) If the cast->type has already been loaded AND the type we are adding
+ *     casting info to has not been loaded (it is in this module), THEN we
+ *     replace the cast->type pointer with the type pointer that has already
+ *     been loaded.
+ *  2) If BOTH types (the one we are adding casting info to, and the
+ *     cast->type) are loaded, THEN the cast info has already been loaded by
+ *     the previous module so we just ignore it.
+ *  3) Finally, if cast->type has not already been loaded, then we add that
+ *     swig_cast_info to the linked list (because the cast->type) pointer will
+ *     be correct.
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* c-mode */
+#endif
+#endif
+
+#if 0
+#define SWIGRUNTIME_DEBUG
+#endif
+
+#ifndef SWIG_INIT_CLIENT_DATA_TYPE
+#define SWIG_INIT_CLIENT_DATA_TYPE void *
+#endif
+
+SWIGRUNTIME void
+SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) {
+  size_t i;
+  swig_module_info *module_head, *iter;
+  int init;
+  
+  /* check to see if the circular list has been setup, if not, set it up */
+  if (swig_module.next==0) {
+    /* Initialize the swig_module */
+    swig_module.type_initial = swig_type_initial;
+    swig_module.cast_initial = swig_cast_initial;
+    swig_module.next = &swig_module;
+    init = 1;
+  } else {
+    init = 0;
+  }
+  
+  /* Try and load any already created modules */
+  module_head = SWIG_GetModule(clientdata);
+  if (!module_head) {
+    /* This is the first module loaded for this interpreter */
+    /* so set the swig module into the interpreter */
+    SWIG_SetModule(clientdata, &swig_module);
+  } else {
+    /* the interpreter has loaded a SWIG module, but has it loaded this one? */
+    iter=module_head;
+    do {
+      if (iter==&swig_module) {
+        /* Our module is already in the list, so there's nothing more to do. */
+        return;
+      }
+      iter=iter->next;
+    } while (iter!= module_head);
+    
+    /* otherwise we must add our module into the list */
+    swig_module.next = module_head->next;
+    module_head->next = &swig_module;
+  }
+  
+  /* When multiple interpreters are used, a module could have already been initialized in
+       a different interpreter, but not yet have a pointer in this interpreter.
+       In this case, we do not want to continue adding types... everything should be
+       set up already */
+  if (init == 0) return;
+  
+  /* Now work on filling in swig_module.types */
+#ifdef SWIGRUNTIME_DEBUG
+  printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size);
+#endif
+  for (i = 0; i < swig_module.size; ++i) {
+    swig_type_info *type = 0;
+    swig_type_info *ret;
+    swig_cast_info *cast;
+    
+#ifdef SWIGRUNTIME_DEBUG
+    printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name);
+#endif
+    
+    /* if there is another module already loaded */
+    if (swig_module.next != &swig_module) {
+      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
+    }
+    if (type) {
+      /* Overwrite clientdata field */
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: found type %s\n", type->name);
+#endif
+      if (swig_module.type_initial[i]->clientdata) {
+        type->clientdata = swig_module.type_initial[i]->clientdata;
+#ifdef SWIGRUNTIME_DEBUG
+        printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name);
+#endif
+      }
+    } else {
+      type = swig_module.type_initial[i];
+    }
+    
+    /* Insert casting types */
+    cast = swig_module.cast_initial[i];
+    while (cast->type) {
+      /* Don't need to add information already in the list */
+      ret = 0;
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: look cast %s\n", cast->type->name);
+#endif
+      if (swig_module.next != &swig_module) {
+        ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
+#ifdef SWIGRUNTIME_DEBUG
+        if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name);
+#endif
+      }
+      if (ret) {
+        if (type == swig_module.type_initial[i]) {
+#ifdef SWIGRUNTIME_DEBUG
+          printf("SWIG_InitializeModule: skip old type %s\n", ret->name);
+#endif
+          cast->type = ret;
+          ret = 0;
+        } else {
+          /* Check for casting already in the list */
+          swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);
+#ifdef SWIGRUNTIME_DEBUG
+          if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name);
+#endif
+          if (!ocast) ret = 0;
+        }
+      }
+      
+      if (!ret) {
+#ifdef SWIGRUNTIME_DEBUG
+        printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name);
+#endif
+        if (type->cast) {
+          type->cast->prev = cast;
+          cast->next = type->cast;
+        }
+        type->cast = cast;
+      }
+      cast++;
+    }
+    /* Set entry in modules->types array equal to the type */
+    swig_module.types[i] = type;
+  }
+  swig_module.types[i] = 0;
+  
+#ifdef SWIGRUNTIME_DEBUG
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+  for (i = 0; i < swig_module.size; ++i) {
+    int j = 0;
+    swig_cast_info *cast = swig_module.cast_initial[i];
+    printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name);
+    while (cast->type) {
+      printf("SWIG_InitializeModule: cast type %s\n", cast->type->name);
+      cast++;
+      ++j;
+    }
+    printf("---- Total casts: %d\n",j);
+  }
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+#endif
+}
+
+/* This function will propagate the clientdata field of type to
+* any new swig_type_info structures that have been added into the list
+* of equivalent types.  It is like calling
+* SWIG_TypeClientData(type, clientdata) a second time.
+*/
+SWIGRUNTIME void
+SWIG_PropagateClientData(void) {
+  size_t i;
+  swig_cast_info *equiv;
+  static int init_run = 0;
+  
+  if (init_run) return;
+  init_run = 1;
+  
+  for (i = 0; i < swig_module.size; i++) {
+    if (swig_module.types[i]->clientdata) {
+      equiv = swig_module.types[i]->cast;
+      while (equiv) {
+        if (!equiv->converter) {
+          if (equiv->type && !equiv->type->clientdata)
+          SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
+        }
+        equiv = equiv->next;
+      }
+    }
+  }
+}
+
+#ifdef __cplusplus
+#if 0
+{
+  /* c-mode */
+#endif
+}
+#endif
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+  
+  /* -----------------------------------------------------------------------------
+   * constants/methods manipulation
+   * ----------------------------------------------------------------------------- */
+  
+  /* Install Constants */
+  SWIGINTERN void
+  SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
+    PyObject *obj = 0;
+    size_t i;
+    for (i = 0; constants[i].type; ++i) {
+      switch(constants[i].type) {
+      case SWIG_PY_POINTER:
+        obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
+        break;
+      case SWIG_PY_BINARY:
+        obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
+        break;
+      default:
+        obj = 0;
+        break;
+      }
+      if (obj) {
+        PyDict_SetItemString(d, constants[i].name, obj);
+        SWIG_Py_DECREF(obj);
+      }
+    }
+  }
+  
+  /* -----------------------------------------------------------------------------
+   * Patch %callback methods' docstrings to hold the callback ptrs
+   * -----------------------------------------------------------------------------*/
+  
+  SWIGINTERN void
+  SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) {
+    size_t i;
+    for (i = 0; methods[i].ml_name; ++i) {
+      const char *c = methods[i].ml_doc;
+      if (!c) continue;
+      c = strstr(c, "swig_ptr: ");
+      if (c) {
+        int j;
+        const swig_const_info *ci = 0;
+        const char *name = c + 10;
+        for (j = 0; const_table[j].type; ++j) {
+          if (strncmp(const_table[j].name, name, 
+              strlen(const_table[j].name)) == 0) {
+            ci = &(const_table[j]);
+            break;
+          }
+        }
+        if (ci) {
+          void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;
+          if (ptr) {
+            size_t shift = (ci->ptype) - types;
+            swig_type_info *ty = types_initial[shift];
+            size_t ldoc = (c - methods[i].ml_doc);
+            size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
+            char *ndoc = (char*)malloc(ldoc + lptr + 10);
+            if (ndoc) {
+              char *buff = ndoc;
+              memcpy(buff, methods[i].ml_doc, ldoc);
+              buff += ldoc;
+              memcpy(buff, "swig_ptr: ", 10);
+              buff += 10;
+              SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);
+              methods[i].ml_doc = ndoc;
+            }
+          }
+        }
+      }
+    }
+  } 
+  
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+/* -----------------------------------------------------------------------------*
+ *  Partial Init method
+ * -----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+#endif
+
+SWIGEXPORT 
+#if PY_VERSION_HEX >= 0x03000000
+PyObject*
+#else
+void
+#endif
+SWIG_init(void) {
+  PyObject *m, *d, *md, *globals;
+  
+#if PY_VERSION_HEX >= 0x03000000
+  static struct PyModuleDef SWIG_module = {
+    PyModuleDef_HEAD_INIT,
+    SWIG_name,
+    NULL,
+    -1,
+    SwigMethods,
+    NULL,
+    NULL,
+    NULL,
+    NULL
+  };
+#endif
+  
+#if defined(SWIGPYTHON_BUILTIN)
+  static SwigPyClientData SwigPyObject_clientdata = {
+    0, 0, 0, 0, 0, 0, 0
+  };
+  static PyGetSetDef this_getset_def = {
+    (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL
+  };
+  static SwigPyGetSet thisown_getset_closure = {
+    SwigPyObject_own,
+    SwigPyObject_own
+  };
+  static PyGetSetDef thisown_getset_def = {
+    (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure
+  };
+  PyTypeObject *builtin_pytype;
+  int builtin_base_count;
+  swig_type_info *builtin_basetype;
+  PyObject *tuple;
+  PyGetSetDescrObject *static_getset;
+  PyTypeObject *metatype;
+  PyTypeObject *swigpyobject;
+  SwigPyClientData *cd;
+  PyObject *public_interface, *public_symbol;
+  PyObject *this_descr;
+  PyObject *thisown_descr;
+  PyObject *self = 0;
+  int i;
+  
+  (void)builtin_pytype;
+  (void)builtin_base_count;
+  (void)builtin_basetype;
+  (void)tuple;
+  (void)static_getset;
+  (void)self;
+  
+  /* Metaclass is used to implement static member variables */
+  metatype = SwigPyObjectType();
+  assert(metatype);
+#endif
+  
+  (void)globals;
+  
+  /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */
+  SWIG_This();
+  SWIG_Python_TypeCache();
+  SwigPyPacked_type();
+#ifndef SWIGPYTHON_BUILTIN
+  SwigPyObject_type();
+#endif
+  
+  /* Fix SwigMethods to carry the callback ptrs when needed */
+  SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);
+  
+#if PY_VERSION_HEX >= 0x03000000
+  m = PyModule_Create(&SWIG_module);
+#else
+  m = Py_InitModule(SWIG_name, SwigMethods);
+#endif
+  
+  md = d = PyModule_GetDict(m);
+  (void)md;
+  
+  SWIG_InitializeModule(0);
+  
+#ifdef SWIGPYTHON_BUILTIN
+  swigpyobject = SwigPyObject_TypeOnce();
+  
+  SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject");
+  assert(SwigPyObject_stype);
+  cd = (SwigPyClientData*) SwigPyObject_stype->clientdata;
+  if (!cd) {
+    SwigPyObject_stype->clientdata = &SwigPyObject_clientdata;
+    SwigPyObject_clientdata.pytype = swigpyobject;
+  } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) {
+    PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules.");
+# if PY_VERSION_HEX >= 0x03000000
+    return NULL;
+# else
+    return;
+# endif
+  }
+  
+  /* All objects have a 'this' attribute */
+  this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def);
+  (void)this_descr;
+  
+  /* All objects have a 'thisown' attribute */
+  thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def);
+  (void)thisown_descr;
+  
+  public_interface = PyList_New(0);
+  public_symbol = 0;
+  (void)public_symbol;
+  
+  PyDict_SetItemString(md, "__all__", public_interface);
+  SWIG_Py_DECREF(public_interface);
+  for (i = 0; SwigMethods[i].ml_name != NULL; ++i)
+  SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name);
+  for (i = 0; swig_const_table[i].name != 0; ++i)
+  SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name);
+#endif
+  
+  SWIG_InstallConstants(d,swig_const_table);
+  
+  
+#ifdef Py_GIL_DISABLED
+  PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
+#endif
+  
+#if PY_VERSION_HEX >= 0x03000000
+  return m;
+#else
+  return;
+#endif
+}
+
diff --git a/lib/python3.11/site-packages/shellingham-1.5.4.dist-info/INSTALLER b/lib/python3.11/site-packages/shellingham-1.5.4.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/lib/python3.11/site-packages/shellingham-1.5.4.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/lib/python3.11/site-packages/shellingham-1.5.4.dist-info/RECORD b/lib/python3.11/site-packages/shellingham-1.5.4.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..d3ba8380cb85c0f0347a35010e93735be83431ed
--- /dev/null
+++ b/lib/python3.11/site-packages/shellingham-1.5.4.dist-info/RECORD
@@ -0,0 +1,21 @@
+shellingham-1.5.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+shellingham-1.5.4.dist-info/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
+shellingham-1.5.4.dist-info/METADATA,sha256=GD2AIgo3STJieVc53TV8xbs_Sb05DMkZjVGA5UUaB_o,3461
+shellingham-1.5.4.dist-info/RECORD,,
+shellingham-1.5.4.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110
+shellingham-1.5.4.dist-info/top_level.txt,sha256=uKMQL5AKxPi4O9_Rbd838QeEs4ImpGQKNbEDZYqgBgk,12
+shellingham-1.5.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
+shellingham/__init__.py,sha256=pAKXUPKUdwyErC0ZjS-5w-fRdSbmdcfvnpt_x1yWqtA,635
+shellingham/__pycache__/__init__.cpython-311.pyc,,
+shellingham/__pycache__/_core.cpython-311.pyc,,
+shellingham/__pycache__/nt.cpython-311.pyc,,
+shellingham/_core.py,sha256=v-CTr_7F7cJAtNnzpa1N_Hl8afkY5yiDA4joGmsUBu0,300
+shellingham/nt.py,sha256=m6J6SuwyqVVlxXT9Bc-9F_1x-T5u0gCFFrRAF2LIkeg,4516
+shellingham/posix/__init__.py,sha256=pB69qtvZJ_yIf48nl4-ZfS3wLwwuXuknXOZhBnC2T1o,3129
+shellingham/posix/__pycache__/__init__.cpython-311.pyc,,
+shellingham/posix/__pycache__/_core.cpython-311.pyc,,
+shellingham/posix/__pycache__/proc.cpython-311.pyc,,
+shellingham/posix/__pycache__/ps.cpython-311.pyc,,
+shellingham/posix/_core.py,sha256=_v18UaXbzr4muNhr3-mH1FdSdjZ_dOXQrtUyomIbKYQ,81
+shellingham/posix/proc.py,sha256=nSUxIuQSotvaDW76i0oTQAM9aZ9PXBLFAEktWljSKCo,2659
+shellingham/posix/ps.py,sha256=NGmDKCukhNp0lahwYCaMXphBYaVbhbiR9BtE0OkT8qU,1770
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/characteristiczero.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/characteristiczero.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4495de33de8a0b671322d574c84f4255400c53ef
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/characteristiczero.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f26010d0fcc99c70cc7453345c932691918e5446
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/compositedomain.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/compositedomain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db14f9267825a95a42bdfc338096c327479a4049
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/compositedomain.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/domain.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/domain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f87535866a74a46cde0203e84ec03a64b741fd05
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/domain.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/domainelement.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/domainelement.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3844c160fb91c0f7057746ca2db6bc92fae31d57
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/domainelement.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/expressiondomain.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/expressiondomain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9034a81906aa186e71d6a5e967b1723236e8caa6
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/expressiondomain.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb4284a8d2e6ac407ba6c0bd460995cf9b75bed0
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/field.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/field.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3933130bea0a9f0b262687a69c4eee3fb5f03c82
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/field.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/finitefield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/finitefield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37cb5f4d51f462df4d92a9875fa5980cf94e4054
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/finitefield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40dca2176848e8502e1db9ab0f170890a9e810cb
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gaussiandomains.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gaussiandomains.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9194134fe6a3a64f1f998342101032359f4e2a0c
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gaussiandomains.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d25856f23405249cfe469f6cee852bad7642830
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..941a0e04a0884e858c70b4721ad9347c917c1482
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..489174bcb02997cb34038519a7694eafcf170333
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/groundtypes.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/groundtypes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9f4589d21b3a19ebfaab7cf3f27acc47998713a
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/groundtypes.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/integerring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/integerring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b2d1b89fed5a7607efc8f4725f9a0a33849b9f43
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/integerring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/modularinteger.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/modularinteger.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b9e0b8f8b6fbf49a313fe5d26946879471c1e88
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/modularinteger.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/mpelements.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/mpelements.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e755d92f4e319a69a2fac34c2bebc1a68a041131
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/mpelements.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/old_fractionfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/old_fractionfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..490655335c01fd9241f31ca4b0fb1af60b79fbed
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/old_fractionfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/old_polynomialring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/old_polynomialring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..408e13b8d3d9af733d90f104b850d50ce4b995fe
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/old_polynomialring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/polynomialring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/polynomialring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0eaff63a0b5ab6641fbcbdc0cbd2be93025452d5
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/polynomialring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonfinitefield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonfinitefield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11278e24544b38f98e496b6f63b1b77bcfbd3824
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonfinitefield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad20fa606eeb1b5b1bdf098b6461f4c152cfe528
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a3b2d6b1311c7900728b382b4a0c65245cf3964
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonrationalfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonrationalfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cb290ae4f5700f8b96a35ba9718577718b347cb
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/pythonrationalfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/quotientring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/quotientring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33d9a516b278315588a1334ad7677540d74fd987
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/quotientring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/rationalfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/rationalfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05338ae511a57b29f5618aefeba569f1d57dc5a2
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/rationalfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/realfield.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/realfield.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22277aa50743f32e51da8c9925a74a929d4e156a
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/realfield.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/ring.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/ring.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84ceff0160f5f868fc14b7414c29cde4508d5759
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/ring.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fb5a466197d570c757078f638ead6290c4b3c03
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__init__.py b/lib/python3.11/site-packages/sympy/polys/matrices/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4ebc3d71ba3dac9ccc695d046d6b3d2ad940fa1
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/__init__.py
@@ -0,0 +1,15 @@
+"""
+
+sympy.polys.matrices package.
+
+The main export from this package is the DomainMatrix class which is a
+lower-level implementation of matrices based on the polys Domains. This
+implementation is typically a lot faster than SymPy's standard Matrix class
+but is a work in progress and is still experimental.
+
+"""
+from .domainmatrix import DomainMatrix, DM
+
+__all__ = [
+    'DomainMatrix', 'DM',
+]
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fd88fc9cdfd40adc5d69aecb94d1fa70c02bd70
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/__init__.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/_dfm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/_dfm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..877f12521384a9fe2fbcec6a3d36b365ee322157
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/_dfm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cd10a97d4149fc0c2d7a563574dee5f8ba58137
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/_typing.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16e9d9e03e494f09b782c2d05075cd04ecbf8f46
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/ddm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abb8824ae650393f9601ac95a71a54f7059bb5e9
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/dense.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/dfm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/dfm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3c954746a8ae6022d92f9ac9496463463bae5eb
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/dfm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9aa080650cbe0be3b0717029ba6c92cce2e3a900
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/domainscalar.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07944378dd3c263b8537f029f0d9296bc6bc16f9
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/eigen.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e70a101e1935da18d48d8d681566482d9c3b5b4
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c017049c419f54b72431092a96a78a6d3139f7f1
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/linsolve.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4f433cbb9eb3a3773a448e2eee17c09f759ffab
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/lll.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16d11605a374ec8d4d5936ec3c1ced3a78797865
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/normalforms.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/rref.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/rref.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d14b781574a106ddf8046cf0280781b4adb4bbad
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/rref.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d633b4fe2d48b860bce6d16be85ce88916b7565
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/__pycache__/sdm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/_dfm.py b/lib/python3.11/site-packages/sympy/polys/matrices/_dfm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d84fe136e6db146a2570739aaa968ae94473f665
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/_dfm.py
@@ -0,0 +1,898 @@
+#
+# sympy.polys.matrices.dfm
+#
+# This modules defines the DFM class which is a wrapper for dense flint
+# matrices as found in python-flint.
+#
+# As of python-flint 0.4.1 matrices over the following domains can be supported
+# by python-flint:
+#
+#   ZZ: flint.fmpz_mat
+#   QQ: flint.fmpq_mat
+#   GF(p): flint.nmod_mat (p prime and p < ~2**62)
+#
+# The underlying flint library has many more domains, but these are not yet
+# supported by python-flint.
+#
+# The DFM class is a wrapper for the flint matrices and provides a common
+# interface for all supported domains that is interchangeable with the DDM
+# and SDM classes so that DomainMatrix can be used with any as its internal
+# matrix representation.
+#
+
+# TODO:
+#
+# Implement the following methods that are provided by python-flint:
+#
+# - hnf (Hermite normal form)
+# - snf (Smith normal form)
+# - minpoly
+# - is_hnf
+# - is_snf
+# - rank
+#
+# The other types DDM and SDM do not have these methods and the algorithms
+# for hnf, snf and rank are already implemented. Algorithms for minpoly,
+# is_hnf and is_snf would need to be added.
+#
+# Add more methods to python-flint to expose more of Flint's functionality
+# and also to make some of the above methods simpler or more efficient e.g.
+# slicing, fancy indexing etc.
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.external.importtools import import_module
+from sympy.utilities.decorator import doctest_depends_on
+
+from sympy.polys.domains import ZZ, QQ
+
+from .exceptions import (
+    DMBadInputError,
+    DMDomainError,
+    DMNonSquareMatrixError,
+    DMNonInvertibleMatrixError,
+    DMRankError,
+    DMShapeError,
+    DMValueError,
+)
+
+
+if GROUND_TYPES != 'flint':
+    __doctest_skip__ = ['*']
+
+
+flint = import_module('flint')
+
+
+__all__ = ['DFM']
+
+
+@doctest_depends_on(ground_types=['flint'])
+class DFM:
+    """
+    Dense FLINT matrix. This class is a wrapper for matrices from python-flint.
+
+    >>> from sympy.polys.domains import ZZ
+    >>> from sympy.polys.matrices.dfm import DFM
+    >>> dfm = DFM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    >>> dfm
+    [[1, 2], [3, 4]]
+    >>> dfm.rep
+    [1, 2]
+    [3, 4]
+    >>> type(dfm.rep)  # doctest: +SKIP
+    
+
+    Usually, the DFM class is not instantiated directly, but is created as the
+    internal representation of :class:`~.DomainMatrix`. When
+    `SYMPY_GROUND_TYPES` is set to `flint` and `python-flint` is installed, the
+    :class:`DFM` class is used automatically as the internal representation of
+    :class:`~.DomainMatrix` in dense format if the domain is supported by
+    python-flint.
+
+    >>> from sympy.polys.matrices.domainmatrix import DM
+    >>> dM = DM([[1, 2], [3, 4]], ZZ)
+    >>> dM.rep
+    [[1, 2], [3, 4]]
+
+    A :class:`~.DomainMatrix` can be converted to :class:`DFM` by calling the
+    :meth:`to_dfm` method:
+
+    >>> dM.to_dfm()
+    [[1, 2], [3, 4]]
+
+    """
+
+    fmt = 'dense'
+    is_DFM = True
+    is_DDM = False
+
+    def __new__(cls, rowslist, shape, domain):
+        """Construct from a nested list."""
+        flint_mat = cls._get_flint_func(domain)
+
+        if 0 not in shape:
+            try:
+                rep = flint_mat(rowslist)
+            except (ValueError, TypeError):
+                raise DMBadInputError(f"Input should be a list of list of {domain}")
+        else:
+            rep = flint_mat(*shape)
+
+        return cls._new(rep, shape, domain)
+
+    @classmethod
+    def _new(cls, rep, shape, domain):
+        """Internal constructor from a flint matrix."""
+        cls._check(rep, shape, domain)
+        obj = object.__new__(cls)
+        obj.rep = rep
+        obj.shape = obj.rows, obj.cols = shape
+        obj.domain = domain
+        return obj
+
+    def _new_rep(self, rep):
+        """Create a new DFM with the same shape and domain but a new rep."""
+        return self._new(rep, self.shape, self.domain)
+
+    @classmethod
+    def _check(cls, rep, shape, domain):
+        repshape = (rep.nrows(), rep.ncols())
+        if repshape != shape:
+            raise DMBadInputError("Shape of rep does not match shape of DFM")
+        if domain == ZZ and not isinstance(rep, flint.fmpz_mat):
+            raise RuntimeError("Rep is not a flint.fmpz_mat")
+        elif domain == QQ and not isinstance(rep, flint.fmpq_mat):
+            raise RuntimeError("Rep is not a flint.fmpq_mat")
+        elif domain not in (ZZ, QQ):
+            raise NotImplementedError("Only ZZ and QQ are supported by DFM")
+
+    @classmethod
+    def _supports_domain(cls, domain):
+        """Return True if the given domain is supported by DFM."""
+        return domain in (ZZ, QQ)
+
+    @classmethod
+    def _get_flint_func(cls, domain):
+        """Return the flint matrix class for the given domain."""
+        if domain == ZZ:
+            return flint.fmpz_mat
+        elif domain == QQ:
+            return flint.fmpq_mat
+        else:
+            raise NotImplementedError("Only ZZ and QQ are supported by DFM")
+
+    @property
+    def _func(self):
+        """Callable to create a flint matrix of the same domain."""
+        return self._get_flint_func(self.domain)
+
+    def __str__(self):
+        """Return ``str(self)``."""
+        return str(self.to_ddm())
+
+    def __repr__(self):
+        """Return ``repr(self)``."""
+        return f'DFM{repr(self.to_ddm())[3:]}'
+
+    def __eq__(self, other):
+        """Return ``self == other``."""
+        if not isinstance(other, DFM):
+            return NotImplemented
+        # Compare domains first because we do *not* want matrices with
+        # different domains to be equal but e.g. a flint fmpz_mat and fmpq_mat
+        # with the same entries will compare equal.
+        return self.domain == other.domain and self.rep == other.rep
+
+    @classmethod
+    def from_list(cls, rowslist, shape, domain):
+        """Construct from a nested list."""
+        return cls(rowslist, shape, domain)
+
+    def to_list(self):
+        """Convert to a nested list."""
+        return self.rep.tolist()
+
+    def copy(self):
+        """Return a copy of self."""
+        return self._new_rep(self._func(self.rep))
+
+    def to_ddm(self):
+        """Convert to a DDM."""
+        return DDM.from_list(self.to_list(), self.shape, self.domain)
+
+    def to_sdm(self):
+        """Convert to a SDM."""
+        return SDM.from_list(self.to_list(), self.shape, self.domain)
+
+    def to_dfm(self):
+        """Return self."""
+        return self
+
+    def to_dfm_or_ddm(self):
+        """
+        Convert to a :class:`DFM`.
+
+        This :class:`DFM` method exists to parallel the :class:`~.DDM` and
+        :class:`~.SDM` methods. For :class:`DFM` it will always return self.
+
+        See Also
+        ========
+
+        to_ddm
+        to_sdm
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm
+        """
+        return self
+
+    @classmethod
+    def from_ddm(cls, ddm):
+        """Convert from a DDM."""
+        return cls.from_list(ddm.to_list(), ddm.shape, ddm.domain)
+
+    @classmethod
+    def from_list_flat(cls, elements, shape, domain):
+        """Inverse of :meth:`to_list_flat`."""
+        func = cls._get_flint_func(domain)
+        try:
+            rep = func(*shape, elements)
+        except ValueError:
+            raise DMBadInputError(f"Incorrect number of elements for shape {shape}")
+        except TypeError:
+            raise DMBadInputError(f"Input should be a list of {domain}")
+        return cls(rep, shape, domain)
+
+    def to_list_flat(self):
+        """Convert to a flat list."""
+        return self.rep.entries()
+
+    def to_flat_nz(self):
+        """Convert to a flat list of non-zeros."""
+        return self.to_ddm().to_flat_nz()
+
+    @classmethod
+    def from_flat_nz(cls, elements, data, domain):
+        """Inverse of :meth:`to_flat_nz`."""
+        return DDM.from_flat_nz(elements, data, domain).to_dfm()
+
+    def to_dod(self):
+        """Convert to a DOD."""
+        return self.to_ddm().to_dod()
+
+    @classmethod
+    def from_dod(cls, dod, shape, domain):
+        """Inverse of :meth:`to_dod`."""
+        return DDM.from_dod(dod, shape, domain).to_dfm()
+
+    def to_dok(self):
+        """Convert to a DOK."""
+        return self.to_ddm().to_dok()
+
+    @classmethod
+    def from_dok(cls, dok, shape, domain):
+        """Inverse of :math:`to_dod`."""
+        return DDM.from_dok(dok, shape, domain).to_dfm()
+
+    def iter_values(self):
+        """Iterater over the non-zero values of the matrix."""
+        m, n = self.shape
+        rep = self.rep
+        for i in range(m):
+            for j in range(n):
+                repij = rep[i, j]
+                if repij:
+                    yield rep[i, j]
+
+    def iter_items(self):
+        """Iterate over indices and values of nonzero elements of the matrix."""
+        m, n = self.shape
+        rep = self.rep
+        for i in range(m):
+            for j in range(n):
+                repij = rep[i, j]
+                if repij:
+                    yield ((i, j), repij)
+
+    def convert_to(self, domain):
+        """Convert to a new domain."""
+        if domain == self.domain:
+            return self.copy()
+        elif domain == QQ and self.domain == ZZ:
+            return self._new(flint.fmpq_mat(self.rep), self.shape, domain)
+        elif domain == ZZ and self.domain == QQ:
+            # XXX: python-flint has no fmpz_mat.from_fmpq_mat
+            return self.to_ddm().convert_to(domain).to_dfm()
+        else:
+            # It is the callers responsibility to convert to DDM before calling
+            # this method if the domain is not supported by DFM.
+            raise NotImplementedError("Only ZZ and QQ are supported by DFM")
+
+    def getitem(self, i, j):
+        """Get the ``(i, j)``-th entry."""
+        # XXX: flint matrices do not support negative indices
+        # XXX: They also raise ValueError instead of IndexError
+        m, n = self.shape
+        if i < 0:
+            i += m
+        if j < 0:
+            j += n
+        try:
+            return self.rep[i, j]
+        except ValueError:
+            raise IndexError(f"Invalid indices ({i}, {j}) for Matrix of shape {self.shape}")
+
+    def setitem(self, i, j, value):
+        """Set the ``(i, j)``-th entry."""
+        # XXX: flint matrices do not support negative indices
+        # XXX: They also raise ValueError instead of IndexError
+        m, n = self.shape
+        if i < 0:
+            i += m
+        if j < 0:
+            j += n
+        try:
+            self.rep[i, j] = value
+        except ValueError:
+            raise IndexError(f"Invalid indices ({i}, {j}) for Matrix of shape {self.shape}")
+
+    def _extract(self, i_indices, j_indices):
+        """Extract a submatrix with no checking."""
+        # Indices must be positive and in range.
+        M = self.rep
+        lol = [[M[i, j] for j in j_indices] for i in i_indices]
+        shape = (len(i_indices), len(j_indices))
+        return self.from_list(lol, shape, self.domain)
+
+    def extract(self, rowslist, colslist):
+        """Extract a submatrix."""
+        # XXX: flint matrices do not support fancy indexing or negative indices
+        #
+        # Check and convert negative indices before calling _extract.
+        m, n = self.shape
+
+        new_rows = []
+        new_cols = []
+
+        for i in rowslist:
+            if i < 0:
+                i_pos = i + m
+            else:
+                i_pos = i
+            if not 0 <= i_pos < m:
+                raise IndexError(f"Invalid row index {i} for Matrix of shape {self.shape}")
+            new_rows.append(i_pos)
+
+        for j in colslist:
+            if j < 0:
+                j_pos = j + n
+            else:
+                j_pos = j
+            if not 0 <= j_pos < n:
+                raise IndexError(f"Invalid column index {j} for Matrix of shape {self.shape}")
+            new_cols.append(j_pos)
+
+        return self._extract(new_rows, new_cols)
+
+    def extract_slice(self, rowslice, colslice):
+        """Slice a DFM."""
+        # XXX: flint matrices do not support slicing
+        m, n = self.shape
+        i_indices = range(m)[rowslice]
+        j_indices = range(n)[colslice]
+        return self._extract(i_indices, j_indices)
+
+    def neg(self):
+        """Negate a DFM matrix."""
+        return self._new_rep(-self.rep)
+
+    def add(self, other):
+        """Add two DFM matrices."""
+        return self._new_rep(self.rep + other.rep)
+
+    def sub(self, other):
+        """Subtract two DFM matrices."""
+        return self._new_rep(self.rep - other.rep)
+
+    def mul(self, other):
+        """Multiply a DFM matrix from the right by a scalar."""
+        return self._new_rep(self.rep * other)
+
+    def rmul(self, other):
+        """Multiply a DFM matrix from the left by a scalar."""
+        return self._new_rep(other * self.rep)
+
+    def mul_elementwise(self, other):
+        """Elementwise multiplication of two DFM matrices."""
+        # XXX: flint matrices do not support elementwise multiplication
+        return self.to_ddm().mul_elementwise(other.to_ddm()).to_dfm()
+
+    def matmul(self, other):
+        """Multiply two DFM matrices."""
+        shape = (self.rows, other.cols)
+        return self._new(self.rep * other.rep, shape, self.domain)
+
+    # XXX: For the most part DomainMatrix does not expect DDM, SDM, or DFM to
+    # have arithmetic operators defined. The only exception is negation.
+    # Perhaps that should be removed.
+
+    def __neg__(self):
+        """Negate a DFM matrix."""
+        return self.neg()
+
+    @classmethod
+    def zeros(cls, shape, domain):
+        """Return a zero DFM matrix."""
+        func = cls._get_flint_func(domain)
+        return cls._new(func(*shape), shape, domain)
+
+    # XXX: flint matrices do not have anything like ones or eye
+    # In the methods below we convert to DDM and then back to DFM which is
+    # probably about as efficient as implementing these methods directly.
+
+    @classmethod
+    def ones(cls, shape, domain):
+        """Return a one DFM matrix."""
+        # XXX: flint matrices do not have anything like ones
+        return DDM.ones(shape, domain).to_dfm()
+
+    @classmethod
+    def eye(cls, n, domain):
+        """Return the identity matrix of size n."""
+        # XXX: flint matrices do not have anything like eye
+        return DDM.eye(n, domain).to_dfm()
+
+    @classmethod
+    def diag(cls, elements, domain):
+        """Return a diagonal matrix."""
+        return DDM.diag(elements, domain).to_dfm()
+
+    def applyfunc(self, func, domain):
+        """Apply a function to each entry of a DFM matrix."""
+        return self.to_ddm().applyfunc(func, domain).to_dfm()
+
+    def transpose(self):
+        """Transpose a DFM matrix."""
+        return self._new(self.rep.transpose(), (self.cols, self.rows), self.domain)
+
+    def hstack(self, *others):
+        """Horizontally stack matrices."""
+        return self.to_ddm().hstack(*[o.to_ddm() for o in others]).to_dfm()
+
+    def vstack(self, *others):
+        """Vertically stack matrices."""
+        return self.to_ddm().vstack(*[o.to_ddm() for o in others]).to_dfm()
+
+    def diagonal(self):
+        """Return the diagonal of a DFM matrix."""
+        M = self.rep
+        m, n = self.shape
+        return [M[i, i] for i in range(min(m, n))]
+
+    def is_upper(self):
+        """Return ``True`` if the matrix is upper triangular."""
+        M = self.rep
+        for i in range(self.rows):
+            for j in range(i):
+                if M[i, j]:
+                    return False
+        return True
+
+    def is_lower(self):
+        """Return ``True`` if the matrix is lower triangular."""
+        M = self.rep
+        for i in range(self.rows):
+            for j in range(i + 1, self.cols):
+                if M[i, j]:
+                    return False
+        return True
+
+    def is_diagonal(self):
+        """Return ``True`` if the matrix is diagonal."""
+        return self.is_upper() and self.is_lower()
+
+    def is_zero_matrix(self):
+        """Return ``True`` if the matrix is the zero matrix."""
+        M = self.rep
+        for i in range(self.rows):
+            for j in range(self.cols):
+                if M[i, j]:
+                    return False
+        return True
+
+    def nnz(self):
+        """Return the number of non-zero elements in the matrix."""
+        return self.to_ddm().nnz()
+
+    def scc(self):
+        """Return the strongly connected components of the matrix."""
+        return self.to_ddm().scc()
+
+    @doctest_depends_on(ground_types='flint')
+    def det(self):
+        """
+        Compute the determinant of the matrix using FLINT.
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix
+        >>> M = Matrix([[1, 2], [3, 4]])
+        >>> dfm = M.to_DM().to_dfm()
+        >>> dfm
+        [[1, 2], [3, 4]]
+        >>> dfm.det()
+        -2
+
+        Notes
+        =====
+
+        Calls the ``.det()`` method of the underlying FLINT matrix.
+
+        For :ref:`ZZ` or :ref:`QQ` this calls ``fmpz_mat_det`` or
+        ``fmpq_mat_det`` respectively.
+
+        At the time of writing the implementation of ``fmpz_mat_det`` uses one
+        of several algorithms depending on the size of the matrix and bit size
+        of the entries. The algorithms used are:
+
+        - Cofactor for very small (up to 4x4) matrices.
+        - Bareiss for small (up to 25x25) matrices.
+        - Modular algorithms for larger matrices (up to 60x60) or for larger
+          matrices with large bit sizes.
+        - Modular "accelerated" for larger matrices (60x60 upwards) if the bit
+          size is smaller than the dimensions of the matrix.
+
+        The implementation of ``fmpq_mat_det`` clears denominators from each
+        row (not the whole matrix) and then calls ``fmpz_mat_det`` and divides
+        by the product of the denominators.
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.det
+            Higher level interface to compute the determinant of a matrix.
+        """
+        # XXX: At least the first three algorithms described above should also
+        # be implemented in the pure Python DDM and SDM classes which at the
+        # time of writng just use Bareiss for all matrices and domains.
+        # Probably in Python the thresholds would be different though.
+        return self.rep.det()
+
+    @doctest_depends_on(ground_types='flint')
+    def charpoly(self):
+        """
+        Compute the characteristic polynomial of the matrix using FLINT.
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix
+        >>> M = Matrix([[1, 2], [3, 4]])
+        >>> dfm = M.to_DM().to_dfm()  # need ground types = 'flint'
+        >>> dfm
+        [[1, 2], [3, 4]]
+        >>> dfm.charpoly()
+        [1, -5, -2]
+
+        Notes
+        =====
+
+        Calls the ``.charpoly()`` method of the underlying FLINT matrix.
+
+        For :ref:`ZZ` or :ref:`QQ` this calls ``fmpz_mat_charpoly`` or
+        ``fmpq_mat_charpoly`` respectively.
+
+        At the time of writing the implementation of ``fmpq_mat_charpoly``
+        clears a denominator from the whole matrix and then calls
+        ``fmpz_mat_charpoly``. The coefficients of the characteristic
+        polynomial are then multiplied by powers of the denominator.
+
+        The ``fmpz_mat_charpoly`` method uses a modular algorithm with CRT
+        reconstruction. The modular algorithm uses ``nmod_mat_charpoly`` which
+        uses Berkowitz for small matrices and non-prime moduli or otherwise
+        the Danilevsky method.
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly
+            Higher level interface to compute the characteristic polynomial of
+            a matrix.
+        """
+        # FLINT polynomial coefficients are in reverse order compared to SymPy.
+        return self.rep.charpoly().coeffs()[::-1]
+
+    @doctest_depends_on(ground_types='flint')
+    def inv(self):
+        """
+        Compute the inverse of a matrix using FLINT.
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix, QQ
+        >>> M = Matrix([[1, 2], [3, 4]])
+        >>> dfm = M.to_DM().to_dfm().convert_to(QQ)
+        >>> dfm
+        [[1, 2], [3, 4]]
+        >>> dfm.inv()
+        [[-2, 1], [3/2, -1/2]]
+        >>> dfm.matmul(dfm.inv())
+        [[1, 0], [0, 1]]
+
+        Notes
+        =====
+
+        Calls the ``.inv()`` method of the underlying FLINT matrix.
+
+        For now this will raise an error if the domain is :ref:`ZZ` but will
+        use the FLINT method for :ref:`QQ`.
+
+        The FLINT methods for :ref:`ZZ` and :ref:`QQ` are ``fmpz_mat_inv`` and
+        ``fmpq_mat_inv`` respectively. The ``fmpz_mat_inv`` method computes an
+        inverse with denominator. This is implemented by calling
+        ``fmpz_mat_solve`` (see notes in :meth:`lu_solve` about the algorithm).
+
+        The ``fmpq_mat_inv`` method clears denominators from each row and then
+        multiplies those into the rhs identity matrix before calling
+        ``fmpz_mat_solve``.
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.inv
+            Higher level method for computing the inverse of a matrix.
+        """
+        # TODO: Implement similar algorithms for DDM and SDM.
+        #
+        # XXX: The flint fmpz_mat and fmpq_mat inv methods both return fmpq_mat
+        # by default. The fmpz_mat method has an optional argument to return
+        # fmpz_mat instead for unimodular matrices.
+        #
+        # The convention in DomainMatrix is to raise an error if the matrix is
+        # not over a field regardless of whether the matrix is invertible over
+        # its domain or over any associated field. Maybe DomainMatrix.inv
+        # should be changed to always return a matrix over an associated field
+        # except with a unimodular argument for returning an inverse over a
+        # ring if possible.
+        #
+        # For now we follow the existing DomainMatrix convention...
+        K = self.domain
+        m, n = self.shape
+
+        if m != n:
+            raise DMNonSquareMatrixError("cannot invert a non-square matrix")
+
+        if K == ZZ:
+            raise DMDomainError("field expected, got %s" % K)
+        elif K == QQ:
+            try:
+                return self._new_rep(self.rep.inv())
+            except ZeroDivisionError:
+                raise DMNonInvertibleMatrixError("matrix is not invertible")
+        else:
+            # If more domains are added for DFM then we will need to consider
+            # what happens here.
+            raise NotImplementedError("DFM.inv() is not implemented for %s" % K)
+
+    def lu(self):
+        """Return the LU decomposition of the matrix."""
+        L, U, swaps = self.to_ddm().lu()
+        return L.to_dfm(), U.to_dfm(), swaps
+
+    # XXX: The lu_solve function should be renamed to solve. Whether or not it
+    # uses an LU decomposition is an implementation detail. A method called
+    # lu_solve would make sense for a situation in which an LU decomposition is
+    # reused several times to solve iwth different rhs but that would imply a
+    # different call signature.
+    #
+    # The underlying python-flint method has an algorithm= argument so we could
+    # use that and have e.g. solve_lu and solve_modular or perhaps also a
+    # method= argument to choose between the two. Flint itself has more
+    # possible algorithms to choose from than are exposed by python-flint.
+
+    @doctest_depends_on(ground_types='flint')
+    def lu_solve(self, rhs):
+        """
+        Solve a matrix equation using FLINT.
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix, QQ
+        >>> M = Matrix([[1, 2], [3, 4]])
+        >>> dfm = M.to_DM().to_dfm().convert_to(QQ)
+        >>> dfm
+        [[1, 2], [3, 4]]
+        >>> rhs = Matrix([1, 2]).to_DM().to_dfm().convert_to(QQ)
+        >>> dfm.lu_solve(rhs)
+        [[0], [1/2]]
+
+        Notes
+        =====
+
+        Calls the ``.solve()`` method of the underlying FLINT matrix.
+
+        For now this will raise an error if the domain is :ref:`ZZ` but will
+        use the FLINT method for :ref:`QQ`.
+
+        The FLINT methods for :ref:`ZZ` and :ref:`QQ` are ``fmpz_mat_solve``
+        and ``fmpq_mat_solve`` respectively. The ``fmpq_mat_solve`` method
+        uses one of two algorithms:
+
+        - For small matrices (<25 rows) it clears denominators between the
+          matrix and rhs and uses ``fmpz_mat_solve``.
+        - For larger matrices it uses ``fmpq_mat_solve_dixon`` which is a
+          modular approach with CRT reconstruction over :ref:`QQ`.
+
+        The ``fmpz_mat_solve`` method uses one of four algorithms:
+
+        - For very small (<= 3x3) matrices it uses a Cramer's rule.
+        - For small (<= 15x15) matrices it uses a fraction-free LU solve.
+        - Otherwise it uses either Dixon or another multimodular approach.
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.lu_solve
+            Higher level interface to solve a matrix equation.
+        """
+        if not self.domain == rhs.domain:
+            raise DMDomainError("Domains must match: %s != %s" % (self.domain, rhs.domain))
+
+        # XXX: As for inv we should consider whether to return a matrix over
+        # over an associated field or attempt to find a solution in the ring.
+        # For now we follow the existing DomainMatrix convention...
+        if not self.domain.is_Field:
+            raise DMDomainError("Field expected, got %s" % self.domain)
+
+        m, n = self.shape
+        j, k = rhs.shape
+        if m != j:
+            raise DMShapeError("Matrix size mismatch: %s * %s vs %s * %s" % (m, n, j, k))
+        sol_shape = (n, k)
+
+        # XXX: The Flint solve method only handles square matrices. Probably
+        # Flint has functions that could be used to solve non-square systems
+        # but they are not exposed in python-flint yet. Alternatively we could
+        # put something here using the features that are available like rref.
+        if m != n:
+            return self.to_ddm().lu_solve(rhs.to_ddm()).to_dfm()
+
+        try:
+            sol = self.rep.solve(rhs.rep)
+        except ZeroDivisionError:
+            raise DMNonInvertibleMatrixError("Matrix det == 0; not invertible.")
+
+        return self._new(sol, sol_shape, self.domain)
+
+    def nullspace(self):
+        """Return a basis for the nullspace of the matrix."""
+        # Code to compute nullspace using flint:
+        #
+        # V, nullity = self.rep.nullspace()
+        # V_dfm = self._new_rep(V)._extract(range(self.rows), range(nullity))
+        #
+        # XXX: That gives the nullspace but does not give us nonpivots. So we
+        # use the slower DDM method anyway. It would be better to change the
+        # signature of the nullspace method to not return nonpivots.
+        #
+        # XXX: Also python-flint exposes a nullspace method for fmpz_mat but
+        # not for fmpq_mat. This is the reverse of the situation for DDM etc
+        # which only allow nullspace over a field. The nullspace method for
+        # DDM, SDM etc should be changed to allow nullspace over ZZ as well.
+        # The DomainMatrix nullspace method does allow the domain to be a ring
+        # but does not directly call the lower-level nullspace methods and uses
+        # rref_den instead. Nullspace methods should also be added to all
+        # matrix types in python-flint.
+        ddm, nonpivots = self.to_ddm().nullspace()
+        return ddm.to_dfm(), nonpivots
+
+    def nullspace_from_rref(self, pivots=None):
+        """Return a basis for the nullspace of the matrix."""
+        # XXX: Use the flint nullspace method!!!
+        sdm, nonpivots = self.to_sdm().nullspace_from_rref(pivots=pivots)
+        return sdm.to_dfm(), nonpivots
+
+    def particular(self):
+        """Return a particular solution to the system."""
+        return self.to_ddm().particular().to_dfm()
+
+    def _lll(self, transform=False, delta=0.99, eta=0.51, rep='zbasis', gram='approx'):
+        """Call the fmpz_mat.lll() method but check rank to avoid segfaults."""
+
+        # XXX: There are tests that pass e.g. QQ(5,6) for delta. That fails
+        # with a TypeError in flint because if QQ is fmpq then conversion with
+        # float fails. We handle that here but there are two better fixes:
+        #
+        # - Make python-flint's fmpq convert with float(x)
+        # - Change the tests because delta should just be a float.
+
+        def to_float(x):
+            if QQ.of_type(x):
+                return float(x.numerator) / float(x.denominator)
+            else:
+                return float(x)
+
+        delta = to_float(delta)
+        eta = to_float(eta)
+
+        if not 0.25 < delta < 1:
+            raise DMValueError("delta must be between 0.25 and 1")
+
+        # XXX: The flint lll method segfaults if the matrix is not full rank.
+        m, n = self.shape
+        if self.rep.rank() != m:
+            raise DMRankError("Matrix must have full row rank for Flint LLL.")
+
+        # Actually call the flint method.
+        return self.rep.lll(transform=transform, delta=delta, eta=eta, rep=rep, gram=gram)
+
+    @doctest_depends_on(ground_types='flint')
+    def lll(self, delta=0.75):
+        """Compute LLL-reduced basis using FLINT.
+
+        See :meth:`lll_transform` for more information.
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix
+        >>> M = Matrix([[1, 2, 3], [4, 5, 6]])
+        >>> M.to_DM().to_dfm().lll()
+        [[2, 1, 0], [-1, 1, 3]]
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.lll
+            Higher level interface to compute LLL-reduced basis.
+        lll_transform
+            Compute LLL-reduced basis and transform matrix.
+        """
+        if self.domain != ZZ:
+            raise DMDomainError("ZZ expected, got %s" % self.domain)
+        elif self.rows > self.cols:
+            raise DMShapeError("Matrix must not have more rows than columns.")
+
+        rep = self._lll(delta=delta)
+        return self._new_rep(rep)
+
+    @doctest_depends_on(ground_types='flint')
+    def lll_transform(self, delta=0.75):
+        """Compute LLL-reduced basis and transform using FLINT.
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix
+        >>> M = Matrix([[1, 2, 3], [4, 5, 6]]).to_DM().to_dfm()
+        >>> M_lll, T = M.lll_transform()
+        >>> M_lll
+        [[2, 1, 0], [-1, 1, 3]]
+        >>> T
+        [[-2, 1], [3, -1]]
+        >>> T.matmul(M) == M_lll
+        True
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.lll
+            Higher level interface to compute LLL-reduced basis.
+        lll
+            Compute LLL-reduced basis without transform matrix.
+        """
+        if self.domain != ZZ:
+            raise DMDomainError("ZZ expected, got %s" % self.domain)
+        elif self.rows > self.cols:
+            raise DMShapeError("Matrix must not have more rows than columns.")
+
+        rep, T = self._lll(transform=True, delta=delta)
+        basis = self._new_rep(rep)
+        T_dfm = self._new(T, (self.rows, self.rows), self.domain)
+        return basis, T_dfm
+
+
+# Avoid circular imports
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.ddm import SDM
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/_typing.py b/lib/python3.11/site-packages/sympy/polys/matrices/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc7c3b601fe85d591ddf853acbf33f5bba64b11c
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/_typing.py
@@ -0,0 +1,16 @@
+from typing import TypeVar, Protocol
+
+
+T = TypeVar('T')
+
+
+class RingElement(Protocol):
+    """A ring element.
+
+    Must support ``+``, ``-``, ``*``, ``**`` and ``-``.
+    """
+    def __add__(self: T, other: T, /) -> T: ...
+    def __sub__(self: T, other: T, /) -> T: ...
+    def __mul__(self: T, other: T, /) -> T: ...
+    def __pow__(self: T, other: int, /) -> T: ...
+    def __neg__(self: T, /) -> T: ...
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/ddm.py b/lib/python3.11/site-packages/sympy/polys/matrices/ddm.py
new file mode 100644
index 0000000000000000000000000000000000000000..77d02b8ad5a0a5ced07d2144b4a11337a705cff8
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/ddm.py
@@ -0,0 +1,1029 @@
+"""
+
+Module for the DDM class.
+
+The DDM class is an internal representation used by DomainMatrix. The letters
+DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using
+elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix
+representation.
+
+Basic usage:
+
+    >>> from sympy import ZZ, QQ
+    >>> from sympy.polys.matrices.ddm import DDM
+    >>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
+    >>> A.shape
+    (2, 2)
+    >>> A
+    [[0, 1], [-1, 0]]
+    >>> type(A)
+    
+    >>> A @ A
+    [[-1, 0], [0, -1]]
+
+The ddm_* functions are designed to operate on DDM as well as on an ordinary
+list of lists:
+
+    >>> from sympy.polys.matrices.dense import ddm_idet
+    >>> ddm_idet(A, QQ)
+    1
+    >>> ddm_idet([[0, 1], [-1, 0]], QQ)
+    1
+    >>> A
+    [[-1, 0], [0, -1]]
+
+Note that ddm_idet modifies the input matrix in-place. It is recommended to
+use the DDM.det method as a friendlier interface to this instead which takes
+care of copying the matrix:
+
+    >>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
+    >>> B.det()
+    1
+
+Normally DDM would not be used directly and is just part of the internal
+representation of DomainMatrix which adds further functionality including e.g.
+unifying domains.
+
+The dense format used by DDM is a list of lists of elements e.g. the 2x2
+identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass
+of list and its list items are plain lists. Elements are accessed as e.g.
+ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the
+jth column of that row. Subclassing list makes e.g. iteration and indexing
+very efficient. We do not override __getitem__ because it would lose that
+benefit.
+
+The core routines are implemented by the ddm_* functions defined in dense.py.
+Those functions are intended to be able to operate on a raw list-of-lists
+representation of matrices with most functions operating in-place. The DDM
+class takes care of copying etc and also stores a Domain object associated
+with its elements. This makes it possible to implement things like A + B with
+domain checking and also shape checking so that the list of lists
+representation is friendlier.
+
+"""
+from itertools import chain
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.utilities.decorator import doctest_depends_on
+
+from .exceptions import (
+    DMBadInputError,
+    DMDomainError,
+    DMNonSquareMatrixError,
+    DMShapeError,
+)
+
+from sympy.polys.domains import QQ
+
+from .dense import (
+        ddm_transpose,
+        ddm_iadd,
+        ddm_isub,
+        ddm_ineg,
+        ddm_imul,
+        ddm_irmul,
+        ddm_imatmul,
+        ddm_irref,
+        ddm_irref_den,
+        ddm_idet,
+        ddm_iinv,
+        ddm_ilu_split,
+        ddm_ilu_solve,
+        ddm_berk,
+        )
+
+from .lll import ddm_lll, ddm_lll_transform
+
+
+if GROUND_TYPES != 'flint':
+    __doctest_skip__ = ['DDM.to_dfm', 'DDM.to_dfm_or_ddm']
+
+
+class DDM(list):
+    """Dense matrix based on polys domain elements
+
+    This is a list subclass and is a wrapper for a list of lists that supports
+    basic matrix arithmetic +, -, *, **.
+    """
+
+    fmt = 'dense'
+    is_DFM = False
+    is_DDM = True
+
+    def __init__(self, rowslist, shape, domain):
+        if not (isinstance(rowslist, list) and all(type(row) is list for row in rowslist)):
+            raise DMBadInputError("rowslist must be a list of lists")
+        m, n = shape
+        if len(rowslist) != m or any(len(row) != n for row in rowslist):
+            raise DMBadInputError("Inconsistent row-list/shape")
+
+        super().__init__(rowslist)
+        self.shape = (m, n)
+        self.rows = m
+        self.cols = n
+        self.domain = domain
+
+    def getitem(self, i, j):
+        return self[i][j]
+
+    def setitem(self, i, j, value):
+        self[i][j] = value
+
+    def extract_slice(self, slice1, slice2):
+        ddm = [row[slice2] for row in self[slice1]]
+        rows = len(ddm)
+        cols = len(ddm[0]) if ddm else len(range(self.shape[1])[slice2])
+        return DDM(ddm, (rows, cols), self.domain)
+
+    def extract(self, rows, cols):
+        ddm = []
+        for i in rows:
+            rowi = self[i]
+            ddm.append([rowi[j] for j in cols])
+        return DDM(ddm, (len(rows), len(cols)), self.domain)
+
+    @classmethod
+    def from_list(cls, rowslist, shape, domain):
+        """
+        Create a :class:`DDM` from a list of lists.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> A = DDM.from_list([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
+        >>> A
+        [[0, 1], [-1, 0]]
+        >>> A == DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ)
+        True
+
+        See Also
+        ========
+
+        from_list_flat
+        """
+        return cls(rowslist, shape, domain)
+
+    @classmethod
+    def from_ddm(cls, other):
+        return other.copy()
+
+    def to_list(self):
+        """
+        Convert to a list of lists.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_list()
+        [[1, 2], [3, 4]]
+
+        See Also
+        ========
+
+        to_list_flat
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_list
+        """
+        return list(self)
+
+    def to_list_flat(self):
+        """
+        Convert to a flat list of elements.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_list_flat()
+        [1, 2, 3, 4]
+        >>> A == DDM.from_list_flat(A.to_list_flat(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_list_flat
+        """
+        flat = []
+        for row in self:
+            flat.extend(row)
+        return flat
+
+    @classmethod
+    def from_list_flat(cls, flat, shape, domain):
+        """
+        Create a :class:`DDM` from a flat list of elements.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> A = DDM.from_list_flat([1, 2, 3, 4], (2, 2), QQ)
+        >>> A
+        [[1, 2], [3, 4]]
+        >>> A == DDM.from_list_flat(A.to_list_flat(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        to_list_flat
+        sympy.polys.matrices.domainmatrix.DomainMatrix.from_list_flat
+        """
+        assert type(flat) is list
+        rows, cols = shape
+        if not (len(flat) == rows*cols):
+            raise DMBadInputError("Inconsistent flat-list shape")
+        lol = [flat[i*cols:(i+1)*cols] for i in range(rows)]
+        return cls(lol, shape, domain)
+
+    def flatiter(self):
+        return chain.from_iterable(self)
+
+    def flat(self):
+        items = []
+        for row in self:
+            items.extend(row)
+        return items
+
+    def to_flat_nz(self):
+        """
+        Convert to a flat list of nonzero elements and data.
+
+        Explanation
+        ===========
+
+        This is used to operate on a list of the elements of a matrix and then
+        reconstruct a matrix using :meth:`from_flat_nz`. Zero elements are
+        included in the list but that may change in the future.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> elements, data = A.to_flat_nz()
+        >>> elements
+        [1, 2, 3, 4]
+        >>> A == DDM.from_flat_nz(elements, data, A.domain)
+        True
+
+        See Also
+        ========
+
+        from_flat_nz
+        sympy.polys.matrices.sdm.SDM.to_flat_nz
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_flat_nz
+        """
+        return self.to_sdm().to_flat_nz()
+
+    @classmethod
+    def from_flat_nz(cls, elements, data, domain):
+        """
+        Reconstruct a :class:`DDM` after calling :meth:`to_flat_nz`.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> elements, data = A.to_flat_nz()
+        >>> elements
+        [1, 2, 3, 4]
+        >>> A == DDM.from_flat_nz(elements, data, A.domain)
+        True
+
+        See Also
+        ========
+
+        to_flat_nz
+        sympy.polys.matrices.sdm.SDM.from_flat_nz
+        sympy.polys.matrices.domainmatrix.DomainMatrix.from_flat_nz
+        """
+        return SDM.from_flat_nz(elements, data, domain).to_ddm()
+
+    def to_dod(self):
+        """
+        Convert to a dictionary of dictionaries (dod) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_dod()
+        {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}
+
+        See Also
+        ========
+
+        from_dod
+        sympy.polys.matrices.sdm.SDM.to_dod
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dod
+        """
+        dod = {}
+        for i, row in enumerate(self):
+            row = {j:e for j, e in enumerate(row) if e}
+            if row:
+                dod[i] = row
+        return dod
+
+    @classmethod
+    def from_dod(cls, dod, shape, domain):
+        """
+        Create a :class:`DDM` from a dictionary of dictionaries (dod) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> dod = {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}
+        >>> A = DDM.from_dod(dod, (2, 2), QQ)
+        >>> A
+        [[1, 2], [3, 4]]
+
+        See Also
+        ========
+
+        to_dod
+        sympy.polys.matrices.sdm.SDM.from_dod
+        sympy.polys.matrices.domainmatrix.DomainMatrix.from_dod
+        """
+        rows, cols = shape
+        lol = [[domain.zero] * cols for _ in range(rows)]
+        for i, row in dod.items():
+            for j, element in row.items():
+                lol[i][j] = element
+        return DDM(lol, shape, domain)
+
+    def to_dok(self):
+        """
+        Convert :class:`DDM` to dictionary of keys (dok) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_dok()
+        {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}
+
+        See Also
+        ========
+
+        from_dok
+        sympy.polys.matrices.sdm.SDM.to_dok
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dok
+        """
+        dok = {}
+        for i, row in enumerate(self):
+            for j, element in enumerate(row):
+                if element:
+                    dok[i, j] = element
+        return dok
+
+    @classmethod
+    def from_dok(cls, dok, shape, domain):
+        """
+        Create a :class:`DDM` from a dictionary of keys (dok) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> dok = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}
+        >>> A = DDM.from_dok(dok, (2, 2), QQ)
+        >>> A
+        [[1, 2], [3, 4]]
+
+        See Also
+        ========
+
+        to_dok
+        sympy.polys.matrices.sdm.SDM.from_dok
+        sympy.polys.matrices.domainmatrix.DomainMatrix.from_dok
+        """
+        rows, cols = shape
+        lol = [[domain.zero] * cols for _ in range(rows)]
+        for (i, j), element in dok.items():
+            lol[i][j] = element
+        return DDM(lol, shape, domain)
+
+    def iter_values(self):
+        """
+        Iterater over the non-zero values of the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[QQ(1), QQ(0)], [QQ(3), QQ(4)]], (2, 2), QQ)
+        >>> list(A.iter_values())
+        [1, 3, 4]
+
+        See Also
+        ========
+
+        iter_items
+        to_list_flat
+        sympy.polys.matrices.domainmatrix.DomainMatrix.iter_values
+        """
+        for row in self:
+            yield from filter(None, row)
+
+    def iter_items(self):
+        """
+        Iterate over indices and values of nonzero elements of the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[QQ(1), QQ(0)], [QQ(3), QQ(4)]], (2, 2), QQ)
+        >>> list(A.iter_items())
+        [((0, 0), 1), ((1, 0), 3), ((1, 1), 4)]
+
+        See Also
+        ========
+
+        iter_values
+        to_dok
+        sympy.polys.matrices.domainmatrix.DomainMatrix.iter_items
+        """
+        for i, row in enumerate(self):
+            for j, element in enumerate(row):
+                if element:
+                    yield (i, j), element
+
+    def to_ddm(self):
+        """
+        Convert to a :class:`DDM`.
+
+        This just returns ``self`` but exists to parallel the corresponding
+        method in other matrix types like :class:`~.SDM`.
+
+        See Also
+        ========
+
+        to_sdm
+        to_dfm
+        to_dfm_or_ddm
+        sympy.polys.matrices.sdm.SDM.to_ddm
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_ddm
+        """
+        return self
+
+    def to_sdm(self):
+        """
+        Convert to a :class:`~.SDM`.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_sdm()
+        {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}
+        >>> type(A.to_sdm())
+        
+
+        See Also
+        ========
+
+        SDM
+        sympy.polys.matrices.sdm.SDM.to_ddm
+        """
+        return SDM.from_list(self, self.shape, self.domain)
+
+    @doctest_depends_on(ground_types=['flint'])
+    def to_dfm(self):
+        """
+        Convert to :class:`~.DDM` to :class:`~.DFM`.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_dfm()
+        [[1, 2], [3, 4]]
+        >>> type(A.to_dfm())
+        
+
+        See Also
+        ========
+
+        DFM
+        sympy.polys.matrices._dfm.DFM.to_ddm
+        """
+        return DFM(list(self), self.shape, self.domain)
+
+    @doctest_depends_on(ground_types=['flint'])
+    def to_dfm_or_ddm(self):
+        """
+        Convert to :class:`~.DFM` if possible or otherwise return self.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy import QQ
+        >>> A = DDM([[1, 2], [3, 4]], (2, 2), QQ)
+        >>> A.to_dfm_or_ddm()
+        [[1, 2], [3, 4]]
+        >>> type(A.to_dfm_or_ddm())
+        
+
+        See Also
+        ========
+
+        to_dfm
+        to_ddm
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm
+        """
+        if DFM._supports_domain(self.domain):
+            return self.to_dfm()
+        return self
+
+    def convert_to(self, K):
+        Kold = self.domain
+        if K == Kold:
+            return self.copy()
+        rows = [[K.convert_from(e, Kold) for e in row] for row in self]
+        return DDM(rows, self.shape, K)
+
+    def __str__(self):
+        rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self]
+        return '[%s]' % ', '.join(rowsstr)
+
+    def __repr__(self):
+        cls = type(self).__name__
+        rows = list.__repr__(self)
+        return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
+
+    def __eq__(self, other):
+        if not isinstance(other, DDM):
+            return False
+        return (super().__eq__(other) and self.domain == other.domain)
+
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
+    @classmethod
+    def zeros(cls, shape, domain):
+        z = domain.zero
+        m, n = shape
+        rowslist = [[z] * n for _ in range(m)]
+        return DDM(rowslist, shape, domain)
+
+    @classmethod
+    def ones(cls, shape, domain):
+        one = domain.one
+        m, n = shape
+        rowlist = [[one] * n for _ in range(m)]
+        return DDM(rowlist, shape, domain)
+
+    @classmethod
+    def eye(cls, size, domain):
+        if isinstance(size, tuple):
+            m, n = size
+        elif isinstance(size, int):
+            m = n = size
+        one = domain.one
+        ddm = cls.zeros((m, n), domain)
+        for i in range(min(m, n)):
+            ddm[i][i] = one
+        return ddm
+
+    def copy(self):
+        copyrows = [row[:] for row in self]
+        return DDM(copyrows, self.shape, self.domain)
+
+    def transpose(self):
+        rows, cols = self.shape
+        if rows:
+            ddmT = ddm_transpose(self)
+        else:
+            ddmT = [[]] * cols
+        return DDM(ddmT, (cols, rows), self.domain)
+
+    def __add__(a, b):
+        if not isinstance(b, DDM):
+            return NotImplemented
+        return a.add(b)
+
+    def __sub__(a, b):
+        if not isinstance(b, DDM):
+            return NotImplemented
+        return a.sub(b)
+
+    def __neg__(a):
+        return a.neg()
+
+    def __mul__(a, b):
+        if b in a.domain:
+            return a.mul(b)
+        else:
+            return NotImplemented
+
+    def __rmul__(a, b):
+        if b in a.domain:
+            return a.mul(b)
+        else:
+            return NotImplemented
+
+    def __matmul__(a, b):
+        if isinstance(b, DDM):
+            return a.matmul(b)
+        else:
+            return NotImplemented
+
+    @classmethod
+    def _check(cls, a, op, b, ashape, bshape):
+        if a.domain != b.domain:
+            msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
+            raise DMDomainError(msg)
+        if ashape != bshape:
+            msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
+            raise DMShapeError(msg)
+
+    def add(a, b):
+        """a + b"""
+        a._check(a, '+', b, a.shape, b.shape)
+        c = a.copy()
+        ddm_iadd(c, b)
+        return c
+
+    def sub(a, b):
+        """a - b"""
+        a._check(a, '-', b, a.shape, b.shape)
+        c = a.copy()
+        ddm_isub(c, b)
+        return c
+
+    def neg(a):
+        """-a"""
+        b = a.copy()
+        ddm_ineg(b)
+        return b
+
+    def mul(a, b):
+        c = a.copy()
+        ddm_imul(c, b)
+        return c
+
+    def rmul(a, b):
+        c = a.copy()
+        ddm_irmul(c, b)
+        return c
+
+    def matmul(a, b):
+        """a @ b (matrix product)"""
+        m, o = a.shape
+        o2, n = b.shape
+        a._check(a, '*', b, o, o2)
+        c = a.zeros((m, n), a.domain)
+        ddm_imatmul(c, a, b)
+        return c
+
+    def mul_elementwise(a, b):
+        assert a.shape == b.shape
+        assert a.domain == b.domain
+        c = [[aij * bij for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)]
+        return DDM(c, a.shape, a.domain)
+
+    def hstack(A, *B):
+        """Horizontally stacks :py:class:`~.DDM` matrices.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import DDM
+
+        >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
+        >>> A.hstack(B)
+        [[1, 2, 5, 6], [3, 4, 7, 8]]
+
+        >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
+        >>> A.hstack(B, C)
+        [[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]]
+        """
+        Anew = list(A.copy())
+        rows, cols = A.shape
+        domain = A.domain
+
+        for Bk in B:
+            Bkrows, Bkcols = Bk.shape
+            assert Bkrows == rows
+            assert Bk.domain == domain
+
+            cols += Bkcols
+
+            for i, Bki in enumerate(Bk):
+                Anew[i].extend(Bki)
+
+        return DDM(Anew, (rows, cols), A.domain)
+
+    def vstack(A, *B):
+        """Vertically stacks :py:class:`~.DDM` matrices.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import DDM
+
+        >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
+        >>> A.vstack(B)
+        [[1, 2], [3, 4], [5, 6], [7, 8]]
+
+        >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
+        >>> A.vstack(B, C)
+        [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
+        """
+        Anew = list(A.copy())
+        rows, cols = A.shape
+        domain = A.domain
+
+        for Bk in B:
+            Bkrows, Bkcols = Bk.shape
+            assert Bkcols == cols
+            assert Bk.domain == domain
+
+            rows += Bkrows
+
+            Anew.extend(Bk.copy())
+
+        return DDM(Anew, (rows, cols), A.domain)
+
+    def applyfunc(self, func, domain):
+        elements = [list(map(func, row)) for row in self]
+        return DDM(elements, self.shape, domain)
+
+    def nnz(a):
+        """Number of non-zero entries in :py:class:`~.DDM` matrix.
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nnz
+        """
+        return sum(sum(map(bool, row)) for row in a)
+
+    def scc(a):
+        """Strongly connected components of a square matrix *a*.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import DDM
+        >>> A = DDM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)
+        >>> A.scc()
+        [[0], [1]]
+
+        See also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.scc
+
+        """
+        return a.to_sdm().scc()
+
+    @classmethod
+    def diag(cls, values, domain):
+        """Returns a square diagonal matrix with *values* on the diagonal.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import DDM
+        >>> DDM.diag([ZZ(1), ZZ(2), ZZ(3)], ZZ)
+        [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
+
+        See also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.diag
+        """
+        return SDM.diag(values, domain).to_ddm()
+
+    def rref(a):
+        """Reduced-row echelon form of a and list of pivots.
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.rref
+            Higher level interface to this function.
+        sympy.polys.matrices.dense.ddm_irref
+            The underlying algorithm.
+        """
+        b = a.copy()
+        K = a.domain
+        partial_pivot = K.is_RealField or K.is_ComplexField
+        pivots = ddm_irref(b, _partial_pivot=partial_pivot)
+        return b, pivots
+
+    def rref_den(a):
+        """Reduced-row echelon form of a with denominator and list of pivots
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den
+            Higher level interface to this function.
+        sympy.polys.matrices.dense.ddm_irref_den
+            The underlying algorithm.
+        """
+        b = a.copy()
+        K = a.domain
+        denom, pivots = ddm_irref_den(b, K)
+        return b, denom, pivots
+
+    def nullspace(a):
+        """Returns a basis for the nullspace of a.
+
+        The domain of the matrix must be a field.
+
+        See Also
+        ========
+
+        rref
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace
+        """
+        rref, pivots = a.rref()
+        return rref.nullspace_from_rref(pivots)
+
+    def nullspace_from_rref(a, pivots=None):
+        """Compute the nullspace of a matrix from its rref.
+
+        The domain of the matrix can be any domain.
+
+        Returns a tuple (basis, nonpivots).
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace
+            The higher level interface to this function.
+        """
+        m, n = a.shape
+        K = a.domain
+
+        if pivots is None:
+            pivots = []
+            last_pivot = -1
+            for i in range(m):
+                ai = a[i]
+                for j in range(last_pivot+1, n):
+                    if ai[j]:
+                        last_pivot = j
+                        pivots.append(j)
+                        break
+
+        if not pivots:
+            return (a.eye(n, K), list(range(n)))
+
+        # After rref the pivots are all one but after rref_den they may not be.
+        pivot_val = a[0][pivots[0]]
+
+        basis = []
+        nonpivots = []
+        for i in range(n):
+            if i in pivots:
+                continue
+            nonpivots.append(i)
+            vec = [pivot_val if i == j else K.zero for j in range(n)]
+            for ii, jj in enumerate(pivots):
+                vec[jj] -= a[ii][i]
+            basis.append(vec)
+
+        basis_ddm = DDM(basis, (len(basis), n), K)
+
+        return (basis_ddm, nonpivots)
+
+    def particular(a):
+        return a.to_sdm().particular().to_ddm()
+
+    def det(a):
+        """Determinant of a"""
+        m, n = a.shape
+        if m != n:
+            raise DMNonSquareMatrixError("Determinant of non-square matrix")
+        b = a.copy()
+        K = b.domain
+        deta = ddm_idet(b, K)
+        return deta
+
+    def inv(a):
+        """Inverse of a"""
+        m, n = a.shape
+        if m != n:
+            raise DMNonSquareMatrixError("Determinant of non-square matrix")
+        ainv = a.copy()
+        K = a.domain
+        ddm_iinv(ainv, a, K)
+        return ainv
+
+    def lu(a):
+        """L, U decomposition of a"""
+        m, n = a.shape
+        K = a.domain
+
+        U = a.copy()
+        L = a.eye(m, K)
+        swaps = ddm_ilu_split(L, U, K)
+
+        return L, U, swaps
+
+    def lu_solve(a, b):
+        """x where a*x = b"""
+        m, n = a.shape
+        m2, o = b.shape
+        a._check(a, 'lu_solve', b, m, m2)
+        if not a.domain.is_Field:
+            raise DMDomainError("lu_solve requires a field")
+
+        L, U, swaps = a.lu()
+        x = a.zeros((n, o), a.domain)
+        ddm_ilu_solve(x, L, U, swaps, b)
+        return x
+
+    def charpoly(a):
+        """Coefficients of characteristic polynomial of a"""
+        K = a.domain
+        m, n = a.shape
+        if m != n:
+            raise DMNonSquareMatrixError("Charpoly of non-square matrix")
+        vec = ddm_berk(a, K)
+        coeffs = [vec[i][0] for i in range(n+1)]
+        return coeffs
+
+    def is_zero_matrix(self):
+        """
+        Says whether this matrix has all zero entries.
+        """
+        zero = self.domain.zero
+        return all(Mij == zero for Mij in self.flatiter())
+
+    def is_upper(self):
+        """
+        Says whether this matrix is upper-triangular. True can be returned
+        even if the matrix is not square.
+        """
+        zero = self.domain.zero
+        return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[:i])
+
+    def is_lower(self):
+        """
+        Says whether this matrix is lower-triangular. True can be returned
+        even if the matrix is not square.
+        """
+        zero = self.domain.zero
+        return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[i+1:])
+
+    def is_diagonal(self):
+        """
+        Says whether this matrix is diagonal. True can be returned even if
+        the matrix is not square.
+        """
+        return self.is_upper() and self.is_lower()
+
+    def diagonal(self):
+        """
+        Returns a list of the elements from the diagonal of the matrix.
+        """
+        m, n = self.shape
+        return [self[i][i] for i in range(min(m, n))]
+
+    def lll(A, delta=QQ(3, 4)):
+        return ddm_lll(A, delta=delta)
+
+    def lll_transform(A, delta=QQ(3, 4)):
+        return ddm_lll_transform(A, delta=delta)
+
+
+from .sdm import SDM
+from .dfm import DFM
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/dense.py b/lib/python3.11/site-packages/sympy/polys/matrices/dense.py
new file mode 100644
index 0000000000000000000000000000000000000000..47ab2d6897c6d9f3781af23ccb68f96f15c7e859
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/dense.py
@@ -0,0 +1,824 @@
+"""
+
+Module for the ddm_* routines for operating on a matrix in list of lists
+matrix representation.
+
+These routines are used internally by the DDM class which also provides a
+friendlier interface for them. The idea here is to implement core matrix
+routines in a way that can be applied to any simple list representation
+without the need to use any particular matrix class. For example we can
+compute the RREF of a matrix like:
+
+    >>> from sympy.polys.matrices.dense import ddm_irref
+    >>> M = [[1, 2, 3], [4, 5, 6]]
+    >>> pivots = ddm_irref(M)
+    >>> M
+    [[1.0, 0.0, -1.0], [0, 1.0, 2.0]]
+
+These are lower-level routines that work mostly in place.The routines at this
+level should not need to know what the domain of the elements is but should
+ideally document what operations they will use and what functions they need to
+be provided with.
+
+The next-level up is the DDM class which uses these routines but wraps them up
+with an interface that handles copying etc and keeps track of the Domain of
+the elements of the matrix:
+
+    >>> from sympy.polys.domains import QQ
+    >>> from sympy.polys.matrices.ddm import DDM
+    >>> M = DDM([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ)
+    >>> M
+    [[1, 2, 3], [4, 5, 6]]
+    >>> Mrref, pivots = M.rref()
+    >>> Mrref
+    [[1, 0, -1], [0, 1, 2]]
+
+"""
+from __future__ import annotations
+from operator import mul
+from .exceptions import (
+    DMShapeError,
+    DMDomainError,
+    DMNonInvertibleMatrixError,
+    DMNonSquareMatrixError,
+)
+from typing import Sequence, TypeVar
+from sympy.polys.matrices._typing import RingElement
+
+
+#: Type variable for the elements of the matrix
+T = TypeVar('T')
+
+#: Type variable for the elements of the matrix that are in a ring
+R = TypeVar('R', bound=RingElement)
+
+
+def ddm_transpose(matrix: Sequence[Sequence[T]]) -> list[list[T]]:
+    """matrix transpose"""
+    return list(map(list, zip(*matrix)))
+
+
+def ddm_iadd(a: list[list[R]], b: Sequence[Sequence[R]]) -> None:
+    """a += b"""
+    for ai, bi in zip(a, b):
+        for j, bij in enumerate(bi):
+            ai[j] += bij
+
+
+def ddm_isub(a: list[list[R]], b: Sequence[Sequence[R]]) -> None:
+    """a -= b"""
+    for ai, bi in zip(a, b):
+        for j, bij in enumerate(bi):
+            ai[j] -= bij
+
+
+def ddm_ineg(a: list[list[R]]) -> None:
+    """a <-- -a"""
+    for ai in a:
+        for j, aij in enumerate(ai):
+            ai[j] = -aij
+
+
+def ddm_imul(a: list[list[R]], b: R) -> None:
+    """a <-- a*b"""
+    for ai in a:
+        for j, aij in enumerate(ai):
+            ai[j] = aij * b
+
+
+def ddm_irmul(a: list[list[R]], b: R) -> None:
+    """a <-- b*a"""
+    for ai in a:
+        for j, aij in enumerate(ai):
+            ai[j] = b * aij
+
+
+def ddm_imatmul(
+    a: list[list[R]], b: Sequence[Sequence[R]], c: Sequence[Sequence[R]]
+) -> None:
+    """a += b @ c"""
+    cT = list(zip(*c))
+
+    for bi, ai in zip(b, a):
+        for j, cTj in enumerate(cT):
+            ai[j] = sum(map(mul, bi, cTj), ai[j])
+
+
+def ddm_irref(a, _partial_pivot=False):
+    """In-place reduced row echelon form of a matrix.
+
+    Compute the reduced row echelon form of $a$. Modifies $a$ in place and
+    returns a list of the pivot columns.
+
+    Uses naive Gauss-Jordan elimination in the ground domain which must be a
+    field.
+
+    This routine is only really suitable for use with simple field domains like
+    :ref:`GF(p)`, :ref:`QQ` and :ref:`QQ(a)` although even for :ref:`QQ` with
+    larger matrices it is possibly more efficient to use fraction free
+    approaches.
+
+    This method is not suitable for use with rational function fields
+    (:ref:`K(x)`) because the elements will blowup leading to costly gcd
+    operations. In this case clearing denominators and using fraction free
+    approaches is likely to be more efficient.
+
+    For inexact numeric domains like :ref:`RR` and :ref:`CC` pass
+    ``_partial_pivot=True`` to use partial pivoting to control rounding errors.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.dense import ddm_irref
+    >>> from sympy import QQ
+    >>> M = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
+    >>> pivots = ddm_irref(M)
+    >>> M
+    [[1, 0, -1], [0, 1, 2]]
+    >>> pivots
+    [0, 1]
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.rref
+        Higher level interface to this routine.
+    ddm_irref_den
+        The fraction free version of this routine.
+    sdm_irref
+        A sparse version of this routine.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Row_echelon_form#Reduced_row_echelon_form
+    """
+    # We compute aij**-1 below and then use multiplication instead of division
+    # in the innermost loop. The domain here is a field so either operation is
+    # defined. There are significant performance differences for some domains
+    # though. In the case of e.g. QQ or QQ(x) inversion is free but
+    # multiplication and division have the same cost so it makes no difference.
+    # In cases like GF(p), QQ, RR or CC though multiplication is
+    # faster than division so reusing a precomputed inverse for many
+    # multiplications can be a lot faster. The biggest win is QQ when
+    # deg(minpoly(a)) is large.
+    #
+    # With domains like QQ(x) this can perform badly for other reasons.
+    # Typically the initial matrix has simple denominators and the
+    # fraction-free approach with exquo (ddm_irref_den) will preserve that
+    # property throughout. The method here causes denominator blowup leading to
+    # expensive gcd reductions in the intermediate expressions. With many
+    # generators like QQ(x,y,z,...) this is extremely bad.
+    #
+    # TODO: Use a nontrivial pivoting strategy to control intermediate
+    # expression growth. Rearranging rows and/or columns could defer the most
+    # complicated elements until the end. If the first pivot is a
+    # complicated/large element then the first round of reduction will
+    # immediately introduce expression blowup across the whole matrix.
+
+    # a is (m x n)
+    m = len(a)
+    if not m:
+        return []
+    n = len(a[0])
+
+    i = 0
+    pivots = []
+
+    for j in range(n):
+        # Proper pivoting should be used for all domains for performance
+        # reasons but it is only strictly needed for RR and CC (and possibly
+        # other domains like RR(x)). This path is used by DDM.rref() if the
+        # domain is RR or CC. It uses partial (row) pivoting based on the
+        # absolute value of the pivot candidates.
+        if _partial_pivot:
+            ip = max(range(i, m), key=lambda ip: abs(a[ip][j]))
+            a[i], a[ip] = a[ip], a[i]
+
+        # pivot
+        aij = a[i][j]
+
+        # zero-pivot
+        if not aij:
+            for ip in range(i+1, m):
+                aij = a[ip][j]
+                # row-swap
+                if aij:
+                    a[i], a[ip] = a[ip], a[i]
+                    break
+            else:
+                # next column
+                continue
+
+        # normalise row
+        ai = a[i]
+        aijinv = aij**-1
+        for l in range(j, n):
+            ai[l] *= aijinv # ai[j] = one
+
+        # eliminate above and below to the right
+        for k, ak in enumerate(a):
+            if k == i or not ak[j]:
+                continue
+            akj = ak[j]
+            ak[j] -= akj # ak[j] = zero
+            for l in range(j+1, n):
+                ak[l] -= akj * ai[l]
+
+        # next row
+        pivots.append(j)
+        i += 1
+
+        # no more rows?
+        if i >= m:
+            break
+
+    return pivots
+
+
+def ddm_irref_den(a, K):
+    """a  <--  rref(a); return (den, pivots)
+
+    Compute the fraction-free reduced row echelon form (RREF) of $a$. Modifies
+    $a$ in place and returns a tuple containing the denominator of the RREF and
+    a list of the pivot columns.
+
+    Explanation
+    ===========
+
+    The algorithm used is the fraction-free version of Gauss-Jordan elimination
+    described as FFGJ in [1]_. Here it is modified to handle zero or missing
+    pivots and to avoid redundant arithmetic.
+
+    The domain $K$ must support exact division (``K.exquo``) but does not need
+    to be a field. This method is suitable for most exact rings and fields like
+    :ref:`ZZ`, :ref:`QQ` and :ref:`QQ(a)`. In the case of :ref:`QQ` or
+    :ref:`K(x)` it might be more efficient to clear denominators and use
+    :ref:`ZZ` or :ref:`K[x]` instead.
+
+    For inexact domains like :ref:`RR` and :ref:`CC` use ``ddm_irref`` instead.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.dense import ddm_irref_den
+    >>> from sympy import ZZ, Matrix
+    >>> M = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)]]
+    >>> den, pivots = ddm_irref_den(M, ZZ)
+    >>> M
+    [[-3, 0, 3], [0, -3, -6]]
+    >>> den
+    -3
+    >>> pivots
+    [0, 1]
+    >>> Matrix(M).rref()[0]
+    Matrix([
+    [1, 0, -1],
+    [0, 1,  2]])
+
+    See Also
+    ========
+
+    ddm_irref
+        A version of this routine that uses field division.
+    sdm_irref
+        A sparse version of :func:`ddm_irref`.
+    sdm_rref_den
+        A sparse version of :func:`ddm_irref_den`.
+    sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den
+        Higher level interface.
+
+    References
+    ==========
+
+    .. [1] Fraction-free algorithms for linear and polynomial equations.
+        George C. Nakos , Peter R. Turner , Robert M. Williams.
+        https://dl.acm.org/doi/10.1145/271130.271133
+    """
+    #
+    # A simpler presentation of this algorithm is given in [1]:
+    #
+    # Given an n x n matrix A and n x 1 matrix b:
+    #
+    #   for i in range(n):
+    #       if i != 0:
+    #           d = a[i-1][i-1]
+    #       for j in range(n):
+    #           if j == i:
+    #               continue
+    #           b[j] = a[i][i]*b[j] - a[j][i]*b[i]
+    #           for k in range(n):
+    #               a[j][k] = a[i][i]*a[j][k] - a[j][i]*a[i][k]
+    #               if i != 0:
+    #                   a[j][k] /= d
+    #
+    # Our version here is a bit more complicated because:
+    #
+    #  1. We use row-swaps to avoid zero pivots.
+    #  2. We allow for some columns to be missing pivots.
+    #  3. We avoid a lot of redundant arithmetic.
+    #
+    # TODO: Use a non-trivial pivoting strategy. Even just row swapping makes a
+    # big difference to performance if e.g. the upper-left entry of the matrix
+    # is a huge polynomial.
+
+    # a is (m x n)
+    m = len(a)
+    if not m:
+        return K.one, []
+    n = len(a[0])
+
+    d = None
+    pivots = []
+    no_pivots = []
+
+    # i, j will be the row and column indices of the current pivot
+    i = 0
+    for j in range(n):
+        # next pivot?
+        aij = a[i][j]
+
+        # swap rows if zero
+        if not aij:
+            for ip in range(i+1, m):
+                aij = a[ip][j]
+                # row-swap
+                if aij:
+                    a[i], a[ip] = a[ip], a[i]
+                    break
+            else:
+                # go to next column
+                no_pivots.append(j)
+                continue
+
+        # Now aij is the pivot and i,j are the row and column. We need to clear
+        # the column above and below but we also need to keep track of the
+        # denominator of the RREF which means also multiplying everything above
+        # and to the left by the current pivot aij and dividing by d (which we
+        # multiplied everything by in the previous iteration so this is an
+        # exact division).
+        #
+        # First handle the upper left corner which is usually already diagonal
+        # with all diagonal entries equal to the current denominator but there
+        # can be other non-zero entries in any column that has no pivot.
+
+        # Update previous pivots in the matrix
+        if pivots:
+            pivot_val = aij * a[0][pivots[0]]
+            # Divide out the common factor
+            if d is not None:
+                pivot_val = K.exquo(pivot_val, d)
+
+            # Could defer this until the end but it is pretty cheap and
+            # helps when debugging.
+            for ip, jp in enumerate(pivots):
+                a[ip][jp] = pivot_val
+
+        # Update columns without pivots
+        for jnp in no_pivots:
+            for ip in range(i):
+                aijp = a[ip][jnp]
+                if aijp:
+                    aijp *= aij
+                    if d is not None:
+                        aijp = K.exquo(aijp, d)
+                    a[ip][jnp] = aijp
+
+        # Eliminate above, below and to the right as in ordinary division free
+        # Gauss-Jordan elmination except also dividing out d from every entry.
+
+        for jp, aj in enumerate(a):
+
+            # Skip the current row
+            if jp == i:
+                continue
+
+            # Eliminate to the right in all rows
+            for kp in range(j+1, n):
+                ajk = aij * aj[kp] - aj[j] * a[i][kp]
+                if d is not None:
+                    ajk = K.exquo(ajk, d)
+                aj[kp] = ajk
+
+            # Set to zero above and below the pivot
+            aj[j] = K.zero
+
+        # next row
+        pivots.append(j)
+        i += 1
+
+        # no more rows left?
+        if i >= m:
+            break
+
+        if not K.is_one(aij):
+            d = aij
+        else:
+            d = None
+
+    if not pivots:
+        denom = K.one
+    else:
+        denom = a[0][pivots[0]]
+
+    return denom, pivots
+
+
+def ddm_idet(a, K):
+    """a  <--  echelon(a); return det
+
+    Explanation
+    ===========
+
+    Compute the determinant of $a$ using the Bareiss fraction-free algorithm.
+    The matrix $a$ is modified in place. Its diagonal elements are the
+    determinants of the leading principal minors. The determinant of $a$ is
+    returned.
+
+    The domain $K$ must support exact division (``K.exquo``). This method is
+    suitable for most exact rings and fields like :ref:`ZZ`, :ref:`QQ` and
+    :ref:`QQ(a)` but not for inexact domains like :ref:`RR` and :ref:`CC`.
+
+    Examples
+    ========
+
+    >>> from sympy import ZZ
+    >>> from sympy.polys.matrices.ddm import ddm_idet
+    >>> a = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]]
+    >>> a
+    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+    >>> ddm_idet(a, ZZ)
+    0
+    >>> a
+    [[1, 2, 3], [4, -3, -6], [7, -6, 0]]
+    >>> [a[i][i] for i in range(len(a))]
+    [1, -3, 0]
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.det
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Bareiss_algorithm
+    .. [2] https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
+    """
+    # Bareiss algorithm
+    # https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
+
+    # a is (m x n)
+    m = len(a)
+    if not m:
+        return K.one
+    n = len(a[0])
+
+    exquo = K.exquo
+    # uf keeps track of the sign change from row swaps
+    uf = K.one
+
+    for k in range(n-1):
+        if not a[k][k]:
+            for i in range(k+1, n):
+                if a[i][k]:
+                    a[k], a[i] = a[i], a[k]
+                    uf = -uf
+                    break
+            else:
+                return K.zero
+
+        akkm1 = a[k-1][k-1] if k else K.one
+
+        for i in range(k+1, n):
+            for j in range(k+1, n):
+                a[i][j] = exquo(a[i][j]*a[k][k] - a[i][k]*a[k][j], akkm1)
+
+    return uf * a[-1][-1]
+
+
+def ddm_iinv(ainv, a, K):
+    """ainv  <--  inv(a)
+
+    Compute the inverse of a matrix $a$ over a field $K$ using Gauss-Jordan
+    elimination. The result is stored in $ainv$.
+
+    Uses division in the ground domain which should be an exact field.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.ddm import ddm_iinv, ddm_imatmul
+    >>> from sympy import QQ
+    >>> a = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
+    >>> ainv = [[None, None], [None, None]]
+    >>> ddm_iinv(ainv, a, QQ)
+    >>> ainv
+    [[-2, 1], [3/2, -1/2]]
+    >>> result = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
+    >>> ddm_imatmul(result, a, ainv)
+    >>> result
+    [[1, 0], [0, 1]]
+
+    See Also
+    ========
+
+    ddm_irref: the underlying routine.
+    """
+    if not K.is_Field:
+        raise DMDomainError('Not a field')
+
+    # a is (m x n)
+    m = len(a)
+    if not m:
+        return
+    n = len(a[0])
+    if m != n:
+        raise DMNonSquareMatrixError
+
+    eye = [[K.one if i==j else K.zero for j in range(n)] for i in range(n)]
+    Aaug = [row + eyerow for row, eyerow in zip(a, eye)]
+    pivots = ddm_irref(Aaug)
+    if pivots != list(range(n)):
+        raise DMNonInvertibleMatrixError('Matrix det == 0; not invertible.')
+    ainv[:] = [row[n:] for row in Aaug]
+
+
+def ddm_ilu_split(L, U, K):
+    """L, U  <--  LU(U)
+
+    Compute the LU decomposition of a matrix $L$ in place and store the lower
+    and upper triangular matrices in $L$ and $U$, respectively. Returns a list
+    of row swaps that were performed.
+
+    Uses division in the ground domain which should be an exact field.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.ddm import ddm_ilu_split
+    >>> from sympy import QQ
+    >>> L = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
+    >>> U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
+    >>> swaps = ddm_ilu_split(L, U, QQ)
+    >>> swaps
+    []
+    >>> L
+    [[0, 0], [3, 0]]
+    >>> U
+    [[1, 2], [0, -2]]
+
+    See Also
+    ========
+
+    ddm_ilu
+    ddm_ilu_solve
+    """
+    m = len(U)
+    if not m:
+        return []
+    n = len(U[0])
+
+    swaps = ddm_ilu(U)
+
+    zeros = [K.zero] * min(m, n)
+    for i in range(1, m):
+        j = min(i, n)
+        L[i][:j] = U[i][:j]
+        U[i][:j] = zeros[:j]
+
+    return swaps
+
+
+def ddm_ilu(a):
+    """a  <--  LU(a)
+
+    Computes the LU decomposition of a matrix in place. Returns a list of
+    row swaps that were performed.
+
+    Uses division in the ground domain which should be an exact field.
+
+    This is only suitable for domains like :ref:`GF(p)`, :ref:`QQ`, :ref:`QQ_I`
+    and :ref:`QQ(a)`. With a rational function field like :ref:`K(x)` it is
+    better to clear denominators and use division-free algorithms. Pivoting is
+    used to avoid exact zeros but not for floating point accuracy so :ref:`RR`
+    and :ref:`CC` are not suitable (use :func:`ddm_irref` instead).
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.dense import ddm_ilu
+    >>> from sympy import QQ
+    >>> a = [[QQ(1, 2), QQ(1, 3)], [QQ(1, 4), QQ(1, 5)]]
+    >>> swaps = ddm_ilu(a)
+    >>> swaps
+    []
+    >>> a
+    [[1/2, 1/3], [1/2, 1/30]]
+
+    The same example using ``Matrix``:
+
+    >>> from sympy import Matrix, S
+    >>> M = Matrix([[S(1)/2, S(1)/3], [S(1)/4, S(1)/5]])
+    >>> L, U, swaps = M.LUdecomposition()
+    >>> L
+    Matrix([
+    [  1, 0],
+    [1/2, 1]])
+    >>> U
+    Matrix([
+    [1/2,  1/3],
+    [  0, 1/30]])
+    >>> swaps
+    []
+
+    See Also
+    ========
+
+    ddm_irref
+    ddm_ilu_solve
+    sympy.matrices.matrixbase.MatrixBase.LUdecomposition
+    """
+    m = len(a)
+    if not m:
+        return []
+    n = len(a[0])
+
+    swaps = []
+
+    for i in range(min(m, n)):
+        if not a[i][i]:
+            for ip in range(i+1, m):
+                if a[ip][i]:
+                    swaps.append((i, ip))
+                    a[i], a[ip] = a[ip], a[i]
+                    break
+            else:
+                # M = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]])
+                continue
+        for j in range(i+1, m):
+            l_ji = a[j][i] / a[i][i]
+            a[j][i] = l_ji
+            for k in range(i+1, n):
+                a[j][k] -= l_ji * a[i][k]
+
+    return swaps
+
+
+def ddm_ilu_solve(x, L, U, swaps, b):
+    """x  <--  solve(L*U*x = swaps(b))
+
+    Solve a linear system, $A*x = b$, given an LU factorization of $A$.
+
+    Uses division in the ground domain which must be a field.
+
+    Modifies $x$ in place.
+
+    Examples
+    ========
+
+    Compute the LU decomposition of $A$ (in place):
+
+    >>> from sympy import QQ
+    >>> from sympy.polys.matrices.dense import ddm_ilu, ddm_ilu_solve
+    >>> A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
+    >>> swaps = ddm_ilu(A)
+    >>> A
+    [[1, 2], [3, -2]]
+    >>> L = U = A
+
+    Solve the linear system:
+
+    >>> b = [[QQ(5)], [QQ(6)]]
+    >>> x = [[None], [None]]
+    >>> ddm_ilu_solve(x, L, U, swaps, b)
+    >>> x
+    [[-4], [9/2]]
+
+    See Also
+    ========
+
+    ddm_ilu
+        Compute the LU decomposition of a matrix in place.
+    ddm_ilu_split
+        Compute the LU decomposition of a matrix and separate $L$ and $U$.
+    sympy.polys.matrices.domainmatrix.DomainMatrix.lu_solve
+        Higher level interface to this function.
+    """
+    m = len(U)
+    if not m:
+        return
+    n = len(U[0])
+
+    m2 = len(b)
+    if not m2:
+        raise DMShapeError("Shape mismtch")
+    o = len(b[0])
+
+    if m != m2:
+        raise DMShapeError("Shape mismtch")
+    if m < n:
+        raise NotImplementedError("Underdetermined")
+
+    if swaps:
+        b = [row[:] for row in b]
+        for i1, i2 in swaps:
+            b[i1], b[i2] = b[i2], b[i1]
+
+    # solve Ly = b
+    y = [[None] * o for _ in range(m)]
+    for k in range(o):
+        for i in range(m):
+            rhs = b[i][k]
+            for j in range(i):
+                rhs -= L[i][j] * y[j][k]
+            y[i][k] = rhs
+
+    if m > n:
+        for i in range(n, m):
+            for j in range(o):
+                if y[i][j]:
+                    raise DMNonInvertibleMatrixError
+
+    # Solve Ux = y
+    for k in range(o):
+        for i in reversed(range(n)):
+            if not U[i][i]:
+                raise DMNonInvertibleMatrixError
+            rhs = y[i][k]
+            for j in range(i+1, n):
+                rhs -= U[i][j] * x[j][k]
+            x[i][k] = rhs / U[i][i]
+
+
+def ddm_berk(M, K):
+    """
+    Berkowitz algorithm for computing the characteristic polynomial.
+
+    Explanation
+    ===========
+
+    The Berkowitz algorithm is a division-free algorithm for computing the
+    characteristic polynomial of a matrix over any commutative ring using only
+    arithmetic in the coefficient ring.
+
+    Examples
+    ========
+
+    >>> from sympy import Matrix
+    >>> from sympy.polys.matrices.dense import ddm_berk
+    >>> from sympy.polys.domains import ZZ
+    >>> M = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+    >>> ddm_berk(M, ZZ)
+    [[1], [-5], [-2]]
+    >>> Matrix(M).charpoly()
+    PurePoly(lambda**2 - 5*lambda - 2, lambda, domain='ZZ')
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly
+        The high-level interface to this function.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Samuelson%E2%80%93Berkowitz_algorithm
+    """
+    m = len(M)
+    if not m:
+        return [[K.one]]
+    n = len(M[0])
+
+    if m != n:
+        raise DMShapeError("Not square")
+
+    if n == 1:
+        return [[K.one], [-M[0][0]]]
+
+    a = M[0][0]
+    R = [M[0][1:]]
+    C = [[row[0]] for row in M[1:]]
+    A = [row[1:] for row in M[1:]]
+
+    q = ddm_berk(A, K)
+
+    T = [[K.zero] * n for _ in range(n+1)]
+    for i in range(n):
+        T[i][i] = K.one
+        T[i+1][i] = -a
+    for i in range(2, n+1):
+        if i == 2:
+            AnC = C
+        else:
+            C = AnC
+            AnC = [[K.zero] for row in C]
+            ddm_imatmul(AnC, A, C)
+        RAnC = [[K.zero]]
+        ddm_imatmul(RAnC, R, AnC)
+        for j in range(0, n+1-i):
+            T[i+j][j] = -RAnC[0][0]
+
+    qout = [[K.zero] for _ in range(n+1)]
+    ddm_imatmul(qout, T, q)
+    return qout
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/dfm.py b/lib/python3.11/site-packages/sympy/polys/matrices/dfm.py
new file mode 100644
index 0000000000000000000000000000000000000000..22938b7004654121f74b020bd6649bee84909e1e
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/dfm.py
@@ -0,0 +1,35 @@
+"""
+sympy.polys.matrices.dfm
+
+Provides the :class:`DFM` class if ``GROUND_TYPES=flint'``. Otherwise, ``DFM``
+is a placeholder class that raises NotImplementedError when instantiated.
+"""
+
+from sympy.external.gmpy import GROUND_TYPES
+
+if GROUND_TYPES == "flint":  # pragma: no cover
+    # When python-flint is installed we will try to use it for dense matrices
+    # if the domain is supported by python-flint.
+    from ._dfm import DFM
+
+else: # pragma: no cover
+    # Other code should be able to import this and it should just present as a
+    # version of DFM that does not support any domains.
+    class DFM_dummy:
+        """
+        Placeholder class for DFM when python-flint is not installed.
+        """
+        def __init__(*args, **kwargs):
+            raise NotImplementedError("DFM requires GROUND_TYPES=flint.")
+
+        @classmethod
+        def _supports_domain(cls, domain):
+            return False
+
+        @classmethod
+        def _get_flint_func(cls, domain):
+            raise NotImplementedError("DFM requires GROUND_TYPES=flint.")
+
+    # mypy really struggles with this kind of conditional type assignment.
+    # Maybe there is a better way to annotate this rather than type: ignore.
+    DFM = DFM_dummy # type: ignore
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/domainmatrix.py b/lib/python3.11/site-packages/sympy/polys/matrices/domainmatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..b91bef314d16364cdbfc18f5f7470d958468a23a
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/domainmatrix.py
@@ -0,0 +1,3850 @@
+"""
+
+Module for the DomainMatrix class.
+
+A DomainMatrix represents a matrix with elements that are in a particular
+Domain. Each DomainMatrix internally wraps a DDM which is used for the
+lower-level operations. The idea is that the DomainMatrix class provides the
+convenience routines for converting between Expr and the poly domains as well
+as unifying matrices with different domains.
+
+"""
+from collections import Counter
+from functools import reduce
+from typing import Union as tUnion, Tuple as tTuple
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.utilities.decorator import doctest_depends_on
+
+from sympy.core.sympify import _sympify
+
+from ..domains import Domain
+
+from ..constructor import construct_domain
+
+from .exceptions import (
+    DMFormatError,
+    DMBadInputError,
+    DMShapeError,
+    DMDomainError,
+    DMNotAField,
+    DMNonSquareMatrixError,
+    DMNonInvertibleMatrixError
+)
+
+from .domainscalar import DomainScalar
+
+from sympy.polys.domains import ZZ, EXRAW, QQ
+
+from sympy.polys.densearith import dup_mul
+from sympy.polys.densebasic import dup_convert
+from sympy.polys.densetools import (
+    dup_mul_ground,
+    dup_quo_ground,
+    dup_content,
+    dup_clear_denoms,
+    dup_primitive,
+    dup_transform,
+)
+from sympy.polys.factortools import dup_factor_list
+from sympy.polys.polyutils import _sort_factors
+
+from .ddm import DDM
+
+from .sdm import SDM
+
+from .dfm import DFM
+
+from .rref import _dm_rref, _dm_rref_den
+
+
+if GROUND_TYPES != 'flint':
+    __doctest_skip__ = ['DomainMatrix.to_dfm', 'DomainMatrix.to_dfm_or_ddm']
+else:
+    __doctest_skip__ = ['DomainMatrix.from_list']
+
+
+def DM(rows, domain):
+    """Convenient alias for DomainMatrix.from_list
+
+    Examples
+    ========
+
+    >>> from sympy import ZZ
+    >>> from sympy.polys.matrices import DM
+    >>> DM([[1, 2], [3, 4]], ZZ)
+    DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
+
+    See Also
+    ========
+
+    DomainMatrix.from_list
+    """
+    return DomainMatrix.from_list(rows, domain)
+
+
+class DomainMatrix:
+    r"""
+    Associate Matrix with :py:class:`~.Domain`
+
+    Explanation
+    ===========
+
+    DomainMatrix uses :py:class:`~.Domain` for its internal representation
+    which makes it faster than the SymPy Matrix class (currently) for many
+    common operations, but this advantage makes it not entirely compatible
+    with Matrix. DomainMatrix are analogous to numpy arrays with "dtype".
+    In the DomainMatrix, each element has a domain such as :ref:`ZZ`
+    or  :ref:`QQ(a)`.
+
+
+    Examples
+    ========
+
+    Creating a DomainMatrix from the existing Matrix class:
+
+    >>> from sympy import Matrix
+    >>> from sympy.polys.matrices import DomainMatrix
+    >>> Matrix1 = Matrix([
+    ...    [1, 2],
+    ...    [3, 4]])
+    >>> A = DomainMatrix.from_Matrix(Matrix1)
+    >>> A
+    DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
+
+    Directly forming a DomainMatrix:
+
+    >>> from sympy import ZZ
+    >>> from sympy.polys.matrices import DomainMatrix
+    >>> A = DomainMatrix([
+    ...    [ZZ(1), ZZ(2)],
+    ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    >>> A
+    DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
+
+    See Also
+    ========
+
+    DDM
+    SDM
+    Domain
+    Poly
+
+    """
+    rep: tUnion[SDM, DDM, DFM]
+    shape: tTuple[int, int]
+    domain: Domain
+
+    def __new__(cls, rows, shape, domain, *, fmt=None):
+        """
+        Creates a :py:class:`~.DomainMatrix`.
+
+        Parameters
+        ==========
+
+        rows : Represents elements of DomainMatrix as list of lists
+        shape : Represents dimension of DomainMatrix
+        domain : Represents :py:class:`~.Domain` of DomainMatrix
+
+        Raises
+        ======
+
+        TypeError
+            If any of rows, shape and domain are not provided
+
+        """
+        if isinstance(rows, (DDM, SDM, DFM)):
+            raise TypeError("Use from_rep to initialise from SDM/DDM")
+        elif isinstance(rows, list):
+            rep = DDM(rows, shape, domain)
+        elif isinstance(rows, dict):
+            rep = SDM(rows, shape, domain)
+        else:
+            msg = "Input should be list-of-lists or dict-of-dicts"
+            raise TypeError(msg)
+
+        if fmt is not None:
+            if fmt == 'sparse':
+                rep = rep.to_sdm()
+            elif fmt == 'dense':
+                rep = rep.to_ddm()
+            else:
+                raise ValueError("fmt should be 'sparse' or 'dense'")
+
+        # Use python-flint for dense matrices if possible
+        if rep.fmt == 'dense' and DFM._supports_domain(domain):
+            rep = rep.to_dfm()
+
+        return cls.from_rep(rep)
+
+    def __reduce__(self):
+        rep = self.rep
+        if rep.fmt == 'dense':
+            arg = self.to_list()
+        elif rep.fmt == 'sparse':
+            arg = dict(rep)
+        else:
+            raise RuntimeError # pragma: no cover
+        args = (arg, rep.shape, rep.domain)
+        return (self.__class__, args)
+
+    def __getitem__(self, key):
+        i, j = key
+        m, n = self.shape
+        if not (isinstance(i, slice) or isinstance(j, slice)):
+            return DomainScalar(self.rep.getitem(i, j), self.domain)
+
+        if not isinstance(i, slice):
+            if not -m <= i < m:
+                raise IndexError("Row index out of range")
+            i = i % m
+            i = slice(i, i+1)
+        if not isinstance(j, slice):
+            if not -n <= j < n:
+                raise IndexError("Column index out of range")
+            j = j % n
+            j = slice(j, j+1)
+
+        return self.from_rep(self.rep.extract_slice(i, j))
+
+    def getitem_sympy(self, i, j):
+        return self.domain.to_sympy(self.rep.getitem(i, j))
+
+    def extract(self, rowslist, colslist):
+        return self.from_rep(self.rep.extract(rowslist, colslist))
+
+    def __setitem__(self, key, value):
+        i, j = key
+        if not self.domain.of_type(value):
+            raise TypeError
+        if isinstance(i, int) and isinstance(j, int):
+            self.rep.setitem(i, j, value)
+        else:
+            raise NotImplementedError
+
+    @classmethod
+    def from_rep(cls, rep):
+        """Create a new DomainMatrix efficiently from DDM/SDM.
+
+        Examples
+        ========
+
+        Create a :py:class:`~.DomainMatrix` with an dense internal
+        representation as :py:class:`~.DDM`:
+
+        >>> from sympy.polys.domains import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> dM = DomainMatrix.from_rep(drep)
+        >>> dM
+        DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
+
+        Create a :py:class:`~.DomainMatrix` with a sparse internal
+        representation as :py:class:`~.SDM`:
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import ZZ
+        >>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ)
+        >>> dM = DomainMatrix.from_rep(drep)
+        >>> dM
+        DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ)
+
+        Parameters
+        ==========
+
+        rep: SDM or DDM
+            The internal sparse or dense representation of the matrix.
+
+        Returns
+        =======
+
+        DomainMatrix
+            A :py:class:`~.DomainMatrix` wrapping *rep*.
+
+        Notes
+        =====
+
+        This takes ownership of rep as its internal representation. If rep is
+        being mutated elsewhere then a copy should be provided to
+        ``from_rep``. Only minimal verification or checking is done on *rep*
+        as this is supposed to be an efficient internal routine.
+
+        """
+        if not (isinstance(rep, (DDM, SDM)) or (DFM is not None and isinstance(rep, DFM))):
+            raise TypeError("rep should be of type DDM or SDM")
+        self = super().__new__(cls)
+        self.rep = rep
+        self.shape = rep.shape
+        self.domain = rep.domain
+        return self
+
+    @classmethod
+    @doctest_depends_on(ground_types=['python', 'gmpy'])
+    def from_list(cls, rows, domain):
+        r"""
+        Convert a list of lists into a DomainMatrix
+
+        Parameters
+        ==========
+
+        rows: list of lists
+            Each element of the inner lists should be either the single arg,
+            or tuple of args, that would be passed to the domain constructor
+            in order to form an element of the domain. See examples.
+
+        Returns
+        =======
+
+        DomainMatrix containing elements defined in rows
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import FF, QQ, ZZ
+        >>> A = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], ZZ)
+        >>> A
+        DomainMatrix([[1, 0, 1], [0, 0, 1]], (2, 3), ZZ)
+        >>> B = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], FF(7))
+        >>> B
+        DomainMatrix([[1 mod 7, 0 mod 7, 1 mod 7], [0 mod 7, 0 mod 7, 1 mod 7]], (2, 3), GF(7))
+        >>> C = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ)
+        >>> C
+        DomainMatrix([[1/2, 3], [1/4, 5]], (2, 2), QQ)
+
+        See Also
+        ========
+
+        from_list_sympy
+
+        """
+        nrows = len(rows)
+        ncols = 0 if not nrows else len(rows[0])
+        conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e)
+        domain_rows = [[conv(e) for e in row] for row in rows]
+        return DomainMatrix(domain_rows, (nrows, ncols), domain)
+
+    @classmethod
+    def from_list_sympy(cls, nrows, ncols, rows, **kwargs):
+        r"""
+        Convert a list of lists of Expr into a DomainMatrix using construct_domain
+
+        Parameters
+        ==========
+
+        nrows: number of rows
+        ncols: number of columns
+        rows: list of lists
+
+        Returns
+        =======
+
+        DomainMatrix containing elements of rows
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy.abc import x, y, z
+        >>> A = DomainMatrix.from_list_sympy(1, 3, [[x, y, z]])
+        >>> A
+        DomainMatrix([[x, y, z]], (1, 3), ZZ[x,y,z])
+
+        See Also
+        ========
+
+        sympy.polys.constructor.construct_domain, from_dict_sympy
+
+        """
+        assert len(rows) == nrows
+        assert all(len(row) == ncols for row in rows)
+
+        items_sympy = [_sympify(item) for row in rows for item in row]
+
+        domain, items_domain = cls.get_domain(items_sympy, **kwargs)
+
+        domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)]
+
+        return DomainMatrix(domain_rows, (nrows, ncols), domain)
+
+    @classmethod
+    def from_dict_sympy(cls, nrows, ncols, elemsdict, **kwargs):
+        """
+
+        Parameters
+        ==========
+
+        nrows: number of rows
+        ncols: number of cols
+        elemsdict: dict of dicts containing non-zero elements of the DomainMatrix
+
+        Returns
+        =======
+
+        DomainMatrix containing elements of elemsdict
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy.abc import x,y,z
+        >>> elemsdict = {0: {0:x}, 1:{1: y}, 2: {2: z}}
+        >>> A = DomainMatrix.from_dict_sympy(3, 3, elemsdict)
+        >>> A
+        DomainMatrix({0: {0: x}, 1: {1: y}, 2: {2: z}}, (3, 3), ZZ[x,y,z])
+
+        See Also
+        ========
+
+        from_list_sympy
+
+        """
+        if not all(0 <= r < nrows for r in elemsdict):
+            raise DMBadInputError("Row out of range")
+        if not all(0 <= c < ncols for row in elemsdict.values() for c in row):
+            raise DMBadInputError("Column out of range")
+
+        items_sympy = [_sympify(item) for row in elemsdict.values() for item in row.values()]
+        domain, items_domain = cls.get_domain(items_sympy, **kwargs)
+
+        idx = 0
+        items_dict = {}
+        for i, row in elemsdict.items():
+            items_dict[i] = {}
+            for j in row:
+                items_dict[i][j] = items_domain[idx]
+                idx += 1
+
+        return DomainMatrix(items_dict, (nrows, ncols), domain)
+
+    @classmethod
+    def from_Matrix(cls, M, fmt='sparse',**kwargs):
+        r"""
+        Convert Matrix to DomainMatrix
+
+        Parameters
+        ==========
+
+        M: Matrix
+
+        Returns
+        =======
+
+        Returns DomainMatrix with identical elements as M
+
+        Examples
+        ========
+
+        >>> from sympy import Matrix
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> M = Matrix([
+        ...    [1.0, 3.4],
+        ...    [2.4, 1]])
+        >>> A = DomainMatrix.from_Matrix(M)
+        >>> A
+        DomainMatrix({0: {0: 1.0, 1: 3.4}, 1: {0: 2.4, 1: 1.0}}, (2, 2), RR)
+
+        We can keep internal representation as ddm using fmt='dense'
+        >>> from sympy import Matrix, QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense')
+        >>> A.rep
+        [[1/2, 3/4], [0, 0]]
+
+        See Also
+        ========
+
+        Matrix
+
+        """
+        if fmt == 'dense':
+            return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs)
+
+        return cls.from_dict_sympy(*M.shape, M.todod(), **kwargs)
+
+    @classmethod
+    def get_domain(cls, items_sympy, **kwargs):
+        K, items_K = construct_domain(items_sympy, **kwargs)
+        return K, items_K
+
+    def choose_domain(self, **opts):
+        """Convert to a domain found by :func:`~.construct_domain`.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> M = DM([[1, 2], [3, 4]], ZZ)
+        >>> M
+        DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
+        >>> M.choose_domain(field=True)
+        DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ)
+
+        >>> from sympy.abc import x
+        >>> M = DM([[1, x], [x**2, x**3]], ZZ[x])
+        >>> M.choose_domain(field=True).domain
+        ZZ(x)
+
+        Keyword arguments are passed to :func:`~.construct_domain`.
+
+        See Also
+        ========
+
+        construct_domain
+        convert_to
+        """
+        elements, data = self.to_sympy().to_flat_nz()
+        dom, elements_dom = construct_domain(elements, **opts)
+        return self.from_flat_nz(elements_dom, data, dom)
+
+    def copy(self):
+        return self.from_rep(self.rep.copy())
+
+    def convert_to(self, K):
+        r"""
+        Change the domain of DomainMatrix to desired domain or field
+
+        Parameters
+        ==========
+
+        K : Represents the desired domain or field.
+            Alternatively, ``None`` may be passed, in which case this method
+            just returns a copy of this DomainMatrix.
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix with the desired domain or field
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ, ZZ_I
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+        >>> A.convert_to(ZZ_I)
+        DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I)
+
+        """
+        if K == self.domain:
+            return self.copy()
+
+        rep = self.rep
+
+        # The DFM, DDM and SDM types do not do any implicit conversions so we
+        # manage switching between DDM and DFM here.
+        if rep.is_DFM and not DFM._supports_domain(K):
+            rep_K = rep.to_ddm().convert_to(K)
+        elif rep.is_DDM and DFM._supports_domain(K):
+            rep_K = rep.convert_to(K).to_dfm()
+        else:
+            rep_K = rep.convert_to(K)
+
+        return self.from_rep(rep_K)
+
+    def to_sympy(self):
+        return self.convert_to(EXRAW)
+
+    def to_field(self):
+        r"""
+        Returns a DomainMatrix with the appropriate field
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix with the appropriate field
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+        >>> A.to_field()
+        DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ)
+
+        """
+        K = self.domain.get_field()
+        return self.convert_to(K)
+
+    def to_sparse(self):
+        """
+        Return a sparse DomainMatrix representation of *self*.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
+        >>> A.rep
+        [[1, 0], [0, 2]]
+        >>> B = A.to_sparse()
+        >>> B.rep
+        {0: {0: 1}, 1: {1: 2}}
+        """
+        if self.rep.fmt == 'sparse':
+            return self
+
+        return self.from_rep(self.rep.to_sdm())
+
+    def to_dense(self):
+        """
+        Return a dense DomainMatrix representation of *self*.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ)
+        >>> A.rep
+        {0: {0: 1}, 1: {1: 2}}
+        >>> B = A.to_dense()
+        >>> B.rep
+        [[1, 0], [0, 2]]
+
+        """
+        rep = self.rep
+
+        if rep.fmt == 'dense':
+            return self
+
+        return self.from_rep(rep.to_dfm_or_ddm())
+
+    def to_ddm(self):
+        """
+        Return a :class:`~.DDM` representation of *self*.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ)
+        >>> ddm = A.to_ddm()
+        >>> ddm
+        [[1, 0], [0, 2]]
+        >>> type(ddm)
+        
+
+        See Also
+        ========
+
+        to_sdm
+        to_dense
+        sympy.polys.matrices.ddm.DDM.to_sdm
+        """
+        return self.rep.to_ddm()
+
+    def to_sdm(self):
+        """
+        Return a :class:`~.SDM` representation of *self*.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
+        >>> sdm = A.to_sdm()
+        >>> sdm
+        {0: {0: 1}, 1: {1: 2}}
+        >>> type(sdm)
+        
+
+        See Also
+        ========
+
+        to_ddm
+        to_sparse
+        sympy.polys.matrices.sdm.SDM.to_ddm
+        """
+        return self.rep.to_sdm()
+
+    @doctest_depends_on(ground_types=['flint'])
+    def to_dfm(self):
+        """
+        Return a :class:`~.DFM` representation of *self*.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
+        >>> dfm = A.to_dfm()
+        >>> dfm
+        [[1, 0], [0, 2]]
+        >>> type(dfm)
+        
+
+        See Also
+        ========
+
+        to_ddm
+        to_dense
+        DFM
+        """
+        return self.rep.to_dfm()
+
+    @doctest_depends_on(ground_types=['flint'])
+    def to_dfm_or_ddm(self):
+        """
+        Return a :class:`~.DFM` or :class:`~.DDM` representation of *self*.
+
+        Explanation
+        ===========
+
+        The :class:`~.DFM` representation can only be used if the ground types
+        are ``flint`` and the ground domain is supported by ``python-flint``.
+        This method will return a :class:`~.DFM` representation if possible,
+        but will return a :class:`~.DDM` representation otherwise.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
+        >>> dfm = A.to_dfm_or_ddm()
+        >>> dfm
+        [[1, 0], [0, 2]]
+        >>> type(dfm)  # Depends on the ground domain and ground types
+        
+
+        See Also
+        ========
+
+        to_ddm: Always return a :class:`~.DDM` representation.
+        to_dfm: Returns a :class:`~.DFM` representation or raise an error.
+        to_dense: Convert internally to a :class:`~.DFM` or :class:`~.DDM`
+        DFM: The :class:`~.DFM` dense FLINT matrix representation.
+        DDM: The Python :class:`~.DDM` dense domain matrix representation.
+        """
+        return self.rep.to_dfm_or_ddm()
+
+    @classmethod
+    def _unify_domain(cls, *matrices):
+        """Convert matrices to a common domain"""
+        domains = {matrix.domain for matrix in matrices}
+        if len(domains) == 1:
+            return matrices
+        domain = reduce(lambda x, y: x.unify(y), domains)
+        return tuple(matrix.convert_to(domain) for matrix in matrices)
+
+    @classmethod
+    def _unify_fmt(cls, *matrices, fmt=None):
+        """Convert matrices to the same format.
+
+        If all matrices have the same format, then return unmodified.
+        Otherwise convert both to the preferred format given as *fmt* which
+        should be 'dense' or 'sparse'.
+        """
+        formats = {matrix.rep.fmt for matrix in matrices}
+        if len(formats) == 1:
+            return matrices
+        if fmt == 'sparse':
+            return tuple(matrix.to_sparse() for matrix in matrices)
+        elif fmt == 'dense':
+            return tuple(matrix.to_dense() for matrix in matrices)
+        else:
+            raise ValueError("fmt should be 'sparse' or 'dense'")
+
+    def unify(self, *others, fmt=None):
+        """
+        Unifies the domains and the format of self and other
+        matrices.
+
+        Parameters
+        ==========
+
+        others : DomainMatrix
+
+        fmt: string 'dense', 'sparse' or `None` (default)
+            The preferred format to convert to if self and other are not
+            already in the same format. If `None` or not specified then no
+            conversion if performed.
+
+        Returns
+        =======
+
+        Tuple[DomainMatrix]
+            Matrices with unified domain and format
+
+        Examples
+        ========
+
+        Unify the domain of DomainMatrix that have different domains:
+
+        >>> from sympy import ZZ, QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+        >>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ)
+        >>> Aq, Bq = A.unify(B)
+        >>> Aq
+        DomainMatrix([[1, 2]], (1, 2), QQ)
+        >>> Bq
+        DomainMatrix([[1/2, 2]], (1, 2), QQ)
+
+        Unify the format (dense or sparse):
+
+        >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+        >>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ)
+        >>> B.rep
+        {0: {0: 1}}
+
+        >>> A2, B2 = A.unify(B, fmt='dense')
+        >>> B2.rep
+        [[1, 0], [0, 0]]
+
+        See Also
+        ========
+
+        convert_to, to_dense, to_sparse
+
+        """
+        matrices = (self,) + others
+        matrices = DomainMatrix._unify_domain(*matrices)
+        if fmt is not None:
+            matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt)
+        return matrices
+
+    def to_Matrix(self):
+        r"""
+        Convert DomainMatrix to Matrix
+
+        Returns
+        =======
+
+        Matrix
+            MutableDenseMatrix for the DomainMatrix
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+        >>> A.to_Matrix()
+        Matrix([
+            [1, 2],
+            [3, 4]])
+
+        See Also
+        ========
+
+        from_Matrix
+
+        """
+        from sympy.matrices.dense import MutableDenseMatrix
+
+        # XXX: If the internal representation of RepMatrix changes then this
+        # might need to be changed also.
+        if self.domain in (ZZ, QQ, EXRAW):
+            if self.rep.fmt == "sparse":
+                rep = self.copy()
+            else:
+                rep = self.to_sparse()
+        else:
+            rep = self.convert_to(EXRAW).to_sparse()
+
+        return MutableDenseMatrix._fromrep(rep)
+
+    def to_list(self):
+        """
+        Convert :class:`DomainMatrix` to list of lists.
+
+        See Also
+        ========
+
+        from_list
+        to_list_flat
+        to_flat_nz
+        to_dok
+        """
+        return self.rep.to_list()
+
+    def to_list_flat(self):
+        """
+        Convert :class:`DomainMatrix` to flat list.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> A.to_list_flat()
+        [1, 2, 3, 4]
+
+        See Also
+        ========
+
+        from_list_flat
+        to_list
+        to_flat_nz
+        to_dok
+        """
+        return self.rep.to_list_flat()
+
+    @classmethod
+    def from_list_flat(cls, elements, shape, domain):
+        """
+        Create :class:`DomainMatrix` from flat list.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> element_list = [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
+        >>> A = DomainMatrix.from_list_flat(element_list, (2, 2), ZZ)
+        >>> A
+        DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
+        >>> A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        to_list_flat
+        """
+        ddm = DDM.from_list_flat(elements, shape, domain)
+        return cls.from_rep(ddm.to_dfm_or_ddm())
+
+    def to_flat_nz(self):
+        """
+        Convert :class:`DomainMatrix` to list of nonzero elements and data.
+
+        Explanation
+        ===========
+
+        Returns a tuple ``(elements, data)`` where ``elements`` is a list of
+        elements of the matrix with zeros possibly excluded. The matrix can be
+        reconstructed by passing these to :meth:`from_flat_nz`. The idea is to
+        be able to modify a flat list of the elements and then create a new
+        matrix of the same shape with the modified elements in the same
+        positions.
+
+        The format of ``data`` differs depending on whether the underlying
+        representation is dense or sparse but either way it represents the
+        positions of the elements in the list in a way that
+        :meth:`from_flat_nz` can use to reconstruct the matrix. The
+        :meth:`from_flat_nz` method should be called on the same
+        :class:`DomainMatrix` that was used to call :meth:`to_flat_nz`.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> elements, data = A.to_flat_nz()
+        >>> elements
+        [1, 2, 3, 4]
+        >>> A == A.from_flat_nz(elements, data, A.domain)
+        True
+
+        Create a matrix with the elements doubled:
+
+        >>> elements_doubled = [2*x for x in elements]
+        >>> A2 = A.from_flat_nz(elements_doubled, data, A.domain)
+        >>> A2 == 2*A
+        True
+
+        See Also
+        ========
+
+        from_flat_nz
+        """
+        return self.rep.to_flat_nz()
+
+    def from_flat_nz(self, elements, data, domain):
+        """
+        Reconstruct :class:`DomainMatrix` after calling :meth:`to_flat_nz`.
+
+        See :meth:`to_flat_nz` for explanation.
+
+        See Also
+        ========
+
+        to_flat_nz
+        """
+        rep = self.rep.from_flat_nz(elements, data, domain)
+        return self.from_rep(rep)
+
+    def to_dod(self):
+        """
+        Convert :class:`DomainMatrix` to dictionary of dictionaries (dod) format.
+
+        Explanation
+        ===========
+
+        Returns a dictionary of dictionaries representing the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[ZZ(1), ZZ(2), ZZ(0)], [ZZ(3), ZZ(0), ZZ(4)]], ZZ)
+        >>> A.to_dod()
+        {0: {0: 1, 1: 2}, 1: {0: 3, 2: 4}}
+        >>> A.to_sparse() == A.from_dod(A.to_dod(), A.shape, A.domain)
+        True
+        >>> A == A.from_dod_like(A.to_dod())
+        True
+
+        See Also
+        ========
+
+        from_dod
+        from_dod_like
+        to_dok
+        to_list
+        to_list_flat
+        to_flat_nz
+        sympy.matrices.matrixbase.MatrixBase.todod
+        """
+        return self.rep.to_dod()
+
+    @classmethod
+    def from_dod(cls, dod, shape, domain):
+        """
+        Create sparse :class:`DomainMatrix` from dict of dict (dod) format.
+
+        See :meth:`to_dod` for explanation.
+
+        See Also
+        ========
+
+        to_dod
+        from_dod_like
+        """
+        return cls.from_rep(SDM.from_dod(dod, shape, domain))
+
+    def from_dod_like(self, dod, domain=None):
+        """
+        Create :class:`DomainMatrix` like ``self`` from dict of dict (dod) format.
+
+        See :meth:`to_dod` for explanation.
+
+        See Also
+        ========
+
+        to_dod
+        from_dod
+        """
+        if domain is None:
+            domain = self.domain
+        return self.from_rep(self.rep.from_dod(dod, self.shape, domain))
+
+    def to_dok(self):
+        """
+        Convert :class:`DomainMatrix` to dictionary of keys (dok) format.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(0)],
+        ...    [ZZ(0), ZZ(4)]], (2, 2), ZZ)
+        >>> A.to_dok()
+        {(0, 0): 1, (1, 1): 4}
+
+        The matrix can be reconstructed by calling :meth:`from_dok` although
+        the reconstructed matrix will always be in sparse format:
+
+        >>> A.to_sparse() == A.from_dok(A.to_dok(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        from_dok
+        to_list
+        to_list_flat
+        to_flat_nz
+        """
+        return self.rep.to_dok()
+
+    @classmethod
+    def from_dok(cls, dok, shape, domain):
+        """
+        Create :class:`DomainMatrix` from dictionary of keys (dok) format.
+
+        See :meth:`to_dok` for explanation.
+
+        See Also
+        ========
+
+        to_dok
+        """
+        return cls.from_rep(SDM.from_dok(dok, shape, domain))
+
+    def iter_values(self):
+        """
+        Iterate over nonzero elements of the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> list(A.iter_values())
+        [1, 3, 4]
+
+        See Also
+        ========
+
+        iter_items
+        to_list_flat
+        sympy.matrices.matrixbase.MatrixBase.iter_values
+        """
+        return self.rep.iter_values()
+
+    def iter_items(self):
+        """
+        Iterate over indices and values of nonzero elements of the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> list(A.iter_items())
+        [((0, 0), 1), ((1, 0), 3), ((1, 1), 4)]
+
+        See Also
+        ========
+
+        iter_values
+        to_dok
+        sympy.matrices.matrixbase.MatrixBase.iter_items
+        """
+        return self.rep.iter_items()
+
+    def nnz(self):
+        """
+        Number of nonzero elements in the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[1, 0], [0, 4]], ZZ)
+        >>> A.nnz()
+        2
+        """
+        return self.rep.nnz()
+
+    def __repr__(self):
+        return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain)
+
+    def transpose(self):
+        """Matrix transpose of ``self``"""
+        return self.from_rep(self.rep.transpose())
+
+    def flat(self):
+        rows, cols = self.shape
+        return [self[i,j].element for i in range(rows) for j in range(cols)]
+
+    @property
+    def is_zero_matrix(self):
+        return self.rep.is_zero_matrix()
+
+    @property
+    def is_upper(self):
+        """
+        Says whether this matrix is upper-triangular. True can be returned
+        even if the matrix is not square.
+        """
+        return self.rep.is_upper()
+
+    @property
+    def is_lower(self):
+        """
+        Says whether this matrix is lower-triangular. True can be returned
+        even if the matrix is not square.
+        """
+        return self.rep.is_lower()
+
+    @property
+    def is_diagonal(self):
+        """
+        True if the matrix is diagonal.
+
+        Can return true for non-square matrices. A matrix is diagonal if
+        ``M[i,j] == 0`` whenever ``i != j``.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> M = DM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], ZZ)
+        >>> M.is_diagonal
+        True
+
+        See Also
+        ========
+
+        is_upper
+        is_lower
+        is_square
+        diagonal
+        """
+        return self.rep.is_diagonal()
+
+    def diagonal(self):
+        """
+        Get the diagonal entries of the matrix as a list.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> M = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ)
+        >>> M.diagonal()
+        [1, 4]
+
+        See Also
+        ========
+
+        is_diagonal
+        diag
+        """
+        return self.rep.diagonal()
+
+    @property
+    def is_square(self):
+        """
+        True if the matrix is square.
+        """
+        return self.shape[0] == self.shape[1]
+
+    def rank(self):
+        rref, pivots = self.rref()
+        return len(pivots)
+
+    def hstack(A, *B):
+        r"""Horizontally stack the given matrices.
+
+        Parameters
+        ==========
+
+        B: DomainMatrix
+            Matrices to stack horizontally.
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix by stacking horizontally.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+
+        >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
+        >>> A.hstack(B)
+        DomainMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], (2, 4), ZZ)
+
+        >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
+        >>> A.hstack(B, C)
+        DomainMatrix([[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]], (2, 6), ZZ)
+
+        See Also
+        ========
+
+        unify
+        """
+        A, *B = A.unify(*B, fmt=A.rep.fmt)
+        return DomainMatrix.from_rep(A.rep.hstack(*(Bk.rep for Bk in B)))
+
+    def vstack(A, *B):
+        r"""Vertically stack the given matrices.
+
+        Parameters
+        ==========
+
+        B: DomainMatrix
+            Matrices to stack vertically.
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix by stacking vertically.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+
+        >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
+        >>> A.vstack(B)
+        DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], (4, 2), ZZ)
+
+        >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
+        >>> A.vstack(B, C)
+        DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]], (6, 2), ZZ)
+
+        See Also
+        ========
+
+        unify
+        """
+        A, *B = A.unify(*B, fmt='dense')
+        return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B)))
+
+    def applyfunc(self, func, domain=None):
+        if domain is None:
+            domain = self.domain
+        return self.from_rep(self.rep.applyfunc(func, domain))
+
+    def __add__(A, B):
+        if not isinstance(B, DomainMatrix):
+            return NotImplemented
+        A, B = A.unify(B, fmt='dense')
+        return A.add(B)
+
+    def __sub__(A, B):
+        if not isinstance(B, DomainMatrix):
+            return NotImplemented
+        A, B = A.unify(B, fmt='dense')
+        return A.sub(B)
+
+    def __neg__(A):
+        return A.neg()
+
+    def __mul__(A, B):
+        """A * B"""
+        if isinstance(B, DomainMatrix):
+            A, B = A.unify(B, fmt='dense')
+            return A.matmul(B)
+        elif B in A.domain:
+            return A.scalarmul(B)
+        elif isinstance(B, DomainScalar):
+            A, B = A.unify(B)
+            return A.scalarmul(B.element)
+        else:
+            return NotImplemented
+
+    def __rmul__(A, B):
+        if B in A.domain:
+            return A.rscalarmul(B)
+        elif isinstance(B, DomainScalar):
+            A, B = A.unify(B)
+            return A.rscalarmul(B.element)
+        else:
+            return NotImplemented
+
+    def __pow__(A, n):
+        """A ** n"""
+        if not isinstance(n, int):
+            return NotImplemented
+        return A.pow(n)
+
+    def _check(a, op, b, ashape, bshape):
+        if a.domain != b.domain:
+            msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
+            raise DMDomainError(msg)
+        if ashape != bshape:
+            msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
+            raise DMShapeError(msg)
+        if a.rep.fmt != b.rep.fmt:
+            msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt)
+            raise DMFormatError(msg)
+        if type(a.rep) != type(b.rep):
+            msg = "Type mismatch: %s %s %s" % (type(a.rep), op, type(b.rep))
+            raise DMFormatError(msg)
+
+    def add(A, B):
+        r"""
+        Adds two DomainMatrix matrices of the same Domain
+
+        Parameters
+        ==========
+
+        A, B: DomainMatrix
+            matrices to add
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix after Addition
+
+        Raises
+        ======
+
+        DMShapeError
+            If the dimensions of the two DomainMatrix are not equal
+
+        ValueError
+            If the domain of the two DomainMatrix are not same
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DomainMatrix([
+        ...    [ZZ(4), ZZ(3)],
+        ...    [ZZ(2), ZZ(1)]], (2, 2), ZZ)
+
+        >>> A.add(B)
+        DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ)
+
+        See Also
+        ========
+
+        sub, matmul
+
+        """
+        A._check('+', B, A.shape, B.shape)
+        return A.from_rep(A.rep.add(B.rep))
+
+
+    def sub(A, B):
+        r"""
+        Subtracts two DomainMatrix matrices of the same Domain
+
+        Parameters
+        ==========
+
+        A, B: DomainMatrix
+            matrices to subtract
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix after Subtraction
+
+        Raises
+        ======
+
+        DMShapeError
+            If the dimensions of the two DomainMatrix are not equal
+
+        ValueError
+            If the domain of the two DomainMatrix are not same
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DomainMatrix([
+        ...    [ZZ(4), ZZ(3)],
+        ...    [ZZ(2), ZZ(1)]], (2, 2), ZZ)
+
+        >>> A.sub(B)
+        DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ)
+
+        See Also
+        ========
+
+        add, matmul
+
+        """
+        A._check('-', B, A.shape, B.shape)
+        return A.from_rep(A.rep.sub(B.rep))
+
+    def neg(A):
+        r"""
+        Returns the negative of DomainMatrix
+
+        Parameters
+        ==========
+
+        A : Represents a DomainMatrix
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix after Negation
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+        >>> A.neg()
+        DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ)
+
+        """
+        return A.from_rep(A.rep.neg())
+
+    def mul(A, b):
+        r"""
+        Performs term by term multiplication for the second DomainMatrix
+        w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are
+        list of DomainMatrix matrices created after term by term multiplication.
+
+        Parameters
+        ==========
+
+        A, B: DomainMatrix
+            matrices to multiply term-wise
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix after term by term multiplication
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> b = ZZ(2)
+
+        >>> A.mul(b)
+        DomainMatrix([[2, 4], [6, 8]], (2, 2), ZZ)
+
+        See Also
+        ========
+
+        matmul
+
+        """
+        return A.from_rep(A.rep.mul(b))
+
+    def rmul(A, b):
+        return A.from_rep(A.rep.rmul(b))
+
+    def matmul(A, B):
+        r"""
+        Performs matrix multiplication of two DomainMatrix matrices
+
+        Parameters
+        ==========
+
+        A, B: DomainMatrix
+            to multiply
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix after multiplication
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DomainMatrix([
+        ...    [ZZ(1), ZZ(1)],
+        ...    [ZZ(0), ZZ(1)]], (2, 2), ZZ)
+
+        >>> A.matmul(B)
+        DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ)
+
+        See Also
+        ========
+
+        mul, pow, add, sub
+
+        """
+
+        A._check('*', B, A.shape[1], B.shape[0])
+        return A.from_rep(A.rep.matmul(B.rep))
+
+    def _scalarmul(A, lamda, reverse):
+        if lamda == A.domain.zero:
+            return DomainMatrix.zeros(A.shape, A.domain)
+        elif lamda == A.domain.one:
+            return A.copy()
+        elif reverse:
+            return A.rmul(lamda)
+        else:
+            return A.mul(lamda)
+
+    def scalarmul(A, lamda):
+        return A._scalarmul(lamda, reverse=False)
+
+    def rscalarmul(A, lamda):
+        return A._scalarmul(lamda, reverse=True)
+
+    def mul_elementwise(A, B):
+        assert A.domain == B.domain
+        return A.from_rep(A.rep.mul_elementwise(B.rep))
+
+    def __truediv__(A, lamda):
+        """ Method for Scalar Division"""
+        if isinstance(lamda, int) or ZZ.of_type(lamda):
+            lamda = DomainScalar(ZZ(lamda), ZZ)
+        elif A.domain.is_Field and lamda in A.domain:
+            K = A.domain
+            lamda = DomainScalar(K.convert(lamda), K)
+
+        if not isinstance(lamda, DomainScalar):
+            return NotImplemented
+
+        A, lamda = A.to_field().unify(lamda)
+        if lamda.element == lamda.domain.zero:
+            raise ZeroDivisionError
+        if lamda.element == lamda.domain.one:
+            return A
+
+        return A.mul(1 / lamda.element)
+
+    def pow(A, n):
+        r"""
+        Computes A**n
+
+        Parameters
+        ==========
+
+        A : DomainMatrix
+
+        n : exponent for A
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix on computing A**n
+
+        Raises
+        ======
+
+        NotImplementedError
+            if n is negative.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(1)],
+        ...    [ZZ(0), ZZ(1)]], (2, 2), ZZ)
+
+        >>> A.pow(2)
+        DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ)
+
+        See Also
+        ========
+
+        matmul
+
+        """
+        nrows, ncols = A.shape
+        if nrows != ncols:
+            raise DMNonSquareMatrixError('Power of a nonsquare matrix')
+        if n < 0:
+            raise NotImplementedError('Negative powers')
+        elif n == 0:
+            return A.eye(nrows, A.domain)
+        elif n == 1:
+            return A
+        elif n % 2 == 1:
+            return A * A**(n - 1)
+        else:
+            sqrtAn = A ** (n // 2)
+            return sqrtAn * sqrtAn
+
+    def scc(self):
+        """Compute the strongly connected components of a DomainMatrix
+
+        Explanation
+        ===========
+
+        A square matrix can be considered as the adjacency matrix for a
+        directed graph where the row and column indices are the vertices. In
+        this graph if there is an edge from vertex ``i`` to vertex ``j`` if
+        ``M[i, j]`` is nonzero. This routine computes the strongly connected
+        components of that graph which are subsets of the rows and columns that
+        are connected by some nonzero element of the matrix. The strongly
+        connected components are useful because many operations such as the
+        determinant can be computed by working with the submatrices
+        corresponding to each component.
+
+        Examples
+        ========
+
+        Find the strongly connected components of a matrix:
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> M = DomainMatrix([[ZZ(1), ZZ(0), ZZ(2)],
+        ...                   [ZZ(0), ZZ(3), ZZ(0)],
+        ...                   [ZZ(4), ZZ(6), ZZ(5)]], (3, 3), ZZ)
+        >>> M.scc()
+        [[1], [0, 2]]
+
+        Compute the determinant from the components:
+
+        >>> MM = M.to_Matrix()
+        >>> MM
+        Matrix([
+        [1, 0, 2],
+        [0, 3, 0],
+        [4, 6, 5]])
+        >>> MM[[1], [1]]
+        Matrix([[3]])
+        >>> MM[[0, 2], [0, 2]]
+        Matrix([
+        [1, 2],
+        [4, 5]])
+        >>> MM.det()
+        -9
+        >>> MM[[1], [1]].det() * MM[[0, 2], [0, 2]].det()
+        -9
+
+        The components are given in reverse topological order and represent a
+        permutation of the rows and columns that will bring the matrix into
+        block lower-triangular form:
+
+        >>> MM[[1, 0, 2], [1, 0, 2]]
+        Matrix([
+        [3, 0, 0],
+        [0, 1, 2],
+        [6, 4, 5]])
+
+        Returns
+        =======
+
+        List of lists of integers
+            Each list represents a strongly connected component.
+
+        See also
+        ========
+
+        sympy.matrices.matrixbase.MatrixBase.strongly_connected_components
+        sympy.utilities.iterables.strongly_connected_components
+
+        """
+        if not self.is_square:
+            raise DMNonSquareMatrixError('Matrix must be square for scc')
+
+        return self.rep.scc()
+
+    def clear_denoms(self, convert=False):
+        """
+        Clear denominators, but keep the domain unchanged.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[(1,2), (1,3)], [(1,4), (1,5)]], QQ)
+        >>> den, Anum = A.clear_denoms()
+        >>> den.to_sympy()
+        60
+        >>> Anum.to_Matrix()
+        Matrix([
+        [30, 20],
+        [15, 12]])
+        >>> den * A == Anum
+        True
+
+        The numerator matrix will be in the same domain as the original matrix
+        unless ``convert`` is set to ``True``:
+
+        >>> A.clear_denoms()[1].domain
+        QQ
+        >>> A.clear_denoms(convert=True)[1].domain
+        ZZ
+
+        The denominator is always in the associated ring:
+
+        >>> A.clear_denoms()[0].domain
+        ZZ
+        >>> A.domain.get_ring()
+        ZZ
+
+        See Also
+        ========
+
+        sympy.polys.polytools.Poly.clear_denoms
+        clear_denoms_rowwise
+        """
+        elems0, data = self.to_flat_nz()
+
+        K0 = self.domain
+        K1 = K0.get_ring() if K0.has_assoc_Ring else K0
+
+        den, elems1 = dup_clear_denoms(elems0, K0, K1, convert=convert)
+
+        if convert:
+            Kden, Knum = K1, K1
+        else:
+            Kden, Knum = K1, K0
+
+        den = DomainScalar(den, Kden)
+        num = self.from_flat_nz(elems1, data, Knum)
+
+        return den, num
+
+    def clear_denoms_rowwise(self, convert=False):
+        """
+        Clear denominators from each row of the matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[(1,2), (1,3), (1,4)], [(1,5), (1,6), (1,7)]], QQ)
+        >>> den, Anum = A.clear_denoms_rowwise()
+        >>> den.to_Matrix()
+        Matrix([
+        [12,   0],
+        [ 0, 210]])
+        >>> Anum.to_Matrix()
+        Matrix([
+        [ 6,  4,  3],
+        [42, 35, 30]])
+
+        The denominator matrix is a diagonal matrix with the denominators of
+        each row on the diagonal. The invariants are:
+
+        >>> den * A == Anum
+        True
+        >>> A == den.to_field().inv() * Anum
+        True
+
+        The numerator matrix will be in the same domain as the original matrix
+        unless ``convert`` is set to ``True``:
+
+        >>> A.clear_denoms_rowwise()[1].domain
+        QQ
+        >>> A.clear_denoms_rowwise(convert=True)[1].domain
+        ZZ
+
+        The domain of the denominator matrix is the associated ring:
+
+        >>> A.clear_denoms_rowwise()[0].domain
+        ZZ
+
+        See Also
+        ========
+
+        sympy.polys.polytools.Poly.clear_denoms
+        clear_denoms
+        """
+        dod = self.to_dod()
+
+        K0 = self.domain
+        K1 = K0.get_ring() if K0.has_assoc_Ring else K0
+
+        diagonals = [K0.one] * self.shape[0]
+        dod_num = {}
+        for i, rowi in dod.items():
+            indices, elems = zip(*rowi.items())
+            den, elems_num = dup_clear_denoms(elems, K0, K1, convert=convert)
+            rowi_num = dict(zip(indices, elems_num))
+            diagonals[i] = den
+            dod_num[i] = rowi_num
+
+        if convert:
+            Kden, Knum = K1, K1
+        else:
+            Kden, Knum = K1, K0
+
+        den = self.diag(diagonals, Kden)
+        num = self.from_dod_like(dod_num, Knum)
+
+        return den, num
+
+    def cancel_denom(self, denom):
+        """
+        Cancel factors between a matrix and a denominator.
+
+        Returns a matrix and denominator on lowest terms.
+
+        Requires ``gcd`` in the ground domain.
+
+        Methods like :meth:`solve_den`, :meth:`inv_den` and :meth:`rref_den`
+        return a matrix and denominator but not necessarily on lowest terms.
+        Reduction to lowest terms without fractions can be performed with
+        :meth:`cancel_denom`.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import ZZ
+        >>> M = DM([[2, 2, 0],
+        ...         [0, 2, 2],
+        ...         [0, 0, 2]], ZZ)
+        >>> Minv, den = M.inv_den()
+        >>> Minv.to_Matrix()
+        Matrix([
+        [1, -1,  1],
+        [0,  1, -1],
+        [0,  0,  1]])
+        >>> den
+        2
+        >>> Minv_reduced, den_reduced = Minv.cancel_denom(den)
+        >>> Minv_reduced.to_Matrix()
+        Matrix([
+        [1, -1,  1],
+        [0,  1, -1],
+        [0,  0,  1]])
+        >>> den_reduced
+        2
+        >>> Minv_reduced.to_field() / den_reduced == Minv.to_field() / den
+        True
+
+        The denominator is made canonical with respect to units (e.g. a
+        negative denominator is made positive):
+
+        >>> M = DM([[2, 2, 0]], ZZ)
+        >>> den = ZZ(-4)
+        >>> M.cancel_denom(den)
+        (DomainMatrix([[-1, -1, 0]], (1, 3), ZZ), 2)
+
+        Any factor common to _all_ elements will be cancelled but there can
+        still be factors in common between _some_ elements of the matrix and
+        the denominator. To cancel factors between each element and the
+        denominator, use :meth:`cancel_denom_elementwise` or otherwise convert
+        to a field and use division:
+
+        >>> M = DM([[4, 6]], ZZ)
+        >>> den = ZZ(12)
+        >>> M.cancel_denom(den)
+        (DomainMatrix([[2, 3]], (1, 2), ZZ), 6)
+        >>> numers, denoms = M.cancel_denom_elementwise(den)
+        >>> numers
+        DomainMatrix([[1, 1]], (1, 2), ZZ)
+        >>> denoms
+        DomainMatrix([[3, 2]], (1, 2), ZZ)
+        >>> M.to_field() / den
+        DomainMatrix([[1/3, 1/2]], (1, 2), QQ)
+
+        See Also
+        ========
+
+        solve_den
+        inv_den
+        rref_den
+        cancel_denom_elementwise
+        """
+        M = self
+        K = self.domain
+
+        if K.is_zero(denom):
+            raise ZeroDivisionError('denominator is zero')
+        elif K.is_one(denom):
+            return (M.copy(), denom)
+
+        elements, data = M.to_flat_nz()
+
+        # First canonicalize the denominator (e.g. multiply by -1).
+        if K.is_negative(denom):
+            u = -K.one
+        else:
+            u = K.canonical_unit(denom)
+
+        # Often after e.g. solve_den the denominator will be much more
+        # complicated than the elements of the numerator. Hopefully it will be
+        # quicker to find the gcd of the numerator and if there is no content
+        # then we do not need to look at the denominator at all.
+        content = dup_content(elements, K)
+        common = K.gcd(content, denom)
+
+        if not K.is_one(content):
+
+            common = K.gcd(content, denom)
+
+            if not K.is_one(common):
+                elements = dup_quo_ground(elements, common, K)
+                denom = K.quo(denom, common)
+
+        if not K.is_one(u):
+            elements = dup_mul_ground(elements, u, K)
+            denom = u * denom
+        elif K.is_one(common):
+            return (M.copy(), denom)
+
+        M_cancelled = M.from_flat_nz(elements, data, K)
+
+        return M_cancelled, denom
+
+    def cancel_denom_elementwise(self, denom):
+        """
+        Cancel factors between the elements of a matrix and a denominator.
+
+        Returns a matrix of numerators and matrix of denominators.
+
+        Requires ``gcd`` in the ground domain.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import ZZ
+        >>> M = DM([[2, 3], [4, 12]], ZZ)
+        >>> denom = ZZ(6)
+        >>> numers, denoms = M.cancel_denom_elementwise(denom)
+        >>> numers.to_Matrix()
+        Matrix([
+        [1, 1],
+        [2, 2]])
+        >>> denoms.to_Matrix()
+        Matrix([
+        [3, 2],
+        [3, 1]])
+        >>> M_frac = (M.to_field() / denom).to_Matrix()
+        >>> M_frac
+        Matrix([
+        [1/3, 1/2],
+        [2/3,   2]])
+        >>> denoms_inverted = denoms.to_Matrix().applyfunc(lambda e: 1/e)
+        >>> numers.to_Matrix().multiply_elementwise(denoms_inverted) == M_frac
+        True
+
+        Use :meth:`cancel_denom` to cancel factors between the matrix and the
+        denominator while preserving the form of a matrix with a scalar
+        denominator.
+
+        See Also
+        ========
+
+        cancel_denom
+        """
+        K = self.domain
+        M = self
+
+        if K.is_zero(denom):
+            raise ZeroDivisionError('denominator is zero')
+        elif K.is_one(denom):
+            M_numers = M.copy()
+            M_denoms = M.ones(M.shape, M.domain)
+            return (M_numers, M_denoms)
+
+        elements, data = M.to_flat_nz()
+
+        cofactors = [K.cofactors(numer, denom) for numer in elements]
+        gcds, numers, denoms = zip(*cofactors)
+
+        M_numers = M.from_flat_nz(list(numers), data, K)
+        M_denoms = M.from_flat_nz(list(denoms), data, K)
+
+        return (M_numers, M_denoms)
+
+    def content(self):
+        """
+        Return the gcd of the elements of the matrix.
+
+        Requires ``gcd`` in the ground domain.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import ZZ
+        >>> M = DM([[2, 4], [4, 12]], ZZ)
+        >>> M.content()
+        2
+
+        See Also
+        ========
+
+        primitive
+        cancel_denom
+        """
+        K = self.domain
+        elements, _ = self.to_flat_nz()
+        return dup_content(elements, K)
+
+    def primitive(self):
+        """
+        Factor out gcd of the elements of a matrix.
+
+        Requires ``gcd`` in the ground domain.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import ZZ
+        >>> M = DM([[2, 4], [4, 12]], ZZ)
+        >>> content, M_primitive = M.primitive()
+        >>> content
+        2
+        >>> M_primitive
+        DomainMatrix([[1, 2], [2, 6]], (2, 2), ZZ)
+        >>> content * M_primitive == M
+        True
+        >>> M_primitive.content() == ZZ(1)
+        True
+
+        See Also
+        ========
+
+        content
+        cancel_denom
+        """
+        K = self.domain
+        elements, data = self.to_flat_nz()
+        content, prims = dup_primitive(elements, K)
+        M_primitive = self.from_flat_nz(prims, data, K)
+        return content, M_primitive
+
+    def rref(self, *, method='auto'):
+        r"""
+        Returns reduced-row echelon form (RREF) and list of pivots.
+
+        If the domain is not a field then it will be converted to a field. See
+        :meth:`rref_den` for the fraction-free version of this routine that
+        returns RREF with denominator instead.
+
+        The domain must either be a field or have an associated fraction field
+        (see :meth:`to_field`).
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...     [QQ(2), QQ(-1), QQ(0)],
+        ...     [QQ(-1), QQ(2), QQ(-1)],
+        ...     [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
+
+        >>> rref_matrix, rref_pivots = A.rref()
+        >>> rref_matrix
+        DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ)
+        >>> rref_pivots
+        (0, 1, 2)
+
+        Parameters
+        ==========
+
+        method : str, optional (default: 'auto')
+            The method to use to compute the RREF. The default is ``'auto'``,
+            which will attempt to choose the fastest method. The other options
+            are:
+
+            - ``A.rref(method='GJ')`` uses Gauss-Jordan elimination with
+              division. If the domain is not a field then it will be converted
+              to a field with :meth:`to_field` first and RREF will be computed
+              by inverting the pivot elements in each row. This is most
+              efficient for very sparse matrices or for matrices whose elements
+              have complex denominators.
+
+            - ``A.rref(method='FF')`` uses fraction-free Gauss-Jordan
+              elimination. Elimination is performed using exact division
+              (``exquo``) to control the growth of the coefficients. In this
+              case the current domain is always used for elimination but if
+              the domain is not a field then it will be converted to a field
+              at the end and divided by the denominator. This is most efficient
+              for dense matrices or for matrices with simple denominators.
+
+            - ``A.rref(method='CD')`` clears the denominators before using
+              fraction-free Gauss-Jordan elimination in the assoicated ring.
+              This is most efficient for dense matrices with very simple
+              denominators.
+
+            - ``A.rref(method='GJ_dense')``, ``A.rref(method='FF_dense')``, and
+              ``A.rref(method='CD_dense')`` are the same as the above methods
+              except that the dense implementations of the algorithms are used.
+              By default ``A.rref(method='auto')`` will usually choose the
+              sparse implementations for RREF.
+
+            Regardless of which algorithm is used the returned matrix will
+            always have the same format (sparse or dense) as the input and its
+            domain will always be the field of fractions of the input domain.
+
+        Returns
+        =======
+
+        (DomainMatrix, list)
+            reduced-row echelon form and list of pivots for the DomainMatrix
+
+        See Also
+        ========
+
+        rref_den
+            RREF with denominator
+        sympy.polys.matrices.sdm.sdm_irref
+            Sparse implementation of ``method='GJ'``.
+        sympy.polys.matrices.sdm.sdm_rref_den
+            Sparse implementation of ``method='FF'`` and ``method='CD'``.
+        sympy.polys.matrices.dense.ddm_irref
+            Dense implementation of ``method='GJ'``.
+        sympy.polys.matrices.dense.ddm_irref_den
+            Dense implementation of ``method='FF'`` and ``method='CD'``.
+        clear_denoms
+            Clear denominators from a matrix, used by ``method='CD'`` and
+            by ``method='GJ'`` when the original domain is not a field.
+
+        """
+        return _dm_rref(self, method=method)
+
+    def rref_den(self, *, method='auto', keep_domain=True):
+        r"""
+        Returns reduced-row echelon form with denominator and list of pivots.
+
+        Requires exact division in the ground domain (``exquo``).
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ, QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...     [ZZ(2), ZZ(-1), ZZ(0)],
+        ...     [ZZ(-1), ZZ(2), ZZ(-1)],
+        ...     [ZZ(0), ZZ(0), ZZ(2)]], (3, 3), ZZ)
+
+        >>> A_rref, denom, pivots = A.rref_den()
+        >>> A_rref
+        DomainMatrix([[6, 0, 0], [0, 6, 0], [0, 0, 6]], (3, 3), ZZ)
+        >>> denom
+        6
+        >>> pivots
+        (0, 1, 2)
+        >>> A_rref.to_field() / denom
+        DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ)
+        >>> A_rref.to_field() / denom == A.convert_to(QQ).rref()[0]
+        True
+
+        Parameters
+        ==========
+
+        method : str, optional (default: 'auto')
+            The method to use to compute the RREF. The default is ``'auto'``,
+            which will attempt to choose the fastest method. The other options
+            are:
+
+            - ``A.rref(method='FF')`` uses fraction-free Gauss-Jordan
+              elimination. Elimination is performed using exact division
+              (``exquo``) to control the growth of the coefficients. In this
+              case the current domain is always used for elimination and the
+              result is always returned as a matrix over the current domain.
+              This is most efficient for dense matrices or for matrices with
+              simple denominators.
+
+            - ``A.rref(method='CD')`` clears denominators before using
+              fraction-free Gauss-Jordan elimination in the assoicated ring.
+              The result will be converted back to the original domain unless
+              ``keep_domain=False`` is passed in which case the result will be
+              over the ring used for elimination. This is most efficient for
+              dense matrices with very simple denominators.
+
+            - ``A.rref(method='GJ')`` uses Gauss-Jordan elimination with
+              division. If the domain is not a field then it will be converted
+              to a field with :meth:`to_field` first and RREF will be computed
+              by inverting the pivot elements in each row. The result is
+              converted back to the original domain by clearing denominators
+              unless ``keep_domain=False`` is passed in which case the result
+              will be over the field used for elimination. This is most
+              efficient for very sparse matrices or for matrices whose elements
+              have complex denominators.
+
+            - ``A.rref(method='GJ_dense')``, ``A.rref(method='FF_dense')``, and
+              ``A.rref(method='CD_dense')`` are the same as the above methods
+              except that the dense implementations of the algorithms are used.
+              By default ``A.rref(method='auto')`` will usually choose the
+              sparse implementations for RREF.
+
+            Regardless of which algorithm is used the returned matrix will
+            always have the same format (sparse or dense) as the input and if
+            ``keep_domain=True`` its domain will always be the same as the
+            input.
+
+        keep_domain : bool, optional
+            If True (the default), the domain of the returned matrix and
+            denominator are the same as the domain of the input matrix. If
+            False, the domain of the returned matrix might be changed to an
+            associated ring or field if the algorithm used a different domain.
+            This is useful for efficiency if the caller does not need the
+            result to be in the original domain e.g. it avoids clearing
+            denominators in the case of ``A.rref(method='GJ')``.
+
+        Returns
+        =======
+
+        (DomainMatrix, scalar, list)
+            Reduced-row echelon form, denominator and list of pivot indices.
+
+        See Also
+        ========
+
+        rref
+            RREF without denominator for field domains.
+        sympy.polys.matrices.sdm.sdm_irref
+            Sparse implementation of ``method='GJ'``.
+        sympy.polys.matrices.sdm.sdm_rref_den
+            Sparse implementation of ``method='FF'`` and ``method='CD'``.
+        sympy.polys.matrices.dense.ddm_irref
+            Dense implementation of ``method='GJ'``.
+        sympy.polys.matrices.dense.ddm_irref_den
+            Dense implementation of ``method='FF'`` and ``method='CD'``.
+        clear_denoms
+            Clear denominators from a matrix, used by ``method='CD'``.
+
+        """
+        return _dm_rref_den(self, method=method, keep_domain=keep_domain)
+
+    def columnspace(self):
+        r"""
+        Returns the columnspace for the DomainMatrix
+
+        Returns
+        =======
+
+        DomainMatrix
+            The columns of this matrix form a basis for the columnspace.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [QQ(1), QQ(-1)],
+        ...    [QQ(2), QQ(-2)]], (2, 2), QQ)
+        >>> A.columnspace()
+        DomainMatrix([[1], [2]], (2, 1), QQ)
+
+        """
+        if not self.domain.is_Field:
+            raise DMNotAField('Not a field')
+        rref, pivots = self.rref()
+        rows, cols = self.shape
+        return self.extract(range(rows), pivots)
+
+    def rowspace(self):
+        r"""
+        Returns the rowspace for the DomainMatrix
+
+        Returns
+        =======
+
+        DomainMatrix
+            The rows of this matrix form a basis for the rowspace.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [QQ(1), QQ(-1)],
+        ...    [QQ(2), QQ(-2)]], (2, 2), QQ)
+        >>> A.rowspace()
+        DomainMatrix([[1, -1]], (1, 2), QQ)
+
+        """
+        if not self.domain.is_Field:
+            raise DMNotAField('Not a field')
+        rref, pivots = self.rref()
+        rows, cols = self.shape
+        return self.extract(range(len(pivots)), range(cols))
+
+    def nullspace(self, divide_last=False):
+        r"""
+        Returns the nullspace for the DomainMatrix
+
+        Returns
+        =======
+
+        DomainMatrix
+            The rows of this matrix form a basis for the nullspace.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([
+        ...    [QQ(2), QQ(-2)],
+        ...    [QQ(4), QQ(-4)]], QQ)
+        >>> A.nullspace()
+        DomainMatrix([[1, 1]], (1, 2), QQ)
+
+        The returned matrix is a basis for the nullspace:
+
+        >>> A_null = A.nullspace().transpose()
+        >>> A * A_null
+        DomainMatrix([[0], [0]], (2, 1), QQ)
+        >>> rows, cols = A.shape
+        >>> nullity = rows - A.rank()
+        >>> A_null.shape == (cols, nullity)
+        True
+
+        Nullspace can also be computed for non-field rings. If the ring is not
+        a field then division is not used. Setting ``divide_last`` to True will
+        raise an error in this case:
+
+        >>> from sympy import ZZ
+        >>> B = DM([[6, -3],
+        ...         [4, -2]], ZZ)
+        >>> B.nullspace()
+        DomainMatrix([[3, 6]], (1, 2), ZZ)
+        >>> B.nullspace(divide_last=True)
+        Traceback (most recent call last):
+        ...
+        DMNotAField: Cannot normalize vectors over a non-field
+
+        Over a ring with ``gcd`` defined the nullspace can potentially be
+        reduced with :meth:`primitive`:
+
+        >>> B.nullspace().primitive()
+        (3, DomainMatrix([[1, 2]], (1, 2), ZZ))
+
+        A matrix over a ring can often be normalized by converting it to a
+        field but it is often a bad idea to do so:
+
+        >>> from sympy.abc import a, b, c
+        >>> from sympy import Matrix
+        >>> M = Matrix([[        a*b,       b + c,        c],
+        ...             [      a - b,         b*c,     c**2],
+        ...             [a*b + a - b, b*c + b + c, c**2 + c]])
+        >>> M.to_DM().domain
+        ZZ[a,b,c]
+        >>> M.to_DM().nullspace().to_Matrix().transpose()
+        Matrix([
+        [                             c**3],
+        [            -a*b*c**2 + a*c - b*c],
+        [a*b**2*c - a*b - a*c + b**2 + b*c]])
+
+        The unnormalized form here is nicer than the normalized form that
+        spreads a large denominator throughout the matrix:
+
+        >>> M.to_DM().to_field().nullspace(divide_last=True).to_Matrix().transpose()
+        Matrix([
+        [                   c**3/(a*b**2*c - a*b - a*c + b**2 + b*c)],
+        [(-a*b*c**2 + a*c - b*c)/(a*b**2*c - a*b - a*c + b**2 + b*c)],
+        [                                                          1]])
+
+        Parameters
+        ==========
+
+        divide_last : bool, optional
+            If False (the default), the vectors are not normalized and the RREF
+            is computed using :meth:`rref_den` and the denominator is
+            discarded. If True, then each row is divided by its final element;
+            the domain must be a field in this case.
+
+        See Also
+        ========
+
+        nullspace_from_rref
+        rref
+        rref_den
+        rowspace
+        """
+        A = self
+        K = A.domain
+
+        if divide_last and not K.is_Field:
+            raise DMNotAField("Cannot normalize vectors over a non-field")
+
+        if divide_last:
+            A_rref, pivots = A.rref()
+        else:
+            A_rref, den, pivots = A.rref_den()
+
+            # Ensure that the sign is canonical before discarding the
+            # denominator. Then M.nullspace().primitive() is canonical.
+            u = K.canonical_unit(den)
+            if u != K.one:
+                A_rref *= u
+
+        A_null = A_rref.nullspace_from_rref(pivots)
+
+        return A_null
+
+    def nullspace_from_rref(self, pivots=None):
+        """
+        Compute nullspace from rref and pivots.
+
+        The domain of the matrix can be any domain.
+
+        The matrix must be in reduced row echelon form already. Otherwise the
+        result will be incorrect. Use :meth:`rref` or :meth:`rref_den` first
+        to get the reduced row echelon form or use :meth:`nullspace` instead.
+
+        See Also
+        ========
+
+        nullspace
+        rref
+        rref_den
+        sympy.polys.matrices.sdm.SDM.nullspace_from_rref
+        sympy.polys.matrices.ddm.DDM.nullspace_from_rref
+        """
+        null_rep, nonpivots = self.rep.nullspace_from_rref(pivots)
+        return self.from_rep(null_rep)
+
+    def inv(self):
+        r"""
+        Finds the inverse of the DomainMatrix if exists
+
+        Returns
+        =======
+
+        DomainMatrix
+            DomainMatrix after inverse
+
+        Raises
+        ======
+
+        ValueError
+            If the domain of DomainMatrix not a Field
+
+        DMNonSquareMatrixError
+            If the DomainMatrix is not a not Square DomainMatrix
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...     [QQ(2), QQ(-1), QQ(0)],
+        ...     [QQ(-1), QQ(2), QQ(-1)],
+        ...     [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
+        >>> A.inv()
+        DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ)
+
+        See Also
+        ========
+
+        neg
+
+        """
+        if not self.domain.is_Field:
+            raise DMNotAField('Not a field')
+        m, n = self.shape
+        if m != n:
+            raise DMNonSquareMatrixError
+        inv = self.rep.inv()
+        return self.from_rep(inv)
+
+    def det(self):
+        r"""
+        Returns the determinant of a square :class:`DomainMatrix`.
+
+        Returns
+        =======
+
+        determinant: DomainElement
+            Determinant of the matrix.
+
+        Raises
+        ======
+
+        ValueError
+            If the domain of DomainMatrix is not a Field
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+        >>> A.det()
+        -2
+
+        """
+        m, n = self.shape
+        if m != n:
+            raise DMNonSquareMatrixError
+        return self.rep.det()
+
+    def adj_det(self):
+        """
+        Adjugate and determinant of a square :class:`DomainMatrix`.
+
+        Returns
+        =======
+
+        (adjugate, determinant) : (DomainMatrix, DomainScalar)
+            The adjugate matrix and determinant of this matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([
+        ...     [ZZ(1), ZZ(2)],
+        ...     [ZZ(3), ZZ(4)]], ZZ)
+        >>> adjA, detA = A.adj_det()
+        >>> adjA
+        DomainMatrix([[4, -2], [-3, 1]], (2, 2), ZZ)
+        >>> detA
+        -2
+
+        See Also
+        ========
+
+        adjugate
+            Returns only the adjugate matrix.
+        det
+            Returns only the determinant.
+        inv_den
+            Returns a matrix/denominator pair representing the inverse matrix
+            but perhaps differing from the adjugate and determinant by a common
+            factor.
+        """
+        m, n = self.shape
+        I_m = self.eye((m, m), self.domain)
+        adjA, detA = self.solve_den_charpoly(I_m, check=False)
+        if self.rep.fmt == "dense":
+            adjA = adjA.to_dense()
+        return adjA, detA
+
+    def adjugate(self):
+        """
+        Adjugate of a square :class:`DomainMatrix`.
+
+        The adjugate matrix is the transpose of the cofactor matrix and is
+        related to the inverse by::
+
+            adj(A) = det(A) * A.inv()
+
+        Unlike the inverse matrix the adjugate matrix can be computed and
+        expressed without division or fractions in the ground domain.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ)
+        >>> A.adjugate()
+        DomainMatrix([[4, -2], [-3, 1]], (2, 2), ZZ)
+
+        Returns
+        =======
+
+        DomainMatrix
+            The adjugate matrix of this matrix with the same domain.
+
+        See Also
+        ========
+
+        adj_det
+        """
+        adjA, detA = self.adj_det()
+        return adjA
+
+    def inv_den(self, method=None):
+        """
+        Return the inverse as a :class:`DomainMatrix` with denominator.
+
+        Returns
+        =======
+
+        (inv, den) : (:class:`DomainMatrix`, :class:`~.DomainElement`)
+            The inverse matrix and its denominator.
+
+        This is more or less equivalent to :meth:`adj_det` except that ``inv``
+        and ``den`` are not guaranteed to be the adjugate and inverse. The
+        ratio ``inv/den`` is equivalent to ``adj/det`` but some factors
+        might be cancelled between ``inv`` and ``den``. In simple cases this
+        might just be a minus sign so that ``(inv, den) == (-adj, -det)`` but
+        factors more complicated than ``-1`` can also be cancelled.
+        Cancellation is not guaranteed to be complete so ``inv`` and ``den``
+        may not be on lowest terms. The denominator ``den`` will be zero if and
+        only if the determinant is zero.
+
+        If the actual adjugate and determinant are needed, use :meth:`adj_det`
+        instead. If the intention is to compute the inverse matrix or solve a
+        system of equations then :meth:`inv_den` is more efficient.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...     [ZZ(2), ZZ(-1), ZZ(0)],
+        ...     [ZZ(-1), ZZ(2), ZZ(-1)],
+        ...     [ZZ(0), ZZ(0), ZZ(2)]], (3, 3), ZZ)
+        >>> Ainv, den = A.inv_den()
+        >>> den
+        6
+        >>> Ainv
+        DomainMatrix([[4, 2, 1], [2, 4, 2], [0, 0, 3]], (3, 3), ZZ)
+        >>> A * Ainv == den * A.eye(A.shape, A.domain).to_dense()
+        True
+
+        Parameters
+        ==========
+
+        method : str, optional
+            The method to use to compute the inverse. Can be one of ``None``,
+            ``'rref'`` or ``'charpoly'``. If ``None`` then the method is
+            chosen automatically (see :meth:`solve_den` for details).
+
+        See Also
+        ========
+
+        inv
+        det
+        adj_det
+        solve_den
+        """
+        I = self.eye(self.shape, self.domain)
+        return self.solve_den(I, method=method)
+
+    def solve_den(self, b, method=None):
+        """
+        Solve matrix equation $Ax = b$ without fractions in the ground domain.
+
+        Examples
+        ========
+
+        Solve a matrix equation over the integers:
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ)
+        >>> b = DM([[ZZ(5)], [ZZ(6)]], ZZ)
+        >>> xnum, xden = A.solve_den(b)
+        >>> xden
+        -2
+        >>> xnum
+        DomainMatrix([[8], [-9]], (2, 1), ZZ)
+        >>> A * xnum == xden * b
+        True
+
+        Solve a matrix equation over a polynomial ring:
+
+        >>> from sympy import ZZ
+        >>> from sympy.abc import x, y, z, a, b
+        >>> R = ZZ[x, y, z, a, b]
+        >>> M = DM([[x*y, x*z], [y*z, x*z]], R)
+        >>> b = DM([[a], [b]], R)
+        >>> M.to_Matrix()
+        Matrix([
+        [x*y, x*z],
+        [y*z, x*z]])
+        >>> b.to_Matrix()
+        Matrix([
+        [a],
+        [b]])
+        >>> xnum, xden = M.solve_den(b)
+        >>> xden
+        x**2*y*z - x*y*z**2
+        >>> xnum.to_Matrix()
+        Matrix([
+        [ a*x*z - b*x*z],
+        [-a*y*z + b*x*y]])
+        >>> M * xnum == xden * b
+        True
+
+        The solution can be expressed over a fraction field which will cancel
+        gcds between the denominator and the elements of the numerator:
+
+        >>> xsol = xnum.to_field() / xden
+        >>> xsol.to_Matrix()
+        Matrix([
+        [           (a - b)/(x*y - y*z)],
+        [(-a*z + b*x)/(x**2*z - x*z**2)]])
+        >>> (M * xsol).to_Matrix() == b.to_Matrix()
+        True
+
+        When solving a large system of equations this cancellation step might
+        be a lot slower than :func:`solve_den` itself. The solution can also be
+        expressed as a ``Matrix`` without attempting any polynomial
+        cancellation between the numerator and denominator giving a less
+        simplified result more quickly:
+
+        >>> xsol_uncancelled = xnum.to_Matrix() / xnum.domain.to_sympy(xden)
+        >>> xsol_uncancelled
+        Matrix([
+        [ (a*x*z - b*x*z)/(x**2*y*z - x*y*z**2)],
+        [(-a*y*z + b*x*y)/(x**2*y*z - x*y*z**2)]])
+        >>> from sympy import cancel
+        >>> cancel(xsol_uncancelled) == xsol.to_Matrix()
+        True
+
+        Parameters
+        ==========
+
+        self : :class:`DomainMatrix`
+            The ``m x n`` matrix $A$ in the equation $Ax = b$. Underdetermined
+            systems are not supported so ``m >= n``: $A$ should be square or
+            have more rows than columns.
+        b : :class:`DomainMatrix`
+            The ``n x m`` matrix $b$ for the rhs.
+        cp : list of :class:`~.DomainElement`, optional
+            The characteristic polynomial of the matrix $A$. If not given, it
+            will be computed using :meth:`charpoly`.
+        method: str, optional
+            The method to use for solving the system. Can be one of ``None``,
+            ``'charpoly'`` or ``'rref'``. If ``None`` (the default) then the
+            method will be chosen automatically.
+
+            The ``charpoly`` method uses :meth:`solve_den_charpoly` and can
+            only be used if the matrix is square. This method is division free
+            and can be used with any domain.
+
+            The ``rref`` method is fraction free but requires exact division
+            in the ground domain (``exquo``). This is also suitable for most
+            domains. This method can be used with overdetermined systems (more
+            equations than unknowns) but not underdetermined systems as a
+            unique solution is sought.
+
+        Returns
+        =======
+
+        (xnum, xden) : (DomainMatrix, DomainElement)
+            The solution of the equation $Ax = b$ as a pair consisting of an
+            ``n x m`` matrix numerator ``xnum`` and a scalar denominator
+            ``xden``.
+
+        The solution $x$ is given by ``x = xnum / xden``. The division free
+        invariant is ``A * xnum == xden * b``. If $A$ is square then the
+        denominator ``xden`` will be a divisor of the determinant $det(A)$.
+
+        Raises
+        ======
+
+        DMNonInvertibleMatrixError
+            If the system $Ax = b$ does not have a unique solution.
+
+        See Also
+        ========
+
+        solve_den_charpoly
+        solve_den_rref
+        inv_den
+        """
+        m, n = self.shape
+        bm, bn = b.shape
+
+        if m != bm:
+            raise DMShapeError("Matrix equation shape mismatch.")
+
+        if method is None:
+            method = 'rref'
+        elif method == 'charpoly' and m != n:
+            raise DMNonSquareMatrixError("method='charpoly' requires a square matrix.")
+
+        if method == 'charpoly':
+            xnum, xden = self.solve_den_charpoly(b)
+        elif method == 'rref':
+            xnum, xden = self.solve_den_rref(b)
+        else:
+            raise DMBadInputError("method should be 'rref' or 'charpoly'")
+
+        return xnum, xden
+
+    def solve_den_rref(self, b):
+        """
+        Solve matrix equation $Ax = b$ using fraction-free RREF
+
+        Solves the matrix equation $Ax = b$ for $x$ and returns the solution
+        as a numerator/denominator pair.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ)
+        >>> b = DM([[ZZ(5)], [ZZ(6)]], ZZ)
+        >>> xnum, xden = A.solve_den_rref(b)
+        >>> xden
+        -2
+        >>> xnum
+        DomainMatrix([[8], [-9]], (2, 1), ZZ)
+        >>> A * xnum == xden * b
+        True
+
+        See Also
+        ========
+
+        solve_den
+        solve_den_charpoly
+        """
+        A = self
+        m, n = A.shape
+        bm, bn = b.shape
+
+        if m != bm:
+            raise DMShapeError("Matrix equation shape mismatch.")
+
+        if m < n:
+            raise DMShapeError("Underdetermined matrix equation.")
+
+        Aaug = A.hstack(b)
+        Aaug_rref, denom, pivots = Aaug.rref_den()
+
+        # XXX: We check here if there are pivots after the last column. If
+        # there were than it possibly means that rref_den performed some
+        # unnecessary elimination. It would be better if rref methods had a
+        # parameter indicating how many columns should be used for elimination.
+        if len(pivots) != n or pivots and pivots[-1] >= n:
+            raise DMNonInvertibleMatrixError("Non-unique solution.")
+
+        xnum = Aaug_rref[:n, n:]
+        xden = denom
+
+        return xnum, xden
+
+    def solve_den_charpoly(self, b, cp=None, check=True):
+        """
+        Solve matrix equation $Ax = b$ using the characteristic polynomial.
+
+        This method solves the square matrix equation $Ax = b$ for $x$ using
+        the characteristic polynomial without any division or fractions in the
+        ground domain.
+
+        Examples
+        ========
+
+        Solve a matrix equation over the integers:
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], ZZ)
+        >>> b = DM([[ZZ(5)], [ZZ(6)]], ZZ)
+        >>> xnum, detA = A.solve_den_charpoly(b)
+        >>> detA
+        -2
+        >>> xnum
+        DomainMatrix([[8], [-9]], (2, 1), ZZ)
+        >>> A * xnum == detA * b
+        True
+
+        Parameters
+        ==========
+
+        self : DomainMatrix
+            The ``n x n`` matrix `A` in the equation `Ax = b`. Must be square
+            and invertible.
+        b : DomainMatrix
+            The ``n x m`` matrix `b` for the rhs.
+        cp : list, optional
+            The characteristic polynomial of the matrix `A` if known. If not
+            given, it will be computed using :meth:`charpoly`.
+        check : bool, optional
+            If ``True`` (the default) check that the determinant is not zero
+            and raise an error if it is. If ``False`` then if the determinant
+            is zero the return value will be equal to ``(A.adjugate()*b, 0)``.
+
+        Returns
+        =======
+
+        (xnum, detA) : (DomainMatrix, DomainElement)
+            The solution of the equation `Ax = b` as a matrix numerator and
+            scalar denominator pair. The denominator is equal to the
+            determinant of `A` and the numerator is ``adj(A)*b``.
+
+        The solution $x$ is given by ``x = xnum / detA``. The division free
+        invariant is ``A * xnum == detA * b``.
+
+        If ``b`` is the identity matrix, then ``xnum`` is the adjugate matrix
+        and we have ``A * adj(A) == detA * I``.
+
+        See Also
+        ========
+
+        solve_den
+            Main frontend for solving matrix equations with denominator.
+        solve_den_rref
+            Solve matrix equations using fraction-free RREF.
+        inv_den
+            Invert a matrix using the characteristic polynomial.
+        """
+        A, b = self.unify(b)
+        m, n = self.shape
+        mb, nb = b.shape
+
+        if m != n:
+            raise DMNonSquareMatrixError("Matrix must be square")
+
+        if mb != m:
+            raise DMShapeError("Matrix and vector must have the same number of rows")
+
+        f, detA = self.adj_poly_det(cp=cp)
+
+        if check and not detA:
+            raise DMNonInvertibleMatrixError("Matrix is not invertible")
+
+        # Compute adj(A)*b = det(A)*inv(A)*b using Horner's method without
+        # constructing inv(A) explicitly.
+        adjA_b = self.eval_poly_mul(f, b)
+
+        return (adjA_b, detA)
+
+    def adj_poly_det(self, cp=None):
+        """
+        Return the polynomial $p$ such that $p(A) = adj(A)$ and also the
+        determinant of $A$.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ)
+        >>> p, detA = A.adj_poly_det()
+        >>> p
+        [-1, 5]
+        >>> p_A = A.eval_poly(p)
+        >>> p_A
+        DomainMatrix([[4, -2], [-3, 1]], (2, 2), QQ)
+        >>> p[0]*A**1 + p[1]*A**0 == p_A
+        True
+        >>> p_A == A.adjugate()
+        True
+        >>> A * A.adjugate() == detA * A.eye(A.shape, A.domain).to_dense()
+        True
+
+        See Also
+        ========
+
+        adjugate
+        eval_poly
+        adj_det
+        """
+
+        # Cayley-Hamilton says that a matrix satisfies its own minimal
+        # polynomial
+        #
+        #   p[0]*A^n + p[1]*A^(n-1) + ... + p[n]*I = 0
+        #
+        # with p[0]=1 and p[n]=(-1)^n*det(A) or
+        #
+        #   det(A)*I = -(-1)^n*(p[0]*A^(n-1) + p[1]*A^(n-2) + ... + p[n-1]*A).
+        #
+        # Define a new polynomial f with f[i] = -(-1)^n*p[i] for i=0..n-1. Then
+        #
+        #   det(A)*I = f[0]*A^n + f[1]*A^(n-1) + ... + f[n-1]*A.
+        #
+        # Multiplying on the right by inv(A) gives
+        #
+        #   det(A)*inv(A) = f[0]*A^(n-1) + f[1]*A^(n-2) + ... + f[n-1].
+        #
+        # So adj(A) = det(A)*inv(A) = f(A)
+
+        A = self
+        m, n = self.shape
+
+        if m != n:
+            raise DMNonSquareMatrixError("Matrix must be square")
+
+        if cp is None:
+            cp = A.charpoly()
+
+        if len(cp) % 2:
+            # n is even
+            detA = cp[-1]
+            f = [-cpi for cpi in cp[:-1]]
+        else:
+            # n is odd
+            detA = -cp[-1]
+            f = cp[:-1]
+
+        return f, detA
+
+    def eval_poly(self, p):
+        """
+        Evaluate polynomial function of a matrix $p(A)$.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ)
+        >>> p = [QQ(1), QQ(2), QQ(3)]
+        >>> p_A = A.eval_poly(p)
+        >>> p_A
+        DomainMatrix([[12, 14], [21, 33]], (2, 2), QQ)
+        >>> p_A == p[0]*A**2 + p[1]*A + p[2]*A**0
+        True
+
+        See Also
+        ========
+
+        eval_poly_mul
+        """
+        A = self
+        m, n = A.shape
+
+        if m != n:
+            raise DMNonSquareMatrixError("Matrix must be square")
+
+        if not p:
+            return self.zeros(self.shape, self.domain)
+        elif len(p) == 1:
+            return p[0] * self.eye(self.shape, self.domain)
+
+        # Evaluate p(A) using Horner's method:
+        # XXX: Use Paterson-Stockmeyer method?
+        I = A.eye(A.shape, A.domain)
+        p_A = p[0] * I
+        for pi in p[1:]:
+            p_A = A*p_A + pi*I
+
+        return p_A
+
+    def eval_poly_mul(self, p, B):
+        r"""
+        Evaluate polynomial matrix product $p(A) \times B$.
+
+        Evaluate the polynomial matrix product $p(A) \times B$ using Horner's
+        method without creating the matrix $p(A)$ explicitly. If $B$ is a
+        column matrix then this method will only use matrix-vector multiplies
+        and no matrix-matrix multiplies are needed.
+
+        If $B$ is square or wide or if $A$ can be represented in a simpler
+        domain than $B$ then it might be faster to evaluate $p(A)$ explicitly
+        (see :func:`eval_poly`) and then multiply with $B$.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DM
+        >>> A = DM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], QQ)
+        >>> b = DM([[QQ(5)], [QQ(6)]], QQ)
+        >>> p = [QQ(1), QQ(2), QQ(3)]
+        >>> p_A_b = A.eval_poly_mul(p, b)
+        >>> p_A_b
+        DomainMatrix([[144], [303]], (2, 1), QQ)
+        >>> p_A_b == p[0]*A**2*b + p[1]*A*b + p[2]*b
+        True
+        >>> A.eval_poly_mul(p, b) == A.eval_poly(p)*b
+        True
+
+        See Also
+        ========
+
+        eval_poly
+        solve_den_charpoly
+        """
+        A = self
+        m, n = A.shape
+        mb, nb = B.shape
+
+        if m != n:
+            raise DMNonSquareMatrixError("Matrix must be square")
+
+        if mb != n:
+            raise DMShapeError("Matrices are not aligned")
+
+        if A.domain != B.domain:
+            raise DMDomainError("Matrices must have the same domain")
+
+        # Given a polynomial p(x) = p[0]*x^n + p[1]*x^(n-1) + ... + p[n-1]
+        # and matrices A and B we want to find
+        #
+        #   p(A)*B = p[0]*A^n*B + p[1]*A^(n-1)*B + ... + p[n-1]*B
+        #
+        # Factoring out A term by term we get
+        #
+        #   p(A)*B = A*(...A*(A*(A*(p[0]*B) + p[1]*B) + p[2]*B) + ...) + p[n-1]*B
+        #
+        # where each pair of brackets represents one iteration of the loop
+        # below starting from the innermost p[0]*B. If B is a column matrix
+        # then products like A*(...) are matrix-vector multiplies and products
+        # like p[i]*B are scalar-vector multiplies so there are no
+        # matrix-matrix multiplies.
+
+        if not p:
+            return B.zeros(B.shape, B.domain, fmt=B.rep.fmt)
+
+        p_A_B = p[0]*B
+
+        for p_i in p[1:]:
+            p_A_B = A*p_A_B + p_i*B
+
+        return p_A_B
+
+    def lu(self):
+        r"""
+        Returns Lower and Upper decomposition of the DomainMatrix
+
+        Returns
+        =======
+
+        (L, U, exchange)
+            L, U are Lower and Upper decomposition of the DomainMatrix,
+            exchange is the list of indices of rows exchanged in the
+            decomposition.
+
+        Raises
+        ======
+
+        ValueError
+            If the domain of DomainMatrix not a Field
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [QQ(1), QQ(-1)],
+        ...    [QQ(2), QQ(-2)]], (2, 2), QQ)
+        >>> L, U, exchange = A.lu()
+        >>> L
+        DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ)
+        >>> U
+        DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ)
+        >>> exchange
+        []
+
+        See Also
+        ========
+
+        lu_solve
+
+        """
+        if not self.domain.is_Field:
+            raise DMNotAField('Not a field')
+        L, U, swaps = self.rep.lu()
+        return self.from_rep(L), self.from_rep(U), swaps
+
+    def lu_solve(self, rhs):
+        r"""
+        Solver for DomainMatrix x in the A*x = B
+
+        Parameters
+        ==========
+
+        rhs : DomainMatrix B
+
+        Returns
+        =======
+
+        DomainMatrix
+            x in A*x = B
+
+        Raises
+        ======
+
+        DMShapeError
+            If the DomainMatrix A and rhs have different number of rows
+
+        ValueError
+            If the domain of DomainMatrix A not a Field
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [QQ(1), QQ(2)],
+        ...    [QQ(3), QQ(4)]], (2, 2), QQ)
+        >>> B = DomainMatrix([
+        ...    [QQ(1), QQ(1)],
+        ...    [QQ(0), QQ(1)]], (2, 2), QQ)
+
+        >>> A.lu_solve(B)
+        DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ)
+
+        See Also
+        ========
+
+        lu
+
+        """
+        if self.shape[0] != rhs.shape[0]:
+            raise DMShapeError("Shape")
+        if not self.domain.is_Field:
+            raise DMNotAField('Not a field')
+        sol = self.rep.lu_solve(rhs.rep)
+        return self.from_rep(sol)
+
+    def _solve(A, b):
+        # XXX: Not sure about this method or its signature. It is just created
+        # because it is needed by the holonomic module.
+        if A.shape[0] != b.shape[0]:
+            raise DMShapeError("Shape")
+        if A.domain != b.domain or not A.domain.is_Field:
+            raise DMNotAField('Not a field')
+        Aaug = A.hstack(b)
+        Arref, pivots = Aaug.rref()
+        particular = Arref.from_rep(Arref.rep.particular())
+        nullspace_rep, nonpivots = Arref[:,:-1].rep.nullspace()
+        nullspace = Arref.from_rep(nullspace_rep)
+        return particular, nullspace
+
+    def charpoly(self):
+        r"""
+        Characteristic polynomial of a square matrix.
+
+        Computes the characteristic polynomial in a fully expanded form using
+        division free arithmetic. If a factorization of the characteristic
+        polynomial is needed then it is more efficient to call
+        :meth:`charpoly_factor_list` than calling :meth:`charpoly` and then
+        factorizing the result.
+
+        Returns
+        =======
+
+        list: list of DomainElement
+            coefficients of the characteristic polynomial
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+        >>> A.charpoly()
+        [1, -5, -2]
+
+        See Also
+        ========
+
+        charpoly_factor_list
+            Compute the factorisation of the characteristic polynomial.
+        charpoly_factor_blocks
+            A partial factorisation of the characteristic polynomial that can
+            be computed more efficiently than either the full factorisation or
+            the fully expanded polynomial.
+        """
+        M = self
+        K = M.domain
+
+        factors = M.charpoly_factor_blocks()
+
+        cp = [K.one]
+
+        for f, mult in factors:
+            for _ in range(mult):
+                cp = dup_mul(cp, f, K)
+
+        return cp
+
+    def charpoly_factor_list(self):
+        """
+        Full factorization of the characteristic polynomial.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import ZZ
+        >>> M = DM([[6, -1, 0, 0],
+        ...         [9, 12, 0, 0],
+        ...         [0,  0, 1, 2],
+        ...         [0,  0, 5, 6]], ZZ)
+
+        Compute the factorization of the characteristic polynomial:
+
+        >>> M.charpoly_factor_list()
+        [([1, -9], 2), ([1, -7, -4], 1)]
+
+        Use :meth:`charpoly` to get the unfactorized characteristic polynomial:
+
+        >>> M.charpoly()
+        [1, -25, 203, -495, -324]
+
+        The same calculations with ``Matrix``:
+
+        >>> M.to_Matrix().charpoly().as_expr()
+        lambda**4 - 25*lambda**3 + 203*lambda**2 - 495*lambda - 324
+        >>> M.to_Matrix().charpoly().as_expr().factor()
+        (lambda - 9)**2*(lambda**2 - 7*lambda - 4)
+
+        Returns
+        =======
+
+        list: list of pairs (factor, multiplicity)
+            A full factorization of the characteristic polynomial.
+
+        See Also
+        ========
+
+        charpoly
+            Expanded form of the characteristic polynomial.
+        charpoly_factor_blocks
+            A partial factorisation of the characteristic polynomial that can
+            be computed more efficiently.
+        """
+        M = self
+        K = M.domain
+
+        # It is more efficient to start from the partial factorization provided
+        # for free by M.charpoly_factor_blocks than the expanded M.charpoly.
+        factors = M.charpoly_factor_blocks()
+
+        factors_irreducible = []
+
+        for factor_i, mult_i in factors:
+
+            _, factors_list = dup_factor_list(factor_i, K)
+
+            for factor_j, mult_j in factors_list:
+                factors_irreducible.append((factor_j, mult_i * mult_j))
+
+        return _collect_factors(factors_irreducible)
+
+    def charpoly_factor_blocks(self):
+        """
+        Partial factorisation of the characteristic polynomial.
+
+        This factorisation arises from a block structure of the matrix (if any)
+        and so the factors are not guaranteed to be irreducible. The
+        :meth:`charpoly_factor_blocks` method is the most efficient way to get
+        a representation of the characteristic polynomial but the result is
+        neither fully expanded nor fully factored.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import ZZ
+        >>> M = DM([[6, -1, 0, 0],
+        ...         [9, 12, 0, 0],
+        ...         [0,  0, 1, 2],
+        ...         [0,  0, 5, 6]], ZZ)
+
+        This computes a partial factorization using only the block structure of
+        the matrix to reveal factors:
+
+        >>> M.charpoly_factor_blocks()
+        [([1, -18, 81], 1), ([1, -7, -4], 1)]
+
+        These factors correspond to the two diagonal blocks in the matrix:
+
+        >>> DM([[6, -1], [9, 12]], ZZ).charpoly()
+        [1, -18, 81]
+        >>> DM([[1, 2], [5, 6]], ZZ).charpoly()
+        [1, -7, -4]
+
+        Use :meth:`charpoly_factor_list` to get a complete factorization into
+        irreducibles:
+
+        >>> M.charpoly_factor_list()
+        [([1, -9], 2), ([1, -7, -4], 1)]
+
+        Use :meth:`charpoly` to get the expanded characteristic polynomial:
+
+        >>> M.charpoly()
+        [1, -25, 203, -495, -324]
+
+        Returns
+        =======
+
+        list: list of pairs (factor, multiplicity)
+            A partial factorization of the characteristic polynomial.
+
+        See Also
+        ========
+
+        charpoly
+            Compute the fully expanded characteristic polynomial.
+        charpoly_factor_list
+            Compute a full factorization of the characteristic polynomial.
+        """
+        M = self
+
+        if not M.is_square:
+            raise DMNonSquareMatrixError("not square")
+
+        # scc returns indices that permute the matrix into block triangular
+        # form and can extract the diagonal blocks. M.charpoly() is equal to
+        # the product of the diagonal block charpolys.
+        components = M.scc()
+
+        block_factors = []
+
+        for indices in components:
+            block = M.extract(indices, indices)
+            block_factors.append((block.charpoly_base(), 1))
+
+        return _collect_factors(block_factors)
+
+    def charpoly_base(self):
+        """
+        Base case for :meth:`charpoly_factor_blocks` after block decomposition.
+
+        This method is used internally by :meth:`charpoly_factor_blocks` as the
+        base case for computing the characteristic polynomial of a block. It is
+        more efficient to call :meth:`charpoly_factor_blocks`, :meth:`charpoly`
+        or :meth:`charpoly_factor_list` rather than call this method directly.
+
+        This will use either the dense or the sparse implementation depending
+        on the sparsity of the matrix and will clear denominators if possible
+        before calling :meth:`charpoly_berk` to compute the characteristic
+        polynomial using the Berkowitz algorithm.
+
+        See Also
+        ========
+
+        charpoly
+        charpoly_factor_list
+        charpoly_factor_blocks
+        charpoly_berk
+        """
+        M = self
+        K = M.domain
+
+        # It seems that the sparse implementation is always faster for random
+        # matrices with fewer than 50% non-zero entries. This does not seem to
+        # depend on domain, size, bit count etc.
+        density = self.nnz() / self.shape[0]**2
+        if density < 0.5:
+            M = M.to_sparse()
+        else:
+            M = M.to_dense()
+
+        # Clearing denominators is always more efficient if it can be done.
+        # Doing it here after block decomposition is good because each block
+        # might have a smaller denominator. However it might be better for
+        # charpoly and charpoly_factor_list to restore the denominators only at
+        # the very end so that they can call e.g. dup_factor_list before
+        # restoring the denominators. The methods would need to be changed to
+        # return (poly, denom) pairs to make that work though.
+        clear_denoms = K.is_Field and K.has_assoc_Ring
+
+        if clear_denoms:
+            clear_denoms = True
+            d, M = M.clear_denoms(convert=True)
+            d = d.element
+            K_f = K
+            K_r = M.domain
+
+        # Berkowitz algorithm over K_r.
+        cp = M.charpoly_berk()
+
+        if clear_denoms:
+            # Restore the denominator in the charpoly over K_f.
+            #
+            # If M = N/d then p_M(x) = p_N(x*d)/d^n.
+            cp = dup_convert(cp, K_r, K_f)
+            p = [K_f.one, K_f.zero]
+            q = [K_f.one/d]
+            cp = dup_transform(cp, p, q, K_f)
+
+        return cp
+
+    def charpoly_berk(self):
+        """Compute the characteristic polynomial using the Berkowitz algorithm.
+
+        This method directly calls the underlying implementation of the
+        Berkowitz algorithm (:meth:`sympy.polys.matrices.dense.ddm_berk` or
+        :meth:`sympy.polys.matrices.sdm.sdm_berk`).
+
+        This is used by :meth:`charpoly` and other methods as the base case for
+        for computing the characteristic polynomial. However those methods will
+        apply other optimizations such as block decomposition, clearing
+        denominators and converting between dense and sparse representations
+        before calling this method. It is more efficient to call those methods
+        instead of this one but this method is provided for direct access to
+        the Berkowitz algorithm.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy import QQ
+        >>> M = DM([[6, -1, 0, 0],
+        ...         [9, 12, 0, 0],
+        ...         [0,  0, 1, 2],
+        ...         [0,  0, 5, 6]], QQ)
+        >>> M.charpoly_berk()
+        [1, -25, 203, -495, -324]
+
+        See Also
+        ========
+
+        charpoly
+        charpoly_base
+        charpoly_factor_list
+        charpoly_factor_blocks
+        sympy.polys.matrices.dense.ddm_berk
+        sympy.polys.matrices.sdm.sdm_berk
+        """
+        return self.rep.charpoly()
+
+    @classmethod
+    def eye(cls, shape, domain):
+        r"""
+        Return identity matrix of size n or shape (m, n).
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> DomainMatrix.eye(3, QQ)
+        DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ)
+
+        """
+        if isinstance(shape, int):
+            shape = (shape, shape)
+        return cls.from_rep(SDM.eye(shape, domain))
+
+    @classmethod
+    def diag(cls, diagonal, domain, shape=None):
+        r"""
+        Return diagonal matrix with entries from ``diagonal``.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import ZZ
+        >>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ)
+        DomainMatrix({0: {0: 5}, 1: {1: 6}}, (2, 2), ZZ)
+
+        """
+        if shape is None:
+            N = len(diagonal)
+            shape = (N, N)
+        return cls.from_rep(SDM.diag(diagonal, domain, shape))
+
+    @classmethod
+    def zeros(cls, shape, domain, *, fmt='sparse'):
+        """Returns a zero DomainMatrix of size shape, belonging to the specified domain
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> DomainMatrix.zeros((2, 3), QQ)
+        DomainMatrix({}, (2, 3), QQ)
+
+        """
+        return cls.from_rep(SDM.zeros(shape, domain))
+
+    @classmethod
+    def ones(cls, shape, domain):
+        """Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy import QQ
+        >>> DomainMatrix.ones((2,3), QQ)
+        DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ)
+
+        """
+        return cls.from_rep(DDM.ones(shape, domain).to_dfm_or_ddm())
+
+    def __eq__(A, B):
+        r"""
+        Checks for two DomainMatrix matrices to be equal or not
+
+        Parameters
+        ==========
+
+        A, B: DomainMatrix
+            to check equality
+
+        Returns
+        =======
+
+        Boolean
+            True for equal, else False
+
+        Raises
+        ======
+
+        NotImplementedError
+            If B is not a DomainMatrix
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> A = DomainMatrix([
+        ...    [ZZ(1), ZZ(2)],
+        ...    [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+        >>> B = DomainMatrix([
+        ...    [ZZ(1), ZZ(1)],
+        ...    [ZZ(0), ZZ(1)]], (2, 2), ZZ)
+        >>> A.__eq__(A)
+        True
+        >>> A.__eq__(B)
+        False
+
+        """
+        if not isinstance(A, type(B)):
+            return NotImplemented
+        return A.domain == B.domain and A.rep == B.rep
+
+    def unify_eq(A, B):
+        if A.shape != B.shape:
+            return False
+        if A.domain != B.domain:
+            A, B = A.unify(B)
+        return A == B
+
+    def lll(A, delta=QQ(3, 4)):
+        """
+        Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.
+        See [1]_ and [2]_.
+
+        Parameters
+        ==========
+
+        delta : QQ, optional
+            The Lovász parameter. Must be in the interval (0.25, 1), with larger
+            values producing a more reduced basis. The default is 0.75 for
+            historical reasons.
+
+        Returns
+        =======
+
+        The reduced basis as a DomainMatrix over ZZ.
+
+        Throws
+        ======
+
+        DMValueError: if delta is not in the range (0.25, 1)
+        DMShapeError: if the matrix is not of shape (m, n) with m <= n
+        DMDomainError: if the matrix domain is not ZZ
+        DMRankError: if the matrix contains linearly dependent rows
+
+        Examples
+        ========
+
+        >>> from sympy.polys.domains import ZZ, QQ
+        >>> from sympy.polys.matrices import DM
+        >>> x = DM([[1, 0, 0, 0, -20160],
+        ...         [0, 1, 0, 0, 33768],
+        ...         [0, 0, 1, 0, 39578],
+        ...         [0, 0, 0, 1, 47757]], ZZ)
+        >>> y = DM([[10, -3, -2, 8, -4],
+        ...         [3, -9, 8, 1, -11],
+        ...         [-3, 13, -9, -3, -9],
+        ...         [-12, -7, -11, 9, -1]], ZZ)
+        >>> assert x.lll(delta=QQ(5, 6)) == y
+
+        Notes
+        =====
+
+        The implementation is derived from the Maple code given in Figures 4.3
+        and 4.4 of [3]_ (pp.68-69). It uses the efficient method of only calculating
+        state updates as they are required.
+
+        See also
+        ========
+
+        lll_transform
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Lenstra%E2%80%93Lenstra%E2%80%93Lov%C3%A1sz_lattice_basis_reduction_algorithm
+        .. [2] https://web.archive.org/web/20221029115428/https://web.cs.elte.hu/~lovasz/scans/lll.pdf
+        .. [3] Murray R. Bremner, "Lattice Basis Reduction: An Introduction to the LLL Algorithm and Its Applications"
+
+        """
+        return DomainMatrix.from_rep(A.rep.lll(delta=delta))
+
+    def lll_transform(A, delta=QQ(3, 4)):
+        """
+        Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm
+        and returns the reduced basis and transformation matrix.
+
+        Explanation
+        ===========
+
+        Parameters, algorithm and basis are the same as for :meth:`lll` except that
+        the return value is a tuple `(B, T)` with `B` the reduced basis and
+        `T` a transformation matrix. The original basis `A` is transformed to
+        `B` with `T*A == B`. If only `B` is needed then :meth:`lll` should be
+        used as it is a little faster.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.domains import ZZ, QQ
+        >>> from sympy.polys.matrices import DM
+        >>> X = DM([[1, 0, 0, 0, -20160],
+        ...         [0, 1, 0, 0, 33768],
+        ...         [0, 0, 1, 0, 39578],
+        ...         [0, 0, 0, 1, 47757]], ZZ)
+        >>> B, T = X.lll_transform(delta=QQ(5, 6))
+        >>> T * X == B
+        True
+
+        See also
+        ========
+
+        lll
+
+        """
+        reduced, transform = A.rep.lll_transform(delta=delta)
+        return DomainMatrix.from_rep(reduced), DomainMatrix.from_rep(transform)
+
+
+def _collect_factors(factors_list):
+    """
+    Collect repeating factors and sort.
+
+    >>> from sympy.polys.matrices.domainmatrix import _collect_factors
+    >>> _collect_factors([([1, 2], 2), ([1, 4], 3), ([1, 2], 5)])
+    [([1, 4], 3), ([1, 2], 7)]
+    """
+    factors = Counter()
+    for factor, exponent in factors_list:
+        factors[tuple(factor)] += exponent
+
+    factors_list = [(list(f), e) for f, e in factors.items()]
+
+    return _sort_factors(factors_list)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/domainscalar.py b/lib/python3.11/site-packages/sympy/polys/matrices/domainscalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..df439a60a0ea0df5f6fac988c06da2a06a4fbac2
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/domainscalar.py
@@ -0,0 +1,122 @@
+"""
+
+Module for the DomainScalar class.
+
+A DomainScalar represents an element which is in a particular
+Domain. The idea is that the DomainScalar class provides the
+convenience routines for unifying elements with different domains.
+
+It assists in Scalar Multiplication and getitem for DomainMatrix.
+
+"""
+from ..constructor import construct_domain
+
+from sympy.polys.domains import Domain, ZZ
+
+
+class DomainScalar:
+    r"""
+    docstring
+    """
+
+    def __new__(cls, element, domain):
+        if not isinstance(domain, Domain):
+            raise TypeError("domain should be of type Domain")
+        if not domain.of_type(element):
+            raise TypeError("element %s should be in domain %s" % (element, domain))
+        return cls.new(element, domain)
+
+    @classmethod
+    def new(cls, element, domain):
+        obj = super().__new__(cls)
+        obj.element = element
+        obj.domain = domain
+        return obj
+
+    def __repr__(self):
+        return repr(self.element)
+
+    @classmethod
+    def from_sympy(cls, expr):
+        [domain, [element]] = construct_domain([expr])
+        return cls.new(element, domain)
+
+    def to_sympy(self):
+        return self.domain.to_sympy(self.element)
+
+    def to_domain(self, domain):
+        element = domain.convert_from(self.element, self.domain)
+        return self.new(element, domain)
+
+    def convert_to(self, domain):
+        return self.to_domain(domain)
+
+    def unify(self, other):
+        domain = self.domain.unify(other.domain)
+        return self.to_domain(domain), other.to_domain(domain)
+
+    def __bool__(self):
+        return bool(self.element)
+
+    def __add__(self, other):
+        if not isinstance(other, DomainScalar):
+            return NotImplemented
+        self, other = self.unify(other)
+        return self.new(self.element + other.element, self.domain)
+
+    def __sub__(self, other):
+        if not isinstance(other, DomainScalar):
+            return NotImplemented
+        self, other = self.unify(other)
+        return self.new(self.element - other.element, self.domain)
+
+    def __mul__(self, other):
+        if not isinstance(other, DomainScalar):
+            if isinstance(other, int):
+                other = DomainScalar(ZZ(other), ZZ)
+            else:
+                return NotImplemented
+
+        self, other = self.unify(other)
+        return self.new(self.element * other.element, self.domain)
+
+    def __floordiv__(self, other):
+        if not isinstance(other, DomainScalar):
+            return NotImplemented
+        self, other = self.unify(other)
+        return self.new(self.domain.quo(self.element, other.element), self.domain)
+
+    def __mod__(self, other):
+        if not isinstance(other, DomainScalar):
+            return NotImplemented
+        self, other = self.unify(other)
+        return self.new(self.domain.rem(self.element, other.element), self.domain)
+
+    def __divmod__(self, other):
+        if not isinstance(other, DomainScalar):
+            return NotImplemented
+        self, other = self.unify(other)
+        q, r = self.domain.div(self.element, other.element)
+        return (self.new(q, self.domain), self.new(r, self.domain))
+
+    def __pow__(self, n):
+        if not isinstance(n, int):
+            return NotImplemented
+        return self.new(self.element**n, self.domain)
+
+    def __pos__(self):
+        return self.new(+self.element, self.domain)
+
+    def __neg__(self):
+        return self.new(-self.element, self.domain)
+
+    def __eq__(self, other):
+        if not isinstance(other, DomainScalar):
+            return NotImplemented
+        return self.element == other.element and self.domain == other.domain
+
+    def is_zero(self):
+        return self.element == self.domain.zero
+
+    def is_one(self):
+        return self.element == self.domain.one
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/eigen.py b/lib/python3.11/site-packages/sympy/polys/matrices/eigen.py
new file mode 100644
index 0000000000000000000000000000000000000000..17d673c6ea09002e1cfd5357f301c447a7af4341
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/eigen.py
@@ -0,0 +1,90 @@
+"""
+
+Routines for computing eigenvectors with DomainMatrix.
+
+"""
+from sympy.core.symbol import Dummy
+
+from ..agca.extensions import FiniteExtension
+from ..factortools import dup_factor_list
+from ..polyroots import roots
+from ..polytools import Poly
+from ..rootoftools import CRootOf
+
+from .domainmatrix import DomainMatrix
+
+
+def dom_eigenvects(A, l=Dummy('lambda')):
+    charpoly = A.charpoly()
+    rows, cols = A.shape
+    domain = A.domain
+    _, factors = dup_factor_list(charpoly, domain)
+
+    rational_eigenvects = []
+    algebraic_eigenvects = []
+    for base, exp in factors:
+        if len(base) == 2:
+            field = domain
+            eigenval = -base[1] / base[0]
+
+            EE_items = [
+                [eigenval if i == j else field.zero for j in range(cols)]
+                for i in range(rows)]
+            EE = DomainMatrix(EE_items, (rows, cols), field)
+
+            basis = (A - EE).nullspace(divide_last=True)
+            rational_eigenvects.append((field, eigenval, exp, basis))
+        else:
+            minpoly = Poly.from_list(base, l, domain=domain)
+            field = FiniteExtension(minpoly)
+            eigenval = field(l)
+
+            AA_items = [
+                [Poly.from_list([item], l, domain=domain).rep for item in row]
+                for row in A.rep.to_ddm()]
+            AA_items = [[field(item) for item in row] for row in AA_items]
+            AA = DomainMatrix(AA_items, (rows, cols), field)
+            EE_items = [
+                [eigenval if i == j else field.zero for j in range(cols)]
+                for i in range(rows)]
+            EE = DomainMatrix(EE_items, (rows, cols), field)
+
+            basis = (AA - EE).nullspace(divide_last=True)
+            algebraic_eigenvects.append((field, minpoly, exp, basis))
+
+    return rational_eigenvects, algebraic_eigenvects
+
+
+def dom_eigenvects_to_sympy(
+    rational_eigenvects, algebraic_eigenvects,
+    Matrix, **kwargs
+):
+    result = []
+
+    for field, eigenvalue, multiplicity, eigenvects in rational_eigenvects:
+        eigenvects = eigenvects.rep.to_ddm()
+        eigenvalue = field.to_sympy(eigenvalue)
+        new_eigenvects = [
+            Matrix([field.to_sympy(x) for x in vect])
+            for vect in eigenvects]
+        result.append((eigenvalue, multiplicity, new_eigenvects))
+
+    for field, minpoly, multiplicity, eigenvects in algebraic_eigenvects:
+        eigenvects = eigenvects.rep.to_ddm()
+        l = minpoly.gens[0]
+
+        eigenvects = [[field.to_sympy(x) for x in vect] for vect in eigenvects]
+
+        degree = minpoly.degree()
+        minpoly = minpoly.as_expr()
+        eigenvals = roots(minpoly, l, **kwargs)
+        if len(eigenvals) != degree:
+            eigenvals = [CRootOf(minpoly, l, idx) for idx in range(degree)]
+
+        for eigenvalue in eigenvals:
+            new_eigenvects = [
+                Matrix([x.subs(l, eigenvalue) for x in vect])
+                for vect in eigenvects]
+            result.append((eigenvalue, multiplicity, new_eigenvects))
+
+    return result
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/exceptions.py b/lib/python3.11/site-packages/sympy/polys/matrices/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1e5a4195c66aceed2d5ac1994381d3dec6a64ba
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/exceptions.py
@@ -0,0 +1,67 @@
+"""
+
+Module to define exceptions to be used in sympy.polys.matrices modules and
+classes.
+
+Ideally all exceptions raised in these modules would be defined and documented
+here and not e.g. imported from matrices. Also ideally generic exceptions like
+ValueError/TypeError would not be raised anywhere.
+
+"""
+
+
+class DMError(Exception):
+    """Base class for errors raised by DomainMatrix"""
+    pass
+
+
+class DMBadInputError(DMError):
+    """list of lists is inconsistent with shape"""
+    pass
+
+
+class DMDomainError(DMError):
+    """domains do not match"""
+    pass
+
+
+class DMNotAField(DMDomainError):
+    """domain is not a field"""
+    pass
+
+
+class DMFormatError(DMError):
+    """mixed dense/sparse not supported"""
+    pass
+
+
+class DMNonInvertibleMatrixError(DMError):
+    """The matrix in not invertible"""
+    pass
+
+
+class DMRankError(DMError):
+    """matrix does not have expected rank"""
+    pass
+
+
+class DMShapeError(DMError):
+    """shapes are inconsistent"""
+    pass
+
+
+class DMNonSquareMatrixError(DMShapeError):
+    """The matrix is not square"""
+    pass
+
+
+class DMValueError(DMError):
+    """The value passed is invalid"""
+    pass
+
+
+__all__ = [
+    'DMError', 'DMBadInputError', 'DMDomainError', 'DMFormatError',
+    'DMRankError', 'DMShapeError', 'DMNotAField',
+    'DMNonInvertibleMatrixError', 'DMNonSquareMatrixError', 'DMValueError'
+]
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/linsolve.py b/lib/python3.11/site-packages/sympy/polys/matrices/linsolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..af74058d859b744cf8fe1059ddb7c775fece79c7
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/linsolve.py
@@ -0,0 +1,230 @@
+#
+# sympy.polys.matrices.linsolve module
+#
+# This module defines the _linsolve function which is the internal workhorse
+# used by linsolve. This computes the solution of a system of linear equations
+# using the SDM sparse matrix implementation in sympy.polys.matrices.sdm. This
+# is a replacement for solve_lin_sys in sympy.polys.solvers which is
+# inefficient for large sparse systems due to the use of a PolyRing with many
+# generators:
+#
+#     https://github.com/sympy/sympy/issues/20857
+#
+# The implementation of _linsolve here handles:
+#
+# - Extracting the coefficients from the Expr/Eq input equations.
+# - Constructing a domain and converting the coefficients to
+#   that domain.
+# - Using the SDM.rref, SDM.nullspace etc methods to generate the full
+#   solution working with arithmetic only in the domain of the coefficients.
+#
+# The routines here are particularly designed to be efficient for large sparse
+# systems of linear equations although as well as dense systems. It is
+# possible that for some small dense systems solve_lin_sys which uses the
+# dense matrix implementation DDM will be more efficient. With smaller systems
+# though the bulk of the time is spent just preprocessing the inputs and the
+# relative time spent in rref is too small to be noticeable.
+#
+
+from collections import defaultdict
+
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+
+from sympy.polys.constructor import construct_domain
+from sympy.polys.solvers import PolyNonlinearError
+
+from .sdm import (
+    SDM,
+    sdm_irref,
+    sdm_particular_from_rref,
+    sdm_nullspace_from_rref
+)
+
+from sympy.utilities.misc import filldedent
+
+
+def _linsolve(eqs, syms):
+
+    """Solve a linear system of equations.
+
+    Examples
+    ========
+
+    Solve a linear system with a unique solution:
+
+    >>> from sympy import symbols, Eq
+    >>> from sympy.polys.matrices.linsolve import _linsolve
+    >>> x, y = symbols('x, y')
+    >>> eqs = [Eq(x + y, 1), Eq(x - y, 2)]
+    >>> _linsolve(eqs, [x, y])
+    {x: 3/2, y: -1/2}
+
+    In the case of underdetermined systems the solution will be expressed in
+    terms of the unknown symbols that are unconstrained:
+
+    >>> _linsolve([Eq(x + y, 0)], [x, y])
+    {x: -y, y: y}
+
+    """
+    # Number of unknowns (columns in the non-augmented matrix)
+    nsyms = len(syms)
+
+    # Convert to sparse augmented matrix (len(eqs) x (nsyms+1))
+    eqsdict, const = _linear_eq_to_dict(eqs, syms)
+    Aaug = sympy_dict_to_dm(eqsdict, const, syms)
+    K = Aaug.domain
+
+    # sdm_irref has issues with float matrices. This uses the ddm_rref()
+    # function. When sdm_rref() can handle float matrices reasonably this
+    # should be removed...
+    if K.is_RealField or K.is_ComplexField:
+        Aaug = Aaug.to_ddm().rref()[0].to_sdm()
+
+    # Compute reduced-row echelon form (RREF)
+    Arref, pivots, nzcols = sdm_irref(Aaug)
+
+    # No solution:
+    if pivots and pivots[-1] == nsyms:
+        return None
+
+    # Particular solution for non-homogeneous system:
+    P = sdm_particular_from_rref(Arref, nsyms+1, pivots)
+
+    # Nullspace - general solution to homogeneous system
+    # Note: using nsyms not nsyms+1 to ignore last column
+    V, nonpivots = sdm_nullspace_from_rref(Arref, K.one, nsyms, pivots, nzcols)
+
+    # Collect together terms from particular and nullspace:
+    sol = defaultdict(list)
+    for i, v in P.items():
+        sol[syms[i]].append(K.to_sympy(v))
+    for npi, Vi in zip(nonpivots, V):
+        sym = syms[npi]
+        for i, v in Vi.items():
+            sol[syms[i]].append(sym * K.to_sympy(v))
+
+    # Use a single call to Add for each term:
+    sol = {s: Add(*terms) for s, terms in sol.items()}
+
+    # Fill in the zeros:
+    zero = S.Zero
+    for s in set(syms) - set(sol):
+        sol[s] = zero
+
+    # All done!
+    return sol
+
+
+def sympy_dict_to_dm(eqs_coeffs, eqs_rhs, syms):
+    """Convert a system of dict equations to a sparse augmented matrix"""
+    elems = set(eqs_rhs).union(*(e.values() for e in eqs_coeffs))
+    K, elems_K = construct_domain(elems, field=True, extension=True)
+    elem_map = dict(zip(elems, elems_K))
+    neqs = len(eqs_coeffs)
+    nsyms = len(syms)
+    sym2index = dict(zip(syms, range(nsyms)))
+    eqsdict = []
+    for eq, rhs in zip(eqs_coeffs, eqs_rhs):
+        eqdict = {sym2index[s]: elem_map[c] for s, c in eq.items()}
+        if rhs:
+            eqdict[nsyms] = -elem_map[rhs]
+        if eqdict:
+            eqsdict.append(eqdict)
+    sdm_aug = SDM(enumerate(eqsdict), (neqs, nsyms + 1), K)
+    return sdm_aug
+
+
+def _linear_eq_to_dict(eqs, syms):
+    """Convert a system Expr/Eq equations into dict form, returning
+    the coefficient dictionaries and a list of syms-independent terms
+    from each expression in ``eqs```.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.linsolve import _linear_eq_to_dict
+    >>> from sympy.abc import x
+    >>> _linear_eq_to_dict([2*x + 3], {x})
+    ([{x: 2}], [3])
+    """
+    coeffs = []
+    ind = []
+    symset = set(syms)
+    for e in eqs:
+        if e.is_Equality:
+            coeff, terms = _lin_eq2dict(e.lhs, symset)
+            cR, tR = _lin_eq2dict(e.rhs, symset)
+            # there were no nonlinear errors so now
+            # cancellation is allowed
+            coeff -= cR
+            for k, v in tR.items():
+                if k in terms:
+                    terms[k] -= v
+                else:
+                    terms[k] = -v
+            # don't store coefficients of 0, however
+            terms = {k: v for k, v in terms.items() if v}
+            c, d = coeff, terms
+        else:
+            c, d = _lin_eq2dict(e, symset)
+        coeffs.append(d)
+        ind.append(c)
+    return coeffs, ind
+
+
+def _lin_eq2dict(a, symset):
+    """return (c, d) where c is the sym-independent part of ``a`` and
+    ``d`` is an efficiently calculated dictionary mapping symbols to
+    their coefficients. A PolyNonlinearError is raised if non-linearity
+    is detected.
+
+    The values in the dictionary will be non-zero.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.linsolve import _lin_eq2dict
+    >>> from sympy.abc import x, y
+    >>> _lin_eq2dict(x + 2*y + 3, {x, y})
+    (3, {x: 1, y: 2})
+    """
+    if a in symset:
+        return S.Zero, {a: S.One}
+    elif a.is_Add:
+        terms_list = defaultdict(list)
+        coeff_list = []
+        for ai in a.args:
+            ci, ti = _lin_eq2dict(ai, symset)
+            coeff_list.append(ci)
+            for mij, cij in ti.items():
+                terms_list[mij].append(cij)
+        coeff = Add(*coeff_list)
+        terms = {sym: Add(*coeffs) for sym, coeffs in terms_list.items()}
+        return coeff, terms
+    elif a.is_Mul:
+        terms = terms_coeff = None
+        coeff_list = []
+        for ai in a.args:
+            ci, ti = _lin_eq2dict(ai, symset)
+            if not ti:
+                coeff_list.append(ci)
+            elif terms is None:
+                terms = ti
+                terms_coeff = ci
+            else:
+                # since ti is not null and we already have
+                # a term, this is a cross term
+                raise PolyNonlinearError(filldedent('''
+                    nonlinear cross-term: %s''' % a))
+        coeff = Mul._from_args(coeff_list)
+        if terms is None:
+            return coeff, {}
+        else:
+            terms = {sym: coeff * c for sym, c in terms.items()}
+            return  coeff * terms_coeff, terms
+    elif not a.has_xfree(symset):
+        return a, {}
+    else:
+        raise PolyNonlinearError('nonlinear term: %s' % a)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/lll.py b/lib/python3.11/site-packages/sympy/polys/matrices/lll.py
new file mode 100644
index 0000000000000000000000000000000000000000..f33f91d92c5e20f89f302991e494a6a5b9fa4b2e
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/lll.py
@@ -0,0 +1,94 @@
+from __future__ import annotations
+
+from math import floor as mfloor
+
+from sympy.polys.domains import ZZ, QQ
+from sympy.polys.matrices.exceptions import DMRankError, DMShapeError, DMValueError, DMDomainError
+
+
+def _ddm_lll(x, delta=QQ(3, 4), return_transform=False):
+    if QQ(1, 4) >= delta or delta >= QQ(1, 1):
+        raise DMValueError("delta must lie in range (0.25, 1)")
+    if x.shape[0] > x.shape[1]:
+        raise DMShapeError("input matrix must have shape (m, n) with m <= n")
+    if x.domain != ZZ:
+        raise DMDomainError("input matrix domain must be ZZ")
+    m = x.shape[0]
+    n = x.shape[1]
+    k = 1
+    y = x.copy()
+    y_star = x.zeros((m, n), QQ)
+    mu = x.zeros((m, m), QQ)
+    g_star = [QQ(0, 1) for _ in range(m)]
+    half = QQ(1, 2)
+    T = x.eye(m, ZZ) if return_transform else None
+    linear_dependent_error = "input matrix contains linearly dependent rows"
+
+    def closest_integer(x):
+        return ZZ(mfloor(x + half))
+
+    def lovasz_condition(k: int) -> bool:
+        return g_star[k] >= ((delta - mu[k][k - 1] ** 2) * g_star[k - 1])
+
+    def mu_small(k: int, j: int) -> bool:
+        return abs(mu[k][j]) <= half
+
+    def dot_rows(x, y, rows: tuple[int, int]):
+        return sum(x[rows[0]][z] * y[rows[1]][z] for z in range(x.shape[1]))
+
+    def reduce_row(T, mu, y, rows: tuple[int, int]):
+        r = closest_integer(mu[rows[0]][rows[1]])
+        y[rows[0]] = [y[rows[0]][z] - r * y[rows[1]][z] for z in range(n)]
+        mu[rows[0]][:rows[1]] = [mu[rows[0]][z] - r * mu[rows[1]][z] for z in range(rows[1])]
+        mu[rows[0]][rows[1]] -= r
+        if return_transform:
+            T[rows[0]] = [T[rows[0]][z] - r * T[rows[1]][z] for z in range(m)]
+
+    for i in range(m):
+        y_star[i] = [QQ.convert_from(z, ZZ) for z in y[i]]
+        for j in range(i):
+            row_dot = dot_rows(y, y_star, (i, j))
+            try:
+                mu[i][j] = row_dot / g_star[j]
+            except ZeroDivisionError:
+                raise DMRankError(linear_dependent_error)
+            y_star[i] = [y_star[i][z] - mu[i][j] * y_star[j][z] for z in range(n)]
+        g_star[i] = dot_rows(y_star, y_star, (i, i))
+    while k < m:
+        if not mu_small(k, k - 1):
+            reduce_row(T, mu, y, (k, k - 1))
+        if lovasz_condition(k):
+            for l in range(k - 2, -1, -1):
+                if not mu_small(k, l):
+                    reduce_row(T, mu, y, (k, l))
+            k += 1
+        else:
+            nu = mu[k][k - 1]
+            alpha = g_star[k] + nu ** 2 * g_star[k - 1]
+            try:
+                beta = g_star[k - 1] / alpha
+            except ZeroDivisionError:
+                raise DMRankError(linear_dependent_error)
+            mu[k][k - 1] = nu * beta
+            g_star[k] = g_star[k] * beta
+            g_star[k - 1] = alpha
+            y[k], y[k - 1] = y[k - 1], y[k]
+            mu[k][:k - 1], mu[k - 1][:k - 1] = mu[k - 1][:k - 1], mu[k][:k - 1]
+            for i in range(k + 1, m):
+                xi = mu[i][k]
+                mu[i][k] = mu[i][k - 1] - nu * xi
+                mu[i][k - 1] = mu[k][k - 1] * mu[i][k] + xi
+            if return_transform:
+                T[k], T[k - 1] = T[k - 1], T[k]
+            k = max(k - 1, 1)
+    assert all(lovasz_condition(i) for i in range(1, m))
+    assert all(mu_small(i, j) for i in range(m) for j in range(i))
+    return y, T
+
+
+def ddm_lll(x, delta=QQ(3, 4)):
+    return _ddm_lll(x, delta=delta, return_transform=False)[0]
+
+
+def ddm_lll_transform(x, delta=QQ(3, 4)):
+    return _ddm_lll(x, delta=delta, return_transform=True)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/normalforms.py b/lib/python3.11/site-packages/sympy/polys/matrices/normalforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..507d9bf53163d56217a9b290bc42510445c20888
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/normalforms.py
@@ -0,0 +1,406 @@
+'''Functions returning normal forms of matrices'''
+
+from collections import defaultdict
+
+from .domainmatrix import DomainMatrix
+from .exceptions import DMDomainError, DMShapeError
+from sympy.ntheory.modular import symmetric_residue
+from sympy.polys.domains import QQ, ZZ
+
+
+# TODO (future work):
+#  There are faster algorithms for Smith and Hermite normal forms, which
+#  we should implement. See e.g. the Kannan-Bachem algorithm:
+#  
+
+
+def smith_normal_form(m):
+    '''
+    Return the Smith Normal Form of a matrix `m` over the ring `domain`.
+    This will only work if the ring is a principal ideal domain.
+
+    Examples
+    ========
+
+    >>> from sympy import ZZ
+    >>> from sympy.polys.matrices import DomainMatrix
+    >>> from sympy.polys.matrices.normalforms import smith_normal_form
+    >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)],
+    ...                   [ZZ(3), ZZ(9), ZZ(6)],
+    ...                   [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ)
+    >>> print(smith_normal_form(m).to_Matrix())
+    Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]])
+
+    '''
+    invs = invariant_factors(m)
+    smf = DomainMatrix.diag(invs, m.domain, m.shape)
+    return smf
+
+
+def add_columns(m, i, j, a, b, c, d):
+    # replace m[:, i] by a*m[:, i] + b*m[:, j]
+    # and m[:, j] by c*m[:, i] + d*m[:, j]
+    for k in range(len(m)):
+        e = m[k][i]
+        m[k][i] = a*e + b*m[k][j]
+        m[k][j] = c*e + d*m[k][j]
+
+
+def invariant_factors(m):
+    '''
+    Return the tuple of abelian invariants for a matrix `m`
+    (as in the Smith-Normal form)
+
+    References
+    ==========
+
+    [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm
+    [2] https://web.archive.org/web/20200331143852/https://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf
+
+    '''
+    domain = m.domain
+    if not domain.is_PID:
+        msg = "The matrix entries must be over a principal ideal domain"
+        raise ValueError(msg)
+
+    if 0 in m.shape:
+        return ()
+
+    rows, cols = shape = m.shape
+    m = list(m.to_dense().rep.to_ddm())
+
+    def add_rows(m, i, j, a, b, c, d):
+        # replace m[i, :] by a*m[i, :] + b*m[j, :]
+        # and m[j, :] by c*m[i, :] + d*m[j, :]
+        for k in range(cols):
+            e = m[i][k]
+            m[i][k] = a*e + b*m[j][k]
+            m[j][k] = c*e + d*m[j][k]
+
+    def clear_column(m):
+        # make m[1:, 0] zero by row and column operations
+        if m[0][0] == 0:
+            return m  # pragma: nocover
+        pivot = m[0][0]
+        for j in range(1, rows):
+            if m[j][0] == 0:
+                continue
+            d, r = domain.div(m[j][0], pivot)
+            if r == 0:
+                add_rows(m, 0, j, 1, 0, -d, 1)
+            else:
+                a, b, g = domain.gcdex(pivot, m[j][0])
+                d_0 = domain.div(m[j][0], g)[0]
+                d_j = domain.div(pivot, g)[0]
+                add_rows(m, 0, j, a, b, d_0, -d_j)
+                pivot = g
+        return m
+
+    def clear_row(m):
+        # make m[0, 1:] zero by row and column operations
+        if m[0][0] == 0:
+            return m  # pragma: nocover
+        pivot = m[0][0]
+        for j in range(1, cols):
+            if m[0][j] == 0:
+                continue
+            d, r = domain.div(m[0][j], pivot)
+            if r == 0:
+                add_columns(m, 0, j, 1, 0, -d, 1)
+            else:
+                a, b, g = domain.gcdex(pivot, m[0][j])
+                d_0 = domain.div(m[0][j], g)[0]
+                d_j = domain.div(pivot, g)[0]
+                add_columns(m, 0, j, a, b, d_0, -d_j)
+                pivot = g
+        return m
+
+    # permute the rows and columns until m[0,0] is non-zero if possible
+    ind = [i for i in range(rows) if m[i][0] != 0]
+    if ind and ind[0] != 0:
+        m[0], m[ind[0]] = m[ind[0]], m[0]
+    else:
+        ind = [j for j in range(cols) if m[0][j] != 0]
+        if ind and ind[0] != 0:
+            for row in m:
+                row[0], row[ind[0]] = row[ind[0]], row[0]
+
+    # make the first row and column except m[0,0] zero
+    while (any(m[0][i] != 0 for i in range(1,cols)) or
+           any(m[i][0] != 0 for i in range(1,rows))):
+        m = clear_column(m)
+        m = clear_row(m)
+
+    if 1 in shape:
+        invs = ()
+    else:
+        lower_right = DomainMatrix([r[1:] for r in m[1:]], (rows-1, cols-1), domain)
+        invs = invariant_factors(lower_right)
+
+    if m[0][0]:
+        result = [m[0][0]]
+        result.extend(invs)
+        # in case m[0] doesn't divide the invariants of the rest of the matrix
+        for i in range(len(result)-1):
+            if result[i] and domain.div(result[i+1], result[i])[1] != 0:
+                g = domain.gcd(result[i+1], result[i])
+                result[i+1] = domain.div(result[i], g)[0]*result[i+1]
+                result[i] = g
+            else:
+                break
+    else:
+        result = invs + (m[0][0],)
+    return tuple(result)
+
+
+def _gcdex(a, b):
+    r"""
+    This supports the functions that compute Hermite Normal Form.
+
+    Explanation
+    ===========
+
+    Let x, y be the coefficients returned by the extended Euclidean
+    Algorithm, so that x*a + y*b = g. In the algorithms for computing HNF,
+    it is critical that x, y not only satisfy the condition of being small
+    in magnitude -- namely that |x| <= |b|/g, |y| <- |a|/g -- but also that
+    y == 0 when a | b.
+
+    """
+    x, y, g = ZZ.gcdex(a, b)
+    if a != 0 and b % a == 0:
+        y = 0
+        x = -1 if a < 0 else 1
+    return x, y, g
+
+
+def _hermite_normal_form(A):
+    r"""
+    Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`.
+
+    Parameters
+    ==========
+
+    A : :py:class:`~.DomainMatrix` over domain :ref:`ZZ`.
+
+    Returns
+    =======
+
+    :py:class:`~.DomainMatrix`
+        The HNF of matrix *A*.
+
+    Raises
+    ======
+
+    DMDomainError
+        If the domain of the matrix is not :ref:`ZZ`.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+       (See Algorithm 2.4.5.)
+
+    """
+    if not A.domain.is_ZZ:
+        raise DMDomainError('Matrix must be over domain ZZ.')
+    # We work one row at a time, starting from the bottom row, and working our
+    # way up.
+    m, n = A.shape
+    A = A.to_dense().rep.to_ddm().copy()
+    # Our goal is to put pivot entries in the rightmost columns.
+    # Invariant: Before processing each row, k should be the index of the
+    # leftmost column in which we have so far put a pivot.
+    k = n
+    for i in range(m - 1, -1, -1):
+        if k == 0:
+            # This case can arise when n < m and we've already found n pivots.
+            # We don't need to consider any more rows, because this is already
+            # the maximum possible number of pivots.
+            break
+        k -= 1
+        # k now points to the column in which we want to put a pivot.
+        # We want zeros in all entries to the left of the pivot column.
+        for j in range(k - 1, -1, -1):
+            if A[i][j] != 0:
+                # Replace cols j, k by lin combs of these cols such that, in row i,
+                # col j has 0, while col k has the gcd of their row i entries. Note
+                # that this ensures a nonzero entry in col k.
+                u, v, d = _gcdex(A[i][k], A[i][j])
+                r, s = A[i][k] // d, A[i][j] // d
+                add_columns(A, k, j, u, v, -s, r)
+        b = A[i][k]
+        # Do not want the pivot entry to be negative.
+        if b < 0:
+            add_columns(A, k, k, -1, 0, -1, 0)
+            b = -b
+        # The pivot entry will be 0 iff the row was 0 from the pivot col all the
+        # way to the left. In this case, we are still working on the same pivot
+        # col for the next row. Therefore:
+        if b == 0:
+            k += 1
+        # If the pivot entry is nonzero, then we want to reduce all entries to its
+        # right in the sense of the division algorithm, i.e. make them all remainders
+        # w.r.t. the pivot as divisor.
+        else:
+            for j in range(k + 1, n):
+                q = A[i][j] // b
+                add_columns(A, j, k, 1, -q, 0, 1)
+    # Finally, the HNF consists of those columns of A in which we succeeded in making
+    # a nonzero pivot.
+    return DomainMatrix.from_rep(A.to_dfm_or_ddm())[:, k:]
+
+
+def _hermite_normal_form_modulo_D(A, D):
+    r"""
+    Perform the mod *D* Hermite Normal Form reduction algorithm on
+    :py:class:`~.DomainMatrix` *A*.
+
+    Explanation
+    ===========
+
+    If *A* is an $m \times n$ matrix of rank $m$, having Hermite Normal Form
+    $W$, and if *D* is any positive integer known in advance to be a multiple
+    of $\det(W)$, then the HNF of *A* can be computed by an algorithm that
+    works mod *D* in order to prevent coefficient explosion.
+
+    Parameters
+    ==========
+
+    A : :py:class:`~.DomainMatrix` over :ref:`ZZ`
+        $m \times n$ matrix, having rank $m$.
+    D : :ref:`ZZ`
+        Positive integer, known to be a multiple of the determinant of the
+        HNF of *A*.
+
+    Returns
+    =======
+
+    :py:class:`~.DomainMatrix`
+        The HNF of matrix *A*.
+
+    Raises
+    ======
+
+    DMDomainError
+        If the domain of the matrix is not :ref:`ZZ`, or
+        if *D* is given but is not in :ref:`ZZ`.
+
+    DMShapeError
+        If the matrix has more rows than columns.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+       (See Algorithm 2.4.8.)
+
+    """
+    if not A.domain.is_ZZ:
+        raise DMDomainError('Matrix must be over domain ZZ.')
+    if not ZZ.of_type(D) or D < 1:
+        raise DMDomainError('Modulus D must be positive element of domain ZZ.')
+
+    def add_columns_mod_R(m, R, i, j, a, b, c, d):
+        # replace m[:, i] by (a*m[:, i] + b*m[:, j]) % R
+        # and m[:, j] by (c*m[:, i] + d*m[:, j]) % R
+        for k in range(len(m)):
+            e = m[k][i]
+            m[k][i] = symmetric_residue((a * e + b * m[k][j]) % R, R)
+            m[k][j] = symmetric_residue((c * e + d * m[k][j]) % R, R)
+
+    W = defaultdict(dict)
+
+    m, n = A.shape
+    if n < m:
+        raise DMShapeError('Matrix must have at least as many columns as rows.')
+    A = A.to_dense().rep.to_ddm().copy()
+    k = n
+    R = D
+    for i in range(m - 1, -1, -1):
+        k -= 1
+        for j in range(k - 1, -1, -1):
+            if A[i][j] != 0:
+                u, v, d = _gcdex(A[i][k], A[i][j])
+                r, s = A[i][k] // d, A[i][j] // d
+                add_columns_mod_R(A, R, k, j, u, v, -s, r)
+        b = A[i][k]
+        if b == 0:
+            A[i][k] = b = R
+        u, v, d = _gcdex(b, R)
+        for ii in range(m):
+            W[ii][i] = u*A[ii][k] % R
+        if W[i][i] == 0:
+            W[i][i] = R
+        for j in range(i + 1, m):
+            q = W[i][j] // W[i][i]
+            add_columns(W, j, i, 1, -q, 0, 1)
+        R //= d
+    return DomainMatrix(W, (m, m), ZZ).to_dense()
+
+
+def hermite_normal_form(A, *, D=None, check_rank=False):
+    r"""
+    Compute the Hermite Normal Form of :py:class:`~.DomainMatrix` *A* over
+    :ref:`ZZ`.
+
+    Examples
+    ========
+
+    >>> from sympy import ZZ
+    >>> from sympy.polys.matrices import DomainMatrix
+    >>> from sympy.polys.matrices.normalforms import hermite_normal_form
+    >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)],
+    ...                   [ZZ(3), ZZ(9), ZZ(6)],
+    ...                   [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ)
+    >>> print(hermite_normal_form(m).to_Matrix())
+    Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]])
+
+    Parameters
+    ==========
+
+    A : $m \times n$ ``DomainMatrix`` over :ref:`ZZ`.
+
+    D : :ref:`ZZ`, optional
+        Let $W$ be the HNF of *A*. If known in advance, a positive integer *D*
+        being any multiple of $\det(W)$ may be provided. In this case, if *A*
+        also has rank $m$, then we may use an alternative algorithm that works
+        mod *D* in order to prevent coefficient explosion.
+
+    check_rank : boolean, optional (default=False)
+        The basic assumption is that, if you pass a value for *D*, then
+        you already believe that *A* has rank $m$, so we do not waste time
+        checking it for you. If you do want this to be checked (and the
+        ordinary, non-modulo *D* algorithm to be used if the check fails), then
+        set *check_rank* to ``True``.
+
+    Returns
+    =======
+
+    :py:class:`~.DomainMatrix`
+        The HNF of matrix *A*.
+
+    Raises
+    ======
+
+    DMDomainError
+        If the domain of the matrix is not :ref:`ZZ`, or
+        if *D* is given but is not in :ref:`ZZ`.
+
+    DMShapeError
+        If the mod *D* algorithm is used but the matrix has more rows than
+        columns.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+       (See Algorithms 2.4.5 and 2.4.8.)
+
+    """
+    if not A.domain.is_ZZ:
+        raise DMDomainError('Matrix must be over domain ZZ.')
+    if D is not None and (not check_rank or A.convert_to(QQ).rank() == A.shape[0]):
+        return _hermite_normal_form_modulo_D(A, D)
+    else:
+        return _hermite_normal_form(A)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/rref.py b/lib/python3.11/site-packages/sympy/polys/matrices/rref.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5a71b04971e8dc8ecac5cc2691f98ba68e35d45
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/rref.py
@@ -0,0 +1,422 @@
+# Algorithms for computing the reduced row echelon form of a matrix.
+#
+# We need to choose carefully which algorithms to use depending on the domain,
+# shape, and sparsity of the matrix as well as things like the bit count in the
+# case of ZZ or QQ. This is important because the algorithms have different
+# performance characteristics in the extremes of dense vs sparse.
+#
+# In all cases we use the sparse implementations but we need to choose between
+# Gauss-Jordan elimination with division and fraction-free Gauss-Jordan
+# elimination. For very sparse matrices over ZZ with low bit counts it is
+# asymptotically faster to use Gauss-Jordan elimination with division. For
+# dense matrices with high bit counts it is asymptotically faster to use
+# fraction-free Gauss-Jordan.
+#
+# The most important thing is to get the extreme cases right because it can
+# make a big difference. In between the extremes though we have to make a
+# choice and here we use empirically determined thresholds based on timings
+# with random sparse matrices.
+#
+# In the case of QQ we have to consider the denominators as well. If the
+# denominators are small then it is faster to clear them and use fraction-free
+# Gauss-Jordan over ZZ. If the denominators are large then it is faster to use
+# Gauss-Jordan elimination with division over QQ.
+#
+# Timings for the various algorithms can be found at
+#
+#   https://github.com/sympy/sympy/issues/25410
+#   https://github.com/sympy/sympy/pull/25443
+
+from sympy.polys.domains import ZZ
+
+from sympy.polys.matrices.sdm import SDM, sdm_irref, sdm_rref_den
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.dense import ddm_irref, ddm_irref_den
+
+
+def _dm_rref(M, *, method='auto'):
+    """
+    Compute the reduced row echelon form of a ``DomainMatrix``.
+
+    This function is the implementation of :meth:`DomainMatrix.rref`.
+
+    Chooses the best algorithm depending on the domain, shape, and sparsity of
+    the matrix as well as things like the bit count in the case of :ref:`ZZ` or
+    :ref:`QQ`. The result is returned over the field associated with the domain
+    of the Matrix.
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.rref
+        The ``DomainMatrix`` method that calls this function.
+    sympy.polys.matrices.rref._dm_rref_den
+        Alternative function for computing RREF with denominator.
+    """
+    method, use_fmt = _dm_rref_choose_method(M, method, denominator=False)
+
+    M, old_fmt = _dm_to_fmt(M, use_fmt)
+
+    if method == 'GJ':
+        # Use Gauss-Jordan with division over the associated field.
+        Mf = _to_field(M)
+        M_rref, pivots = _dm_rref_GJ(Mf)
+
+    elif method == 'FF':
+        # Use fraction-free GJ over the current domain.
+        M_rref_f, den, pivots = _dm_rref_den_FF(M)
+        M_rref = _to_field(M_rref_f) / den
+
+    elif method == 'CD':
+        # Clear denominators and use fraction-free GJ in the associated ring.
+        _, Mr = M.clear_denoms_rowwise(convert=True)
+        M_rref_f, den, pivots = _dm_rref_den_FF(Mr)
+        M_rref = _to_field(M_rref_f) / den
+
+    else:
+        raise ValueError(f"Unknown method for rref: {method}")
+
+    M_rref, _ = _dm_to_fmt(M_rref, old_fmt)
+
+    # Invariants:
+    #   - M_rref is in the same format (sparse or dense) as the input matrix.
+    #   - M_rref is in the associated field domain and any denominator was
+    #     divided in (so is implicitly 1 now).
+
+    return M_rref, pivots
+
+
+def _dm_rref_den(M, *, keep_domain=True, method='auto'):
+    """
+    Compute the reduced row echelon form of a ``DomainMatrix`` with denominator.
+
+    This function is the implementation of :meth:`DomainMatrix.rref_den`.
+
+    Chooses the best algorithm depending on the domain, shape, and sparsity of
+    the matrix as well as things like the bit count in the case of :ref:`ZZ` or
+    :ref:`QQ`. The result is returned over the same domain as the input matrix
+    unless ``keep_domain=False`` in which case the result might be over an
+    associated ring or field domain.
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den
+        The ``DomainMatrix`` method that calls this function.
+    sympy.polys.matrices.rref._dm_rref
+        Alternative function for computing RREF without denominator.
+    """
+    method, use_fmt = _dm_rref_choose_method(M, method, denominator=True)
+
+    M, old_fmt = _dm_to_fmt(M, use_fmt)
+
+    if method == 'FF':
+        # Use fraction-free GJ over the current domain.
+        M_rref, den, pivots = _dm_rref_den_FF(M)
+
+    elif method == 'GJ':
+        # Use Gauss-Jordan with division over the associated field.
+        M_rref_f, pivots = _dm_rref_GJ(_to_field(M))
+
+        # Convert back to the ring?
+        if keep_domain and M_rref_f.domain != M.domain:
+            _, M_rref = M_rref_f.clear_denoms(convert=True)
+
+            if pivots:
+                den = M_rref[0, pivots[0]].element
+            else:
+                den = M_rref.domain.one
+        else:
+            # Possibly an associated field
+            M_rref = M_rref_f
+            den = M_rref.domain.one
+
+    elif method == 'CD':
+        # Clear denominators and use fraction-free GJ in the associated ring.
+        _, Mr = M.clear_denoms_rowwise(convert=True)
+
+        M_rref_r, den, pivots = _dm_rref_den_FF(Mr)
+
+        if keep_domain and M_rref_r.domain != M.domain:
+            # Convert back to the field
+            M_rref = _to_field(M_rref_r) / den
+            den = M.domain.one
+        else:
+            # Possibly an associated ring
+            M_rref = M_rref_r
+
+            if pivots:
+                den = M_rref[0, pivots[0]].element
+            else:
+                den = M_rref.domain.one
+    else:
+        raise ValueError(f"Unknown method for rref: {method}")
+
+    M_rref, _ = _dm_to_fmt(M_rref, old_fmt)
+
+    # Invariants:
+    #   - M_rref is in the same format (sparse or dense) as the input matrix.
+    #   - If keep_domain=True then M_rref and den are in the same domain as the
+    #     input matrix
+    #   - If keep_domain=False then M_rref might be in an associated ring or
+    #     field domain but den is always in the same domain as M_rref.
+
+    return M_rref, den, pivots
+
+
+def _dm_to_fmt(M, fmt):
+    """Convert a matrix to the given format and return the old format."""
+    old_fmt = M.rep.fmt
+    if old_fmt == fmt:
+        pass
+    elif fmt == 'dense':
+        M = M.to_dense()
+    elif fmt == 'sparse':
+        M = M.to_sparse()
+    else:
+        raise ValueError(f'Unknown format: {fmt}') # pragma: no cover
+    return M, old_fmt
+
+
+# These are the four basic implementations that we want to choose between:
+
+
+def _dm_rref_GJ(M):
+    """Compute RREF using Gauss-Jordan elimination with division."""
+    if M.rep.fmt == 'sparse':
+        return _dm_rref_GJ_sparse(M)
+    else:
+        return _dm_rref_GJ_dense(M)
+
+
+def _dm_rref_den_FF(M):
+    """Compute RREF using fraction-free Gauss-Jordan elimination."""
+    if M.rep.fmt == 'sparse':
+        return _dm_rref_den_FF_sparse(M)
+    else:
+        return _dm_rref_den_FF_dense(M)
+
+
+def _dm_rref_GJ_sparse(M):
+    """Compute RREF using sparse Gauss-Jordan elimination with division."""
+    M_rref_d, pivots, _ = sdm_irref(M.rep)
+    M_rref_sdm = SDM(M_rref_d, M.shape, M.domain)
+    pivots = tuple(pivots)
+    return M.from_rep(M_rref_sdm), pivots
+
+
+def _dm_rref_GJ_dense(M):
+    """Compute RREF using dense Gauss-Jordan elimination with division."""
+    partial_pivot = M.domain.is_RR or M.domain.is_CC
+    ddm = M.rep.to_ddm().copy()
+    pivots = ddm_irref(ddm, _partial_pivot=partial_pivot)
+    M_rref_ddm = DDM(ddm, M.shape, M.domain)
+    pivots = tuple(pivots)
+    return M.from_rep(M_rref_ddm.to_dfm_or_ddm()), pivots
+
+
+def _dm_rref_den_FF_sparse(M):
+    """Compute RREF using sparse fraction-free Gauss-Jordan elimination."""
+    M_rref_d, den, pivots = sdm_rref_den(M.rep, M.domain)
+    M_rref_sdm = SDM(M_rref_d, M.shape, M.domain)
+    pivots = tuple(pivots)
+    return M.from_rep(M_rref_sdm), den, pivots
+
+
+def _dm_rref_den_FF_dense(M):
+    """Compute RREF using sparse fraction-free Gauss-Jordan elimination."""
+    ddm = M.rep.to_ddm().copy()
+    den, pivots = ddm_irref_den(ddm, M.domain)
+    M_rref_ddm = DDM(ddm, M.shape, M.domain)
+    pivots = tuple(pivots)
+    return M.from_rep(M_rref_ddm.to_dfm_or_ddm()), den, pivots
+
+
+def _dm_rref_choose_method(M, method, *, denominator=False):
+    """Choose the fastest method for computing RREF for M."""
+
+    if method != 'auto':
+        if method.endswith('_dense'):
+            method = method[:-len('_dense')]
+            use_fmt = 'dense'
+        else:
+            use_fmt = 'sparse'
+
+    else:
+        # The sparse implementations are always faster
+        use_fmt = 'sparse'
+
+        K = M.domain
+
+        if K.is_ZZ:
+            method = _dm_rref_choose_method_ZZ(M, denominator=denominator)
+        elif K.is_QQ:
+            method = _dm_rref_choose_method_QQ(M, denominator=denominator)
+        elif K.is_RR or K.is_CC:
+            # TODO: Add partial pivot support to the sparse implementations.
+            method = 'GJ'
+            use_fmt = 'dense'
+        elif K.is_EX and M.rep.fmt == 'dense' and not denominator:
+            # Do not switch to the sparse implementation for EX because the
+            # domain does not have proper canonicalization and the sparse
+            # implementation gives equivalent but non-identical results over EX
+            # from performing arithmetic in a different order. Specifically
+            # test_issue_23718 ends up getting a more complicated expression
+            # when using the sparse implementation. Probably the best fix for
+            # this is something else but for now we stick with the dense
+            # implementation for EX if the matrix is already dense.
+            method = 'GJ'
+            use_fmt = 'dense'
+        else:
+            # This is definitely suboptimal. More work is needed to determine
+            # the best method for computing RREF over different domains.
+            if denominator:
+                method = 'FF'
+            else:
+                method = 'GJ'
+
+    return method, use_fmt
+
+
+def _dm_rref_choose_method_QQ(M, *, denominator=False):
+    """Choose the fastest method for computing RREF over QQ."""
+    # The same sorts of considerations apply here as in the case of ZZ. Here
+    # though a new more significant consideration is what sort of denominators
+    # we have and what to do with them so we focus on that.
+
+    # First compute the density. This is the average number of non-zero entries
+    # per row but only counting rows that have at least one non-zero entry
+    # since RREF can ignore fully zero rows.
+    density, _, ncols = _dm_row_density(M)
+
+    # For sparse matrices use Gauss-Jordan elimination over QQ regardless.
+    if density < min(5, ncols/2):
+        return 'GJ'
+
+    # Compare the bit-length of the lcm of the denominators to the bit length
+    # of the numerators.
+    #
+    # The threshold here is empirical: we prefer rref over QQ if clearing
+    # denominators would result in a numerator matrix having 5x the bit size of
+    # the current numerators.
+    numers, denoms = _dm_QQ_numers_denoms(M)
+    numer_bits = max([n.bit_length() for n in numers], default=1)
+
+    denom_lcm = ZZ.one
+    for d in denoms:
+        denom_lcm = ZZ.lcm(denom_lcm, d)
+        if denom_lcm.bit_length() > 5*numer_bits:
+            return 'GJ'
+
+    # If we get here then the matrix is dense and the lcm of the denominators
+    # is not too large compared to the numerators. For particularly small
+    # denominators it is fastest just to clear them and use fraction-free
+    # Gauss-Jordan over ZZ. With very small denominators this is a little
+    # faster than using rref_den over QQ but there is an intermediate regime
+    # where rref_den over QQ is significantly faster. The small denominator
+    # case is probably very common because small fractions like 1/2 or 1/3 are
+    # often seen in user inputs.
+
+    if denom_lcm.bit_length() < 50:
+        return 'CD'
+    else:
+        return 'FF'
+
+
+def _dm_rref_choose_method_ZZ(M, *, denominator=False):
+    """Choose the fastest method for computing RREF over ZZ."""
+    # In the extreme of very sparse matrices and low bit counts it is faster to
+    # use Gauss-Jordan elimination over QQ rather than fraction-free
+    # Gauss-Jordan over ZZ. In the opposite extreme of dense matrices and high
+    # bit counts it is faster to use fraction-free Gauss-Jordan over ZZ. These
+    # two extreme cases need to be handled differently because they lead to
+    # different asymptotic complexities. In between these two extremes we need
+    # a threshold for deciding which method to use. This threshold is
+    # determined empirically by timing the two methods with random matrices.
+
+    # The disadvantage of using empirical timings is that future optimisations
+    # might change the relative speeds so this can easily become out of date.
+    # The main thing is to get the asymptotic complexity right for the extreme
+    # cases though so the precise value of the threshold is hopefully not too
+    # important.
+
+    # Empirically determined parameter.
+    PARAM = 10000
+
+    # First compute the density. This is the average number of non-zero entries
+    # per row but only counting rows that have at least one non-zero entry
+    # since RREF can ignore fully zero rows.
+    density, nrows_nz, ncols = _dm_row_density(M)
+
+    # For small matrices use QQ if more than half the entries are zero.
+    if nrows_nz < 10:
+        if density < ncols/2:
+            return 'GJ'
+        else:
+            return 'FF'
+
+    # These are just shortcuts for the formula below.
+    if density < 5:
+        return 'GJ'
+    elif density > 5 + PARAM/nrows_nz:
+        return 'FF'  # pragma: no cover
+
+    # Maximum bitsize of any entry.
+    elements = _dm_elements(M)
+    bits = max([e.bit_length() for e in elements], default=1)
+
+    # Wideness parameter. This is 1 for square or tall matrices but >1 for wide
+    # matrices.
+    wideness = max(1, 2/3*ncols/nrows_nz)
+
+    max_density = (5 + PARAM/(nrows_nz*bits**2)) * wideness
+
+    if density < max_density:
+        return 'GJ'
+    else:
+        return 'FF'
+
+
+def _dm_row_density(M):
+    """Density measure for sparse matrices.
+
+    Defines the "density", ``d`` as the average number of non-zero entries per
+    row except ignoring rows that are fully zero. RREF can ignore fully zero
+    rows so they are excluded. By definition ``d >= 1`` except that we define
+    ``d = 0`` for the zero matrix.
+
+    Returns ``(density, nrows_nz, ncols)`` where ``nrows_nz`` counts the number
+    of nonzero rows and ``ncols`` is the number of columns.
+    """
+    # Uses the SDM dict-of-dicts representation.
+    ncols = M.shape[1]
+    rows_nz = M.rep.to_sdm().values()
+    if not rows_nz:
+        return 0, 0, ncols
+    else:
+        nrows_nz = len(rows_nz)
+        density = sum(map(len, rows_nz)) / nrows_nz
+        return density, nrows_nz, ncols
+
+
+def _dm_elements(M):
+    """Return nonzero elements of a DomainMatrix."""
+    elements, _ = M.to_flat_nz()
+    return elements
+
+
+def _dm_QQ_numers_denoms(Mq):
+    """Returns the numerators and denominators of a DomainMatrix over QQ."""
+    elements = _dm_elements(Mq)
+    numers = [e.numerator for e in elements]
+    denoms = [e.denominator for e in elements]
+    return numers, denoms
+
+
+def _to_field(M):
+    """Convert a DomainMatrix to a field if possible."""
+    K = M.domain
+    if K.has_assoc_Field:
+        return M.to_field()
+    else:
+        return M
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/sdm.py b/lib/python3.11/site-packages/sympy/polys/matrices/sdm.py
new file mode 100644
index 0000000000000000000000000000000000000000..5afe39adfad5b28dad209742d34af9bf9cac6991
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/sdm.py
@@ -0,0 +1,2164 @@
+"""
+
+Module for the SDM class.
+
+"""
+
+from operator import add, neg, pos, sub, mul
+from collections import defaultdict
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.utilities.decorator import doctest_depends_on
+from sympy.utilities.iterables import _strongly_connected_components
+
+from .exceptions import DMBadInputError, DMDomainError, DMShapeError
+
+from sympy.polys.domains import QQ
+
+from .ddm import DDM
+
+
+if GROUND_TYPES != 'flint':
+    __doctest_skip__ = ['SDM.to_dfm', 'SDM.to_dfm_or_ddm']
+
+
+class SDM(dict):
+    r"""Sparse matrix based on polys domain elements
+
+    This is a dict subclass and is a wrapper for a dict of dicts that supports
+    basic matrix arithmetic +, -, *, **.
+
+
+    In order to create a new :py:class:`~.SDM`, a dict
+    of dicts mapping non-zero elements to their
+    corresponding row and column in the matrix is needed.
+
+    We also need to specify the shape and :py:class:`~.Domain`
+    of our :py:class:`~.SDM` object.
+
+    We declare a 2x2 :py:class:`~.SDM` matrix belonging
+    to QQ domain as shown below.
+    The 2x2 Matrix in the example is
+
+    .. math::
+           A = \left[\begin{array}{ccc}
+                0 & \frac{1}{2} \\
+                0 & 0 \end{array} \right]
+
+
+    >>> from sympy.polys.matrices.sdm import SDM
+    >>> from sympy import QQ
+    >>> elemsdict = {0:{1:QQ(1, 2)}}
+    >>> A = SDM(elemsdict, (2, 2), QQ)
+    >>> A
+    {0: {1: 1/2}}
+
+    We can manipulate :py:class:`~.SDM` the same way
+    as a Matrix class
+
+    >>> from sympy import ZZ
+    >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+    >>> B  = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
+    >>> A + B
+    {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}
+
+    Multiplication
+
+    >>> A*B
+    {0: {1: 8}, 1: {0: 3}}
+    >>> A*ZZ(2)
+    {0: {1: 4}, 1: {0: 2}}
+
+    """
+
+    fmt = 'sparse'
+    is_DFM = False
+    is_DDM = False
+
+    def __init__(self, elemsdict, shape, domain):
+        super().__init__(elemsdict)
+        self.shape = self.rows, self.cols = m, n = shape
+        self.domain = domain
+
+        if not all(0 <= r < m for r in self):
+            raise DMBadInputError("Row out of range")
+        if not all(0 <= c < n for row in self.values() for c in row):
+            raise DMBadInputError("Column out of range")
+
+    def getitem(self, i, j):
+        try:
+            return self[i][j]
+        except KeyError:
+            m, n = self.shape
+            if -m <= i < m and -n <= j < n:
+                try:
+                    return self[i % m][j % n]
+                except KeyError:
+                    return self.domain.zero
+            else:
+                raise IndexError("index out of range")
+
+    def setitem(self, i, j, value):
+        m, n = self.shape
+        if not (-m <= i < m and -n <= j < n):
+            raise IndexError("index out of range")
+        i, j = i % m, j % n
+        if value:
+            try:
+                self[i][j] = value
+            except KeyError:
+                self[i] = {j: value}
+        else:
+            rowi = self.get(i, None)
+            if rowi is not None:
+                try:
+                    del rowi[j]
+                except KeyError:
+                    pass
+                else:
+                    if not rowi:
+                        del self[i]
+
+    def extract_slice(self, slice1, slice2):
+        m, n = self.shape
+        ri = range(m)[slice1]
+        ci = range(n)[slice2]
+
+        sdm = {}
+        for i, row in self.items():
+            if i in ri:
+                row = {ci.index(j): e for j, e in row.items() if j in ci}
+                if row:
+                    sdm[ri.index(i)] = row
+
+        return self.new(sdm, (len(ri), len(ci)), self.domain)
+
+    def extract(self, rows, cols):
+        if not (self and rows and cols):
+            return self.zeros((len(rows), len(cols)), self.domain)
+
+        m, n = self.shape
+        if not (-m <= min(rows) <= max(rows) < m):
+            raise IndexError('Row index out of range')
+        if not (-n <= min(cols) <= max(cols) < n):
+            raise IndexError('Column index out of range')
+
+        # rows and cols can contain duplicates e.g. M[[1, 2, 2], [0, 1]]
+        # Build a map from row/col in self to list of rows/cols in output
+        rowmap = defaultdict(list)
+        colmap = defaultdict(list)
+        for i2, i1 in enumerate(rows):
+            rowmap[i1 % m].append(i2)
+        for j2, j1 in enumerate(cols):
+            colmap[j1 % n].append(j2)
+
+        # Used to efficiently skip zero rows/cols
+        rowset = set(rowmap)
+        colset = set(colmap)
+
+        sdm1 = self
+        sdm2 = {}
+        for i1 in rowset & sdm1.keys():
+            row1 = sdm1[i1]
+            row2 = {}
+            for j1 in colset & row1.keys():
+                row1_j1 = row1[j1]
+                for j2 in colmap[j1]:
+                    row2[j2] = row1_j1
+            if row2:
+                for i2 in rowmap[i1]:
+                    sdm2[i2] = row2.copy()
+
+        return self.new(sdm2, (len(rows), len(cols)), self.domain)
+
+    def __str__(self):
+        rowsstr = []
+        for i, row in self.items():
+            elemsstr = ', '.join('%s: %s' % (j, elem) for j, elem in row.items())
+            rowsstr.append('%s: {%s}' % (i, elemsstr))
+        return '{%s}' % ', '.join(rowsstr)
+
+    def __repr__(self):
+        cls = type(self).__name__
+        rows = dict.__repr__(self)
+        return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain)
+
+    @classmethod
+    def new(cls, sdm, shape, domain):
+        """
+
+        Parameters
+        ==========
+
+        sdm: A dict of dicts for non-zero elements in SDM
+        shape: tuple representing dimension of SDM
+        domain: Represents :py:class:`~.Domain` of SDM
+
+        Returns
+        =======
+
+        An :py:class:`~.SDM` object
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> elemsdict = {0:{1: QQ(2)}}
+        >>> A = SDM.new(elemsdict, (2, 2), QQ)
+        >>> A
+        {0: {1: 2}}
+
+        """
+        return cls(sdm, shape, domain)
+
+    def copy(A):
+        """
+        Returns the copy of a :py:class:`~.SDM` object
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> elemsdict = {0:{1:QQ(2)}, 1:{}}
+        >>> A = SDM(elemsdict, (2, 2), QQ)
+        >>> B = A.copy()
+        >>> B
+        {0: {1: 2}, 1: {}}
+
+        """
+        Ac = {i: Ai.copy() for i, Ai in A.items()}
+        return A.new(Ac, A.shape, A.domain)
+
+    @classmethod
+    def from_list(cls, ddm, shape, domain):
+        """
+        Create :py:class:`~.SDM` object from a list of lists.
+
+        Parameters
+        ==========
+
+        ddm:
+            list of lists containing domain elements
+        shape:
+            Dimensions of :py:class:`~.SDM` matrix
+        domain:
+            Represents :py:class:`~.Domain` of :py:class:`~.SDM` object
+
+        Returns
+        =======
+
+        :py:class:`~.SDM` containing elements of ddm
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> ddm = [[QQ(1, 2), QQ(0)], [QQ(0), QQ(3, 4)]]
+        >>> A = SDM.from_list(ddm, (2, 2), QQ)
+        >>> A
+        {0: {0: 1/2}, 1: {1: 3/4}}
+
+        See Also
+        ========
+
+        to_list
+        from_list_flat
+        from_dok
+        from_ddm
+        """
+
+        m, n = shape
+        if not (len(ddm) == m and all(len(row) == n for row in ddm)):
+            raise DMBadInputError("Inconsistent row-list/shape")
+        getrow = lambda i: {j:ddm[i][j] for j in range(n) if ddm[i][j]}
+        irows = ((i, getrow(i)) for i in range(m))
+        sdm = {i: row for i, row in irows if row}
+        return cls(sdm, shape, domain)
+
+    @classmethod
+    def from_ddm(cls, ddm):
+        """
+        Create :py:class:`~.SDM` from a :py:class:`~.DDM`.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.ddm import DDM
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> ddm = DDM( [[QQ(1, 2), 0], [0, QQ(3, 4)]], (2, 2), QQ)
+        >>> A = SDM.from_ddm(ddm)
+        >>> A
+        {0: {0: 1/2}, 1: {1: 3/4}}
+        >>> SDM.from_ddm(ddm).to_ddm() == ddm
+        True
+
+        See Also
+        ========
+
+        to_ddm
+        from_list
+        from_list_flat
+        from_dok
+        """
+        return cls.from_list(ddm, ddm.shape, ddm.domain)
+
+    def to_list(M):
+        """
+        Convert a :py:class:`~.SDM` object to a list of lists.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> elemsdict = {0:{1:QQ(2)}, 1:{}}
+        >>> A = SDM(elemsdict, (2, 2), QQ)
+        >>> A.to_list()
+        [[0, 2], [0, 0]]
+
+
+        """
+        m, n = M.shape
+        zero = M.domain.zero
+        ddm = [[zero] * n for _ in range(m)]
+        for i, row in M.items():
+            for j, e in row.items():
+                ddm[i][j] = e
+        return ddm
+
+    def to_list_flat(M):
+        """
+        Convert :py:class:`~.SDM` to a flat list.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0:{1:QQ(2)}, 1:{0: QQ(3)}}, (2, 2), QQ)
+        >>> A.to_list_flat()
+        [0, 2, 3, 0]
+        >>> A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        from_list_flat
+        to_list
+        to_dok
+        to_ddm
+        """
+        m, n = M.shape
+        zero = M.domain.zero
+        flat = [zero] * (m * n)
+        for i, row in M.items():
+            for j, e in row.items():
+                flat[i*n + j] = e
+        return flat
+
+    @classmethod
+    def from_list_flat(cls, elements, shape, domain):
+        """
+        Create :py:class:`~.SDM` from a flat list of elements.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM.from_list_flat([QQ(0), QQ(2), QQ(0), QQ(0)], (2, 2), QQ)
+        >>> A
+        {0: {1: 2}}
+        >>> A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        to_list_flat
+        from_list
+        from_dok
+        from_ddm
+        """
+        m, n = shape
+        if len(elements) != m * n:
+            raise DMBadInputError("Inconsistent flat-list shape")
+        sdm = defaultdict(dict)
+        for inj, element in enumerate(elements):
+            if element:
+                i, j = divmod(inj, n)
+                sdm[i][j] = element
+        return cls(sdm, shape, domain)
+
+    def to_flat_nz(M):
+        """
+        Convert :class:`SDM` to a flat list of nonzero elements and data.
+
+        Explanation
+        ===========
+
+        This is used to operate on a list of the elements of a matrix and then
+        reconstruct a modified matrix with elements in the same positions using
+        :meth:`from_flat_nz`. Zero elements are omitted from the list.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0:{1:QQ(2)}, 1:{0: QQ(3)}}, (2, 2), QQ)
+        >>> elements, data = A.to_flat_nz()
+        >>> elements
+        [2, 3]
+        >>> A == A.from_flat_nz(elements, data, A.domain)
+        True
+
+        See Also
+        ========
+
+        from_flat_nz
+        to_list_flat
+        sympy.polys.matrices.ddm.DDM.to_flat_nz
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_flat_nz
+        """
+        dok = M.to_dok()
+        indices = tuple(dok)
+        elements = list(dok.values())
+        data = (indices, M.shape)
+        return elements, data
+
+    @classmethod
+    def from_flat_nz(cls, elements, data, domain):
+        """
+        Reconstruct a :class:`~.SDM` after calling :meth:`to_flat_nz`.
+
+        See :meth:`to_flat_nz` for explanation.
+
+        See Also
+        ========
+
+        to_flat_nz
+        from_list_flat
+        sympy.polys.matrices.ddm.DDM.from_flat_nz
+        sympy.polys.matrices.domainmatrix.DomainMatrix.from_flat_nz
+        """
+        indices, shape = data
+        dok = dict(zip(indices, elements))
+        return cls.from_dok(dok, shape, domain)
+
+    def to_dod(M):
+        """
+        Convert to dictionary of dictionaries (dod) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ)
+        >>> A.to_dod()
+        {0: {1: 2}, 1: {0: 3}}
+
+        See Also
+        ========
+
+        from_dod
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dod
+        """
+        return {i: row.copy() for i, row in M.items()}
+
+    @classmethod
+    def from_dod(cls, dod, shape, domain):
+        """
+        Create :py:class:`~.SDM` from dictionary of dictionaries (dod) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> dod = {0: {1: QQ(2)}, 1: {0: QQ(3)}}
+        >>> A = SDM.from_dod(dod, (2, 2), QQ)
+        >>> A
+        {0: {1: 2}, 1: {0: 3}}
+        >>> A == SDM.from_dod(A.to_dod(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        to_dod
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dod
+        """
+        sdm = defaultdict(dict)
+        for i, row in dod.items():
+            for j, e in row.items():
+                if e:
+                    sdm[i][j] = e
+        return cls(sdm, shape, domain)
+
+    def to_dok(M):
+        """
+        Convert to dictionary of keys (dok) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ)
+        >>> A.to_dok()
+        {(0, 1): 2, (1, 0): 3}
+
+        See Also
+        ========
+
+        from_dok
+        to_list
+        to_list_flat
+        to_ddm
+        """
+        return {(i, j): e for i, row in M.items() for j, e in row.items()}
+
+    @classmethod
+    def from_dok(cls, dok, shape, domain):
+        """
+        Create :py:class:`~.SDM` from dictionary of keys (dok) format.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> dok = {(0, 1): QQ(2), (1, 0): QQ(3)}
+        >>> A = SDM.from_dok(dok, (2, 2), QQ)
+        >>> A
+        {0: {1: 2}, 1: {0: 3}}
+        >>> A == SDM.from_dok(A.to_dok(), A.shape, A.domain)
+        True
+
+        See Also
+        ========
+
+        to_dok
+        from_list
+        from_list_flat
+        from_ddm
+        """
+        sdm = defaultdict(dict)
+        for (i, j), e in dok.items():
+            if e:
+                sdm[i][j] = e
+        return cls(sdm, shape, domain)
+
+    def iter_values(M):
+        """
+        Iterate over the nonzero values of a :py:class:`~.SDM` matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ)
+        >>> list(A.iter_values())
+        [2, 3]
+
+        """
+        for row in M.values():
+            yield from row.values()
+
+    def iter_items(M):
+        """
+        Iterate over indices and values of the nonzero elements.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3)}}, (2, 2), QQ)
+        >>> list(A.iter_items())
+        [((0, 1), 2), ((1, 0), 3)]
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.iter_items
+        """
+        for i, row in M.items():
+            for j, e in row.items():
+                yield (i, j), e
+
+    def to_ddm(M):
+        """
+        Convert a :py:class:`~.SDM` object to a :py:class:`~.DDM` object
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
+        >>> A.to_ddm()
+        [[0, 2], [0, 0]]
+
+        """
+        return DDM(M.to_list(), M.shape, M.domain)
+
+    def to_sdm(M):
+        """
+        Convert to :py:class:`~.SDM` format (returns self).
+        """
+        return M
+
+    @doctest_depends_on(ground_types=['flint'])
+    def to_dfm(M):
+        """
+        Convert a :py:class:`~.SDM` object to a :py:class:`~.DFM` object
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
+        >>> A.to_dfm()
+        [[0, 2], [0, 0]]
+
+        See Also
+        ========
+
+        to_ddm
+        to_dfm_or_ddm
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm
+        """
+        return M.to_ddm().to_dfm()
+
+    @doctest_depends_on(ground_types=['flint'])
+    def to_dfm_or_ddm(M):
+        """
+        Convert to :py:class:`~.DFM` if possible, else :py:class:`~.DDM`.
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
+        >>> A.to_dfm_or_ddm()
+        [[0, 2], [0, 0]]
+        >>> type(A.to_dfm_or_ddm())  # depends on the ground types
+        
+
+        See Also
+        ========
+
+        to_ddm
+        to_dfm
+        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm
+        """
+        return M.to_ddm().to_dfm_or_ddm()
+
+    @classmethod
+    def zeros(cls, shape, domain):
+        r"""
+
+        Returns a :py:class:`~.SDM` of size shape,
+        belonging to the specified domain
+
+        In the example below we declare a matrix A where,
+
+        .. math::
+            A := \left[\begin{array}{ccc}
+            0 & 0 & 0 \\
+            0 & 0 & 0 \end{array} \right]
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM.zeros((2, 3), QQ)
+        >>> A
+        {}
+
+        """
+        return cls({}, shape, domain)
+
+    @classmethod
+    def ones(cls, shape, domain):
+        one = domain.one
+        m, n = shape
+        row = dict(zip(range(n), [one]*n))
+        sdm = {i: row.copy() for i in range(m)}
+        return cls(sdm, shape, domain)
+
+    @classmethod
+    def eye(cls, shape, domain):
+        """
+
+        Returns a identity :py:class:`~.SDM` matrix of dimensions
+        size x size, belonging to the specified domain
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> I = SDM.eye((2, 2), QQ)
+        >>> I
+        {0: {0: 1}, 1: {1: 1}}
+
+        """
+        if isinstance(shape, int):
+            rows, cols = shape, shape
+        else:
+            rows, cols = shape
+        one = domain.one
+        sdm = {i: {i: one} for i in range(min(rows, cols))}
+        return cls(sdm, (rows, cols), domain)
+
+    @classmethod
+    def diag(cls, diagonal, domain, shape=None):
+        if shape is None:
+            shape = (len(diagonal), len(diagonal))
+        sdm = {i: {i: v} for i, v in enumerate(diagonal) if v}
+        return cls(sdm, shape, domain)
+
+    def transpose(M):
+        """
+
+        Returns the transpose of a :py:class:`~.SDM` matrix
+
+        Examples
+        ========
+
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy import QQ
+        >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
+        >>> A.transpose()
+        {1: {0: 2}}
+
+        """
+        MT = sdm_transpose(M)
+        return M.new(MT, M.shape[::-1], M.domain)
+
+    def __add__(A, B):
+        if not isinstance(B, SDM):
+            return NotImplemented
+        elif A.shape != B.shape:
+            raise DMShapeError("Matrix size mismatch: %s + %s" % (A.shape, B.shape))
+        return A.add(B)
+
+    def __sub__(A, B):
+        if not isinstance(B, SDM):
+            return NotImplemented
+        elif A.shape != B.shape:
+            raise DMShapeError("Matrix size mismatch: %s - %s" % (A.shape, B.shape))
+        return A.sub(B)
+
+    def __neg__(A):
+        return A.neg()
+
+    def __mul__(A, B):
+        """A * B"""
+        if isinstance(B, SDM):
+            return A.matmul(B)
+        elif B in A.domain:
+            return A.mul(B)
+        else:
+            return NotImplemented
+
+    def __rmul__(a, b):
+        if b in a.domain:
+            return a.rmul(b)
+        else:
+            return NotImplemented
+
+    def matmul(A, B):
+        """
+        Performs matrix multiplication of two SDM matrices
+
+        Parameters
+        ==========
+
+        A, B: SDM to multiply
+
+        Returns
+        =======
+
+        SDM
+            SDM after multiplication
+
+        Raises
+        ======
+
+        DomainError
+            If domain of A does not match
+            with that of B
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> B = SDM({0:{0:ZZ(2), 1:ZZ(3)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
+        >>> A.matmul(B)
+        {0: {0: 8}, 1: {0: 2, 1: 3}}
+
+        """
+        if A.domain != B.domain:
+            raise DMDomainError
+        m, n = A.shape
+        n2, o = B.shape
+        if n != n2:
+            raise DMShapeError
+        C = sdm_matmul(A, B, A.domain, m, o)
+        return A.new(C, (m, o), A.domain)
+
+    def mul(A, b):
+        """
+        Multiplies each element of A with a scalar b
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> A.mul(ZZ(3))
+        {0: {1: 6}, 1: {0: 3}}
+
+        """
+        Csdm = unop_dict(A, lambda aij: aij*b)
+        return A.new(Csdm, A.shape, A.domain)
+
+    def rmul(A, b):
+        Csdm = unop_dict(A, lambda aij: b*aij)
+        return A.new(Csdm, A.shape, A.domain)
+
+    def mul_elementwise(A, B):
+        if A.domain != B.domain:
+            raise DMDomainError
+        if A.shape != B.shape:
+            raise DMShapeError
+        zero = A.domain.zero
+        fzero = lambda e: zero
+        Csdm = binop_dict(A, B, mul, fzero, fzero)
+        return A.new(Csdm, A.shape, A.domain)
+
+    def add(A, B):
+        """
+
+        Adds two :py:class:`~.SDM` matrices
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
+        >>> A.add(B)
+        {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}
+
+        """
+        Csdm = binop_dict(A, B, add, pos, pos)
+        return A.new(Csdm, A.shape, A.domain)
+
+    def sub(A, B):
+        """
+
+        Subtracts two :py:class:`~.SDM` matrices
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> B  = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
+        >>> A.sub(B)
+        {0: {0: -3, 1: 2}, 1: {0: 1, 1: -4}}
+
+        """
+        Csdm = binop_dict(A, B, sub, pos, neg)
+        return A.new(Csdm, A.shape, A.domain)
+
+    def neg(A):
+        """
+
+        Returns the negative of a :py:class:`~.SDM` matrix
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> A.neg()
+        {0: {1: -2}, 1: {0: -1}}
+
+        """
+        Csdm = unop_dict(A, neg)
+        return A.new(Csdm, A.shape, A.domain)
+
+    def convert_to(A, K):
+        """
+        Converts the :py:class:`~.Domain` of a :py:class:`~.SDM` matrix to K
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ, QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> A.convert_to(QQ)
+        {0: {1: 2}, 1: {0: 1}}
+
+        """
+        Kold = A.domain
+        if K == Kold:
+            return A.copy()
+        Ak = unop_dict(A, lambda e: K.convert_from(e, Kold))
+        return A.new(Ak, A.shape, K)
+
+    def nnz(A):
+        """Number of non-zero elements in the :py:class:`~.SDM` matrix.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+        >>> A.nnz()
+        2
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nnz
+        """
+        return sum(map(len, A.values()))
+
+    def scc(A):
+        """Strongly connected components of a square matrix *A*.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0: ZZ(2)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
+        >>> A.scc()
+        [[0], [1]]
+
+        See also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.scc
+        """
+        rows, cols = A.shape
+        assert rows == cols
+        V = range(rows)
+        Emap = {v: list(A.get(v, [])) for v in V}
+        return _strongly_connected_components(V, Emap)
+
+    def rref(A):
+        """
+
+        Returns reduced-row echelon form and list of pivots for the :py:class:`~.SDM`
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ)
+        >>> A.rref()
+        ({0: {0: 1, 1: 2}}, [0])
+
+        """
+        B, pivots, _ = sdm_irref(A)
+        return A.new(B, A.shape, A.domain), pivots
+
+    def rref_den(A):
+        """
+
+        Returns reduced-row echelon form (RREF) with denominator and pivots.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ)
+        >>> A.rref_den()
+        ({0: {0: 1, 1: 2}}, 1, [0])
+
+        """
+        K = A.domain
+        A_rref_sdm, denom, pivots = sdm_rref_den(A, K)
+        A_rref = A.new(A_rref_sdm, A.shape, A.domain)
+        return A_rref, denom, pivots
+
+    def inv(A):
+        """
+
+        Returns inverse of a matrix A
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+        >>> A.inv()
+        {0: {0: -2, 1: 1}, 1: {0: 3/2, 1: -1/2}}
+
+        """
+        return A.to_dfm_or_ddm().inv().to_sdm()
+
+    def det(A):
+        """
+        Returns determinant of A
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+        >>> A.det()
+        -2
+
+        """
+        # It would be better to have a sparse implementation of det for use
+        # with very sparse matrices. Extremely sparse matrices probably just
+        # have determinant zero and we could probably detect that very quickly.
+        # In the meantime, we convert to a dense matrix and use ddm_idet.
+        #
+        # If GROUND_TYPES=flint though then we will use Flint's implementation
+        # if possible (dfm).
+        return A.to_dfm_or_ddm().det()
+
+    def lu(A):
+        """
+
+        Returns LU decomposition for a matrix A
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+        >>> A.lu()
+        ({0: {0: 1}, 1: {0: 3, 1: 1}}, {0: {0: 1, 1: 2}, 1: {1: -2}}, [])
+
+        """
+        L, U, swaps = A.to_ddm().lu()
+        return A.from_ddm(L), A.from_ddm(U), swaps
+
+    def lu_solve(A, b):
+        """
+
+        Uses LU decomposition to solve Ax = b,
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+        >>> b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
+        >>> A.lu_solve(b)
+        {1: {0: 1/2}}
+
+        """
+        return A.from_ddm(A.to_ddm().lu_solve(b.to_ddm()))
+
+    def nullspace(A):
+        """
+        Nullspace of a :py:class:`~.SDM` matrix A.
+
+        The domain of the matrix must be a field.
+
+        It is better to use the :meth:`~.DomainMatrix.nullspace` method rather
+        than this method which is otherwise no longer used.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ)
+        >>> A.nullspace()
+        ({0: {0: -2, 1: 1}}, [1])
+
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace
+            The preferred way to get the nullspace of a matrix.
+
+        """
+        ncols = A.shape[1]
+        one = A.domain.one
+        B, pivots, nzcols = sdm_irref(A)
+        K, nonpivots = sdm_nullspace_from_rref(B, one, ncols, pivots, nzcols)
+        K = dict(enumerate(K))
+        shape = (len(K), ncols)
+        return A.new(K, shape, A.domain), nonpivots
+
+    def nullspace_from_rref(A, pivots=None):
+        """
+        Returns nullspace for a :py:class:`~.SDM` matrix ``A`` in RREF.
+
+        The domain of the matrix can be any domain.
+
+        The matrix must already be in reduced row echelon form (RREF).
+
+        Examples
+        ========
+
+        >>> from sympy import QQ
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ)
+        >>> A_rref, pivots = A.rref()
+        >>> A_null, nonpivots = A_rref.nullspace_from_rref(pivots)
+        >>> A_null
+        {0: {0: -2, 1: 1}}
+        >>> pivots
+        [0]
+        >>> nonpivots
+        [1]
+
+        See Also
+        ========
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace
+            The higher-level function that would usually be called instead of
+            calling this one directly.
+
+        sympy.polys.matrices.domainmatrix.DomainMatrix.nullspace_from_rref
+            The higher-level direct equivalent of this function.
+
+        sympy.polys.matrices.ddm.DDM.nullspace_from_rref
+            The equivalent function for dense :py:class:`~.DDM` matrices.
+
+        """
+        m, n = A.shape
+        K = A.domain
+
+        if pivots is None:
+            pivots = sorted(map(min, A.values()))
+
+        if not pivots:
+            return A.eye((n, n), K), list(range(n))
+        elif len(pivots) == n:
+            return A.zeros((0, n), K), []
+
+        # In fraction-free RREF the nonzero entry inserted for the pivots is
+        # not necessarily 1.
+        pivot_val = A[0][pivots[0]]
+        assert not K.is_zero(pivot_val)
+
+        pivots_set = set(pivots)
+
+        # Loop once over all nonzero entries making a map from column indices
+        # to the nonzero entries in that column along with the row index of the
+        # nonzero entry. This is basically the transpose of the matrix.
+        nonzero_cols = defaultdict(list)
+        for i, Ai in A.items():
+            for j, Aij in Ai.items():
+                nonzero_cols[j].append((i, Aij))
+
+        # Usually in SDM we want to avoid looping over the dimensions of the
+        # matrix because it is optimised to support extremely sparse matrices.
+        # Here in nullspace though every zero column becomes a nonzero column
+        # so we need to loop once over the columns at least (range(n)) rather
+        # than just the nonzero entries of the matrix. We can still avoid
+        # an inner loop over the rows though by using the nonzero_cols map.
+        basis = []
+        nonpivots = []
+        for j in range(n):
+            if j in pivots_set:
+                continue
+            nonpivots.append(j)
+
+            vec = {j: pivot_val}
+            for ip, Aij in nonzero_cols[j]:
+                vec[pivots[ip]] = -Aij
+
+            basis.append(vec)
+
+        sdm = dict(enumerate(basis))
+        A_null = A.new(sdm, (len(basis), n), K)
+
+        return (A_null, nonpivots)
+
+    def particular(A):
+        ncols = A.shape[1]
+        B, pivots, nzcols = sdm_irref(A)
+        P = sdm_particular_from_rref(B, ncols, pivots)
+        rep = {0:P} if P else {}
+        return A.new(rep, (1, ncols-1), A.domain)
+
+    def hstack(A, *B):
+        """Horizontally stacks :py:class:`~.SDM` matrices.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+
+        >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
+        >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
+        >>> A.hstack(B)
+        {0: {0: 1, 1: 2, 2: 5, 3: 6}, 1: {0: 3, 1: 4, 2: 7, 3: 8}}
+
+        >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
+        >>> A.hstack(B, C)
+        {0: {0: 1, 1: 2, 2: 5, 3: 6, 4: 9, 5: 10}, 1: {0: 3, 1: 4, 2: 7, 3: 8, 4: 11, 5: 12}}
+        """
+        Anew = dict(A.copy())
+        rows, cols = A.shape
+        domain = A.domain
+
+        for Bk in B:
+            Bkrows, Bkcols = Bk.shape
+            assert Bkrows == rows
+            assert Bk.domain == domain
+
+            for i, Bki in Bk.items():
+                Ai = Anew.get(i, None)
+                if Ai is None:
+                    Anew[i] = Ai = {}
+                for j, Bkij in Bki.items():
+                    Ai[j + cols] = Bkij
+            cols += Bkcols
+
+        return A.new(Anew, (rows, cols), A.domain)
+
+    def vstack(A, *B):
+        """Vertically stacks :py:class:`~.SDM` matrices.
+
+        Examples
+        ========
+
+        >>> from sympy import ZZ
+        >>> from sympy.polys.matrices.sdm import SDM
+
+        >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
+        >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
+        >>> A.vstack(B)
+        {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}}
+
+        >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
+        >>> A.vstack(B, C)
+        {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}, 4: {0: 9, 1: 10}, 5: {0: 11, 1: 12}}
+        """
+        Anew = dict(A.copy())
+        rows, cols = A.shape
+        domain = A.domain
+
+        for Bk in B:
+            Bkrows, Bkcols = Bk.shape
+            assert Bkcols == cols
+            assert Bk.domain == domain
+
+            for i, Bki in Bk.items():
+                Anew[i + rows] = Bki
+            rows += Bkrows
+
+        return A.new(Anew, (rows, cols), A.domain)
+
+    def applyfunc(self, func, domain):
+        sdm = {i: {j: func(e) for j, e in row.items()} for i, row in self.items()}
+        return self.new(sdm, self.shape, domain)
+
+    def charpoly(A):
+        """
+        Returns the coefficients of the characteristic polynomial
+        of the :py:class:`~.SDM` matrix. These elements will be domain elements.
+        The domain of the elements will be same as domain of the :py:class:`~.SDM`.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ, Symbol
+        >>> from sympy.polys.matrices.sdm import SDM
+        >>> from sympy.polys import Poly
+        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+        >>> A.charpoly()
+        [1, -5, -2]
+
+        We can create a polynomial using the
+        coefficients using :py:class:`~.Poly`
+
+        >>> x = Symbol('x')
+        >>> p = Poly(A.charpoly(), x, domain=A.domain)
+        >>> p
+        Poly(x**2 - 5*x - 2, x, domain='QQ')
+
+        """
+        K = A.domain
+        n, _ = A.shape
+        pdict = sdm_berk(A, n, K)
+        plist = [K.zero] * (n + 1)
+        for i, pi in pdict.items():
+            plist[i] = pi
+        return plist
+
+    def is_zero_matrix(self):
+        """
+        Says whether this matrix has all zero entries.
+        """
+        return not self
+
+    def is_upper(self):
+        """
+        Says whether this matrix is upper-triangular. True can be returned
+        even if the matrix is not square.
+        """
+        return all(i <= j for i, row in self.items() for j in row)
+
+    def is_lower(self):
+        """
+        Says whether this matrix is lower-triangular. True can be returned
+        even if the matrix is not square.
+        """
+        return all(i >= j for i, row in self.items() for j in row)
+
+    def is_diagonal(self):
+        """
+        Says whether this matrix is diagonal. True can be returned
+        even if the matrix is not square.
+        """
+        return all(i == j for i, row in self.items() for j in row)
+
+    def diagonal(self):
+        """
+        Returns the diagonal of the matrix as a list.
+        """
+        m, n = self.shape
+        zero = self.domain.zero
+        return [row.get(i, zero) for i, row in self.items() if i < n]
+
+    def lll(A, delta=QQ(3, 4)):
+        """
+        Returns the LLL-reduced basis for the :py:class:`~.SDM` matrix.
+        """
+        return A.to_dfm_or_ddm().lll(delta=delta).to_sdm()
+
+    def lll_transform(A, delta=QQ(3, 4)):
+        """
+        Returns the LLL-reduced basis and transformation matrix.
+        """
+        reduced, transform = A.to_dfm_or_ddm().lll_transform(delta=delta)
+        return reduced.to_sdm(), transform.to_sdm()
+
+
+def binop_dict(A, B, fab, fa, fb):
+    Anz, Bnz = set(A), set(B)
+    C = {}
+
+    for i in Anz & Bnz:
+        Ai, Bi = A[i], B[i]
+        Ci = {}
+        Anzi, Bnzi = set(Ai), set(Bi)
+        for j in Anzi & Bnzi:
+            Cij = fab(Ai[j], Bi[j])
+            if Cij:
+                Ci[j] = Cij
+        for j in Anzi - Bnzi:
+            Cij = fa(Ai[j])
+            if Cij:
+                Ci[j] = Cij
+        for j in Bnzi - Anzi:
+            Cij = fb(Bi[j])
+            if Cij:
+                Ci[j] = Cij
+        if Ci:
+            C[i] = Ci
+
+    for i in Anz - Bnz:
+        Ai = A[i]
+        Ci = {}
+        for j, Aij in Ai.items():
+            Cij = fa(Aij)
+            if Cij:
+                Ci[j] = Cij
+        if Ci:
+            C[i] = Ci
+
+    for i in Bnz - Anz:
+        Bi = B[i]
+        Ci = {}
+        for j, Bij in Bi.items():
+            Cij = fb(Bij)
+            if Cij:
+                Ci[j] = Cij
+        if Ci:
+            C[i] = Ci
+
+    return C
+
+
+def unop_dict(A, f):
+    B = {}
+    for i, Ai in A.items():
+        Bi = {}
+        for j, Aij in Ai.items():
+            Bij = f(Aij)
+            if Bij:
+                Bi[j] = Bij
+        if Bi:
+            B[i] = Bi
+    return B
+
+
+def sdm_transpose(M):
+    MT = {}
+    for i, Mi in M.items():
+        for j, Mij in Mi.items():
+            try:
+                MT[j][i] = Mij
+            except KeyError:
+                MT[j] = {i: Mij}
+    return MT
+
+
+def sdm_dotvec(A, B, K):
+    return K.sum(A[j] * B[j] for j in A.keys() & B.keys())
+
+
+def sdm_matvecmul(A, B, K):
+    C = {}
+    for i, Ai in A.items():
+        Ci = sdm_dotvec(Ai, B, K)
+        if Ci:
+            C[i] = Ci
+    return C
+
+
+def sdm_matmul(A, B, K, m, o):
+    #
+    # Should be fast if A and B are very sparse.
+    # Consider e.g. A = B = eye(1000).
+    #
+    # The idea here is that we compute C = A*B in terms of the rows of C and
+    # B since the dict of dicts representation naturally stores the matrix as
+    # rows. The ith row of C (Ci) is equal to the sum of Aik * Bk where Bk is
+    # the kth row of B. The algorithm below loops over each nonzero element
+    # Aik of A and if the corresponding row Bj is nonzero then we do
+    #    Ci += Aik * Bk.
+    # To make this more efficient we don't need to loop over all elements Aik.
+    # Instead for each row Ai we compute the intersection of the nonzero
+    # columns in Ai with the nonzero rows in B. That gives the k such that
+    # Aik and Bk are both nonzero. In Python the intersection of two sets
+    # of int can be computed very efficiently.
+    #
+    if K.is_EXRAW:
+        return sdm_matmul_exraw(A, B, K, m, o)
+
+    C = {}
+    B_knz = set(B)
+    for i, Ai in A.items():
+        Ci = {}
+        Ai_knz = set(Ai)
+        for k in Ai_knz & B_knz:
+            Aik = Ai[k]
+            for j, Bkj in B[k].items():
+                Cij = Ci.get(j, None)
+                if Cij is not None:
+                    Cij = Cij + Aik * Bkj
+                    if Cij:
+                        Ci[j] = Cij
+                    else:
+                        Ci.pop(j)
+                else:
+                    Cij = Aik * Bkj
+                    if Cij:
+                        Ci[j] = Cij
+        if Ci:
+            C[i] = Ci
+    return C
+
+
+def sdm_matmul_exraw(A, B, K, m, o):
+    #
+    # Like sdm_matmul above except that:
+    #
+    # - Handles cases like 0*oo -> nan (sdm_matmul skips multipication by zero)
+    # - Uses K.sum (Add(*items)) for efficient addition of Expr
+    #
+    zero = K.zero
+    C = {}
+    B_knz = set(B)
+    for i, Ai in A.items():
+        Ci_list = defaultdict(list)
+        Ai_knz = set(Ai)
+
+        # Nonzero row/column pair
+        for k in Ai_knz & B_knz:
+            Aik = Ai[k]
+            if zero * Aik == zero:
+                # This is the main inner loop:
+                for j, Bkj in B[k].items():
+                    Ci_list[j].append(Aik * Bkj)
+            else:
+                for j in range(o):
+                    Ci_list[j].append(Aik * B[k].get(j, zero))
+
+        # Zero row in B, check for infinities in A
+        for k in Ai_knz - B_knz:
+            zAik = zero * Ai[k]
+            if zAik != zero:
+                for j in range(o):
+                    Ci_list[j].append(zAik)
+
+        # Add terms using K.sum (Add(*terms)) for efficiency
+        Ci = {}
+        for j, Cij_list in Ci_list.items():
+            Cij = K.sum(Cij_list)
+            if Cij:
+                Ci[j] = Cij
+        if Ci:
+            C[i] = Ci
+
+    # Find all infinities in B
+    for k, Bk in B.items():
+        for j, Bkj in Bk.items():
+            if zero * Bkj != zero:
+                for i in range(m):
+                    Aik = A.get(i, {}).get(k, zero)
+                    # If Aik is not zero then this was handled above
+                    if Aik == zero:
+                        Ci = C.get(i, {})
+                        Cij = Ci.get(j, zero) + Aik * Bkj
+                        if Cij != zero:
+                            Ci[j] = Cij
+                        else:  # pragma: no cover
+                            # Not sure how we could get here but let's raise an
+                            # exception just in case.
+                            raise RuntimeError
+                        C[i] = Ci
+
+    return C
+
+
+def sdm_irref(A):
+    """RREF and pivots of a sparse matrix *A*.
+
+    Compute the reduced row echelon form (RREF) of the matrix *A* and return a
+    list of the pivot columns. This routine does not work in place and leaves
+    the original matrix *A* unmodified.
+
+    The domain of the matrix must be a field.
+
+    Examples
+    ========
+
+    This routine works with a dict of dicts sparse representation of a matrix:
+
+    >>> from sympy import QQ
+    >>> from sympy.polys.matrices.sdm import sdm_irref
+    >>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}
+    >>> Arref, pivots, _ = sdm_irref(A)
+    >>> Arref
+    {0: {0: 1}, 1: {1: 1}}
+    >>> pivots
+    [0, 1]
+
+    The analogous calculation with :py:class:`~.MutableDenseMatrix` would be
+
+    >>> from sympy import Matrix
+    >>> M = Matrix([[1, 2], [3, 4]])
+    >>> Mrref, pivots = M.rref()
+    >>> Mrref
+    Matrix([
+    [1, 0],
+    [0, 1]])
+    >>> pivots
+    (0, 1)
+
+    Notes
+    =====
+
+    The cost of this algorithm is determined purely by the nonzero elements of
+    the matrix. No part of the cost of any step in this algorithm depends on
+    the number of rows or columns in the matrix. No step depends even on the
+    number of nonzero rows apart from the primary loop over those rows. The
+    implementation is much faster than ddm_rref for sparse matrices. In fact
+    at the time of writing it is also (slightly) faster than the dense
+    implementation even if the input is a fully dense matrix so it seems to be
+    faster in all cases.
+
+    The elements of the matrix should support exact division with ``/``. For
+    example elements of any domain that is a field (e.g. ``QQ``) should be
+    fine. No attempt is made to handle inexact arithmetic.
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.rref
+        The higher-level function that would normally be used to call this
+        routine.
+    sympy.polys.matrices.dense.ddm_irref
+        The dense equivalent of this routine.
+    sdm_rref_den
+        Fraction-free version of this routine.
+    """
+    #
+    # Any zeros in the matrix are not stored at all so an element is zero if
+    # its row dict has no index at that key. A row is entirely zero if its
+    # row index is not in the outer dict. Since rref reorders the rows and
+    # removes zero rows we can completely discard the row indices. The first
+    # step then copies the row dicts into a list sorted by the index of the
+    # first nonzero column in each row.
+    #
+    # The algorithm then processes each row Ai one at a time. Previously seen
+    # rows are used to cancel their pivot columns from Ai. Then a pivot from
+    # Ai is chosen and is cancelled from all previously seen rows. At this
+    # point Ai joins the previously seen rows. Once all rows are seen all
+    # elimination has occurred and the rows are sorted by pivot column index.
+    #
+    # The previously seen rows are stored in two separate groups. The reduced
+    # group consists of all rows that have been reduced to a single nonzero
+    # element (the pivot). There is no need to attempt any further reduction
+    # with these. Rows that still have other nonzeros need to be considered
+    # when Ai is cancelled from the previously seen rows.
+    #
+    # A dict nonzerocolumns is used to map from a column index to a set of
+    # previously seen rows that still have a nonzero element in that column.
+    # This means that we can cancel the pivot from Ai into the previously seen
+    # rows without needing to loop over each row that might have a zero in
+    # that column.
+    #
+
+    # Row dicts sorted by index of first nonzero column
+    # (Maybe sorting is not needed/useful.)
+    Arows = sorted((Ai.copy() for Ai in A.values()), key=min)
+
+    # Each processed row has an associated pivot column.
+    # pivot_row_map maps from the pivot column index to the row dict.
+    # This means that we can represent a set of rows purely as a set of their
+    # pivot indices.
+    pivot_row_map = {}
+
+    # Set of pivot indices for rows that are fully reduced to a single nonzero.
+    reduced_pivots = set()
+
+    # Set of pivot indices for rows not fully reduced
+    nonreduced_pivots = set()
+
+    # Map from column index to a set of pivot indices representing the rows
+    # that have a nonzero at that column.
+    nonzero_columns = defaultdict(set)
+
+    while Arows:
+        # Select pivot element and row
+        Ai = Arows.pop()
+
+        # Nonzero columns from fully reduced pivot rows can be removed
+        Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced_pivots}
+
+        # Others require full row cancellation
+        for j in nonreduced_pivots & set(Ai):
+            Aj = pivot_row_map[j]
+            Aij = Ai[j]
+            Ainz = set(Ai)
+            Ajnz = set(Aj)
+            for k in Ajnz - Ainz:
+                Ai[k] = - Aij * Aj[k]
+            Ai.pop(j)
+            Ainz.remove(j)
+            for k in Ajnz & Ainz:
+                Aik = Ai[k] - Aij * Aj[k]
+                if Aik:
+                    Ai[k] = Aik
+                else:
+                    Ai.pop(k)
+
+        # We have now cancelled previously seen pivots from Ai.
+        # If it is zero then discard it.
+        if not Ai:
+            continue
+
+        # Choose a pivot from Ai:
+        j = min(Ai)
+        Aij = Ai[j]
+        pivot_row_map[j] = Ai
+        Ainz = set(Ai)
+
+        # Normalise the pivot row to make the pivot 1.
+        #
+        # This approach is slow for some domains. Cross cancellation might be
+        # better for e.g. QQ(x) with division delayed to the final steps.
+        Aijinv = Aij**-1
+        for l in Ai:
+            Ai[l] *= Aijinv
+
+        # Use Aij to cancel column j from all previously seen rows
+        for k in nonzero_columns.pop(j, ()):
+            Ak = pivot_row_map[k]
+            Akj = Ak[j]
+            Aknz = set(Ak)
+            for l in Ainz - Aknz:
+                Ak[l] = - Akj * Ai[l]
+                nonzero_columns[l].add(k)
+            Ak.pop(j)
+            Aknz.remove(j)
+            for l in Ainz & Aknz:
+                Akl = Ak[l] - Akj * Ai[l]
+                if Akl:
+                    Ak[l] = Akl
+                else:
+                    # Drop nonzero elements
+                    Ak.pop(l)
+                    if l != j:
+                        nonzero_columns[l].remove(k)
+            if len(Ak) == 1:
+                reduced_pivots.add(k)
+                nonreduced_pivots.remove(k)
+
+        if len(Ai) == 1:
+            reduced_pivots.add(j)
+        else:
+            nonreduced_pivots.add(j)
+            for l in Ai:
+                if l != j:
+                    nonzero_columns[l].add(j)
+
+    # All done!
+    pivots = sorted(reduced_pivots | nonreduced_pivots)
+    pivot2row = {p: n for n, p in enumerate(pivots)}
+    nonzero_columns = {c: {pivot2row[p] for p in s} for c, s in nonzero_columns.items()}
+    rows = [pivot_row_map[i] for i in pivots]
+    rref = dict(enumerate(rows))
+    return rref, pivots, nonzero_columns
+
+
+def sdm_rref_den(A, K):
+    """
+    Return the reduced row echelon form (RREF) of A with denominator.
+
+    The RREF is computed using fraction-free Gauss-Jordan elimination.
+
+    Explanation
+    ===========
+
+    The algorithm used is the fraction-free version of Gauss-Jordan elimination
+    described as FFGJ in [1]_. Here it is modified to handle zero or missing
+    pivots and to avoid redundant arithmetic. This implementation is also
+    optimized for sparse matrices.
+
+    The domain $K$ must support exact division (``K.exquo``) but does not need
+    to be a field. This method is suitable for most exact rings and fields like
+    :ref:`ZZ`, :ref:`QQ` and :ref:`QQ(a)`. In the case of :ref:`QQ` or
+    :ref:`K(x)` it might be more efficient to clear denominators and use
+    :ref:`ZZ` or :ref:`K[x]` instead.
+
+    For inexact domains like :ref:`RR` and :ref:`CC` use ``ddm_irref`` instead.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.matrices.sdm import sdm_rref_den
+    >>> from sympy.polys.domains import ZZ
+    >>> A = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}
+    >>> A_rref, den, pivots = sdm_rref_den(A, ZZ)
+    >>> A_rref
+    {0: {0: -2}, 1: {1: -2}}
+    >>> den
+    -2
+    >>> pivots
+    [0, 1]
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.rref_den
+        Higher-level interface to ``sdm_rref_den`` that would usually be used
+        instead of calling this function directly.
+    sympy.polys.matrices.sdm.sdm_rref_den
+        The ``SDM`` method that uses this function.
+    sdm_irref
+        Computes RREF using field division.
+    ddm_irref_den
+        The dense version of this algorithm.
+
+    References
+    ==========
+
+    .. [1] Fraction-free algorithms for linear and polynomial equations.
+        George C. Nakos , Peter R. Turner , Robert M. Williams.
+        https://dl.acm.org/doi/10.1145/271130.271133
+    """
+    #
+    # We represent each row of the matrix as a dict mapping column indices to
+    # nonzero elements. We will build the RREF matrix starting from an empty
+    # matrix and appending one row at a time. At each step we will have the
+    # RREF of the rows we have processed so far.
+    #
+    # Our representation of the RREF divides it into three parts:
+    #
+    # 1. Fully reduced rows having only a single nonzero element (the pivot).
+    # 2. Partially reduced rows having nonzeros after the pivot.
+    # 3. The current denominator and divisor.
+    #
+    # For example if the incremental RREF might be:
+    #
+    #   [2, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+    #   [0, 0, 2, 0, 0, 0, 7, 0, 0, 0]
+    #   [0, 0, 0, 0, 0, 2, 0, 0, 0, 0]
+    #   [0, 0, 0, 0, 0, 0, 0, 2, 0, 0]
+    #   [0, 0, 0, 0, 0, 0, 0, 0, 2, 0]
+    #
+    # Here the second row is partially reduced and the other rows are fully
+    # reduced. The denominator would be 2 in this case. We distinguish the
+    # fully reduced rows because we can handle them more efficiently when
+    # adding a new row.
+    #
+    # When adding a new row we need to multiply it by the current denominator.
+    # Then we reduce the new row by cross cancellation with the previous rows.
+    # Then if it is not reduced to zero we take its leading entry as the new
+    # pivot, cross cancel the new row from the previous rows and update the
+    # denominator. In the fraction-free version this last step requires
+    # multiplying and dividing the whole matrix by the new pivot and the
+    # current divisor. The advantage of building the RREF one row at a time is
+    # that in the sparse case we only need to work with the relatively sparse
+    # upper rows of the matrix. The simple version of FFGJ in [1] would
+    # multiply and divide all the dense lower rows at each step.
+
+    # Handle the trivial cases.
+    if not A:
+        return ({}, K.one, [])
+    elif len(A) == 1:
+        Ai, = A.values()
+        j = min(Ai)
+        Aij = Ai[j]
+        return ({0: Ai.copy()}, Aij, [j])
+
+    # For inexact domains like RR[x] we use quo and discard the remainder.
+    # Maybe it would be better for K.exquo to do this automatically.
+    if K.is_Exact:
+        exquo = K.exquo
+    else:
+        exquo = K.quo
+
+    # Make sure we have the rows in order to make this deterministic from the
+    # outset.
+    _, rows_in_order = zip(*sorted(A.items()))
+
+    col_to_row_reduced = {}
+    col_to_row_unreduced = {}
+    reduced = col_to_row_reduced.keys()
+    unreduced = col_to_row_unreduced.keys()
+
+    # Our representation of the RREF so far.
+    A_rref_rows = []
+    denom = None
+    divisor = None
+
+    # The rows that remain to be added to the RREF. These are sorted by the
+    # column index of their leading entry. Note that sorted() is stable so the
+    # previous sort by unique row index is still needed to make this
+    # deterministic (there may be multiple rows with the same leading column).
+    A_rows = sorted(rows_in_order, key=min)
+
+    for Ai in A_rows:
+
+        # All fully reduced columns can be immediately discarded.
+        Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced}
+
+        # We need to multiply the new row by the current denominator to bring
+        # it into the same scale as the previous rows and then cross-cancel to
+        # reduce it wrt the previous unreduced rows. All pivots in the previous
+        # rows are equal to denom so the coefficients we need to make a linear
+        # combination of the previous rows to cancel into the new row are just
+        # the ones that are already in the new row *before* we multiply by
+        # denom. We compute that linear combination first and then multiply the
+        # new row by denom before subtraction.
+        Ai_cancel = {}
+
+        for j in unreduced & Ai.keys():
+            # Remove the pivot column from the new row since it would become
+            # zero anyway.
+            Aij = Ai.pop(j)
+
+            Aj = A_rref_rows[col_to_row_unreduced[j]]
+
+            for k, Ajk in Aj.items():
+                Aik_cancel = Ai_cancel.get(k)
+                if Aik_cancel is None:
+                    Ai_cancel[k] = Aij * Ajk
+                else:
+                    Aik_cancel = Aik_cancel + Aij * Ajk
+                    if Aik_cancel:
+                        Ai_cancel[k] = Aik_cancel
+                    else:
+                        Ai_cancel.pop(k)
+
+        # Multiply the new row by the current denominator and subtract.
+        Ai_nz = set(Ai)
+        Ai_cancel_nz = set(Ai_cancel)
+
+        d = denom or K.one
+
+        for k in Ai_cancel_nz - Ai_nz:
+            Ai[k] = -Ai_cancel[k]
+
+        for k in Ai_nz - Ai_cancel_nz:
+            Ai[k] = Ai[k] * d
+
+        for k in Ai_cancel_nz & Ai_nz:
+            Aik = Ai[k] * d - Ai_cancel[k]
+            if Aik:
+                Ai[k] = Aik
+            else:
+                Ai.pop(k)
+
+        # Now Ai has the same scale as the other rows and is reduced wrt the
+        # unreduced rows.
+
+        # If the row is reduced to zero then discard it.
+        if not Ai:
+            continue
+
+        # Choose a pivot for this row.
+        j = min(Ai)
+        Aij = Ai.pop(j)
+
+        # Cross cancel the unreduced rows by the new row.
+        #     a[k][l] = (a[i][j]*a[k][l] - a[k][j]*a[i][l]) / divisor
+        for pk, k in list(col_to_row_unreduced.items()):
+
+            Ak = A_rref_rows[k]
+
+            if j not in Ak:
+                # This row is already reduced wrt the new row but we need to
+                # bring it to the same scale as the new denominator. This step
+                # is not needed in sdm_irref.
+                for l, Akl in Ak.items():
+                    Akl = Akl * Aij
+                    if divisor is not None:
+                        Akl = exquo(Akl, divisor)
+                    Ak[l] = Akl
+                continue
+
+            Akj = Ak.pop(j)
+            Ai_nz = set(Ai)
+            Ak_nz = set(Ak)
+
+            for l in Ai_nz - Ak_nz:
+                Ak[l] = - Akj * Ai[l]
+                if divisor is not None:
+                    Ak[l] = exquo(Ak[l], divisor)
+
+            # This loop also not needed in sdm_irref.
+            for l in Ak_nz - Ai_nz:
+                Ak[l] = Aij * Ak[l]
+                if divisor is not None:
+                    Ak[l] = exquo(Ak[l], divisor)
+
+            for l in Ai_nz & Ak_nz:
+                Akl = Aij * Ak[l] - Akj * Ai[l]
+                if Akl:
+                    if divisor is not None:
+                        Akl = exquo(Akl, divisor)
+                    Ak[l] = Akl
+                else:
+                    Ak.pop(l)
+
+            if not Ak:
+                col_to_row_unreduced.pop(pk)
+                col_to_row_reduced[pk] = k
+
+        i = len(A_rref_rows)
+        A_rref_rows.append(Ai)
+        if Ai:
+            col_to_row_unreduced[j] = i
+        else:
+            col_to_row_reduced[j] = i
+
+        # Update the denominator.
+        if not K.is_one(Aij):
+            if denom is None:
+                denom = Aij
+            else:
+                denom *= Aij
+
+        if divisor is not None:
+            denom = exquo(denom, divisor)
+
+        # Update the divisor.
+        divisor = denom
+
+    if denom is None:
+        denom = K.one
+
+    # Sort the rows by their leading column index.
+    col_to_row = {**col_to_row_reduced, **col_to_row_unreduced}
+    row_to_col = {i: j for j, i in col_to_row.items()}
+    A_rref_rows_col = [(row_to_col[i], Ai) for i, Ai in enumerate(A_rref_rows)]
+    pivots, A_rref = zip(*sorted(A_rref_rows_col))
+    pivots = list(pivots)
+
+    # Insert the pivot values
+    for i, Ai in enumerate(A_rref):
+        Ai[pivots[i]] = denom
+
+    A_rref_sdm = dict(enumerate(A_rref))
+
+    return A_rref_sdm, denom, pivots
+
+
+def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols):
+    """Get nullspace from A which is in RREF"""
+    nonpivots = sorted(set(range(ncols)) - set(pivots))
+
+    K = []
+    for j in nonpivots:
+        Kj = {j:one}
+        for i in nonzero_cols.get(j, ()):
+            Kj[pivots[i]] = -A[i][j]
+        K.append(Kj)
+
+    return K, nonpivots
+
+
+def sdm_particular_from_rref(A, ncols, pivots):
+    """Get a particular solution from A which is in RREF"""
+    P = {}
+    for i, j in enumerate(pivots):
+        Ain = A[i].get(ncols-1, None)
+        if Ain is not None:
+            P[j] = Ain / A[i][j]
+    return P
+
+
+def sdm_berk(M, n, K):
+    """
+    Berkowitz algorithm for computing the characteristic polynomial.
+
+    Explanation
+    ===========
+
+    The Berkowitz algorithm is a division-free algorithm for computing the
+    characteristic polynomial of a matrix over any commutative ring using only
+    arithmetic in the coefficient ring. This implementation is for sparse
+    matrices represented in a dict-of-dicts format (like :class:`SDM`).
+
+    Examples
+    ========
+
+    >>> from sympy import Matrix
+    >>> from sympy.polys.matrices.sdm import sdm_berk
+    >>> from sympy.polys.domains import ZZ
+    >>> M = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}
+    >>> sdm_berk(M, 2, ZZ)
+    {0: 1, 1: -5, 2: -2}
+    >>> Matrix([[1, 2], [3, 4]]).charpoly()
+    PurePoly(lambda**2 - 5*lambda - 2, lambda, domain='ZZ')
+
+    See Also
+    ========
+
+    sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly
+        The high-level interface to this function.
+    sympy.polys.matrices.dense.ddm_berk
+        The dense version of this function.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Samuelson%E2%80%93Berkowitz_algorithm
+    """
+    zero = K.zero
+    one = K.one
+
+    if n == 0:
+        return {0: one}
+    elif n == 1:
+        pdict = {0: one}
+        if M00 := M.get(0, {}).get(0, zero):
+            pdict[1] = -M00
+
+    # M = [[a, R],
+    #      [C, A]]
+    a, R, C, A = K.zero, {}, {}, defaultdict(dict)
+    for i, Mi in M.items():
+        for j, Mij in Mi.items():
+            if i and j:
+                A[i-1][j-1] = Mij
+            elif i:
+                C[i-1] = Mij
+            elif j:
+                R[j-1] = Mij
+            else:
+                a = Mij
+
+    # T = [       1,      0,    0,  0, 0, ... ]
+    #     [      -a,      1,    0,  0, 0, ... ]
+    #     [    -R*C,     -a,    1,  0, 0, ... ]
+    #     [  -R*A*C,   -R*C,   -a,  1, 0, ... ]
+    #     [-R*A^2*C, -R*A*C, -R*C, -a, 1, ... ]
+    #     [ ...                               ]
+    # T is (n+1) x n
+    #
+    # In the sparse case we might have A^m*C = 0 for some m making T banded
+    # rather than triangular so we just compute the nonzero entries of the
+    # first column rather than constructing the matrix explicitly.
+
+    AnC = C
+    RC = sdm_dotvec(R, C, K)
+
+    Tvals = [one, -a, -RC]
+    for i in range(3, n+1):
+        AnC = sdm_matvecmul(A, AnC, K)
+        if not AnC:
+            break
+        RAnC = sdm_dotvec(R, AnC, K)
+        Tvals.append(-RAnC)
+
+    # Strip trailing zeros
+    while Tvals and not Tvals[-1]:
+        Tvals.pop()
+
+    q = sdm_berk(A, n-1, K)
+
+    # This would be the explicit multiplication T*q but we can do better:
+    #
+    #  T = {}
+    #  for i in range(n+1):
+    #      Ti = {}
+    #      for j in range(max(0, i-len(Tvals)+1), min(i+1, n)):
+    #          Ti[j] = Tvals[i-j]
+    #      T[i] = Ti
+    #  Tq = sdm_matvecmul(T, q, K)
+    #
+    # In the sparse case q might be mostly zero. We know that T[i,j] is nonzero
+    # for i <= j < i + len(Tvals) so if q does not have a nonzero entry in that
+    # range then Tq[j] must be zero. We exploit this potential banded
+    # structure and the potential sparsity of q to compute Tq more efficiently.
+
+    Tvals = Tvals[::-1]
+
+    Tq = {}
+
+    for i in range(min(q), min(max(q)+len(Tvals), n+1)):
+        Ti = dict(enumerate(Tvals, i-len(Tvals)+1))
+        if Tqi := sdm_dotvec(Ti, q, K):
+            Tq[i] = Tqi
+
+    return Tq
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__init__.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/__init__.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..719a441eba1068b5bad5f436926e9a638dcba145
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/__init__.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_ddm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_ddm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f66a8021c7ef3a843e1bb72b58cda286299dcd04
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_ddm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_dense.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_dense.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aae8255c4a70fc573278836574d564c8435b9a9e
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_dense.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainscalar.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainscalar.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf480eb24867084a58148e9bd57ee5de45dbedbf
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_domainscalar.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_eigen.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_eigen.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc6ce23830da6b38e5022eb7bc6c553eba7d9b87
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_eigen.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_inverse.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_inverse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2978aa2d753ee6a2368562ee062809cdd7d5f3f2
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_inverse.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_linsolve.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_linsolve.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bdcabeba26c9a5bcff05a01c3d5a98e4618d1c1
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_linsolve.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_lll.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_lll.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef3409b996ee0a4df83e0e9e8f31bd7c21b0e231
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_lll.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_normalforms.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_normalforms.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6382a77b959f58a4843fefd4c0b01c445920075a
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_normalforms.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_nullspace.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_nullspace.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c85109d695bdb88ac606bd3e059ac2277694549
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_nullspace.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_rref.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_rref.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..748de645f86ac1251ad49857834ea8b4da4a2b82
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_rref.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_sdm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_sdm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6d84efc22d5b87ab55d55c2d9d457674103c420
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_sdm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_xxm.cpython-311.pyc b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_xxm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..840970099860ce485767d1b546bf1c12c86ca5b0
Binary files /dev/null and b/lib/python3.11/site-packages/sympy/polys/matrices/tests/__pycache__/test_xxm.cpython-311.pyc differ
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_ddm.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_ddm.py
new file mode 100644
index 0000000000000000000000000000000000000000..44c862461e85d503696e621874c10d67d8ee1f1d
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_ddm.py
@@ -0,0 +1,558 @@
+from sympy.testing.pytest import raises
+from sympy.external.gmpy import GROUND_TYPES
+
+from sympy.polys import ZZ, QQ
+
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.exceptions import (
+    DMShapeError, DMNonInvertibleMatrixError, DMDomainError,
+    DMBadInputError)
+
+
+def test_DDM_init():
+    items = [[ZZ(0), ZZ(1), ZZ(2)], [ZZ(3), ZZ(4), ZZ(5)]]
+    shape = (2, 3)
+    ddm = DDM(items, shape, ZZ)
+    assert ddm.shape == shape
+    assert ddm.rows == 2
+    assert ddm.cols == 3
+    assert ddm.domain == ZZ
+
+    raises(DMBadInputError, lambda: DDM([[ZZ(2), ZZ(3)]], (2, 2), ZZ))
+    raises(DMBadInputError, lambda: DDM([[ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ))
+
+
+def test_DDM_getsetitem():
+    ddm = DDM([[ZZ(2), ZZ(3)], [ZZ(4), ZZ(5)]], (2, 2), ZZ)
+
+    assert ddm[0][0] == ZZ(2)
+    assert ddm[0][1] == ZZ(3)
+    assert ddm[1][0] == ZZ(4)
+    assert ddm[1][1] == ZZ(5)
+
+    raises(IndexError, lambda: ddm[2][0])
+    raises(IndexError, lambda: ddm[0][2])
+
+    ddm[0][0] = ZZ(-1)
+    assert ddm[0][0] == ZZ(-1)
+
+
+def test_DDM_str():
+    ddm = DDM([[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ)
+    if GROUND_TYPES == 'gmpy': # pragma: no cover
+        assert str(ddm) == '[[0, 1], [2, 3]]'
+        assert repr(ddm) == 'DDM([[mpz(0), mpz(1)], [mpz(2), mpz(3)]], (2, 2), ZZ)'
+    else:        # pragma: no cover
+        assert repr(ddm) == 'DDM([[0, 1], [2, 3]], (2, 2), ZZ)'
+        assert str(ddm) == '[[0, 1], [2, 3]]'
+
+
+def test_DDM_eq():
+    items = [[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]]
+    ddm1 = DDM(items, (2, 2), ZZ)
+    ddm2 = DDM(items, (2, 2), ZZ)
+
+    assert (ddm1 == ddm1) is True
+    assert (ddm1 == items) is False
+    assert (items == ddm1) is False
+    assert (ddm1 == ddm2) is True
+    assert (ddm2 == ddm1) is True
+
+    assert (ddm1 != ddm1) is False
+    assert (ddm1 != items) is True
+    assert (items != ddm1) is True
+    assert (ddm1 != ddm2) is False
+    assert (ddm2 != ddm1) is False
+
+    ddm3 = DDM([[ZZ(0), ZZ(1)], [ZZ(3), ZZ(3)]], (2, 2), ZZ)
+    ddm3 = DDM(items, (2, 2), QQ)
+
+    assert (ddm1 == ddm3) is False
+    assert (ddm3 == ddm1) is False
+    assert (ddm1 != ddm3) is True
+    assert (ddm3 != ddm1) is True
+
+
+def test_DDM_convert_to():
+    ddm = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    assert ddm.convert_to(ZZ) == ddm
+    ddmq = ddm.convert_to(QQ)
+    assert ddmq.domain == QQ
+
+
+def test_DDM_zeros():
+    ddmz = DDM.zeros((3, 4), QQ)
+    assert list(ddmz) == [[QQ(0)] * 4] * 3
+    assert ddmz.shape == (3, 4)
+    assert ddmz.domain == QQ
+
+def test_DDM_ones():
+    ddmone = DDM.ones((2, 3), QQ)
+    assert list(ddmone) == [[QQ(1)] * 3] * 2
+    assert ddmone.shape == (2, 3)
+    assert ddmone.domain == QQ
+
+def test_DDM_eye():
+    ddmz = DDM.eye(3, QQ)
+    f = lambda i, j: QQ(1) if i == j else QQ(0)
+    assert list(ddmz) == [[f(i, j) for i in range(3)] for j in range(3)]
+    assert ddmz.shape == (3, 3)
+    assert ddmz.domain == QQ
+
+
+def test_DDM_copy():
+    ddm1 = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    ddm2 = ddm1.copy()
+    assert (ddm1 == ddm2) is True
+    ddm1[0][0] = QQ(-1)
+    assert (ddm1 == ddm2) is False
+    ddm2[0][0] = QQ(-1)
+    assert (ddm1 == ddm2) is True
+
+
+def test_DDM_transpose():
+    ddm = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    ddmT = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
+    assert ddm.transpose() == ddmT
+    ddm02 = DDM([], (0, 2), QQ)
+    ddm02T = DDM([[], []], (2, 0), QQ)
+    assert ddm02.transpose() == ddm02T
+    assert ddm02T.transpose() == ddm02
+    ddm0 = DDM([], (0, 0), QQ)
+    assert ddm0.transpose() == ddm0
+
+
+def test_DDM_add():
+    A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ)
+    C = DDM([[ZZ(4)], [ZZ(6)]], (2, 1), ZZ)
+    AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    assert A + B == A.add(B) == C
+
+    raises(DMShapeError, lambda: A + DDM([[ZZ(5)]], (1, 1), ZZ))
+    raises(TypeError, lambda: A + ZZ(1))
+    raises(TypeError, lambda: ZZ(1) + A)
+    raises(DMDomainError, lambda: A + AQ)
+    raises(DMDomainError, lambda: AQ + A)
+
+
+def test_DDM_sub():
+    A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ)
+    C = DDM([[ZZ(-2)], [ZZ(-2)]], (2, 1), ZZ)
+    AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    D = DDM([[ZZ(5)]], (1, 1), ZZ)
+    assert A - B == A.sub(B) == C
+
+    raises(TypeError, lambda: A - ZZ(1))
+    raises(TypeError, lambda: ZZ(1) - A)
+    raises(DMShapeError, lambda: A - D)
+    raises(DMShapeError, lambda: D - A)
+    raises(DMShapeError, lambda: A.sub(D))
+    raises(DMShapeError, lambda: D.sub(A))
+    raises(DMDomainError, lambda: A - AQ)
+    raises(DMDomainError, lambda: AQ - A)
+    raises(DMDomainError, lambda: A.sub(AQ))
+    raises(DMDomainError, lambda: AQ.sub(A))
+
+
+def test_DDM_neg():
+    A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    An = DDM([[ZZ(-1)], [ZZ(-2)]], (2, 1), ZZ)
+    assert -A == A.neg() == An
+    assert -An == An.neg() == A
+
+
+def test_DDM_mul():
+    A = DDM([[ZZ(1)]], (1, 1), ZZ)
+    A2 = DDM([[ZZ(2)]], (1, 1), ZZ)
+    assert A * ZZ(2) == A2
+    assert ZZ(2) * A == A2
+    raises(TypeError, lambda: [[1]] * A)
+    raises(TypeError, lambda: A * [[1]])
+
+
+def test_DDM_matmul():
+    A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    B = DDM([[ZZ(3), ZZ(4)]], (1, 2), ZZ)
+    AB = DDM([[ZZ(3), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
+    BA = DDM([[ZZ(11)]], (1, 1), ZZ)
+
+    assert A @ B == A.matmul(B) == AB
+    assert B @ A == B.matmul(A) == BA
+
+    raises(TypeError, lambda: A @ 1)
+    raises(TypeError, lambda: A @ [[3, 4]])
+
+    Bq = DDM([[QQ(3), QQ(4)]], (1, 2), QQ)
+
+    raises(DMDomainError, lambda: A @ Bq)
+    raises(DMDomainError, lambda: Bq @ A)
+
+    C = DDM([[ZZ(1)]], (1, 1), ZZ)
+
+    assert A @ C == A.matmul(C) == A
+
+    raises(DMShapeError, lambda: C @ A)
+    raises(DMShapeError, lambda: C.matmul(A))
+
+    Z04 = DDM([], (0, 4), ZZ)
+    Z40 = DDM([[]]*4, (4, 0), ZZ)
+    Z50 = DDM([[]]*5, (5, 0), ZZ)
+    Z05 = DDM([], (0, 5), ZZ)
+    Z45 = DDM([[0] * 5] * 4, (4, 5), ZZ)
+    Z54 = DDM([[0] * 4] * 5, (5, 4), ZZ)
+    Z00 = DDM([], (0, 0), ZZ)
+
+    assert Z04 @ Z45 == Z04.matmul(Z45) == Z05
+    assert Z45 @ Z50 == Z45.matmul(Z50) == Z40
+    assert Z00 @ Z04 == Z00.matmul(Z04) == Z04
+    assert Z50 @ Z00 == Z50.matmul(Z00) == Z50
+    assert Z00 @ Z00 == Z00.matmul(Z00) == Z00
+    assert Z50 @ Z04 == Z50.matmul(Z04) == Z54
+
+    raises(DMShapeError, lambda: Z05 @ Z40)
+    raises(DMShapeError, lambda: Z05.matmul(Z40))
+
+
+def test_DDM_hstack():
+    A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ)
+    B = DDM([[ZZ(4), ZZ(5)]], (1, 2), ZZ)
+    C = DDM([[ZZ(6)]], (1, 1), ZZ)
+
+    Ah = A.hstack(B)
+    assert Ah.shape == (1, 5)
+    assert Ah.domain == ZZ
+    assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5)]], (1, 5), ZZ)
+
+    Ah = A.hstack(B, C)
+    assert Ah.shape == (1, 6)
+    assert Ah.domain == ZZ
+    assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5), ZZ(6)]], (1, 6), ZZ)
+
+
+def test_DDM_vstack():
+    A = DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)]], (3, 1), ZZ)
+    B = DDM([[ZZ(4)], [ZZ(5)]], (2, 1), ZZ)
+    C = DDM([[ZZ(6)]], (1, 1), ZZ)
+
+    Ah = A.vstack(B)
+    assert Ah.shape == (5, 1)
+    assert Ah.domain == ZZ
+    assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)]], (5, 1), ZZ)
+
+    Ah = A.vstack(B, C)
+    assert Ah.shape == (6, 1)
+    assert Ah.domain == ZZ
+    assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)], [ZZ(6)]], (6, 1), ZZ)
+
+
+def test_DDM_applyfunc():
+    A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ)
+    B = DDM([[ZZ(2), ZZ(4), ZZ(6)]], (1, 3), ZZ)
+    assert A.applyfunc(lambda x: 2*x, ZZ) == B
+
+def test_DDM_rref():
+
+    A = DDM([], (0, 4), QQ)
+    assert A.rref() == (A, [])
+
+    A = DDM([[QQ(0), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
+    Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+    pivots = [0, 1]
+    assert A.rref() == (Ar, pivots)
+
+    A = DDM([[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]], (2, 3), QQ)
+    Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ)
+    pivots = [0, 1]
+    assert A.rref() == (Ar, pivots)
+
+    A = DDM([[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]], (2, 3), QQ)
+    Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ)
+    pivots = [0, 1]
+    assert A.rref() == (Ar, pivots)
+
+    A = DDM([[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]], (3, 2), QQ)
+    Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]], (3, 2), QQ)
+    pivots = [0, 1]
+    assert A.rref() == (Ar, pivots)
+
+    A = DDM([[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]], (2, 3), QQ)
+    Ar = DDM([[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]], (2, 3), QQ)
+    pivots = [0, 2]
+    assert A.rref() == (Ar, pivots)
+
+
+def test_DDM_nullspace():
+    # more tests are in test_nullspace.py
+    A = DDM([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
+    Anull = DDM([[QQ(-1), QQ(1)]], (1, 2), QQ)
+    nonpivots = [1]
+    assert A.nullspace() == (Anull, nonpivots)
+
+
+def test_DDM_particular():
+    A = DDM([[QQ(1), QQ(0)]], (1, 2), QQ)
+    assert A.particular() == DDM.zeros((1, 1), QQ)
+
+
+def test_DDM_det():
+    # 0x0 case
+    A = DDM([], (0, 0), ZZ)
+    assert A.det() == ZZ(1)
+
+    # 1x1 case
+    A = DDM([[ZZ(2)]], (1, 1), ZZ)
+    assert A.det() == ZZ(2)
+
+    # 2x2 case
+    A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.det() == ZZ(-2)
+
+    # 3x3 with swap
+    A = DDM([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ)
+    assert A.det() == ZZ(0)
+
+    # 2x2 QQ case
+    A = DDM([[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]], (2, 2), QQ)
+    assert A.det() == QQ(-1, 24)
+
+    # Nonsquare error
+    A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    raises(DMShapeError, lambda: A.det())
+
+    # Nonsquare error with empty matrix
+    A = DDM([], (0, 1), ZZ)
+    raises(DMShapeError, lambda: A.det())
+
+
+def test_DDM_inv():
+    A = DDM([[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]], (2, 2), QQ)
+    Ainv = DDM([[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ)
+    assert A.inv() == Ainv
+
+    A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
+    raises(DMShapeError, lambda: A.inv())
+
+    A = DDM([[ZZ(2)]], (1, 1), ZZ)
+    raises(DMDomainError, lambda: A.inv())
+
+    A = DDM([], (0, 0), QQ)
+    assert A.inv() == A
+
+    A = DDM([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: A.inv())
+
+
+def test_DDM_lu():
+    A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    L, U, swaps = A.lu()
+    assert L == DDM([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ)
+    assert U == DDM([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ)
+    assert swaps == []
+
+    A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]
+    Lexp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]]
+    Uexp = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
+    to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows]
+    A = DDM(to_dom(A, QQ), (4, 4), QQ)
+    Lexp = DDM(to_dom(Lexp, QQ), (4, 4), QQ)
+    Uexp = DDM(to_dom(Uexp, QQ), (4, 4), QQ)
+    L, U, swaps = A.lu()
+    assert L == Lexp
+    assert U == Uexp
+    assert swaps == []
+
+
+def test_DDM_lu_solve():
+    # Basic example
+    A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    x = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    assert A.lu_solve(b) == x
+
+    # Example with swaps
+    A = DDM([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    assert A.lu_solve(b) == x
+
+    # Overdetermined, consistent
+    A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
+    b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
+    assert A.lu_solve(b) == x
+
+    # Overdetermined, inconsistent
+    b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
+
+    # Square, noninvertible
+    A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
+    b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
+
+    # Underdetermined
+    A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
+    b = DDM([[QQ(3)]], (1, 1), QQ)
+    raises(NotImplementedError, lambda: A.lu_solve(b))
+
+    # Domain mismatch
+    bz = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    raises(DMDomainError, lambda: A.lu_solve(bz))
+
+    # Shape mismatch
+    b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
+    raises(DMShapeError, lambda: A.lu_solve(b3))
+
+
+def test_DDM_charpoly():
+    A = DDM([], (0, 0), ZZ)
+    assert A.charpoly() == [ZZ(1)]
+
+    A = DDM([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(4), ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+    Avec = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)]
+    assert A.charpoly() == Avec
+
+    A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: A.charpoly())
+
+
+def test_DDM_getitem():
+    dm = DDM([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(4), ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+
+    assert dm.getitem(1, 1) == ZZ(5)
+    assert dm.getitem(1, -2) == ZZ(5)
+    assert dm.getitem(-1, -3) == ZZ(7)
+
+    raises(IndexError, lambda: dm.getitem(3, 3))
+
+
+def test_DDM_setitem():
+    dm = DDM.zeros((3, 3), ZZ)
+    dm.setitem(0, 0, 1)
+    dm.setitem(1, -2, 1)
+    dm.setitem(-1, -1, 1)
+    assert dm == DDM.eye(3, ZZ)
+
+    raises(IndexError, lambda: dm.setitem(3, 3, 0))
+
+
+def test_DDM_extract_slice():
+    dm = DDM([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(4), ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+
+    assert dm.extract_slice(slice(0, 3), slice(0, 3)) == dm
+    assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ)
+    assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ)
+    assert dm.extract_slice(slice(2, 3), slice(-2)) == DDM([[ZZ(7)]], (1, 1), ZZ)
+    assert dm.extract_slice(slice(0, 2), slice(-2)) == DDM([[1], [4]], (2, 1), ZZ)
+    assert dm.extract_slice(slice(-1), slice(-1)) == DDM([[1, 2], [4, 5]], (2, 2), ZZ)
+
+    assert dm.extract_slice(slice(2), slice(3, 4)) == DDM([[], []], (2, 0), ZZ)
+    assert dm.extract_slice(slice(3, 4), slice(2)) == DDM([], (0, 2), ZZ)
+    assert dm.extract_slice(slice(3, 4), slice(3, 4)) == DDM([], (0, 0), ZZ)
+
+
+def test_DDM_extract():
+    dm1 = DDM([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(4), ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+    dm2 = DDM([
+        [ZZ(6), ZZ(4)],
+        [ZZ(3), ZZ(1)]], (2, 2), ZZ)
+    assert dm1.extract([1, 0], [2, 0]) == dm2
+    assert dm1.extract([-2, 0], [-1, 0]) == dm2
+
+    assert dm1.extract([], []) == DDM.zeros((0, 0), ZZ)
+    assert dm1.extract([1], []) == DDM.zeros((1, 0), ZZ)
+    assert dm1.extract([], [1]) == DDM.zeros((0, 1), ZZ)
+
+    raises(IndexError, lambda: dm2.extract([2], [0]))
+    raises(IndexError, lambda: dm2.extract([0], [2]))
+    raises(IndexError, lambda: dm2.extract([-3], [0]))
+    raises(IndexError, lambda: dm2.extract([0], [-3]))
+
+
+def test_DDM_flat():
+    dm = DDM([
+        [ZZ(6), ZZ(4)],
+        [ZZ(3), ZZ(1)]], (2, 2), ZZ)
+    assert dm.flat() == [ZZ(6), ZZ(4), ZZ(3), ZZ(1)]
+
+
+def test_DDM_is_zero_matrix():
+    A = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ)
+    Azero = DDM.zeros((1, 2), QQ)
+    assert A.is_zero_matrix() is False
+    assert Azero.is_zero_matrix() is True
+
+
+def test_DDM_is_upper():
+    # Wide matrices:
+    A = DDM([
+        [QQ(1), QQ(2), QQ(3), QQ(4)],
+        [QQ(0), QQ(5), QQ(6), QQ(7)],
+        [QQ(0), QQ(0), QQ(8), QQ(9)]
+    ], (3, 4), QQ)
+    B = DDM([
+        [QQ(1), QQ(2), QQ(3), QQ(4)],
+        [QQ(0), QQ(5), QQ(6), QQ(7)],
+        [QQ(0), QQ(7), QQ(8), QQ(9)]
+    ], (3, 4), QQ)
+    assert A.is_upper() is True
+    assert B.is_upper() is False
+
+    # Tall matrices:
+    A = DDM([
+        [QQ(1), QQ(2), QQ(3)],
+        [QQ(0), QQ(5), QQ(6)],
+        [QQ(0), QQ(0), QQ(8)],
+        [QQ(0), QQ(0), QQ(0)]
+    ], (4, 3), QQ)
+    B = DDM([
+        [QQ(1), QQ(2), QQ(3)],
+        [QQ(0), QQ(5), QQ(6)],
+        [QQ(0), QQ(0), QQ(8)],
+        [QQ(0), QQ(0), QQ(10)]
+    ], (4, 3), QQ)
+    assert A.is_upper() is True
+    assert B.is_upper() is False
+
+
+def test_DDM_is_lower():
+    # Tall matrices:
+    A = DDM([
+        [QQ(1), QQ(2), QQ(3), QQ(4)],
+        [QQ(0), QQ(5), QQ(6), QQ(7)],
+        [QQ(0), QQ(0), QQ(8), QQ(9)]
+    ], (3, 4), QQ).transpose()
+    B = DDM([
+        [QQ(1), QQ(2), QQ(3), QQ(4)],
+        [QQ(0), QQ(5), QQ(6), QQ(7)],
+        [QQ(0), QQ(7), QQ(8), QQ(9)]
+    ], (3, 4), QQ).transpose()
+    assert A.is_lower() is True
+    assert B.is_lower() is False
+
+    # Wide matrices:
+    A = DDM([
+        [QQ(1), QQ(2), QQ(3)],
+        [QQ(0), QQ(5), QQ(6)],
+        [QQ(0), QQ(0), QQ(8)],
+        [QQ(0), QQ(0), QQ(0)]
+    ], (4, 3), QQ).transpose()
+    B = DDM([
+        [QQ(1), QQ(2), QQ(3)],
+        [QQ(0), QQ(5), QQ(6)],
+        [QQ(0), QQ(0), QQ(8)],
+        [QQ(0), QQ(0), QQ(10)]
+    ], (4, 3), QQ).transpose()
+    assert A.is_lower() is True
+    assert B.is_lower() is False
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_dense.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_dense.py
new file mode 100644
index 0000000000000000000000000000000000000000..75315ebf6b2ae7d53b4a5737578d3ac5ed4ea36a
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_dense.py
@@ -0,0 +1,350 @@
+from sympy.testing.pytest import raises
+
+from sympy.polys import ZZ, QQ
+
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.dense import (
+        ddm_transpose,
+        ddm_iadd, ddm_isub, ddm_ineg, ddm_imatmul, ddm_imul, ddm_irref,
+        ddm_idet, ddm_iinv, ddm_ilu, ddm_ilu_split, ddm_ilu_solve, ddm_berk)
+
+from sympy.polys.matrices.exceptions import (
+    DMDomainError,
+    DMNonInvertibleMatrixError,
+    DMNonSquareMatrixError,
+    DMShapeError,
+)
+
+
+def test_ddm_transpose():
+    a = [[1, 2], [3, 4]]
+    assert ddm_transpose(a) == [[1, 3], [2, 4]]
+
+
+def test_ddm_iadd():
+    a = [[1, 2], [3, 4]]
+    b = [[5, 6], [7, 8]]
+    ddm_iadd(a, b)
+    assert a == [[6, 8], [10, 12]]
+
+
+def test_ddm_isub():
+    a = [[1, 2], [3, 4]]
+    b = [[5, 6], [7, 8]]
+    ddm_isub(a, b)
+    assert a == [[-4, -4], [-4, -4]]
+
+
+def test_ddm_ineg():
+    a = [[1, 2], [3, 4]]
+    ddm_ineg(a)
+    assert a == [[-1, -2], [-3, -4]]
+
+
+def test_ddm_matmul():
+    a = [[1, 2], [3, 4]]
+    ddm_imul(a, 2)
+    assert a == [[2, 4], [6, 8]]
+
+    a = [[1, 2], [3, 4]]
+    ddm_imul(a, 0)
+    assert a == [[0, 0], [0, 0]]
+
+
+def test_ddm_imatmul():
+    a = [[1, 2, 3], [4, 5, 6]]
+    b = [[1, 2], [3, 4], [5, 6]]
+
+    c1 = [[0, 0], [0, 0]]
+    ddm_imatmul(c1, a, b)
+    assert c1 == [[22, 28], [49, 64]]
+
+    c2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
+    ddm_imatmul(c2, b, a)
+    assert c2 == [[9, 12, 15], [19, 26, 33], [29, 40, 51]]
+
+    b3 = [[1], [2], [3]]
+    c3 = [[0], [0]]
+    ddm_imatmul(c3, a, b3)
+    assert c3 == [[14], [32]]
+
+
+def test_ddm_irref():
+    # Empty matrix
+    A = []
+    Ar = []
+    pivots = []
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+    # Standard square case
+    A = [[QQ(0), QQ(1)], [QQ(1), QQ(1)]]
+    Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
+    pivots = [0, 1]
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+    # m < n  case
+    A = [[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]]
+    Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]]
+    pivots = [0, 1]
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+    # same m < n  but reversed
+    A = [[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]]
+    Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]]
+    pivots = [0, 1]
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+    # m > n case
+    A = [[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]]
+    Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]]
+    pivots = [0, 1]
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+    # Example with missing pivot
+    A = [[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]]
+    Ar = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]]
+    pivots = [0, 2]
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+    # Example with missing pivot and no replacement
+    A = [[QQ(0), QQ(1)], [QQ(0), QQ(2)], [QQ(1), QQ(0)]]
+    Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]]
+    pivots = [0, 1]
+    assert ddm_irref(A) == pivots
+    assert A == Ar
+
+
+def test_ddm_idet():
+    A = []
+    assert ddm_idet(A, ZZ) == ZZ(1)
+
+    A = [[ZZ(2)]]
+    assert ddm_idet(A, ZZ) == ZZ(2)
+
+    A = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+    assert ddm_idet(A, ZZ) == ZZ(-2)
+
+    A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]]
+    assert ddm_idet(A, ZZ) == ZZ(-1)
+
+    A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]]
+    assert ddm_idet(A, ZZ) == ZZ(0)
+
+    A = [[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]]
+    assert ddm_idet(A, QQ) == QQ(-1, 24)
+
+
+def test_ddm_inv():
+    A = []
+    Ainv = []
+    ddm_iinv(Ainv, A, QQ)
+    assert Ainv == A
+
+    A = []
+    Ainv = []
+    raises(DMDomainError, lambda: ddm_iinv(Ainv, A, ZZ))
+
+    A = [[QQ(1), QQ(2)]]
+    Ainv = [[QQ(0), QQ(0)]]
+    raises(DMNonSquareMatrixError, lambda: ddm_iinv(Ainv, A, QQ))
+
+    A = [[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]]
+    Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
+    Ainv_expected = [[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]]
+    ddm_iinv(Ainv, A, QQ)
+    assert Ainv == Ainv_expected
+
+    A = [[QQ(1, 1), QQ(2, 1)], [QQ(2, 1), QQ(4, 1)]]
+    Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]]
+    raises(DMNonInvertibleMatrixError, lambda: ddm_iinv(Ainv, A, QQ))
+
+
+def test_ddm_ilu():
+    A = []
+    Alu = []
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == []
+
+    A = [[]]
+    Alu = [[]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == []
+
+    A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
+    Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == []
+
+    A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]]
+    Alu = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == [(0, 1)]
+
+    A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)], [QQ(7), QQ(8), QQ(9)]]
+    Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)], [QQ(7), QQ(2), QQ(0)]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == []
+
+    A = [[QQ(0), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(1), QQ(1), QQ(2)]]
+    Alu = [[QQ(1), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(0), QQ(1), QQ(-1)]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == [(0, 2)]
+
+    A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
+    Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == []
+
+    A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]]
+    Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)], [QQ(5), QQ(2)]]
+    swaps = ddm_ilu(A)
+    assert A == Alu
+    assert swaps == []
+
+
+def test_ddm_ilu_split():
+    U = []
+    L = []
+    Uexp = []
+    Lexp = []
+    swaps = ddm_ilu_split(L, U, QQ)
+    assert U == Uexp
+    assert L == Lexp
+    assert swaps == []
+
+    U = [[]]
+    L = [[QQ(1)]]
+    Uexp = [[]]
+    Lexp = [[QQ(1)]]
+    swaps = ddm_ilu_split(L, U, QQ)
+    assert U == Uexp
+    assert L == Lexp
+    assert swaps == []
+
+    U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
+    L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
+    Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]]
+    Lexp = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]]
+    swaps = ddm_ilu_split(L, U, QQ)
+    assert U == Uexp
+    assert L == Lexp
+    assert swaps == []
+
+    U = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]]
+    L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
+    Uexp = [[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]]
+    Lexp = [[QQ(1), QQ(0)], [QQ(4), QQ(1)]]
+    swaps = ddm_ilu_split(L, U, QQ)
+    assert U == Uexp
+    assert L == Lexp
+    assert swaps == []
+
+    U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]]
+    L = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(1), QQ(0)], [QQ(0), QQ(0), QQ(1)]]
+    Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]]
+    Lexp = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]]
+    swaps = ddm_ilu_split(L, U, QQ)
+    assert U == Uexp
+    assert L == Lexp
+    assert swaps == []
+
+
+def test_ddm_ilu_solve():
+    # Basic example
+    # A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]]
+    U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]]
+    L = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]]
+    swaps = []
+    b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
+    xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    ddm_ilu_solve(x, L, U, swaps, b)
+    assert x == xexp
+
+    # Example with swaps
+    # A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]]
+    U = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]]
+    L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]]
+    swaps = [(0, 1)]
+    b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
+    xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    ddm_ilu_solve(x, L, U, swaps, b)
+    assert x == xexp
+
+    # Overdetermined, consistent
+    # A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
+    U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]]
+    L = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]]
+    swaps = []
+    b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
+    x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ)
+    xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    ddm_ilu_solve(x, L, U, swaps, b)
+    assert x == xexp
+
+    # Overdetermined, inconsistent
+    b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
+
+    # Square, noninvertible
+    # A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
+    U = [[QQ(1), QQ(2)], [QQ(0), QQ(0)]]
+    L = [[QQ(1), QQ(0)], [QQ(1), QQ(1)]]
+    swaps = []
+    b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
+
+    # Underdetermined
+    # A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ)
+    U = [[QQ(1), QQ(2)]]
+    L = [[QQ(1)]]
+    swaps = []
+    b = DDM([[QQ(3)]], (1, 1), QQ)
+    raises(NotImplementedError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
+
+    # Shape mismatch
+    b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
+    raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b3))
+
+    # Empty shape mismatch
+    U = [[QQ(1)]]
+    L = [[QQ(1)]]
+    swaps = []
+    x = [[QQ(1)]]
+    b = []
+    raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b))
+
+    # Empty system
+    U = []
+    L = []
+    swaps = []
+    b = []
+    x = []
+    ddm_ilu_solve(x, L, U, swaps, b)
+    assert x == []
+
+
+def test_ddm_charpoly():
+    A = []
+    assert ddm_berk(A, ZZ) == [[ZZ(1)]]
+
+    A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]]
+    Avec = [[ZZ(1)], [ZZ(-15)], [ZZ(-18)], [ZZ(0)]]
+    assert ddm_berk(A, ZZ) == Avec
+
+    A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: ddm_berk(A, ZZ))
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..f75124d3822f026505e5f182658e70ba197a3c16
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_domainmatrix.py
@@ -0,0 +1,1345 @@
+from sympy.external.gmpy import GROUND_TYPES
+
+from sympy import Integer, Rational, S, sqrt, Matrix, symbols
+from sympy import FF, ZZ, QQ, QQ_I, EXRAW
+
+from sympy.polys.matrices.domainmatrix import DomainMatrix, DomainScalar, DM
+from sympy.polys.matrices.exceptions import (
+    DMBadInputError, DMDomainError, DMShapeError, DMFormatError, DMNotAField,
+    DMNonSquareMatrixError, DMNonInvertibleMatrixError,
+)
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.sdm import SDM
+
+from sympy.testing.pytest import raises
+
+
+def test_DM():
+    ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A = DM([[1, 2], [3, 4]], ZZ)
+    if GROUND_TYPES != 'flint':
+        assert A.rep == ddm
+    else:
+        assert A.rep == ddm.to_dfm()
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+
+def test_DomainMatrix_init():
+    lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+    dod = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}
+    ddm = DDM(lol, (2, 2), ZZ)
+    sdm = SDM(dod, (2, 2), ZZ)
+
+    A = DomainMatrix(lol, (2, 2), ZZ)
+    if GROUND_TYPES != 'flint':
+        assert A.rep == ddm
+    else:
+        assert A.rep == ddm.to_dfm()
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    A = DomainMatrix(dod, (2, 2), ZZ)
+    assert A.rep == sdm
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    raises(TypeError, lambda: DomainMatrix(ddm, (2, 2), ZZ))
+    raises(TypeError, lambda: DomainMatrix(sdm, (2, 2), ZZ))
+    raises(TypeError, lambda: DomainMatrix(Matrix([[1]]), (1, 1), ZZ))
+
+    for fmt, rep in [('sparse', sdm), ('dense', ddm)]:
+        if fmt == 'dense' and GROUND_TYPES == 'flint':
+            rep = rep.to_dfm()
+        A = DomainMatrix(lol, (2, 2), ZZ, fmt=fmt)
+        assert A.rep == rep
+        A = DomainMatrix(dod, (2, 2), ZZ, fmt=fmt)
+        assert A.rep == rep
+
+    raises(ValueError, lambda: DomainMatrix(lol, (2, 2), ZZ, fmt='invalid'))
+
+    raises(DMBadInputError, lambda: DomainMatrix([[ZZ(1), ZZ(2)]], (2, 2), ZZ))
+
+
+def test_DomainMatrix_from_rep():
+    ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A = DomainMatrix.from_rep(ddm)
+    # XXX: Should from_rep convert to DFM?
+    assert A.rep == ddm
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    sdm = SDM({0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    A = DomainMatrix.from_rep(sdm)
+    assert A.rep == sdm
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
+    raises(TypeError, lambda: DomainMatrix.from_rep(A))
+
+
+def test_DomainMatrix_from_list():
+    ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A = DomainMatrix.from_list([[1, 2], [3, 4]], ZZ)
+    if GROUND_TYPES != 'flint':
+        assert A.rep == ddm
+    else:
+        assert A.rep == ddm.to_dfm()
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    dom = FF(7)
+    ddm = DDM([[dom(1), dom(2)], [dom(3), dom(4)]], (2, 2), dom)
+    A = DomainMatrix.from_list([[1, 2], [3, 4]], dom)
+    # Not a DFM because FF(7) is not supported by DFM
+    assert A.rep == ddm
+    assert A.shape == (2, 2)
+    assert A.domain == dom
+
+    ddm = DDM([[QQ(1, 2), QQ(3, 1)], [QQ(1, 4), QQ(5, 1)]], (2, 2), QQ)
+    A = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ)
+    if GROUND_TYPES != 'flint':
+        assert A.rep == ddm
+    else:
+        assert A.rep == ddm.to_dfm()
+    assert A.shape == (2, 2)
+    assert A.domain == QQ
+
+
+def test_DomainMatrix_from_list_sympy():
+    ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A = DomainMatrix.from_list_sympy(2, 2, [[1, 2], [3, 4]])
+    if GROUND_TYPES != 'flint':
+        assert A.rep == ddm
+    else:
+        assert A.rep == ddm.to_dfm()
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    K = QQ.algebraic_field(sqrt(2))
+    ddm = DDM(
+        [[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))],
+         [K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]],
+        (2, 2),
+        K
+    )
+    A = DomainMatrix.from_list_sympy(
+        2, 2, [[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]],
+        extension=True)
+    assert A.rep == ddm
+    assert A.shape == (2, 2)
+    assert A.domain == K
+
+
+def test_DomainMatrix_from_dict_sympy():
+    sdm = SDM({0: {0: QQ(1, 2)}, 1: {1: QQ(2, 3)}}, (2, 2), QQ)
+    sympy_dict = {0: {0: Rational(1, 2)}, 1: {1: Rational(2, 3)}}
+    A = DomainMatrix.from_dict_sympy(2, 2, sympy_dict)
+    assert A.rep == sdm
+    assert A.shape == (2, 2)
+    assert A.domain == QQ
+
+    fds = DomainMatrix.from_dict_sympy
+    raises(DMBadInputError, lambda: fds(2, 2, {3: {0: Rational(1, 2)}}))
+    raises(DMBadInputError, lambda: fds(2, 2, {0: {3: Rational(1, 2)}}))
+
+
+def test_DomainMatrix_from_Matrix():
+    sdm = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
+    A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]]))
+    assert A.rep == sdm
+    assert A.shape == (2, 2)
+    assert A.domain == ZZ
+
+    K = QQ.algebraic_field(sqrt(2))
+    sdm = SDM(
+        {0: {0: K.convert(1 + sqrt(2)), 1: K.convert(2 + sqrt(2))},
+         1: {0: K.convert(3 + sqrt(2)), 1: K.convert(4 + sqrt(2))}},
+        (2, 2),
+        K
+    )
+    A = DomainMatrix.from_Matrix(
+        Matrix([[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]]),
+        extension=True)
+    assert A.rep == sdm
+    assert A.shape == (2, 2)
+    assert A.domain == K
+
+    A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense')
+    ddm = DDM([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]], (2, 2), QQ)
+
+    if GROUND_TYPES != 'flint':
+        assert A.rep == ddm
+    else:
+        assert A.rep == ddm.to_dfm()
+    assert A.shape == (2, 2)
+    assert A.domain == QQ
+
+
+def test_DomainMatrix_eq():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A == A
+    B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(1)]], (2, 2), ZZ)
+    assert A != B
+    C = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+    assert A != C
+
+
+def test_DomainMatrix_unify_eq():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B1 = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    B2 = DomainMatrix([[QQ(1), QQ(3)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    B3 = DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
+    assert A.unify_eq(B1) is True
+    assert A.unify_eq(B2) is False
+    assert A.unify_eq(B3) is False
+
+
+def test_DomainMatrix_get_domain():
+    K, items = DomainMatrix.get_domain([1, 2, 3, 4])
+    assert items == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
+    assert K == ZZ
+
+    K, items = DomainMatrix.get_domain([1, 2, 3, Rational(1, 2)])
+    assert items == [QQ(1), QQ(2), QQ(3), QQ(1, 2)]
+    assert K == QQ
+
+
+def test_DomainMatrix_convert_to():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aq = A.convert_to(QQ)
+    assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+
+
+def test_DomainMatrix_choose_domain():
+    A = [[1, 2], [3, 0]]
+    assert DM(A, QQ).choose_domain() == DM(A, ZZ)
+    assert DM(A, QQ).choose_domain(field=True) == DM(A, QQ)
+    assert DM(A, ZZ).choose_domain(field=True) == DM(A, QQ)
+
+    x = symbols('x')
+    B = [[1, x], [x**2, x**3]]
+    assert DM(B, QQ[x]).choose_domain(field=True) == DM(B, ZZ.frac_field(x))
+
+
+def test_DomainMatrix_to_flat_nz():
+    Adm = DM([[1, 2], [3, 0]], ZZ)
+    Addm = Adm.rep.to_ddm()
+    Asdm = Adm.rep.to_sdm()
+    for A in [Adm, Addm, Asdm]:
+        elems, data = A.to_flat_nz()
+        assert A.from_flat_nz(elems, data, A.domain) == A
+        elemsq = [QQ(e) for e in elems]
+        assert A.from_flat_nz(elemsq, data, QQ) == A.convert_to(QQ)
+        elems2 = [2*e for e in elems]
+        assert A.from_flat_nz(elems2, data, A.domain) == 2*A
+
+
+def test_DomainMatrix_to_sympy():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_sympy() == A.convert_to(EXRAW)
+
+
+def test_DomainMatrix_to_field():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aq = A.to_field()
+    assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+
+
+def test_DomainMatrix_to_sparse():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A_sparse = A.to_sparse()
+    assert A_sparse.rep == {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}
+
+
+def test_DomainMatrix_to_dense():
+    A = DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
+    A_dense = A.to_dense()
+    ddm = DDM([[1, 2], [3, 4]], (2, 2), ZZ)
+    if GROUND_TYPES != 'flint':
+        assert A_dense.rep == ddm
+    else:
+        assert A_dense.rep == ddm.to_dfm()
+
+
+def test_DomainMatrix_unify():
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    assert Az.unify(Az) == (Az, Az)
+    assert Az.unify(Aq) == (Aq, Aq)
+    assert Aq.unify(Az) == (Aq, Aq)
+    assert Aq.unify(Aq) == (Aq, Aq)
+
+    As = DomainMatrix({0: {1: ZZ(1)}, 1:{0:ZZ(2)}}, (2, 2), ZZ)
+    Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+    assert As.unify(As) == (As, As)
+    assert Ad.unify(Ad) == (Ad, Ad)
+
+    Bs, Bd = As.unify(Ad, fmt='dense')
+    assert Bs.rep == DDM([[0, 1], [2, 0]], (2, 2), ZZ).to_dfm_or_ddm()
+    assert Bd.rep == DDM([[1, 2],[3, 4]], (2, 2), ZZ).to_dfm_or_ddm()
+
+    Bs, Bd = As.unify(Ad, fmt='sparse')
+    assert Bs.rep == SDM({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ)
+    assert Bd.rep == SDM({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
+
+    raises(ValueError, lambda: As.unify(Ad, fmt='invalid'))
+
+
+def test_DomainMatrix_to_Matrix():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A_Matrix = Matrix([[1, 2], [3, 4]])
+    assert A.to_Matrix() == A_Matrix
+    assert A.to_sparse().to_Matrix() == A_Matrix
+    assert A.convert_to(QQ).to_Matrix() == A_Matrix
+    assert A.convert_to(QQ.algebraic_field(sqrt(2))).to_Matrix() == A_Matrix
+
+
+def test_DomainMatrix_to_list():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_list() == [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+
+
+def test_DomainMatrix_to_list_flat():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_list_flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
+
+
+def test_DomainMatrix_flat():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
+
+
+def test_DomainMatrix_from_list_flat():
+    nums = [ZZ(1), ZZ(2), ZZ(3), ZZ(4)]
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+    assert DomainMatrix.from_list_flat(nums, (2, 2), ZZ) == A
+    assert DDM.from_list_flat(nums, (2, 2), ZZ) == A.rep.to_ddm()
+    assert SDM.from_list_flat(nums, (2, 2), ZZ) == A.rep.to_sdm()
+
+    assert A == A.from_list_flat(A.to_list_flat(), A.shape, A.domain)
+
+    raises(DMBadInputError, DomainMatrix.from_list_flat, nums, (2, 3), ZZ)
+    raises(DMBadInputError, DDM.from_list_flat, nums, (2, 3), ZZ)
+    raises(DMBadInputError, SDM.from_list_flat, nums, (2, 3), ZZ)
+
+
+def test_DomainMatrix_to_dod():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_dod() == {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}
+    A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_dod() == {0: {0: ZZ(1)}, 1: {1: ZZ(4)}}
+
+
+def test_DomainMatrix_from_dod():
+    items = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}
+    A = DM([[1, 2], [3, 4]], ZZ)
+    assert DomainMatrix.from_dod(items, (2, 2), ZZ) == A.to_sparse()
+    assert A.from_dod_like(items) == A
+    assert A.from_dod_like(items, QQ) == A.convert_to(QQ)
+
+
+def test_DomainMatrix_to_dok():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_dok() == {(0, 0):ZZ(1), (0, 1):ZZ(2), (1, 0):ZZ(3), (1, 1):ZZ(4)}
+    A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(4)]], (2, 2), ZZ)
+    dok = {(0, 0):ZZ(1), (1, 1):ZZ(4)}
+    assert A.to_dok() == dok
+    assert A.to_dense().to_dok() == dok
+    assert A.to_sparse().to_dok() == dok
+    assert A.rep.to_ddm().to_dok() == dok
+    assert A.rep.to_sdm().to_dok() == dok
+
+
+def test_DomainMatrix_from_dok():
+    items = {(0, 0): ZZ(1), (1, 1): ZZ(2)}
+    A = DM([[1, 0], [0, 2]], ZZ)
+    assert DomainMatrix.from_dok(items, (2, 2), ZZ) == A.to_sparse()
+    assert DDM.from_dok(items, (2, 2), ZZ) == A.rep.to_ddm()
+    assert SDM.from_dok(items, (2, 2), ZZ) == A.rep.to_sdm()
+
+
+def test_DomainMatrix_repr():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert repr(A) == 'DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)'
+
+
+def test_DomainMatrix_transpose():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    AT = DomainMatrix([[ZZ(1), ZZ(3)], [ZZ(2), ZZ(4)]], (2, 2), ZZ)
+    assert A.transpose() == AT
+
+
+def test_DomainMatrix_is_zero_matrix():
+    A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
+    B = DomainMatrix([[ZZ(0)]], (1, 1), ZZ)
+    assert A.is_zero_matrix is False
+    assert B.is_zero_matrix is True
+
+
+def test_DomainMatrix_is_upper():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(0), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.is_upper is True
+    assert B.is_upper is False
+
+
+def test_DomainMatrix_is_lower():
+    A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.is_lower is True
+    assert B.is_lower is False
+
+
+def test_DomainMatrix_is_diagonal():
+    A = DM([[1, 0], [0, 4]], ZZ)
+    B = DM([[1, 2], [3, 4]], ZZ)
+    assert A.is_diagonal is A.to_sparse().is_diagonal is True
+    assert B.is_diagonal is B.to_sparse().is_diagonal is False
+
+
+def test_DomainMatrix_is_square():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]], (3, 2), ZZ)
+    assert A.is_square is True
+    assert B.is_square is False
+
+
+def test_DomainMatrix_diagonal():
+    A = DM([[1, 2], [3, 4]], ZZ)
+    assert A.diagonal() == A.to_sparse().diagonal() == [ZZ(1), ZZ(4)]
+    A = DM([[1, 2], [3, 4], [5, 6]], ZZ)
+    assert A.diagonal() == A.to_sparse().diagonal() == [ZZ(1), ZZ(4)]
+    A = DM([[1, 2, 3], [4, 5, 6]], ZZ)
+    assert A.diagonal() == A.to_sparse().diagonal() == [ZZ(1), ZZ(5)]
+
+
+def test_DomainMatrix_rank():
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(6), QQ(8)]], (3, 2), QQ)
+    assert A.rank() == 2
+
+
+def test_DomainMatrix_add():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
+    assert A + A == A.add(A) == B
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    L = [[2, 3], [3, 4]]
+    raises(TypeError, lambda: A + L)
+    raises(TypeError, lambda: L + A)
+
+    A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: A1 + A2)
+    raises(DMShapeError, lambda: A2 + A1)
+    raises(DMShapeError, lambda: A1.add(A2))
+    raises(DMShapeError, lambda: A2.add(A1))
+
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Asum = DomainMatrix([[QQ(2), QQ(4)], [QQ(6), QQ(8)]], (2, 2), QQ)
+    assert Az + Aq == Asum
+    assert Aq + Az == Asum
+    raises(DMDomainError, lambda: Az.add(Aq))
+    raises(DMDomainError, lambda: Aq.add(Az))
+
+    As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ)
+    Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+    Asd = As + Ad
+    Ads = Ad + As
+    assert Asd == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ)
+    assert Asd.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ).to_dfm_or_ddm()
+    assert Ads == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ)
+    assert Ads.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ).to_dfm_or_ddm()
+    raises(DMFormatError, lambda: As.add(Ad))
+
+
+def test_DomainMatrix_sub():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
+    assert A - A == A.sub(A) == B
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    L = [[2, 3], [3, 4]]
+    raises(TypeError, lambda: A - L)
+    raises(TypeError, lambda: L - A)
+
+    A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: A1 - A2)
+    raises(DMShapeError, lambda: A2 - A1)
+    raises(DMShapeError, lambda: A1.sub(A2))
+    raises(DMShapeError, lambda: A2.sub(A1))
+
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Adiff = DomainMatrix([[QQ(0), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ)
+    assert Az - Aq == Adiff
+    assert Aq - Az == Adiff
+    raises(DMDomainError, lambda: Az.sub(Aq))
+    raises(DMDomainError, lambda: Aq.sub(Az))
+
+    As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ)
+    Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+    Asd = As - Ad
+    Ads = Ad - As
+    assert Asd == DomainMatrix([[-1, -1], [-1, -4]], (2, 2), ZZ)
+    assert Asd.rep == DDM([[-1, -1], [-1, -4]], (2, 2), ZZ).to_dfm_or_ddm()
+    assert Asd == -Ads
+    assert Asd.rep == -Ads.rep
+
+
+def test_DomainMatrix_neg():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aneg = DomainMatrix([[ZZ(-1), ZZ(-2)], [ZZ(-3), ZZ(-4)]], (2, 2), ZZ)
+    assert -A == A.neg() == Aneg
+
+
+def test_DomainMatrix_mul():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ)
+    assert A*A == A.matmul(A) == A2
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    L = [[1, 2], [3, 4]]
+    raises(TypeError, lambda: A * L)
+    raises(TypeError, lambda: L * A)
+
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Aprod = DomainMatrix([[QQ(7), QQ(10)], [QQ(15), QQ(22)]], (2, 2), QQ)
+    assert Az * Aq == Aprod
+    assert Aq * Az == Aprod
+    raises(DMDomainError, lambda: Az.matmul(Aq))
+    raises(DMDomainError, lambda: Aq.matmul(Az))
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    AA = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
+    x = ZZ(2)
+    assert A * x == x * A == A.mul(x) == AA
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    AA = DomainMatrix.zeros((2, 2), ZZ)
+    x = ZZ(0)
+    assert A * x == x * A == A.mul(x).to_sparse() == AA
+
+    As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ)
+    Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+
+    Asd = As * Ad
+    Ads = Ad * As
+    assert Asd == DomainMatrix([[3, 4], [2, 4]], (2, 2), ZZ)
+    assert Asd.rep == DDM([[3, 4], [2, 4]], (2, 2), ZZ).to_dfm_or_ddm()
+    assert Ads == DomainMatrix([[4, 1], [8, 3]], (2, 2), ZZ)
+    assert Ads.rep == DDM([[4, 1], [8, 3]], (2, 2), ZZ).to_dfm_or_ddm()
+
+
+def test_DomainMatrix_mul_elementwise():
+    A = DomainMatrix([[ZZ(2), ZZ(2)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(4), ZZ(0)], [ZZ(3), ZZ(0)]], (2, 2), ZZ)
+    C = DomainMatrix([[ZZ(8), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
+    assert A.mul_elementwise(B) == C
+    assert B.mul_elementwise(A) == C
+
+
+def test_DomainMatrix_pow():
+    eye = DomainMatrix.eye(2, ZZ)
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ)
+    A3 = DomainMatrix([[ZZ(37), ZZ(54)], [ZZ(81), ZZ(118)]], (2, 2), ZZ)
+    assert A**0 == A.pow(0) == eye
+    assert A**1 == A.pow(1) == A
+    assert A**2 == A.pow(2) == A2
+    assert A**3 == A.pow(3) == A3
+
+    raises(TypeError, lambda: A ** Rational(1, 2))
+    raises(NotImplementedError, lambda: A ** -1)
+    raises(NotImplementedError, lambda: A.pow(-1))
+
+    A = DomainMatrix.zeros((2, 1), ZZ)
+    raises(DMNonSquareMatrixError, lambda: A ** 1)
+
+
+def test_DomainMatrix_clear_denoms():
+    A = DM([[(1,2),(1,3)],[(1,4),(1,5)]], QQ)
+
+    den_Z = DomainScalar(ZZ(60), ZZ)
+    Anum_Z = DM([[30, 20], [15, 12]], ZZ)
+    Anum_Q = Anum_Z.convert_to(QQ)
+
+    assert A.clear_denoms() == (den_Z, Anum_Q)
+    assert A.clear_denoms(convert=True) == (den_Z, Anum_Z)
+    assert A * den_Z == Anum_Q
+    assert A == Anum_Q / den_Z
+
+
+def test_DomainMatrix_clear_denoms_rowwise():
+    A = DM([[(1,2),(1,3)],[(1,4),(1,5)]], QQ)
+
+    den_Z = DM([[6, 0], [0, 20]], ZZ).to_sparse()
+    Anum_Z = DM([[3, 2], [5, 4]], ZZ)
+    Anum_Q = DM([[3, 2], [5, 4]], QQ)
+
+    assert A.clear_denoms_rowwise() == (den_Z, Anum_Q)
+    assert A.clear_denoms_rowwise(convert=True) == (den_Z, Anum_Z)
+    assert den_Z * A == Anum_Q
+    assert A == den_Z.to_field().inv() * Anum_Q
+
+    A = DM([[(1,2),(1,3),0,0],[0,0,0,0], [(1,4),(1,5),(1,6),(1,7)]], QQ)
+    den_Z = DM([[6, 0, 0], [0, 1, 0], [0, 0, 420]], ZZ).to_sparse()
+    Anum_Z = DM([[3, 2, 0, 0], [0, 0, 0, 0], [105, 84, 70, 60]], ZZ)
+    Anum_Q = Anum_Z.convert_to(QQ)
+
+    assert A.clear_denoms_rowwise() == (den_Z, Anum_Q)
+    assert A.clear_denoms_rowwise(convert=True) == (den_Z, Anum_Z)
+    assert den_Z * A == Anum_Q
+    assert A == den_Z.to_field().inv() * Anum_Q
+
+
+def test_DomainMatrix_cancel_denom():
+    A = DM([[2, 4], [6, 8]], ZZ)
+    assert A.cancel_denom(ZZ(1)) == (DM([[2, 4], [6, 8]], ZZ), ZZ(1))
+    assert A.cancel_denom(ZZ(3)) == (DM([[2, 4], [6, 8]], ZZ), ZZ(3))
+    assert A.cancel_denom(ZZ(4)) == (DM([[1, 2], [3, 4]], ZZ), ZZ(2))
+
+    A = DM([[1, 2], [3, 4]], ZZ)
+    assert A.cancel_denom(ZZ(2)) == (A, ZZ(2))
+    assert A.cancel_denom(ZZ(-2)) == (-A, ZZ(2))
+
+    # Test canonicalization of denominator over Gaussian rationals.
+    A = DM([[1, 2], [3, 4]], QQ_I)
+    assert A.cancel_denom(QQ_I(0,2)) == (QQ_I(0,-1)*A, QQ_I(2))
+
+    raises(ZeroDivisionError, lambda: A.cancel_denom(ZZ(0)))
+
+
+def test_DomainMatrix_cancel_denom_elementwise():
+    A = DM([[2, 4], [6, 8]], ZZ)
+    numers, denoms = A.cancel_denom_elementwise(ZZ(1))
+    assert numers == DM([[2, 4], [6, 8]], ZZ)
+    assert denoms == DM([[1, 1], [1, 1]], ZZ)
+    numers, denoms = A.cancel_denom_elementwise(ZZ(4))
+    assert numers == DM([[1, 1], [3, 2]], ZZ)
+    assert denoms == DM([[2, 1], [2, 1]], ZZ)
+
+    raises(ZeroDivisionError, lambda: A.cancel_denom_elementwise(ZZ(0)))
+
+
+def test_DomainMatrix_content_primitive():
+    A = DM([[2, 4], [6, 8]], ZZ)
+    A_primitive = DM([[1, 2], [3, 4]], ZZ)
+    A_content = ZZ(2)
+    assert A.content() == A_content
+    assert A.primitive() == (A_content, A_primitive)
+
+
+def test_DomainMatrix_scc():
+    Ad = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)],
+                       [ZZ(0), ZZ(1), ZZ(0)],
+                       [ZZ(2), ZZ(0), ZZ(4)]], (3, 3), ZZ)
+    As = Ad.to_sparse()
+    Addm = Ad.rep
+    Asdm = As.rep
+    for A in [Ad, As, Addm, Asdm]:
+        assert Ad.scc() == [[1], [0, 2]]
+
+    A = DM([[ZZ(1), ZZ(2), ZZ(3)]], ZZ)
+    raises(DMNonSquareMatrixError, lambda: A.scc())
+
+
+def test_DomainMatrix_rref():
+    # More tests in test_rref.py
+    A = DomainMatrix([], (0, 1), QQ)
+    assert A.rref() == (A, ())
+
+    A = DomainMatrix([[QQ(1)]], (1, 1), QQ)
+    assert A.rref() == (A, (0,))
+
+    A = DomainMatrix([[QQ(0)]], (1, 1), QQ)
+    assert A.rref() == (A, ())
+
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Ar, pivots = A.rref()
+    assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+    assert pivots == (0, 1)
+
+    A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Ar, pivots = A.rref()
+    assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+    assert pivots == (0, 1)
+
+    A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
+    Ar, pivots = A.rref()
+    assert Ar == DomainMatrix([[QQ(0), QQ(1)], [QQ(0), QQ(0)]], (2, 2), QQ)
+    assert pivots == (1,)
+
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    Ar, pivots = Az.rref()
+    assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+    assert pivots == (0, 1)
+
+    methods = ('auto', 'GJ', 'FF', 'CD', 'GJ_dense', 'FF_dense', 'CD_dense')
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    for method in methods:
+        Ar, pivots = Az.rref(method=method)
+        assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+        assert pivots == (0, 1)
+
+    raises(ValueError, lambda: Az.rref(method='foo'))
+    raises(ValueError, lambda: Az.rref_den(method='foo'))
+
+
+def test_DomainMatrix_columnspace():
+    A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ)
+    Acol = DomainMatrix([[QQ(1), QQ(1)], [QQ(2), QQ(3)]], (2, 2), QQ)
+    assert A.columnspace() == Acol
+
+    Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ)
+    raises(DMNotAField, lambda: Az.columnspace())
+
+    A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse')
+    Acol = DomainMatrix({0: {0: QQ(1), 1: QQ(1)}, 1: {0: QQ(2), 1: QQ(3)}}, (2, 2), QQ)
+    assert A.columnspace() == Acol
+
+
+def test_DomainMatrix_rowspace():
+    A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ)
+    assert A.rowspace() == A
+
+    Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ)
+    raises(DMNotAField, lambda: Az.rowspace())
+
+    A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse')
+    assert A.rowspace() == A
+
+
+def test_DomainMatrix_nullspace():
+    A = DomainMatrix([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ)
+    Anull = DomainMatrix([[QQ(-1), QQ(1)]], (1, 2), QQ)
+    assert A.nullspace() == Anull
+
+    A = DomainMatrix([[ZZ(1), ZZ(1)], [ZZ(1), ZZ(1)]], (2, 2), ZZ)
+    Anull = DomainMatrix([[ZZ(-1), ZZ(1)]], (1, 2), ZZ)
+    assert A.nullspace() == Anull
+
+    raises(DMNotAField, lambda: A.nullspace(divide_last=True))
+
+    A = DomainMatrix([[ZZ(2), ZZ(2)], [ZZ(2), ZZ(2)]], (2, 2), ZZ)
+    Anull = DomainMatrix([[ZZ(-2), ZZ(2)]], (1, 2), ZZ)
+
+    Arref, den, pivots = A.rref_den()
+    assert den == ZZ(2)
+    assert Arref.nullspace_from_rref() == Anull
+    assert Arref.nullspace_from_rref(pivots) == Anull
+    assert Arref.to_sparse().nullspace_from_rref() == Anull.to_sparse()
+    assert Arref.to_sparse().nullspace_from_rref(pivots) == Anull.to_sparse()
+
+
+def test_DomainMatrix_solve():
+    # XXX: Maybe the _solve method should be changed...
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
+    b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    particular = DomainMatrix([[1, 0]], (1, 2), QQ)
+    nullspace = DomainMatrix([[-2, 1]], (1, 2), QQ)
+    assert A._solve(b) == (particular, nullspace)
+
+    b3 = DomainMatrix([[QQ(1)], [QQ(1)], [QQ(1)]], (3, 1), QQ)
+    raises(DMShapeError, lambda: A._solve(b3))
+
+    bz = DomainMatrix([[ZZ(1)], [ZZ(1)]], (2, 1), ZZ)
+    raises(DMNotAField, lambda: A._solve(bz))
+
+
+def test_DomainMatrix_inv():
+    A = DomainMatrix([], (0, 0), QQ)
+    assert A.inv() == A
+
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Ainv = DomainMatrix([[QQ(-2), QQ(1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ)
+    assert A.inv() == Ainv
+
+    Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    raises(DMNotAField, lambda: Az.inv())
+
+    Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
+    raises(DMNonSquareMatrixError, lambda: Ans.inv())
+
+    Aninv = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(6)]], (2, 2), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: Aninv.inv())
+
+
+def test_DomainMatrix_det():
+    A = DomainMatrix([], (0, 0), ZZ)
+    assert A.det() == 1
+
+    A = DomainMatrix([[1]], (1, 1), ZZ)
+    assert A.det() == 1
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.det() == ZZ(-2)
+
+    A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ)
+    assert A.det() == ZZ(-1)
+
+    A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ)
+    assert A.det() == ZZ(0)
+
+    Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
+    raises(DMNonSquareMatrixError, lambda: Ans.det())
+
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    assert A.det() == QQ(-2)
+
+
+def test_DomainMatrix_eval_poly():
+    dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    p = [ZZ(1), ZZ(2), ZZ(3)]
+    result = DomainMatrix([[ZZ(12), ZZ(14)], [ZZ(21), ZZ(33)]], (2, 2), ZZ)
+    assert dM.eval_poly(p) == result == p[0]*dM**2 + p[1]*dM + p[2]*dM**0
+    assert dM.eval_poly([]) == dM.zeros(dM.shape, dM.domain)
+    assert dM.eval_poly([ZZ(2)]) == 2*dM.eye(2, dM.domain)
+
+    dM2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMNonSquareMatrixError, lambda: dM2.eval_poly([ZZ(1)]))
+
+
+def test_DomainMatrix_eval_poly_mul():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    p = [ZZ(1), ZZ(2), ZZ(3)]
+    result = DomainMatrix([[ZZ(40)], [ZZ(87)]], (2, 1), ZZ)
+    assert A.eval_poly_mul(p, b) == result == p[0]*A**2*b + p[1]*A*b + p[2]*b
+
+    dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    dM1 = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    raises(DMNonSquareMatrixError, lambda: dM1.eval_poly_mul([ZZ(1)], b))
+    b1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: dM.eval_poly_mul([ZZ(1)], b1))
+    bq = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    raises(DMDomainError, lambda: dM.eval_poly_mul([ZZ(1)], bq))
+
+
+def _check_solve_den(A, b, xnum, xden):
+    # Examples for solve_den, solve_den_charpoly, solve_den_rref should use
+    # this so that all methods and types are tested.
+
+    case1 = (A, xnum, b)
+    case2 = (A.to_sparse(), xnum.to_sparse(), b.to_sparse())
+
+    for Ai, xnum_i, b_i in [case1, case2]:
+        # The key invariant for solve_den:
+        assert Ai*xnum_i == xden*b_i
+
+        # solve_den_rref can differ at least by a minus sign
+        answers = [(xnum_i, xden), (-xnum_i, -xden)]
+        assert Ai.solve_den(b) in answers
+        assert Ai.solve_den(b, method='rref') in answers
+        assert Ai.solve_den_rref(b) in answers
+
+        # charpoly can only be used if A is square and guarantees to return the
+        # actual determinant as a denominator.
+        m, n = Ai.shape
+        if m == n:
+            assert Ai.solve_den(b_i, method='charpoly') == (xnum_i, xden)
+            assert Ai.solve_den_charpoly(b_i) == (xnum_i, xden)
+        else:
+            raises(DMNonSquareMatrixError, lambda: Ai.solve_den_charpoly(b))
+            raises(DMNonSquareMatrixError, lambda: Ai.solve_den(b, method='charpoly'))
+
+
+def test_DomainMatrix_solve_den():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    result = DomainMatrix([[ZZ(0)], [ZZ(-1)]], (2, 1), ZZ)
+    den = ZZ(-2)
+    _check_solve_den(A, b, result, den)
+
+    A = DomainMatrix([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(1), ZZ(2), ZZ(4)],
+        [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)], [ZZ(3)]], (3, 1), ZZ)
+    result = DomainMatrix([[ZZ(2)], [ZZ(0)], [ZZ(-1)]], (3, 1), ZZ)
+    den = ZZ(-1)
+    _check_solve_den(A, b, result, den)
+
+    A = DomainMatrix([[ZZ(2)], [ZZ(2)]], (2, 1), ZZ)
+    b = DomainMatrix([[ZZ(3)], [ZZ(3)]], (2, 1), ZZ)
+    result = DomainMatrix([[ZZ(3)]], (1, 1), ZZ)
+    den = ZZ(2)
+    _check_solve_den(A, b, result, den)
+
+
+def test_DomainMatrix_solve_den_charpoly():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    A1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMNonSquareMatrixError, lambda: A1.solve_den_charpoly(b))
+    b1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: A.solve_den_charpoly(b1))
+    bq = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    raises(DMDomainError, lambda: A.solve_den_charpoly(bq))
+
+
+def test_DomainMatrix_solve_den_charpoly_check():
+    # Test check
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(2), ZZ(4)]], (2, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(3)]], (2, 1), ZZ)
+    raises(DMNonInvertibleMatrixError, lambda: A.solve_den_charpoly(b))
+    adjAb = DomainMatrix([[ZZ(-2)], [ZZ(1)]], (2, 1), ZZ)
+    assert A.adjugate() * b == adjAb
+    assert A.solve_den_charpoly(b, check=False) == (adjAb, ZZ(0))
+
+
+def test_DomainMatrix_solve_den_errors():
+    A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    raises(DMShapeError, lambda: A.solve_den(b))
+    raises(DMShapeError, lambda: A.solve_den_rref(b))
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    b = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: A.solve_den(b))
+    raises(DMShapeError, lambda: A.solve_den_rref(b))
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    b1 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    raises(DMShapeError, lambda: A.solve_den(b1))
+
+    A = DomainMatrix([[ZZ(2)]], (1, 1), ZZ)
+    b = DomainMatrix([[ZZ(2)]], (1, 1), ZZ)
+    raises(DMBadInputError, lambda: A.solve_den(b1, method='invalid'))
+
+    A = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    raises(DMNonSquareMatrixError, lambda: A.solve_den_charpoly(b))
+
+
+def test_DomainMatrix_solve_den_rref_underdetermined():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(1), ZZ(2)]], (2, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(1)]], (2, 1), ZZ)
+    raises(DMNonInvertibleMatrixError, lambda: A.solve_den(b))
+    raises(DMNonInvertibleMatrixError, lambda: A.solve_den_rref(b))
+
+
+def test_DomainMatrix_adj_poly_det():
+    A = DM([[ZZ(1), ZZ(2), ZZ(3)],
+            [ZZ(4), ZZ(5), ZZ(6)],
+            [ZZ(7), ZZ(8), ZZ(9)]], ZZ)
+    p, detA = A.adj_poly_det()
+    assert p == [ZZ(1), ZZ(-15), ZZ(-18)]
+    assert A.adjugate() == p[0]*A**2 + p[1]*A**1 + p[2]*A**0 == A.eval_poly(p)
+    assert A.det() == detA
+
+    A = DM([[ZZ(1), ZZ(2), ZZ(3)],
+            [ZZ(7), ZZ(8), ZZ(9)]], ZZ)
+    raises(DMNonSquareMatrixError, lambda: A.adj_poly_det())
+
+
+def test_DomainMatrix_inv_den():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    den = ZZ(-2)
+    result = DomainMatrix([[ZZ(4), ZZ(-2)], [ZZ(-3), ZZ(1)]], (2, 2), ZZ)
+    assert A.inv_den() == (result, den)
+
+
+def test_DomainMatrix_adjugate():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    result = DomainMatrix([[ZZ(4), ZZ(-2)], [ZZ(-3), ZZ(1)]], (2, 2), ZZ)
+    assert A.adjugate() == result
+
+
+def test_DomainMatrix_adj_det():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    adjA = DomainMatrix([[ZZ(4), ZZ(-2)], [ZZ(-3), ZZ(1)]], (2, 2), ZZ)
+    assert A.adj_det() == (adjA, ZZ(-2))
+
+
+def test_DomainMatrix_lu():
+    A = DomainMatrix([], (0, 0), QQ)
+    assert A.lu() == (A, A, [])
+
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    L = DomainMatrix([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ)
+    U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ)
+    swaps = []
+    assert A.lu() == (L, U, swaps)
+
+    A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+    U = DomainMatrix([[QQ(3), QQ(4)], [QQ(0), QQ(2)]], (2, 2), QQ)
+    swaps = [(0, 1)]
+    assert A.lu() == (L, U, swaps)
+
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
+    L = DomainMatrix([[QQ(1), QQ(0)], [QQ(2), QQ(1)]], (2, 2), QQ)
+    U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(0)]], (2, 2), QQ)
+    swaps = []
+    assert A.lu() == (L, U, swaps)
+
+    A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
+    L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ)
+    U = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ)
+    swaps = []
+    assert A.lu() == (L, U, swaps)
+
+    A = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ)
+    L = DomainMatrix([[QQ(1), QQ(0)], [QQ(4), QQ(1)]], (2, 2), QQ)
+    U = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]], (2, 3), QQ)
+    swaps = []
+    assert A.lu() == (L, U, swaps)
+
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
+    L = DomainMatrix([
+        [QQ(1), QQ(0), QQ(0)],
+        [QQ(3), QQ(1), QQ(0)],
+        [QQ(5), QQ(2), QQ(1)]], (3, 3), QQ)
+    U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]], (3, 2), QQ)
+    swaps = []
+    assert A.lu() == (L, U, swaps)
+
+    A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]
+    L = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]]
+    U = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]]
+    to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows]
+    A = DomainMatrix(to_dom(A, QQ), (4, 4), QQ)
+    L = DomainMatrix(to_dom(L, QQ), (4, 4), QQ)
+    U = DomainMatrix(to_dom(U, QQ), (4, 4), QQ)
+    assert A.lu() == (L, U, [])
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    raises(DMNotAField, lambda: A.lu())
+
+
+def test_DomainMatrix_lu_solve():
+    # Base case
+    A = b = x = DomainMatrix([], (0, 0), QQ)
+    assert A.lu_solve(b) == x
+
+    # Basic example
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    assert A.lu_solve(b) == x
+
+    # Example with swaps
+    A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    assert A.lu_solve(b) == x
+
+    # Non-invertible
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ)
+    b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
+
+    # Overdetermined, consistent
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
+    b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ)
+    x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ)
+    assert A.lu_solve(b) == x
+
+    # Overdetermined, inconsistent
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ)
+    b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ)
+    raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b))
+
+    # Underdetermined
+    A = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
+    b = DomainMatrix([[QQ(1)]], (1, 1), QQ)
+    raises(NotImplementedError, lambda: A.lu_solve(b))
+
+    # Non-field
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ)
+    raises(DMNotAField, lambda: A.lu_solve(b))
+
+    # Shape mismatch
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    b = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
+    raises(DMShapeError, lambda: A.lu_solve(b))
+
+
+def test_DomainMatrix_charpoly():
+    A = DomainMatrix([], (0, 0), ZZ)
+    p = [ZZ(1)]
+    assert A.charpoly() == p
+    assert A.to_sparse().charpoly() == p
+
+    A = DomainMatrix([[1]], (1, 1), ZZ)
+    p = [ZZ(1), ZZ(-1)]
+    assert A.charpoly() == p
+    assert A.to_sparse().charpoly() == p
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    p = [ZZ(1), ZZ(-5), ZZ(-2)]
+    assert A.charpoly() == p
+    assert A.to_sparse().charpoly() == p
+
+    A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+    p = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)]
+    assert A.charpoly() == p
+    assert A.to_sparse().charpoly() == p
+
+    A = DomainMatrix([[ZZ(0), ZZ(1), ZZ(0)],
+                      [ZZ(1), ZZ(0), ZZ(1)],
+                      [ZZ(0), ZZ(1), ZZ(0)]], (3, 3), ZZ)
+    p = [ZZ(1), ZZ(0), ZZ(-2), ZZ(0)]
+    assert A.charpoly() == p
+    assert A.to_sparse().charpoly() == p
+
+    A = DM([[17, 0, 30,  0,  0,  0, 0,  0, 0, 0],
+            [ 0, 0,  0,  0,  0,  0, 0,  0, 0, 0],
+            [69, 0,  0,  0,  0, 86, 0,  0, 0, 0],
+            [23, 0,  0,  0,  0,  0, 0,  0, 0, 0],
+            [ 0, 0,  0,  0,  0,  0, 0,  0, 0, 0],
+            [ 0, 0,  0, 13,  0,  0, 0,  0, 0, 0],
+            [ 0, 0,  0,  0,  0,  0, 0, 32, 0, 0],
+            [ 0, 0,  0,  0, 37, 67, 0,  0, 0, 0],
+            [ 0, 0,  0,  0,  0,  0, 0,  0, 0, 0],
+            [ 0, 0,  0,  0,  0,  0, 0,  0, 0, 0]], ZZ)
+    p = ZZ.map([1, -17, -2070, 0, -771420, 0, 0, 0, 0, 0, 0])
+    assert A.charpoly() == p
+    assert A.to_sparse().charpoly() == p
+
+    Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ)
+    raises(DMNonSquareMatrixError, lambda: Ans.charpoly())
+
+
+def test_DomainMatrix_charpoly_factor_list():
+    A = DomainMatrix([], (0, 0), ZZ)
+    assert A.charpoly_factor_list() == []
+
+    A = DM([[1]], ZZ)
+    assert A.charpoly_factor_list() == [
+        ([ZZ(1), ZZ(-1)], 1)
+    ]
+
+    A = DM([[1, 2], [3, 4]], ZZ)
+    assert A.charpoly_factor_list() == [
+        ([ZZ(1), ZZ(-5), ZZ(-2)], 1)
+    ]
+
+    A = DM([[1, 2, 0], [3, 4, 0], [0, 0, 1]], ZZ)
+    assert A.charpoly_factor_list() == [
+        ([ZZ(1), ZZ(-1)], 1),
+        ([ZZ(1), ZZ(-5), ZZ(-2)], 1)
+    ]
+
+
+def test_DomainMatrix_eye():
+    A = DomainMatrix.eye(3, QQ)
+    assert A.rep == SDM.eye((3, 3), QQ)
+    assert A.shape == (3, 3)
+    assert A.domain == QQ
+
+
+def test_DomainMatrix_zeros():
+    A = DomainMatrix.zeros((1, 2), QQ)
+    assert A.rep == SDM.zeros((1, 2), QQ)
+    assert A.shape == (1, 2)
+    assert A.domain == QQ
+
+
+def test_DomainMatrix_ones():
+    A = DomainMatrix.ones((2, 3), QQ)
+    if GROUND_TYPES != 'flint':
+        assert A.rep == DDM.ones((2, 3), QQ)
+    else:
+        assert A.rep == SDM.ones((2, 3), QQ).to_dfm()
+    assert A.shape == (2, 3)
+    assert A.domain == QQ
+
+
+def test_DomainMatrix_diag():
+    A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (2, 2), ZZ)
+    assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ) == A
+
+    A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (3, 4), ZZ)
+    assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ, (3, 4)) == A
+
+
+def test_DomainMatrix_hstack():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
+    C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
+
+    AB = DomainMatrix([
+        [ZZ(1), ZZ(2), ZZ(5), ZZ(6)],
+        [ZZ(3), ZZ(4), ZZ(7), ZZ(8)]], (2, 4), ZZ)
+    ABC = DomainMatrix([
+        [ZZ(1), ZZ(2), ZZ(5), ZZ(6), ZZ(9), ZZ(10)],
+        [ZZ(3), ZZ(4), ZZ(7), ZZ(8), ZZ(11), ZZ(12)]], (2, 6), ZZ)
+    assert A.hstack(B) == AB
+    assert A.hstack(B, C) == ABC
+
+
+def test_DomainMatrix_vstack():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
+    C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
+
+    AB = DomainMatrix([
+        [ZZ(1), ZZ(2)],
+        [ZZ(3), ZZ(4)],
+        [ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8)]], (4, 2), ZZ)
+    ABC = DomainMatrix([
+        [ZZ(1), ZZ(2)],
+        [ZZ(3), ZZ(4)],
+        [ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8)],
+        [ZZ(9), ZZ(10)],
+        [ZZ(11), ZZ(12)]], (6, 2), ZZ)
+    assert A.vstack(B) == AB
+    assert A.vstack(B, C) == ABC
+
+
+def test_DomainMatrix_applyfunc():
+    A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
+    B = DomainMatrix([[ZZ(2), ZZ(4)]], (1, 2), ZZ)
+    assert A.applyfunc(lambda x: 2*x) == B
+
+
+def test_DomainMatrix_scalarmul():
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    lamda = DomainScalar(QQ(3)/QQ(2), QQ)
+    assert A * lamda == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ)
+    assert A * 2 == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
+    assert 2 * A == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ)
+    assert A * DomainScalar(ZZ(0), ZZ) == DomainMatrix({}, (2, 2), ZZ)
+    assert A * DomainScalar(ZZ(1), ZZ) == A
+
+    raises(TypeError, lambda: A * 1.5)
+
+
+def test_DomainMatrix_truediv():
+    A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]]))
+    lamda = DomainScalar(QQ(3)/QQ(2), QQ)
+    assert A / lamda == DomainMatrix({0: {0: QQ(2, 3), 1: QQ(4, 3)}, 1: {0: QQ(2), 1: QQ(8, 3)}}, (2, 2), QQ)
+    b = DomainScalar(ZZ(1), ZZ)
+    assert A / b == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
+
+    assert A / 1 == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
+    assert A / 2 == DomainMatrix({0: {0: QQ(1, 2), 1: QQ(1)}, 1: {0: QQ(3, 2), 1: QQ(2)}}, (2, 2), QQ)
+
+    raises(ZeroDivisionError, lambda: A / 0)
+    raises(TypeError, lambda: A / 1.5)
+    raises(ZeroDivisionError, lambda: A / DomainScalar(ZZ(0), ZZ))
+
+    A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A.to_field() / 2 == DomainMatrix([[QQ(1, 2), QQ(1)], [QQ(3, 2), QQ(2)]], (2, 2), QQ)
+    assert A / 2 == DomainMatrix([[QQ(1, 2), QQ(1)], [QQ(3, 2), QQ(2)]], (2, 2), QQ)
+    assert A.to_field() / QQ(2,3) == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ)
+
+
+def test_DomainMatrix_getitem():
+    dM = DomainMatrix([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(4), ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+
+    assert dM[1:,:-2] == DomainMatrix([[ZZ(4)], [ZZ(7)]], (2, 1), ZZ)
+    assert dM[2,:-2] == DomainMatrix([[ZZ(7)]], (1, 1), ZZ)
+    assert dM[:-2,:-2] == DomainMatrix([[ZZ(1)]], (1, 1), ZZ)
+    assert dM[:-1,0:2] == DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(4), ZZ(5)]], (2, 2), ZZ)
+    assert dM[:, -1] == DomainMatrix([[ZZ(3)], [ZZ(6)], [ZZ(9)]], (3, 1), ZZ)
+    assert dM[-1, :] == DomainMatrix([[ZZ(7), ZZ(8), ZZ(9)]], (1, 3), ZZ)
+    assert dM[::-1, :] == DomainMatrix([
+                            [ZZ(7), ZZ(8), ZZ(9)],
+                            [ZZ(4), ZZ(5), ZZ(6)],
+                            [ZZ(1), ZZ(2), ZZ(3)]], (3, 3), ZZ)
+
+    raises(IndexError, lambda: dM[4, :-2])
+    raises(IndexError, lambda: dM[:-2, 4])
+
+    assert dM[1, 2] == DomainScalar(ZZ(6), ZZ)
+    assert dM[-2, 2] == DomainScalar(ZZ(6), ZZ)
+    assert dM[1, -2] == DomainScalar(ZZ(5), ZZ)
+    assert dM[-1, -3] == DomainScalar(ZZ(7), ZZ)
+
+    raises(IndexError, lambda: dM[3, 3])
+    raises(IndexError, lambda: dM[1, 4])
+    raises(IndexError, lambda: dM[-1, -4])
+
+    dM = DomainMatrix({0: {0: ZZ(1)}}, (10, 10), ZZ)
+    assert dM[5, 5] == DomainScalar(ZZ(0), ZZ)
+    assert dM[0, 0] == DomainScalar(ZZ(1), ZZ)
+
+    dM = DomainMatrix({1: {0: 1}}, (2,1), ZZ)
+    assert dM[0:, 0] == DomainMatrix({1: {0: 1}}, (2, 1), ZZ)
+    raises(IndexError, lambda: dM[3, 0])
+
+    dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
+    assert dM[:2,:2] == DomainMatrix({}, (2, 2), ZZ)
+    assert dM[2:,2:] == DomainMatrix({0: {0: 1}, 2: {2: 1}}, (3, 3), ZZ)
+    assert dM[3:,3:] == DomainMatrix({1: {1: 1}}, (2, 2), ZZ)
+    assert dM[2:, 6:] == DomainMatrix({}, (3, 0), ZZ)
+
+
+def test_DomainMatrix_getitem_sympy():
+    dM = DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
+    val1 = dM.getitem_sympy(0, 0)
+    assert val1 is S.Zero
+    val2 = dM.getitem_sympy(2, 2)
+    assert val2 == 2 and isinstance(val2, Integer)
+
+
+def test_DomainMatrix_extract():
+    dM1 = DomainMatrix([
+        [ZZ(1), ZZ(2), ZZ(3)],
+        [ZZ(4), ZZ(5), ZZ(6)],
+        [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ)
+    dM2 = DomainMatrix([
+        [ZZ(1), ZZ(3)],
+        [ZZ(7), ZZ(9)]], (2, 2), ZZ)
+    assert dM1.extract([0, 2], [0, 2]) == dM2
+    assert dM1.to_sparse().extract([0, 2], [0, 2]) == dM2.to_sparse()
+    assert dM1.extract([0, -1], [0, -1]) == dM2
+    assert dM1.to_sparse().extract([0, -1], [0, -1]) == dM2.to_sparse()
+
+    dM3 = DomainMatrix([
+        [ZZ(1), ZZ(2), ZZ(2)],
+        [ZZ(4), ZZ(5), ZZ(5)],
+        [ZZ(4), ZZ(5), ZZ(5)]], (3, 3), ZZ)
+    assert dM1.extract([0, 1, 1], [0, 1, 1]) == dM3
+    assert dM1.to_sparse().extract([0, 1, 1], [0, 1, 1]) == dM3.to_sparse()
+
+    empty = [
+        ([], [], (0, 0)),
+        ([1], [], (1, 0)),
+        ([], [1], (0, 1)),
+    ]
+    for rows, cols, size in empty:
+        assert dM1.extract(rows, cols) == DomainMatrix.zeros(size, ZZ).to_dense()
+        assert dM1.to_sparse().extract(rows, cols) == DomainMatrix.zeros(size, ZZ)
+
+    dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    bad_indices = [([2], [0]), ([0], [2]), ([-3], [0]), ([0], [-3])]
+    for rows, cols in bad_indices:
+        raises(IndexError, lambda: dM.extract(rows, cols))
+        raises(IndexError, lambda: dM.to_sparse().extract(rows, cols))
+
+
+def test_DomainMatrix_setitem():
+    dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
+    dM[2, 2] = ZZ(2)
+    assert dM == DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
+    def setitem(i, j, val):
+        dM[i, j] = val
+    raises(TypeError, lambda: setitem(2, 2, QQ(1, 2)))
+    raises(NotImplementedError, lambda: setitem(slice(1, 2), 2, ZZ(1)))
+
+
+def test_DomainMatrix_pickling():
+    import pickle
+    dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ)
+    assert pickle.loads(pickle.dumps(dM)) == dM
+    dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert pickle.loads(pickle.dumps(dM)) == dM
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_domainscalar.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_domainscalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c507caf079cc62ba23ba171a50d0d27c98eb6d9
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_domainscalar.py
@@ -0,0 +1,153 @@
+from sympy.testing.pytest import raises
+
+from sympy.core.symbol import S
+from sympy.polys import ZZ, QQ
+from sympy.polys.matrices.domainscalar import DomainScalar
+from sympy.polys.matrices.domainmatrix import DomainMatrix
+
+
+def test_DomainScalar___new__():
+    raises(TypeError, lambda: DomainScalar(ZZ(1), QQ))
+    raises(TypeError, lambda: DomainScalar(ZZ(1), 1))
+
+
+def test_DomainScalar_new():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = A.new(ZZ(4), ZZ)
+    assert B == DomainScalar(ZZ(4), ZZ)
+
+
+def test_DomainScalar_repr():
+    A = DomainScalar(ZZ(1), ZZ)
+    assert repr(A) in {'1', 'mpz(1)'}
+
+
+def test_DomainScalar_from_sympy():
+    expr = S(1)
+    B = DomainScalar.from_sympy(expr)
+    assert B == DomainScalar(ZZ(1), ZZ)
+
+
+def test_DomainScalar_to_sympy():
+    B = DomainScalar(ZZ(1), ZZ)
+    expr = B.to_sympy()
+    assert expr.is_Integer and expr == 1
+
+
+def test_DomainScalar_to_domain():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = A.to_domain(QQ)
+    assert B == DomainScalar(QQ(1), QQ)
+
+
+def test_DomainScalar_convert_to():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = A.convert_to(QQ)
+    assert B == DomainScalar(QQ(1), QQ)
+
+
+def test_DomainScalar_unify():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    A, B = A.unify(B)
+    assert A.domain == B.domain == QQ
+
+
+def test_DomainScalar_add():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    assert A + B == DomainScalar(QQ(3), QQ)
+
+    raises(TypeError, lambda: A + 1.5)
+
+def test_DomainScalar_sub():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    assert A - B == DomainScalar(QQ(-1), QQ)
+
+    raises(TypeError, lambda: A - 1.5)
+
+def test_DomainScalar_mul():
+    A = DomainScalar(ZZ(1), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    dm = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
+    assert A * B == DomainScalar(QQ(2), QQ)
+    assert A * dm == dm
+    assert B * 2 == DomainScalar(QQ(4), QQ)
+
+    raises(TypeError, lambda: A * 1.5)
+
+
+def test_DomainScalar_floordiv():
+    A = DomainScalar(ZZ(-5), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    assert A // B == DomainScalar(QQ(-5, 2), QQ)
+    C = DomainScalar(ZZ(2), ZZ)
+    assert A // C == DomainScalar(ZZ(-3), ZZ)
+
+    raises(TypeError, lambda: A // 1.5)
+
+
+def test_DomainScalar_mod():
+    A = DomainScalar(ZZ(5), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    assert A % B == DomainScalar(QQ(0), QQ)
+    C = DomainScalar(ZZ(2), ZZ)
+    assert A % C == DomainScalar(ZZ(1), ZZ)
+
+    raises(TypeError, lambda: A % 1.5)
+
+
+def test_DomainScalar_divmod():
+    A = DomainScalar(ZZ(5), ZZ)
+    B = DomainScalar(QQ(2), QQ)
+    assert divmod(A, B) == (DomainScalar(QQ(5, 2), QQ), DomainScalar(QQ(0), QQ))
+    C = DomainScalar(ZZ(2), ZZ)
+    assert divmod(A, C) == (DomainScalar(ZZ(2), ZZ), DomainScalar(ZZ(1), ZZ))
+
+    raises(TypeError, lambda: divmod(A, 1.5))
+
+
+def test_DomainScalar_pow():
+    A = DomainScalar(ZZ(-5), ZZ)
+    B = A**(2)
+    assert B == DomainScalar(ZZ(25), ZZ)
+
+    raises(TypeError, lambda: A**(1.5))
+
+
+def test_DomainScalar_pos():
+    A = DomainScalar(QQ(2), QQ)
+    B = DomainScalar(QQ(2), QQ)
+    assert  +A == B
+
+
+def test_DomainScalar_neg():
+    A = DomainScalar(QQ(2), QQ)
+    B = DomainScalar(QQ(-2), QQ)
+    assert  -A == B
+
+
+def test_DomainScalar_eq():
+    A = DomainScalar(QQ(2), QQ)
+    assert A == A
+    B = DomainScalar(ZZ(-5), ZZ)
+    assert A != B
+    C = DomainScalar(ZZ(2), ZZ)
+    assert A != C
+    D = [1]
+    assert A != D
+
+
+def test_DomainScalar_isZero():
+    A = DomainScalar(ZZ(0), ZZ)
+    assert A.is_zero() == True
+    B = DomainScalar(ZZ(1), ZZ)
+    assert B.is_zero() == False
+
+
+def test_DomainScalar_isOne():
+    A = DomainScalar(ZZ(1), ZZ)
+    assert A.is_one() == True
+    B = DomainScalar(ZZ(0), ZZ)
+    assert B.is_one() == False
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_eigen.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_eigen.py
new file mode 100644
index 0000000000000000000000000000000000000000..70482eab686d5b4e1c45d552f5eccb5bdaa9e1ed
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_eigen.py
@@ -0,0 +1,90 @@
+"""
+Tests for the sympy.polys.matrices.eigen module
+"""
+
+from sympy.core.singleton import S
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.matrices.dense import Matrix
+
+from sympy.polys.agca.extensions import FiniteExtension
+from sympy.polys.domains import QQ
+from sympy.polys.polytools import Poly
+from sympy.polys.rootoftools import CRootOf
+from sympy.polys.matrices.domainmatrix import DomainMatrix
+
+from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy
+
+
+def test_dom_eigenvects_rational():
+    # Rational eigenvalues
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ)
+    rational_eigenvects = [
+        (QQ, QQ(3), 1, DomainMatrix([[QQ(1), QQ(1)]], (1, 2), QQ)),
+        (QQ, QQ(0), 1, DomainMatrix([[QQ(-2), QQ(1)]], (1, 2), QQ)),
+    ]
+    assert dom_eigenvects(A) == (rational_eigenvects, [])
+
+    # Test converting to Expr:
+    sympy_eigenvects = [
+        (S(3), 1, [Matrix([1, 1])]),
+        (S(0), 1, [Matrix([-2, 1])]),
+    ]
+    assert dom_eigenvects_to_sympy(rational_eigenvects, [], Matrix) == sympy_eigenvects
+
+
+def test_dom_eigenvects_algebraic():
+    # Algebraic eigenvalues
+    A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ)
+    Avects = dom_eigenvects(A)
+
+    # Extract the dummy to build the expected result:
+    lamda = Avects[1][0][1].gens[0]
+    irreducible = Poly(lamda**2 - 5*lamda - 2, lamda, domain=QQ)
+    K = FiniteExtension(irreducible)
+    KK = K.from_sympy
+    algebraic_eigenvects = [
+        (K, irreducible, 1, DomainMatrix([[KK((lamda-4)/3), KK(1)]], (1, 2), K)),
+    ]
+    assert Avects == ([], algebraic_eigenvects)
+
+    # Test converting to Expr:
+    sympy_eigenvects = [
+        (S(5)/2 - sqrt(33)/2, 1, [Matrix([[-sqrt(33)/6 - S(1)/2], [1]])]),
+        (S(5)/2 + sqrt(33)/2, 1, [Matrix([[-S(1)/2 + sqrt(33)/6], [1]])]),
+    ]
+    assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects
+
+
+def test_dom_eigenvects_rootof():
+    # Algebraic eigenvalues
+    A = DomainMatrix([
+        [0, 0, 0, 0, -1],
+        [1, 0, 0, 0, 1],
+        [0, 1, 0, 0, 0],
+        [0, 0, 1, 0, 0],
+        [0, 0, 0, 1, 0]], (5, 5), QQ)
+    Avects = dom_eigenvects(A)
+
+    # Extract the dummy to build the expected result:
+    lamda = Avects[1][0][1].gens[0]
+    irreducible = Poly(lamda**5 - lamda + 1, lamda, domain=QQ)
+    K = FiniteExtension(irreducible)
+    KK = K.from_sympy
+    algebraic_eigenvects = [
+        (K, irreducible, 1,
+            DomainMatrix([
+                [KK(lamda**4-1), KK(lamda**3), KK(lamda**2), KK(lamda), KK(1)]
+            ], (1, 5), K)),
+    ]
+    assert Avects == ([], algebraic_eigenvects)
+
+    # Test converting to Expr (slow):
+    l0, l1, l2, l3, l4 = [CRootOf(lamda**5 - lamda + 1, i) for i in range(5)]
+    sympy_eigenvects = [
+        (l0, 1, [Matrix([-1 + l0**4, l0**3, l0**2, l0, 1])]),
+        (l1, 1, [Matrix([-1 + l1**4, l1**3, l1**2, l1, 1])]),
+        (l2, 1, [Matrix([-1 + l2**4, l2**3, l2**2, l2, 1])]),
+        (l3, 1, [Matrix([-1 + l3**4, l3**3, l3**2, l3, 1])]),
+        (l4, 1, [Matrix([-1 + l4**4, l4**3, l4**2, l4, 1])]),
+    ]
+    assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_inverse.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_inverse.py
new file mode 100644
index 0000000000000000000000000000000000000000..47c82799324518bd7d1cc2405ade0aa0a5a4f6e9
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_inverse.py
@@ -0,0 +1,193 @@
+from sympy import ZZ, Matrix
+from sympy.polys.matrices import DM, DomainMatrix
+from sympy.polys.matrices.dense import ddm_iinv
+from sympy.polys.matrices.exceptions import DMNonInvertibleMatrixError
+from sympy.matrices.exceptions import NonInvertibleMatrixError
+
+import pytest
+from sympy.testing.pytest import raises
+from sympy.core.numbers import all_close
+
+from sympy.abc import x
+
+
+# Examples are given as adjugate matrix and determinant adj_det should match
+# these exactly but inv_den only matches after cancel_denom.
+
+
+INVERSE_EXAMPLES = [
+
+    (
+        'zz_1',
+        DomainMatrix([], (0, 0), ZZ),
+        DomainMatrix([], (0, 0), ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_2',
+        DM([[2]], ZZ),
+        DM([[1]], ZZ),
+        ZZ(2),
+    ),
+
+    (
+        'zz_3',
+        DM([[2, 0],
+            [0, 2]], ZZ),
+        DM([[2, 0],
+            [0, 2]], ZZ),
+        ZZ(4),
+    ),
+
+    (
+        'zz_4',
+        DM([[1, 2],
+            [3, 4]], ZZ),
+        DM([[ 4, -2],
+            [-3,  1]], ZZ),
+        ZZ(-2),
+    ),
+
+    (
+        'zz_5',
+        DM([[2, 2, 0],
+            [0, 2, 2],
+            [0, 0, 2]], ZZ),
+        DM([[4, -4, 4],
+            [0, 4, -4],
+            [0, 0,  4]], ZZ),
+        ZZ(8),
+    ),
+
+    (
+        'zz_6',
+        DM([[1, 2, 3],
+            [4, 5, 6],
+            [7, 8, 9]], ZZ),
+        DM([[-3,   6, -3],
+            [ 6, -12,  6],
+            [-3,   6, -3]], ZZ),
+        ZZ(0),
+    ),
+]
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_Matrix_inv(name, A, A_inv, den):
+
+    def _check(**kwargs):
+        if den != 0:
+            assert A.inv(**kwargs) == A_inv
+        else:
+            raises(NonInvertibleMatrixError, lambda: A.inv(**kwargs))
+
+    K = A.domain
+    A = A.to_Matrix()
+    A_inv = A_inv.to_Matrix() / K.to_sympy(den)
+    _check()
+    for method in ['GE', 'LU', 'ADJ', 'CH', 'LDL', 'QR']:
+        _check(method=method)
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_dm_inv_den(name, A, A_inv, den):
+    if den != 0:
+        A_inv_f, den_f = A.inv_den()
+        assert A_inv_f.cancel_denom(den_f) == A_inv.cancel_denom(den)
+    else:
+        raises(DMNonInvertibleMatrixError, lambda: A.inv_den())
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_dm_inv(name, A, A_inv, den):
+    A = A.to_field()
+    if den != 0:
+        A_inv = A_inv.to_field() / den
+        assert A.inv() == A_inv
+    else:
+        raises(DMNonInvertibleMatrixError, lambda: A.inv())
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_ddm_inv(name, A, A_inv, den):
+    A = A.to_field().to_ddm()
+    if den != 0:
+        A_inv = (A_inv.to_field() / den).to_ddm()
+        assert A.inv() == A_inv
+    else:
+        raises(DMNonInvertibleMatrixError, lambda: A.inv())
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_sdm_inv(name, A, A_inv, den):
+    A = A.to_field().to_sdm()
+    if den != 0:
+        A_inv = (A_inv.to_field() / den).to_sdm()
+        assert A.inv() == A_inv
+    else:
+        raises(DMNonInvertibleMatrixError, lambda: A.inv())
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_dense_ddm_iinv(name, A, A_inv, den):
+    A = A.to_field().to_ddm().copy()
+    K = A.domain
+    A_result = A.copy()
+    if den != 0:
+        A_inv = (A_inv.to_field() / den).to_ddm()
+        ddm_iinv(A_result, A, K)
+        assert A_result == A_inv
+    else:
+        raises(DMNonInvertibleMatrixError, lambda: ddm_iinv(A_result, A, K))
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_Matrix_adjugate(name, A, A_inv, den):
+    A = A.to_Matrix()
+    A_inv = A_inv.to_Matrix()
+    assert A.adjugate() == A_inv
+    for method in ["bareiss", "berkowitz", "bird", "laplace", "lu"]:
+        assert A.adjugate(method=method) == A_inv
+
+
+@pytest.mark.parametrize('name, A, A_inv, den', INVERSE_EXAMPLES)
+def test_dm_adj_det(name, A, A_inv, den):
+    assert A.adj_det() == (A_inv, den)
+
+
+def test_inverse_inexact():
+
+    M = Matrix([[x-0.3, -0.06, -0.22],
+                [-0.46, x-0.48, -0.41],
+                [-0.14, -0.39, x-0.64]])
+
+    Mn = Matrix([[1.0*x**2 - 1.12*x + 0.1473, 0.06*x + 0.0474, 0.22*x - 0.081],
+                 [0.46*x - 0.237, 1.0*x**2 - 0.94*x + 0.1612, 0.41*x - 0.0218],
+                 [0.14*x + 0.1122, 0.39*x - 0.1086, 1.0*x**2 - 0.78*x + 0.1164]])
+
+    d = 1.0*x**3 - 1.42*x**2 + 0.4249*x - 0.0546540000000002
+
+    Mi = Mn / d
+
+    M_dm = M.to_DM()
+    M_dmd = M_dm.to_dense()
+    M_dm_num, M_dm_den = M_dm.inv_den()
+    M_dmd_num, M_dmd_den = M_dmd.inv_den()
+
+    # XXX: We don't check M_dm().to_field().inv() which currently uses division
+    # and produces a more complicate result from gcd cancellation failing.
+    # DomainMatrix.inv() over RR(x) should be changed to clear denominators and
+    # use DomainMatrix.inv_den().
+
+    Minvs = [
+        M.inv(),
+        (M_dm_num.to_field() / M_dm_den).to_Matrix(),
+        (M_dmd_num.to_field() / M_dmd_den).to_Matrix(),
+        M_dm_num.to_Matrix() / M_dm_den.as_expr(),
+        M_dmd_num.to_Matrix() / M_dmd_den.as_expr(),
+    ]
+
+    for Minv in Minvs:
+        for Mi1, Mi2 in zip(Minv.flat(), Mi.flat()):
+            assert all_close(Mi2, Mi1)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_linsolve.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_linsolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d8cd7eb9feb27c59d6a32ceb3f04118eae971e2
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_linsolve.py
@@ -0,0 +1,111 @@
+#
+# test_linsolve.py
+#
+#    Test the internal implementation of linsolve.
+#
+
+from sympy.testing.pytest import raises
+
+from sympy.core.numbers import I
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.abc import x, y, z
+
+from sympy.polys.matrices.linsolve import _linsolve
+from sympy.polys.solvers import PolyNonlinearError
+
+
+def test__linsolve():
+    assert _linsolve([], [x]) == {x:x}
+    assert _linsolve([S.Zero], [x]) == {x:x}
+    assert _linsolve([x-1,x-2], [x]) is None
+    assert _linsolve([x-1], [x]) == {x:1}
+    assert _linsolve([x-1, y], [x, y]) == {x:1, y:S.Zero}
+    assert _linsolve([2*I], [x]) is None
+    raises(PolyNonlinearError, lambda: _linsolve([x*(1 + x)], [x]))
+
+
+def test__linsolve_float():
+
+    # This should give the exact answer:
+    eqs = [
+        y - x,
+        y - 0.0216 * x
+    ]
+    sol = {x:0.0, y:0.0}
+    assert _linsolve(eqs, (x, y)) == sol
+
+    # Other cases should be close to eps
+
+    def all_close(sol1, sol2, eps=1e-15):
+        close = lambda a, b: abs(a - b) < eps
+        assert sol1.keys() == sol2.keys()
+        return all(close(sol1[s], sol2[s]) for s in sol1)
+
+    eqs = [
+        0.8*x +         0.8*z + 0.2,
+        0.9*x + 0.7*y + 0.2*z + 0.9,
+        0.7*x + 0.2*y + 0.2*z + 0.5
+    ]
+    sol_exact = {x:-29/42, y:-11/21, z:37/84}
+    sol_linsolve = _linsolve(eqs, [x,y,z])
+    assert all_close(sol_exact, sol_linsolve)
+
+    eqs = [
+        0.9*x + 0.3*y + 0.4*z + 0.6,
+        0.6*x + 0.9*y + 0.1*z + 0.7,
+        0.4*x + 0.6*y + 0.9*z + 0.5
+    ]
+    sol_exact = {x:-88/175, y:-46/105, z:-1/25}
+    sol_linsolve = _linsolve(eqs, [x,y,z])
+    assert all_close(sol_exact, sol_linsolve)
+
+    eqs = [
+        0.4*x + 0.3*y + 0.6*z + 0.7,
+        0.4*x + 0.3*y + 0.9*z + 0.9,
+        0.7*x + 0.9*y,
+    ]
+    sol_exact = {x:-9/5, y:7/5, z:-2/3}
+    sol_linsolve = _linsolve(eqs, [x,y,z])
+    assert all_close(sol_exact, sol_linsolve)
+
+    eqs = [
+        x*(0.7 + 0.6*I) + y*(0.4 + 0.7*I) + z*(0.9 + 0.1*I) + 0.5,
+        0.2*I*x + 0.2*I*y + z*(0.9 + 0.2*I) + 0.1,
+        x*(0.9 + 0.7*I) + y*(0.9 + 0.7*I) + z*(0.9 + 0.4*I) + 0.4,
+    ]
+    sol_exact = {
+        x:-6157/7995 - 411/5330*I,
+        y:8519/15990 + 1784/7995*I,
+        z:-34/533 + 107/1599*I,
+    }
+    sol_linsolve = _linsolve(eqs, [x,y,z])
+    assert all_close(sol_exact, sol_linsolve)
+
+    # XXX: This system for x and y over RR(z) is problematic.
+    #
+    # eqs = [
+    #     x*(0.2*z + 0.9) + y*(0.5*z + 0.8) + 0.6,
+    #     0.1*x*z + y*(0.1*z + 0.6) + 0.9,
+    # ]
+    #
+    # linsolve(eqs, [x, y])
+    # The solution for x comes out as
+    #
+    #       -3.9e-5*z**2 - 3.6e-5*z - 8.67361737988404e-20
+    #  x =  ----------------------------------------------
+    #           3.0e-6*z**3 - 1.3e-5*z**2 - 5.4e-5*z
+    #
+    # The 8e-20 in the numerator should be zero which would allow z to cancel
+    # from top and bottom. It should be possible to avoid this somehow because
+    # the inverse of the matrix only has a quadratic factor (the determinant)
+    # in the denominator.
+
+
+def test__linsolve_deprecated():
+    raises(PolyNonlinearError, lambda:
+        _linsolve([Eq(x**2, x**2 + y)], [x, y]))
+    raises(PolyNonlinearError, lambda:
+        _linsolve([(x + y)**2 - x**2], [x]))
+    raises(PolyNonlinearError, lambda:
+        _linsolve([Eq((x + y)**2, x**2)], [x]))
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_lll.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_lll.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cf91a00703532f02d763656d6117018fbc496cf
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_lll.py
@@ -0,0 +1,145 @@
+from sympy.polys.domains import ZZ, QQ
+from sympy.polys.matrices import DM
+from sympy.polys.matrices.domainmatrix import DomainMatrix
+from sympy.polys.matrices.exceptions import DMRankError, DMValueError, DMShapeError, DMDomainError
+from sympy.polys.matrices.lll import _ddm_lll, ddm_lll, ddm_lll_transform
+from sympy.testing.pytest import raises
+
+
+def test_lll():
+    normal_test_data = [
+        (
+            DM([[1, 0, 0, 0, -20160],
+                [0, 1, 0, 0, 33768],
+                [0, 0, 1, 0, 39578],
+                [0, 0, 0, 1, 47757]], ZZ),
+            DM([[10, -3, -2, 8, -4],
+                [3, -9, 8, 1, -11],
+                [-3, 13, -9, -3, -9],
+                [-12, -7, -11, 9, -1]], ZZ)
+        ),
+        (
+            DM([[20, 52, 3456],
+                [14, 31, -1],
+                [34, -442, 0]], ZZ),
+            DM([[14, 31, -1],
+                [188, -101, -11],
+                [236, 13, 3443]], ZZ)
+        ),
+        (
+            DM([[34, -1, -86, 12],
+                [-54, 34, 55, 678],
+                [23, 3498, 234, 6783],
+                [87, 49, 665, 11]], ZZ),
+            DM([[34, -1, -86, 12],
+                [291, 43, 149, 83],
+                [-54, 34, 55, 678],
+                [-189, 3077, -184, -223]], ZZ)
+        )
+    ]
+    delta = QQ(5, 6)
+    for basis_dm, reduced_dm in normal_test_data:
+        reduced = _ddm_lll(basis_dm.rep.to_ddm(), delta=delta)[0]
+        assert reduced == reduced_dm.rep.to_ddm()
+
+        reduced = ddm_lll(basis_dm.rep.to_ddm(), delta=delta)
+        assert reduced == reduced_dm.rep.to_ddm()
+
+        reduced, transform = _ddm_lll(basis_dm.rep.to_ddm(), delta=delta, return_transform=True)
+        assert reduced == reduced_dm.rep.to_ddm()
+        assert transform.matmul(basis_dm.rep.to_ddm()) == reduced_dm.rep.to_ddm()
+
+        reduced, transform = ddm_lll_transform(basis_dm.rep.to_ddm(), delta=delta)
+        assert reduced == reduced_dm.rep.to_ddm()
+        assert transform.matmul(basis_dm.rep.to_ddm()) == reduced_dm.rep.to_ddm()
+
+        reduced = basis_dm.rep.lll(delta=delta)
+        assert reduced == reduced_dm.rep
+
+        reduced, transform = basis_dm.rep.lll_transform(delta=delta)
+        assert reduced == reduced_dm.rep
+        assert transform.matmul(basis_dm.rep) == reduced_dm.rep
+
+        reduced = basis_dm.rep.to_sdm().lll(delta=delta)
+        assert reduced == reduced_dm.rep.to_sdm()
+
+        reduced, transform = basis_dm.rep.to_sdm().lll_transform(delta=delta)
+        assert reduced == reduced_dm.rep.to_sdm()
+        assert transform.matmul(basis_dm.rep.to_sdm()) == reduced_dm.rep.to_sdm()
+
+        reduced = basis_dm.lll(delta=delta)
+        assert reduced == reduced_dm
+
+        reduced, transform = basis_dm.lll_transform(delta=delta)
+        assert reduced == reduced_dm
+        assert transform.matmul(basis_dm) == reduced_dm
+
+
+def test_lll_linear_dependent():
+    linear_dependent_test_data = [
+        DM([[0, -1, -2, -3],
+            [1, 0, -1, -2],
+            [2, 1, 0, -1],
+            [3, 2, 1, 0]], ZZ),
+        DM([[1, 0, 0, 1],
+            [0, 1, 0, 1],
+            [0, 0, 1, 1],
+            [1, 2, 3, 6]], ZZ),
+        DM([[3, -5, 1],
+            [4, 6, 0],
+            [10, -4, 2]], ZZ)
+    ]
+    for not_basis in linear_dependent_test_data:
+        raises(DMRankError, lambda: _ddm_lll(not_basis.rep.to_ddm()))
+        raises(DMRankError, lambda: ddm_lll(not_basis.rep.to_ddm()))
+        raises(DMRankError, lambda: not_basis.rep.lll())
+        raises(DMRankError, lambda: not_basis.rep.to_sdm().lll())
+        raises(DMRankError, lambda: not_basis.lll())
+        raises(DMRankError, lambda: _ddm_lll(not_basis.rep.to_ddm(), return_transform=True))
+        raises(DMRankError, lambda: ddm_lll_transform(not_basis.rep.to_ddm()))
+        raises(DMRankError, lambda: not_basis.rep.lll_transform())
+        raises(DMRankError, lambda: not_basis.rep.to_sdm().lll_transform())
+        raises(DMRankError, lambda: not_basis.lll_transform())
+
+
+def test_lll_wrong_delta():
+    dummy_matrix = DomainMatrix.ones((3, 3), ZZ)
+    for wrong_delta in [QQ(-1, 4), QQ(0, 1), QQ(1, 4), QQ(1, 1), QQ(100, 1)]:
+        raises(DMValueError, lambda: _ddm_lll(dummy_matrix.rep, delta=wrong_delta))
+        raises(DMValueError, lambda: ddm_lll(dummy_matrix.rep, delta=wrong_delta))
+        raises(DMValueError, lambda: dummy_matrix.rep.lll(delta=wrong_delta))
+        raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll(delta=wrong_delta))
+        raises(DMValueError, lambda: dummy_matrix.lll(delta=wrong_delta))
+        raises(DMValueError, lambda: _ddm_lll(dummy_matrix.rep, delta=wrong_delta, return_transform=True))
+        raises(DMValueError, lambda: ddm_lll_transform(dummy_matrix.rep, delta=wrong_delta))
+        raises(DMValueError, lambda: dummy_matrix.rep.lll_transform(delta=wrong_delta))
+        raises(DMValueError, lambda: dummy_matrix.rep.to_sdm().lll_transform(delta=wrong_delta))
+        raises(DMValueError, lambda: dummy_matrix.lll_transform(delta=wrong_delta))
+
+
+def test_lll_wrong_shape():
+    wrong_shape_matrix = DomainMatrix.ones((4, 3), ZZ)
+    raises(DMShapeError, lambda: _ddm_lll(wrong_shape_matrix.rep))
+    raises(DMShapeError, lambda: ddm_lll(wrong_shape_matrix.rep))
+    raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll())
+    raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll())
+    raises(DMShapeError, lambda: wrong_shape_matrix.lll())
+    raises(DMShapeError, lambda: _ddm_lll(wrong_shape_matrix.rep, return_transform=True))
+    raises(DMShapeError, lambda: ddm_lll_transform(wrong_shape_matrix.rep))
+    raises(DMShapeError, lambda: wrong_shape_matrix.rep.lll_transform())
+    raises(DMShapeError, lambda: wrong_shape_matrix.rep.to_sdm().lll_transform())
+    raises(DMShapeError, lambda: wrong_shape_matrix.lll_transform())
+
+
+def test_lll_wrong_domain():
+    wrong_domain_matrix = DomainMatrix.ones((3, 3), QQ)
+    raises(DMDomainError, lambda: _ddm_lll(wrong_domain_matrix.rep))
+    raises(DMDomainError, lambda: ddm_lll(wrong_domain_matrix.rep))
+    raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll())
+    raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll())
+    raises(DMDomainError, lambda: wrong_domain_matrix.lll())
+    raises(DMDomainError, lambda: _ddm_lll(wrong_domain_matrix.rep, return_transform=True))
+    raises(DMDomainError, lambda: ddm_lll_transform(wrong_domain_matrix.rep))
+    raises(DMDomainError, lambda: wrong_domain_matrix.rep.lll_transform())
+    raises(DMDomainError, lambda: wrong_domain_matrix.rep.to_sdm().lll_transform())
+    raises(DMDomainError, lambda: wrong_domain_matrix.lll_transform())
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_normalforms.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_normalforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3471400c877608003a14e55b4ffe49df6f6bd09
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_normalforms.py
@@ -0,0 +1,75 @@
+from sympy.testing.pytest import raises
+
+from sympy.core.symbol import Symbol
+from sympy.polys.matrices.normalforms import (
+    invariant_factors, smith_normal_form,
+    hermite_normal_form, _hermite_normal_form, _hermite_normal_form_modulo_D)
+from sympy.polys.domains import ZZ, QQ
+from sympy.polys.matrices import DomainMatrix, DM
+from sympy.polys.matrices.exceptions import DMDomainError, DMShapeError
+
+
+def test_smith_normal():
+
+    m = DM([[12, 6, 4, 8], [3, 9, 6, 12], [2, 16, 14, 28], [20, 10, 10, 20]], ZZ)
+    smf = DM([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]], ZZ)
+    assert smith_normal_form(m).to_dense() == smf
+
+    x = Symbol('x')
+    m = DM([[x-1,  1, -1],
+            [  0,  x, -1],
+            [  0, -1,  x]], QQ[x])
+    dx = m.domain.gens[0]
+    assert invariant_factors(m) == (1, dx-1, dx**2-1)
+
+    zr = DomainMatrix([], (0, 2), ZZ)
+    zc = DomainMatrix([[], []], (2, 0), ZZ)
+    assert smith_normal_form(zr).to_dense() == zr
+    assert smith_normal_form(zc).to_dense() == zc
+
+    assert smith_normal_form(DM([[2, 4]], ZZ)).to_dense() == DM([[2, 0]], ZZ)
+    assert smith_normal_form(DM([[0, -2]], ZZ)).to_dense() == DM([[-2, 0]], ZZ)
+    assert smith_normal_form(DM([[0], [-2]], ZZ)).to_dense() == DM([[-2], [0]], ZZ)
+
+    m =   DM([[3, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0]], ZZ)
+    snf = DM([[1, 0, 0, 0], [0, 6, 0, 0], [0, 0, 0, 0]], ZZ)
+    assert smith_normal_form(m).to_dense() == snf
+
+    raises(ValueError, lambda: smith_normal_form(DM([[1]], ZZ[x])))
+
+
+def test_hermite_normal():
+    m = DM([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ)
+    hnf = DM([[1, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ)
+    assert hermite_normal_form(m) == hnf
+    assert hermite_normal_form(m, D=ZZ(2)) == hnf
+    assert hermite_normal_form(m, D=ZZ(2), check_rank=True) == hnf
+
+    m = m.transpose()
+    hnf = DM([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]], ZZ)
+    assert hermite_normal_form(m) == hnf
+    raises(DMShapeError, lambda: _hermite_normal_form_modulo_D(m, ZZ(96)))
+    raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, QQ(96)))
+
+    m = DM([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ)
+    hnf = DM([[4, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ)
+    assert hermite_normal_form(m) == hnf
+    assert hermite_normal_form(m, D=ZZ(8)) == hnf
+    assert hermite_normal_form(m, D=ZZ(8), check_rank=True) == hnf
+
+    m = DM([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]], ZZ)
+    hnf = DM([[26, 2], [0, 9], [0, 1]], ZZ)
+    assert hermite_normal_form(m) == hnf
+
+    m = DM([[2, 7], [0, 0], [0, 0]], ZZ)
+    hnf = DM([[1], [0], [0]], ZZ)
+    assert hermite_normal_form(m) == hnf
+
+    m = DM([[-2, 1], [0, 1]], ZZ)
+    hnf = DM([[2, 1], [0, 1]], ZZ)
+    assert hermite_normal_form(m) == hnf
+
+    m = DomainMatrix([[QQ(1)]], (1, 1), QQ)
+    raises(DMDomainError, lambda: hermite_normal_form(m))
+    raises(DMDomainError, lambda: _hermite_normal_form(m))
+    raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, ZZ(1)))
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_nullspace.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_nullspace.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbb025b7dc9dff31bc97d86e175147ffede5a7e3
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_nullspace.py
@@ -0,0 +1,209 @@
+from sympy import ZZ, Matrix
+from sympy.polys.matrices import DM, DomainMatrix
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.sdm import SDM
+
+import pytest
+
+zeros = lambda shape, K: DomainMatrix.zeros(shape, K).to_dense()
+eye = lambda n, K: DomainMatrix.eye(n, K).to_dense()
+
+
+#
+# DomainMatrix.nullspace can have a divided answer or can return an undivided
+# uncanonical answer. The uncanonical answer is not unique but we can make it
+# unique by making it primitive (remove gcd). The tests here all show the
+# primitive form. We test two things:
+#
+#   A.nullspace().primitive()[1] == answer.
+#   A.nullspace(divide_last=True) == _divide_last(answer).
+#
+# The nullspace as returned by DomainMatrix and related classes is the
+# transpose of the nullspace as returned by Matrix. Matrix returns a list of
+# of column vectors whereas DomainMatrix returns a matrix whose rows are the
+# nullspace vectors.
+#
+
+
+NULLSPACE_EXAMPLES = [
+
+    (
+        'zz_1',
+         DM([[ 1, 2, 3]], ZZ),
+         DM([[-2, 1, 0],
+             [-3, 0, 1]], ZZ),
+    ),
+
+    (
+        'zz_2',
+         zeros((0, 0), ZZ),
+         zeros((0, 0), ZZ),
+    ),
+
+    (
+        'zz_3',
+        zeros((2, 0), ZZ),
+        zeros((0, 0), ZZ),
+    ),
+
+    (
+        'zz_4',
+        zeros((0, 2), ZZ),
+        eye(2, ZZ),
+    ),
+
+    (
+        'zz_5',
+        zeros((2, 2), ZZ),
+        eye(2, ZZ),
+    ),
+
+    (
+        'zz_6',
+        DM([[1, 2],
+            [3, 4]], ZZ),
+        zeros((0, 2), ZZ),
+    ),
+
+    (
+        'zz_7',
+        DM([[1, 1],
+            [1, 1]], ZZ),
+        DM([[-1, 1]], ZZ),
+    ),
+
+    (
+        'zz_8',
+        DM([[1],
+            [1]], ZZ),
+        zeros((0, 1), ZZ),
+    ),
+
+    (
+        'zz_9',
+        DM([[1, 1]], ZZ),
+        DM([[-1, 1]], ZZ),
+    ),
+
+    (
+        'zz_10',
+        DM([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+            [1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
+            [0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
+            [0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
+            [0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], ZZ),
+        DM([[ 0,  0, 1,  0,  0, 0, 0, 0, 0, 0],
+            [-1,  0, 0,  0,  0, 0, 1, 0, 0, 0],
+            [ 0, -1, 0,  0,  0, 0, 0, 1, 0, 0],
+            [ 0,  0, 0, -1,  0, 0, 0, 0, 1, 0],
+            [ 0,  0, 0,  0, -1, 0, 0, 0, 0, 1]], ZZ),
+    ),
+
+]
+
+
+def _to_DM(A, ans):
+    """Convert the answer to DomainMatrix."""
+    if isinstance(A, DomainMatrix):
+        return A.to_dense()
+    elif isinstance(A, DDM):
+        return DomainMatrix(list(A), A.shape, A.domain).to_dense()
+    elif isinstance(A, SDM):
+        return DomainMatrix(dict(A), A.shape, A.domain).to_dense()
+    else:
+        assert False # pragma: no cover
+
+
+def _divide_last(null):
+    """Normalize the nullspace by the rightmost non-zero entry."""
+    null = null.to_field()
+
+    if null.is_zero_matrix:
+        return null
+
+    rows = []
+    for i in range(null.shape[0]):
+        for j in reversed(range(null.shape[1])):
+            if null[i, j]:
+                rows.append(null[i, :] / null[i, j])
+                break
+        else:
+            assert False # pragma: no cover
+
+    return DomainMatrix.vstack(*rows)
+
+
+def _check_primitive(null, null_ans):
+    """Check that the primitive of the answer matches."""
+    null = _to_DM(null, null_ans)
+    cont, null_prim = null.primitive()
+    assert null_prim == null_ans
+
+
+def _check_divided(null, null_ans):
+    """Check the divided answer."""
+    null = _to_DM(null, null_ans)
+    null_ans_norm = _divide_last(null_ans)
+    assert null == null_ans_norm
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_Matrix_nullspace(name, A, A_null):
+    A = A.to_Matrix()
+
+    A_null_cols = A.nullspace()
+
+    # We have to patch up the case where the nullspace is empty
+    if A_null_cols:
+        A_null_found = Matrix.hstack(*A_null_cols)
+    else:
+        A_null_found = Matrix.zeros(A.cols, 0)
+
+    A_null_found = A_null_found.to_DM().to_field().to_dense()
+
+    # The Matrix result is the transpose of DomainMatrix result.
+    A_null_found = A_null_found.transpose()
+
+    _check_divided(A_null_found, A_null)
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_dm_dense_nullspace(name, A, A_null):
+    A = A.to_field().to_dense()
+    A_null_found = A.nullspace(divide_last=True)
+    _check_divided(A_null_found, A_null)
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_dm_sparse_nullspace(name, A, A_null):
+    A = A.to_field().to_sparse()
+    A_null_found = A.nullspace(divide_last=True)
+    _check_divided(A_null_found, A_null)
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_ddm_nullspace(name, A, A_null):
+    A = A.to_field().to_ddm()
+    A_null_found, _ = A.nullspace()
+    _check_divided(A_null_found, A_null)
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_sdm_nullspace(name, A, A_null):
+    A = A.to_field().to_sdm()
+    A_null_found, _ = A.nullspace()
+    _check_divided(A_null_found, A_null)
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_dm_dense_nullspace_fracfree(name, A, A_null):
+    A = A.to_dense()
+    A_null_found = A.nullspace()
+    _check_primitive(A_null_found, A_null)
+
+
+@pytest.mark.parametrize('name, A, A_null', NULLSPACE_EXAMPLES)
+def test_dm_sparse_nullspace_fracfree(name, A, A_null):
+    A = A.to_sparse()
+    A_null_found = A.nullspace()
+    _check_primitive(A_null_found, A_null)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_rref.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_rref.py
new file mode 100644
index 0000000000000000000000000000000000000000..49def18c8132c0537540163a96bf6cf323c5a85c
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_rref.py
@@ -0,0 +1,737 @@
+from sympy import ZZ, QQ, ZZ_I, EX, Matrix, eye, zeros, symbols
+from sympy.polys.matrices import DM, DomainMatrix
+from sympy.polys.matrices.dense import ddm_irref_den, ddm_irref
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.sdm import SDM, sdm_irref, sdm_rref_den
+
+import pytest
+
+
+#
+# The dense and sparse implementations of rref_den are ddm_irref_den and
+# sdm_irref_den. These can give results that differ by some factor and also
+# give different results if the order of the rows is changed. The tests below
+# show all results on lowest terms as should be returned by cancel_denom.
+#
+# The EX domain is also a case where the dense and sparse implementations
+# can give results in different forms: the results should be equivalent but
+# are not canonical because EX does not have a canonical form.
+#
+
+
+a, b, c, d = symbols('a, b, c, d')
+
+
+qq_large_1 = DM([
+[  (1,2),  (1,3),  (1,5),  (1,7), (1,11), (1,13), (1,17), (1,19), (1,23), (1,29), (1,31)],
+[ (1,37), (1,41), (1,43), (1,47), (1,53), (1,59), (1,61), (1,67), (1,71), (1,73), (1,79)],
+[ (1,83), (1,89), (1,97),(1,101),(1,103),(1,107),(1,109),(1,113),(1,127),(1,131),(1,137)],
+[(1,139),(1,149),(1,151),(1,157),(1,163),(1,167),(1,173),(1,179),(1,181),(1,191),(1,193)],
+[(1,197),(1,199),(1,211),(1,223),(1,227),(1,229),(1,233),(1,239),(1,241),(1,251),(1,257)],
+[(1,263),(1,269),(1,271),(1,277),(1,281),(1,283),(1,293),(1,307),(1,311),(1,313),(1,317)],
+[(1,331),(1,337),(1,347),(1,349),(1,353),(1,359),(1,367),(1,373),(1,379),(1,383),(1,389)],
+[(1,397),(1,401),(1,409),(1,419),(1,421),(1,431),(1,433),(1,439),(1,443),(1,449),(1,457)],
+[(1,461),(1,463),(1,467),(1,479),(1,487),(1,491),(1,499),(1,503),(1,509),(1,521),(1,523)],
+[(1,541),(1,547),(1,557),(1,563),(1,569),(1,571),(1,577),(1,587),(1,593),(1,599),(1,601)],
+[(1,607),(1,613),(1,617),(1,619),(1,631),(1,641),(1,643),(1,647),(1,653),(1,659),(1,661)]],
+        QQ)
+
+qq_large_2 = qq_large_1 + 10**100 * DomainMatrix.eye(11, QQ)
+
+
+RREF_EXAMPLES = [
+    (
+        'zz_1',
+         DM([[1, 2, 3]], ZZ),
+         DM([[1, 2, 3]], ZZ),
+         ZZ(1),
+    ),
+
+    (
+        'zz_2',
+         DomainMatrix([], (0, 0), ZZ),
+         DomainMatrix([], (0, 0), ZZ),
+         ZZ(1),
+    ),
+
+    (
+        'zz_3',
+        DM([[1, 2],
+            [3, 4]], ZZ),
+        DM([[1, 0],
+            [0, 1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_4',
+        DM([[1, 0],
+            [3, 4]], ZZ),
+        DM([[1, 0],
+            [0, 1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_5',
+        DM([[0, 2],
+            [3, 4]], ZZ),
+        DM([[1, 0],
+            [0, 1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_6',
+        DM([[1, 2, 3],
+            [4, 5, 6],
+            [7, 8, 9]], ZZ),
+        DM([[1, 0, -1],
+            [0, 1,  2],
+            [0, 0,  0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_7',
+        DM([[0, 0, 0],
+            [0, 0, 0],
+            [1, 0, 0]], ZZ),
+        DM([[1, 0, 0],
+            [0, 0, 0],
+            [0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_8',
+        DM([[0, 0, 0],
+            [0, 0, 0],
+            [0, 0, 0]], ZZ),
+        DM([[0, 0, 0],
+            [0, 0, 0],
+            [0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_9',
+        DM([[1, 1, 0],
+            [0, 0, 2],
+            [0, 0, 0]], ZZ),
+        DM([[1, 1, 0],
+            [0, 0, 1],
+            [0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_10',
+        DM([[2, 2, 0],
+            [0, 0, 2],
+            [0, 0, 0]], ZZ),
+        DM([[1, 1, 0],
+            [0, 0, 1],
+            [0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_11',
+        DM([[2, 2, 0],
+            [0, 2, 2],
+            [0, 0, 2]], ZZ),
+        DM([[1, 0, 0],
+            [0, 1, 0],
+            [0, 0, 1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_12',
+        DM([[ 1,  2,  3],
+            [ 4,  5,  6],
+            [ 7,  8,  9],
+            [10, 11, 12]], ZZ),
+        DM([[1,  0, -1],
+            [0,  1,  2],
+            [0,  0,  0],
+            [0,  0,  0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_13',
+        DM([[ 1,  2,  3],
+            [ 4,  5,  6],
+            [ 7,  8,  9],
+            [10, 11, 13]], ZZ),
+        DM([[ 1,  0,  0],
+            [ 0,  1,  0],
+            [ 0,  0,  1],
+            [ 0,  0,  0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_14',
+        DM([[1, 2,  4, 3],
+            [4, 5, 10, 6],
+            [7, 8, 16, 9]], ZZ),
+        DM([[1, 0, 0, -1],
+            [0, 1, 2,  2],
+            [0, 0, 0,  0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_15',
+        DM([[1, 2,  4, 3],
+            [4, 5, 10, 6],
+            [7, 8, 17, 9]], ZZ),
+        DM([[1, 0, 0, -1],
+            [0, 1, 0,  2],
+            [0, 0, 1,  0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_16',
+        DM([[1, 2, 0, 1],
+            [1, 1, 9, 0]], ZZ),
+        DM([[1, 0, 18, -1],
+            [0, 1, -9,  1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_17',
+        DM([[1, 1, 1],
+            [1, 2, 2]], ZZ),
+        DM([[1, 0, 0],
+            [0, 1, 1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        # Here the sparse implementation and dense implementation give very
+        # different denominators: 4061232 and -1765176.
+        'zz_18',
+        DM([[94, 24,  0, 27, 0],
+            [79,  0,  0,  0, 0],
+            [85, 16, 71, 81, 0],
+            [ 0,  0, 72, 77, 0],
+            [21,  0, 34,  0, 0]], ZZ),
+        DM([[ 1,  0,  0,  0, 0],
+            [ 0,  1,  0,  0, 0],
+            [ 0,  0,  1,  0, 0],
+            [ 0,  0,  0,  1, 0],
+            [ 0,  0,  0,  0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        # Let's have a denominator that cannot be cancelled.
+        'zz_19',
+        DM([[1, 2, 4],
+            [4, 5, 6]], ZZ),
+        DM([[3, 0, -8],
+            [0, 3, 10]], ZZ),
+        ZZ(3),
+    ),
+
+    (
+        'zz_20',
+        DM([[0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 4]], ZZ),
+        DM([[0, 0, 0, 0, 1],
+            [0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_21',
+        DM([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+            [1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
+            [0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
+            [0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
+            [0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], ZZ),
+        DM([[1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
+            [0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
+            [0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
+            [0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
+            [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_22',
+        DM([[1, 1, 1, 0, 1],
+            [1, 1, 0, 1, 0],
+            [1, 0, 1, 0, 1],
+            [1, 1, 0, 1, 0],
+            [1, 0, 0, 0, 0]], ZZ),
+        DM([[1, 0, 0, 0, 0],
+            [0, 1, 0, 0, 0],
+            [0, 0, 1, 0, 1],
+            [0, 0, 0, 1, 0],
+            [0, 0, 0, 0, 0]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_large_1',
+        DM([
+[ 0,  0,  0, 81,  0,  0, 75,  0,  0,  0,  0,  0,  0, 27,  0,  0,  0,  0,  0,  0],
+[ 0,  0,  0,  0,  0, 86,  0, 92, 79, 54,  0,  7,  0,  0,  0,  0, 79,  0,  0,  0],
+[89, 54, 81,  0,  0, 20,  0,  0,  0,  0,  0,  0, 51,  0, 94,  0,  0, 77,  0,  0],
+[ 0,  0,  0, 96,  0,  0,  0,  0,  0,  0,  0,  0, 48, 29,  0,  0,  5,  0, 32,  0],
+[ 0, 70,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 60,  0,  0,  0, 11],
+[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 37,  0, 43,  0,  0],
+[ 0,  0,  0,  0,  0, 38, 91,  0,  0,  0,  0, 38,  0,  0,  0,  0,  0, 26,  0,  0],
+[69,  0,  0,  0,  0,  0, 94,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 55],
+[ 0, 13, 18, 49, 49, 88,  0,  0, 35, 54,  0,  0, 51,  0,  0,  0,  0,  0,  0, 87],
+[ 0,  0,  0,  0, 31,  0, 40,  0,  0,  0,  0,  0,  0, 50,  0,  0,  0,  0, 88,  0],
+[ 0,  0,  0,  0,  0,  0,  0,  0, 98,  0,  0,  0, 15, 53,  0, 92,  0,  0,  0,  0],
+[ 0,  0,  0, 95,  0,  0,  0, 36,  0,  0,  0,  0,  0, 72,  0,  0,  0,  0, 73, 19],
+[ 0, 65, 14, 96,  0,  0,  0,  0,  0,  0,  0,  0,  0, 90,  0,  0,  0, 34,  0,  0],
+[ 0,  0,  0, 16, 39, 44,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 51,  0,  0],
+[ 0, 17,  0,  0,  0, 99, 84, 13, 50, 84,  0,  0,  0,  0, 95,  0, 43, 33, 20,  0],
+[79,  0, 17, 52, 99, 12, 69,  0, 98,  0, 68,  0,  0,  0,  0,  0,  0,  0,  0,  0],
+[ 0,  0,  0, 82,  0, 44,  0,  0,  0, 97,  0,  0,  0,  0,  0, 10,  0,  0, 31,  0],
+[ 0,  0, 21,  0, 67,  0,  0,  0,  0,  0,  4,  0, 50,  0,  0,  0, 33,  0,  0,  0],
+[ 0,  0,  0,  0,  9, 42,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8],
+[ 0, 77,  0,  0,  0,  0,  0,  0,  0,  0, 34, 93,  0,  0,  0,  0, 47,  0,  0,  0]],
+           ZZ),
+        DM([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
+            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_large_2',
+        DM([
+[ 0,  0,  0,  0, 50,  0,  6, 81,  0,  1, 86,  0,  0, 98, 82, 94,  4,  0,  0, 29],
+[ 0, 44, 43,  0, 62,  0,  0,  0, 60,  0,  0,  0,  0, 71,  9,  0, 57, 41,  0, 93],
+[ 0,  0, 28,  0, 74, 89, 42,  0, 28,  0,  6,  0,  0,  0, 44,  0,  0,  0, 77, 19],
+[ 0, 21, 82,  0, 30, 88,  0, 89, 68,  0,  0,  0, 79, 41,  0,  0, 99,  0,  0,  0],
+[31,  0,  0,  0, 19, 64,  0,  0, 79,  0,  5,  0, 72, 10, 60, 32, 64, 59,  0, 24],
+[ 0,  0,  0,  0,  0, 57,  0, 94,  0, 83, 20,  0,  0,  9, 31,  0, 49, 26, 58,  0],
+[ 0, 65, 56, 31, 64,  0,  0,  0,  0,  0,  0, 52, 85,  0,  0,  0,  0, 51,  0,  0],
+[ 0, 35,  0,  0,  0, 69,  0,  0, 64,  0,  0,  0,  0, 70,  0,  0, 90,  0, 75, 76],
+[69,  7,  0, 90,  0,  0, 84,  0, 47, 69, 19, 20, 42,  0,  0, 32, 71, 35,  0,  0],
+[39,  0, 90,  0,  0,  4, 85,  0,  0, 55,  0,  0,  0, 35, 67, 40,  0, 40,  0, 77],
+[98, 63,  0, 71,  0, 50,  0,  2, 61,  0, 38,  0,  0,  0,  0, 75,  0, 40, 33, 56],
+[ 0, 73,  0, 64,  0, 38,  0, 35, 61,  0,  0, 52,  0,  7,  0, 51,  0,  0,  0, 34],
+[ 0,  0, 28,  0, 34,  5, 63, 45, 14, 42, 60, 16, 76, 54, 99,  0, 28, 30,  0,  0],
+[58, 37, 14,  0,  0,  0, 94,  0,  0, 90,  0,  0,  0,  0,  0,  0,  0,  8, 90, 53],
+[86, 74, 94,  0, 49, 10, 60,  0, 40, 18,  0,  0,  0, 31, 60, 24,  0,  1,  0, 29],
+[53,  0,  0, 97,  0,  0, 58,  0,  0, 39, 44, 47,  0,  0,  0, 12, 50,  0,  0, 11],
+[ 4,  0, 92, 10, 28,  0,  0, 89,  0,  0, 18, 54, 23, 39,  0,  2,  0, 48,  0, 92],
+[ 0,  0, 90, 77, 95, 33,  0,  0, 49, 22, 39,  0,  0,  0,  0,  0,  0, 40,  0,  0],
+[96,  0,  0,  0,  0, 38, 86,  0, 22, 76,  0,  0,  0,  0, 83, 88, 95, 65, 72,  0],
+[81, 65,  0,  4, 60,  0, 19,  0,  0, 68,  0,  0, 89,  0, 67, 22,  0,  0, 55, 33]],
+           ZZ),
+        DM([
+[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
+[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]],
+           ZZ),
+        ZZ(1),
+    ),
+
+    (
+        'zz_large_3',
+        DM([
+[62,35,89,58,22,47,30,28,52,72,17,56,80,26,64,21,10,35,24,42,96,32,23,50,92,37,76,94,63,66],
+[20,47,96,34,10,98,19,6,29,2,19,92,61,94,38,41,32,9,5,94,31,58,27,41,72,85,61,62,40,46],
+[69,26,35,68,25,52,94,13,38,65,81,10,29,15,5,4,13,99,85,0,80,51,60,60,26,77,85,2,87,25],
+[99,58,69,15,52,12,18,7,27,56,12,54,21,92,38,95,33,83,28,1,44,8,29,84,92,12,2,25,46,46],
+[93,13,55,48,35,87,24,40,23,35,25,32,0,19,0,85,4,79,26,11,46,75,7,96,76,11,7,57,99,75],
+[128,85,26,51,161,173,77,78,85,103,123,58,91,147,38,91,161,36,123,81,102,25,75,59,17,150,112,65,77,143],
+[15,59,61,82,12,83,34,8,94,71,66,7,91,21,48,69,26,12,64,38,97,87,38,15,51,33,93,43,66,89],
+[74,74,53,39,69,90,41,80,32,66,40,83,87,87,61,38,12,80,24,49,37,90,19,33,56,0,46,57,56,60],
+[82,11,0,25,56,58,39,49,92,93,80,38,19,62,33,85,19,61,14,30,45,91,97,34,97,53,92,28,33,43],
+[83,79,41,16,95,35,53,45,26,4,71,76,61,69,69,72,87,92,59,72,54,11,22,83,8,57,77,55,19,22],
+[49,34,13,31,72,77,52,70,46,41,37,6,42,66,35,6,75,33,62,57,30,14,26,31,9,95,89,13,12,90],
+[29,3,49,30,51,32,77,41,38,50,16,1,87,81,93,88,58,91,83,0,38,67,29,64,60,84,5,60,23,28],
+[79,51,13,20,89,96,25,8,39,62,86,52,49,81,3,85,86,3,61,24,72,11,49,28,8,55,23,52,65,53],
+[96,86,73,20,41,20,37,18,10,61,85,24,40,83,69,41,4,92,23,99,64,33,18,36,32,56,60,98,39,24],
+[32,62,47,80,51,66,17,1,9,30,65,75,75,88,99,92,64,53,53,86,38,51,41,14,35,18,39,25,26,32],
+[39,21,8,16,33,6,35,85,75,62,43,34,18,68,71,28,32,18,12,0,81,53,1,99,3,5,45,99,35,33],
+[19,95,89,45,75,94,92,5,84,93,34,17,50,56,79,98,68,82,65,81,51,90,5,95,33,71,46,61,14,7],
+[53,92,8,49,67,84,21,79,49,95,66,48,36,14,62,97,26,45,58,31,83,48,11,89,67,72,91,34,56,89],
+[56,76,99,92,40,8,0,16,15,48,35,72,91,46,81,14,86,60,51,7,33,12,53,78,48,21,3,89,15,79],
+[81,43,33,49,6,49,36,32,57,74,87,91,17,37,31,17,67,1,40,38,69,8,3,48,59,37,64,97,11,3],
+[98,48,77,16,2,48,57,38,63,59,79,35,16,71,60,86,71,41,14,76,80,97,77,69,4,58,22,55,26,73],
+[80,47,78,44,31,48,47,29,29,62,19,21,17,24,19,3,53,93,97,57,13,54,12,10,77,66,60,75,32,21],
+[86,63,2,13,71,38,86,23,18,15,91,65,77,65,9,92,50,0,17,42,99,80,99,27,10,99,92,9,87,84],
+[66,27,72,13,13,15,72,75,39,3,14,71,15,68,10,19,49,54,11,29,47,20,63,13,97,47,24,62,16,96],
+[42,63,83,60,49,68,9,53,75,87,40,25,12,63,0,12,0,95,46,46,55,25,89,1,51,1,1,96,80,52],
+[35,9,97,13,86,39,66,48,41,57,23,38,11,9,35,72,88,13,41,60,10,64,71,23,1,5,23,57,6,19],
+[70,61,5,50,72,60,77,13,41,94,1,45,52,22,99,47,27,18,99,42,16,48,26,9,88,77,10,94,11,92],
+[55,68,58,2,72,56,81,52,79,37,1,40,21,46,27,60,37,13,97,42,85,98,69,60,76,44,42,46,29,73],
+[73,0,43,17,89,97,45,2,68,14,55,60,95,2,74,85,88,68,93,76,38,76,2,51,45,76,50,79,56,18],
+[72,58,41,39,24,80,23,79,44,7,98,75,30,6,85,60,20,58,77,71,90,51,38,80,30,15,33,10,82,8]],
+            ZZ),
+        Matrix([
+    [eye(29) * 2028539767964472550625641331179545072876560857886207583101,
+     Matrix([ 4260575808093245475167216057435155595594339172099000182569,
+              169148395880755256182802335904188369274227936894862744452,
+              4915975976683942569102447281579134986891620721539038348914,
+              6113916866367364958834844982578214901958429746875633283248,
+              5585689617819894460378537031623265659753379011388162534838,
+              359776822829880747716695359574308645968094838905181892423,
+              -2800926112141776386671436511182421432449325232461665113305,
+              941642292388230001722444876624818265766384442910688463158,
+              3648811843256146649321864698600908938933015862008642023935,
+              -4104526163246702252932955226754097174212129127510547462419,
+              -704814955438106792441896903238080197619233342348191408078,
+              1640882266829725529929398131287244562048075707575030019335,
+              -4068330845192910563212155694231438198040299927120544468520,
+              136589038308366497790495711534532612862715724187671166593,
+              2544937011460702462290799932536905731142196510605191645593,
+              755591839174293940486133926192300657264122907519174116472,
+              -3683838489869297144348089243628436188645897133242795965021,
+              -522207137101161299969706310062775465103537953077871128403,
+              -2260451796032703984456606059649402832441331339246756656334,
+              -6476809325293587953616004856993300606040336446656916663680,
+              3521944238996782387785653800944972787867472610035040989081,
+              2270762115788407950241944504104975551914297395787473242379,
+              -3259947194628712441902262570532921252128444706733549251156,
+              -5624569821491886970999097239695637132075823246850431083557,
+              -3262698255682055804320585332902837076064075936601504555698,
+              5786719943788937667411185880136324396357603606944869545501,
+              -955257841973865996077323863289453200904051299086000660036,
+              -1294235552446355326174641248209752679127075717918392702116,
+              -3718353510747301598130831152458342785269166356215331448279,
+             ]),],
+        [zeros(1, 29), zeros(1, 1)],
+        ]).to_DM().to_dense(),
+        ZZ(2028539767964472550625641331179545072876560857886207583101),
+    ),
+
+
+    (
+        'qq_1',
+        DM([[(1,2), 0], [0, 2]], QQ),
+        DM([[1, 0], [0, 1]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # Standard square case
+        'qq_2',
+        DM([[0, 1],
+            [1, 1]], QQ),
+        DM([[1, 0],
+            [0, 1]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # m < n  case
+        'qq_3',
+        DM([[1, 2, 1],
+            [3, 4, 1]], QQ),
+        DM([[1, 0, -1],
+            [0, 1,  1]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # same m < n  but reversed
+        'qq_4',
+        DM([[3, 4, 1],
+            [1, 2, 1]], QQ),
+        DM([[1, 0, -1],
+            [0, 1,  1]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # m > n case
+        'qq_5',
+        DM([[1, 0],
+            [1, 3],
+            [0, 1]], QQ),
+        DM([[1, 0],
+            [0, 1],
+            [0, 0]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # Example with missing pivot
+        'qq_6',
+        DM([[1, 0, 1],
+            [3, 0, 1]], QQ),
+        DM([[1, 0, 0],
+            [0, 0, 1]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # This is intended to trigger the threshold where we give up on
+        # clearing denominators.
+        'qq_large_1',
+        qq_large_1,
+        DomainMatrix.eye(11, QQ).to_dense(),
+        QQ(1),
+    ),
+
+    (
+        # This is intended to trigger the threshold where we use rref_den over
+        # QQ.
+        'qq_large_2',
+        qq_large_2,
+        DomainMatrix.eye(11, QQ).to_dense(),
+        QQ(1),
+    ),
+
+    (
+        # Example with missing pivot and no replacement
+
+        # This example is just enough to show a different result from the dense
+        # and sparse versions of the algorithm:
+        #
+        #   >>> A = Matrix([[0, 1], [0, 2], [1, 0]])
+        #   >>> A.to_DM().to_sparse().rref_den()[0].to_Matrix()
+        #   Matrix([
+        #   [1, 0],
+        #   [0, 1],
+        #   [0, 0]])
+        #   >>> A.to_DM().to_dense().rref_den()[0].to_Matrix()
+        #   Matrix([
+        #   [2, 0],
+        #   [0, 2],
+        #   [0, 0]])
+        #
+        'qq_7',
+        DM([[0, 1],
+            [0, 2],
+            [1, 0]], QQ),
+        DM([[1, 0],
+            [0, 1],
+            [0, 0]], QQ),
+        QQ(1),
+    ),
+
+    (
+        # Gaussian integers
+        'zz_i_1',
+        DM([[(0,1), 1, 1],
+            [    1, 1, 1]], ZZ_I),
+        DM([[1, 0, 0],
+            [0, 1, 1]], ZZ_I),
+        ZZ_I(1),
+    ),
+
+    (
+        # EX: test_issue_23718
+        'EX_1',
+        DM([
+        [a, b, 1],
+        [c, d, 1]], EX),
+        DM([[a*d - b*c,         0, -b + d],
+            [        0, a*d - b*c,  a - c]], EX),
+        EX(a*d - b*c),
+    ),
+
+]
+
+
+def _to_DM(A, ans):
+    """Convert the answer to DomainMatrix."""
+    if isinstance(A, DomainMatrix):
+        return A.to_dense()
+    elif isinstance(A, Matrix):
+        return A.to_DM(ans.domain).to_dense()
+
+    if not (hasattr(A, 'shape') and hasattr(A, 'domain')):
+        shape, domain = ans.shape, ans.domain
+    else:
+        shape, domain = A.shape, A.domain
+
+    if isinstance(A, (DDM, list)):
+        return DomainMatrix(list(A), shape, domain).to_dense()
+    elif isinstance(A, (SDM, dict)):
+        return DomainMatrix(dict(A), shape, domain).to_dense()
+    else:
+        assert False # pragma: no cover
+
+
+def _pivots(A_rref):
+    """Return the pivots from the rref of A."""
+    return tuple(sorted(map(min, A_rref.to_sdm().values())))
+
+
+def _check_cancel(result, rref_ans, den_ans):
+    """Check the cancelled result."""
+    rref, den, pivots = result
+    if isinstance(rref, (DDM, SDM, list, dict)):
+        assert type(pivots) is list
+        pivots = tuple(pivots)
+    rref = _to_DM(rref, rref_ans)
+    rref2, den2 = rref.cancel_denom(den)
+    assert rref2 == rref_ans
+    assert den2 == den_ans
+    assert pivots == _pivots(rref)
+
+
+def _check_divide(result, rref_ans, den_ans):
+    """Check the divided result."""
+    rref, pivots = result
+    if isinstance(rref, (DDM, SDM, list, dict)):
+        assert type(pivots) is list
+        pivots = tuple(pivots)
+    rref_ans = rref_ans.to_field() / den_ans
+    rref = _to_DM(rref, rref_ans)
+    assert rref == rref_ans
+    assert _pivots(rref) == pivots
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_Matrix_rref(name, A, A_rref, den):
+    K = A.domain
+    A = A.to_Matrix()
+    A_rref_found, pivots = A.rref()
+    if K.is_EX:
+        A_rref_found = A_rref_found.expand()
+    _check_divide((A_rref_found, pivots), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_dense_rref(name, A, A_rref, den):
+    A = A.to_field()
+    _check_divide(A.rref(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_dense_rref_den(name, A, A_rref, den):
+    _check_cancel(A.rref_den(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_sparse_rref(name, A, A_rref, den):
+    A = A.to_field().to_sparse()
+    _check_divide(A.rref(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_sparse_rref_den(name, A, A_rref, den):
+    A = A.to_sparse()
+    _check_cancel(A.rref_den(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_sparse_rref_den_keep_domain(name, A, A_rref, den):
+    A = A.to_sparse()
+    A_rref_f, den_f, pivots_f = A.rref_den(keep_domain=False)
+    A_rref_f = A_rref_f.to_field() / den_f
+    _check_divide((A_rref_f, pivots_f), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_sparse_rref_den_keep_domain_CD(name, A, A_rref, den):
+    A = A.to_sparse()
+    A_rref_f, den_f, pivots_f = A.rref_den(keep_domain=False, method='CD')
+    A_rref_f = A_rref_f.to_field() / den_f
+    _check_divide((A_rref_f, pivots_f), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_dm_sparse_rref_den_keep_domain_GJ(name, A, A_rref, den):
+    A = A.to_sparse()
+    A_rref_f, den_f, pivots_f = A.rref_den(keep_domain=False, method='GJ')
+    A_rref_f = A_rref_f.to_field() / den_f
+    _check_divide((A_rref_f, pivots_f), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_ddm_rref_den(name, A, A_rref, den):
+    A = A.to_ddm()
+    _check_cancel(A.rref_den(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_sdm_rref_den(name, A, A_rref, den):
+    A = A.to_sdm()
+    _check_cancel(A.rref_den(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_ddm_rref(name, A, A_rref, den):
+    A = A.to_field().to_ddm()
+    _check_divide(A.rref(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_sdm_rref(name, A, A_rref, den):
+    A = A.to_field().to_sdm()
+    _check_divide(A.rref(), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_ddm_irref(name, A, A_rref, den):
+    A = A.to_field().to_ddm().copy()
+    pivots_found = ddm_irref(A)
+    _check_divide((A, pivots_found), A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_ddm_irref_den(name, A, A_rref, den):
+    A = A.to_ddm().copy()
+    (den_found, pivots_found) = ddm_irref_den(A, A.domain)
+    result = (A, den_found, pivots_found)
+    _check_cancel(result, A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_sparse_sdm_rref(name, A, A_rref, den):
+    A = A.to_field().to_sdm()
+    _check_divide(sdm_irref(A)[:2], A_rref, den)
+
+
+@pytest.mark.parametrize('name, A, A_rref, den', RREF_EXAMPLES)
+def test_sparse_sdm_rref_den(name, A, A_rref, den):
+    A = A.to_sdm().copy()
+    K = A.domain
+    _check_cancel(sdm_rref_den(A, K), A_rref, den)
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_sdm.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_sdm.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd7e5d460a1b2d44279a2a1772cc901f80ca733e
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_sdm.py
@@ -0,0 +1,428 @@
+"""
+Tests for the basic functionality of the SDM class.
+"""
+
+from itertools import product
+
+from sympy.core.singleton import S
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.testing.pytest import raises
+
+from sympy.polys.domains import QQ, ZZ, EXRAW
+from sympy.polys.matrices.sdm import SDM
+from sympy.polys.matrices.ddm import DDM
+from sympy.polys.matrices.exceptions import (DMBadInputError, DMDomainError,
+                                             DMShapeError)
+
+
+def test_SDM():
+    A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
+    assert A.domain == ZZ
+    assert A.shape == (2, 2)
+    assert dict(A) == {0:{0:ZZ(1)}}
+
+    raises(DMBadInputError, lambda: SDM({5:{1:ZZ(0)}}, (2, 2), ZZ))
+    raises(DMBadInputError, lambda: SDM({0:{5:ZZ(0)}}, (2, 2), ZZ))
+
+
+def test_DDM_str():
+    sdm = SDM({0:{0:ZZ(1)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
+    assert str(sdm) == '{0: {0: 1}, 1: {1: 1}}'
+    if GROUND_TYPES == 'gmpy': # pragma: no cover
+        assert repr(sdm) == 'SDM({0: {0: mpz(1)}, 1: {1: mpz(1)}}, (2, 2), ZZ)'
+    else:        # pragma: no cover
+        assert repr(sdm) == 'SDM({0: {0: 1}, 1: {1: 1}}, (2, 2), ZZ)'
+
+
+def test_SDM_new():
+    A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
+    B = A.new({}, (2, 2), ZZ)
+    assert B == SDM({}, (2, 2), ZZ)
+
+
+def test_SDM_copy():
+    A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
+    B = A.copy()
+    assert A == B
+    A[0][0] = ZZ(2)
+    assert A != B
+
+
+def test_SDM_from_list():
+    A = SDM.from_list([[ZZ(0), ZZ(1)], [ZZ(1), ZZ(0)]], (2, 2), ZZ)
+    assert A == SDM({0:{1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+
+    raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ))
+    raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0), ZZ(1)]], (2, 2), ZZ))
+
+
+def test_SDM_to_list():
+    A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
+    assert A.to_list() == [[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]]
+
+    A = SDM({}, (0, 2), ZZ)
+    assert A.to_list() == []
+
+    A = SDM({}, (2, 0), ZZ)
+    assert A.to_list() == [[], []]
+
+
+def test_SDM_to_list_flat():
+    A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
+    assert A.to_list_flat() == [ZZ(0), ZZ(1), ZZ(0), ZZ(0)]
+
+
+def test_SDM_to_dok():
+    A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
+    assert A.to_dok() == {(0, 1): ZZ(1)}
+
+
+def test_SDM_from_ddm():
+    A = DDM([[ZZ(1), ZZ(0)], [ZZ(1), ZZ(0)]], (2, 2), ZZ)
+    B = SDM.from_ddm(A)
+    assert B.domain == ZZ
+    assert B.shape == (2, 2)
+    assert dict(B) == {0:{0:ZZ(1)}, 1:{0:ZZ(1)}}
+
+
+def test_SDM_to_ddm():
+    A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
+    B = DDM([[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
+    assert A.to_ddm() == B
+
+
+def test_SDM_to_sdm():
+    A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
+    assert A.to_sdm() == A
+
+
+def test_SDM_getitem():
+    A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    assert A.getitem(0, 0) == ZZ.zero
+    assert A.getitem(0, 1) == ZZ.one
+    assert A.getitem(1, 0) == ZZ.zero
+    assert A.getitem(-2, -2) == ZZ.zero
+    assert A.getitem(-2, -1) == ZZ.one
+    assert A.getitem(-1, -2) == ZZ.zero
+    raises(IndexError, lambda: A.getitem(2, 0))
+    raises(IndexError, lambda: A.getitem(0, 2))
+
+
+def test_SDM_setitem():
+    A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    A.setitem(0, 0, ZZ(1))
+    assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
+    A.setitem(1, 0, ZZ(1))
+    assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
+    A.setitem(1, 0, ZZ(0))
+    assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
+    # Repeat the above test so that this time the row is empty
+    A.setitem(1, 0, ZZ(0))
+    assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
+    A.setitem(0, 0, ZZ(0))
+    assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    # This time the row is there but column is empty
+    A.setitem(0, 0, ZZ(0))
+    assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    raises(IndexError, lambda: A.setitem(2, 0, ZZ(1)))
+    raises(IndexError, lambda: A.setitem(0, 2, ZZ(1)))
+
+
+def test_SDM_extract_slice():
+    A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    B = A.extract_slice(slice(1, 2), slice(1, 2))
+    assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
+
+
+def test_SDM_extract():
+    A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    B = A.extract([1], [1])
+    assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
+    B = A.extract([1, 0], [1, 0])
+    assert B == SDM({0:{0:ZZ(4), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(1)}}, (2, 2), ZZ)
+    B = A.extract([1, 1], [1, 1])
+    assert B == SDM({0:{0:ZZ(4), 1:ZZ(4)}, 1:{0:ZZ(4), 1:ZZ(4)}}, (2, 2), ZZ)
+    B = A.extract([-1], [-1])
+    assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
+
+    A = SDM({}, (2, 2), ZZ)
+    B = A.extract([0, 1, 0], [0, 0])
+    assert B == SDM({}, (3, 2), ZZ)
+
+    A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    assert A.extract([], []) == SDM.zeros((0, 0), ZZ)
+    assert A.extract([1], []) == SDM.zeros((1, 0), ZZ)
+    assert A.extract([], [1]) == SDM.zeros((0, 1), ZZ)
+
+    raises(IndexError, lambda: A.extract([2], [0]))
+    raises(IndexError, lambda: A.extract([0], [2]))
+    raises(IndexError, lambda: A.extract([-3], [0]))
+    raises(IndexError, lambda: A.extract([0], [-3]))
+
+
+def test_SDM_zeros():
+    A = SDM.zeros((2, 2), ZZ)
+    assert A.domain == ZZ
+    assert A.shape == (2, 2)
+    assert dict(A) == {}
+
+def test_SDM_ones():
+    A = SDM.ones((1, 2), QQ)
+    assert A.domain == QQ
+    assert A.shape == (1, 2)
+    assert dict(A) == {0:{0:QQ(1), 1:QQ(1)}}
+
+def test_SDM_eye():
+    A = SDM.eye((2, 2), ZZ)
+    assert A.domain == ZZ
+    assert A.shape == (2, 2)
+    assert dict(A) == {0:{0:ZZ(1)}, 1:{1:ZZ(1)}}
+
+
+def test_SDM_diag():
+    A = SDM.diag([ZZ(1), ZZ(2)], ZZ, (2, 3))
+    assert A == SDM({0:{0:ZZ(1)}, 1:{1:ZZ(2)}}, (2, 3), ZZ)
+
+
+def test_SDM_transpose():
+    A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(1), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(4)}}, (2, 2), ZZ)
+    assert A.transpose() == B
+
+    A = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ)
+    B = SDM({1:{0:ZZ(2)}}, (2, 2), ZZ)
+    assert A.transpose() == B
+
+    A = SDM({0:{1:ZZ(2)}}, (1, 2), ZZ)
+    B = SDM({1:{0:ZZ(2)}}, (2, 1), ZZ)
+    assert A.transpose() == B
+
+
+def test_SDM_mul():
+    A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
+    assert A*ZZ(2) == B
+    assert ZZ(2)*A == B
+
+    raises(TypeError, lambda: A*QQ(1, 2))
+    raises(TypeError, lambda: QQ(1, 2)*A)
+
+
+def test_SDM_mul_elementwise():
+    A = SDM({0:{0:ZZ(2), 1:ZZ(2)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(4)}, 1:{0:ZZ(3)}}, (2, 2), ZZ)
+    C = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ)
+    assert A.mul_elementwise(B) == C
+    assert B.mul_elementwise(A) == C
+
+    Aq = A.convert_to(QQ)
+    A1 = SDM({0:{0:ZZ(1)}}, (1, 1), ZZ)
+
+    raises(DMDomainError, lambda: Aq.mul_elementwise(B))
+    raises(DMShapeError, lambda: A1.mul_elementwise(B))
+
+
+def test_SDM_matmul():
+    A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
+    assert A.matmul(A) == A*A == B
+
+    C = SDM({0:{0:ZZ(2)}}, (2, 2), QQ)
+    raises(DMDomainError, lambda: A.matmul(C))
+
+    A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(7), 1:ZZ(10)}, 1:{0:ZZ(15), 1:ZZ(22)}}, (2, 2), ZZ)
+    assert A.matmul(A) == A*A == B
+
+    A22 = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
+    A32 = SDM({0:{0:ZZ(2)}}, (3, 2), ZZ)
+    A23 = SDM({0:{0:ZZ(4)}}, (2, 3), ZZ)
+    A33 = SDM({0:{0:ZZ(8)}}, (3, 3), ZZ)
+    A22 = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ)
+    assert A32.matmul(A23) == A33
+    assert A23.matmul(A32) == A22
+    # XXX: @ not supported by SDM...
+    #assert A32.matmul(A23) == A32 @ A23 == A33
+    #assert A23.matmul(A32) == A23 @ A32 == A22
+    #raises(DMShapeError, lambda: A23 @ A22)
+    raises(DMShapeError, lambda: A23.matmul(A22))
+
+    A = SDM({0: {0: ZZ(-1), 1: ZZ(1)}}, (1, 2), ZZ)
+    B = SDM({0: {0: ZZ(-1)}, 1: {0: ZZ(-1)}}, (2, 1), ZZ)
+    assert A.matmul(B) == A*B == SDM({}, (1, 1), ZZ)
+
+
+def test_matmul_exraw():
+
+    def dm(d):
+        result = {}
+        for i, row in d.items():
+            row = {j:val for j, val in row.items() if val}
+            if row:
+                result[i] = row
+        return SDM(result, (2, 2), EXRAW)
+
+    values = [S.NegativeInfinity, S.NegativeOne, S.Zero, S.One, S.Infinity]
+    for a, b, c, d in product(*[values]*4):
+        Ad = dm({0: {0:a, 1:b}, 1: {0:c, 1:d}})
+        Ad2 = dm({0: {0:a*a + b*c, 1:a*b + b*d}, 1:{0:c*a + d*c, 1: c*b + d*d}})
+        assert Ad * Ad == Ad2
+
+
+def test_SDM_add():
+    A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
+    C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{1:ZZ(6)}}, (2, 2), ZZ)
+    assert A.add(B) == B.add(A) == A + B == B + A == C
+
+    A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
+    C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
+    assert A.add(B) == B.add(A) == A + B == B + A == C
+
+    raises(TypeError, lambda: A + [])
+
+
+def test_SDM_sub():
+    A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
+    B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
+    C = SDM({0:{0:ZZ(-1), 1:ZZ(1)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
+    assert A.sub(B) == A - B == C
+
+    raises(TypeError, lambda: A - [])
+
+
+def test_SDM_neg():
+    A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
+    B = SDM({0:{1:ZZ(-1)}, 1:{0:ZZ(-2), 1:ZZ(-3)}}, (2, 2), ZZ)
+    assert A.neg() == -A == B
+
+
+def test_SDM_convert_to():
+    A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
+    B = SDM({0:{1:QQ(1)}, 1:{0:QQ(2), 1:QQ(3)}}, (2, 2), QQ)
+    C = A.convert_to(QQ)
+    assert C == B
+    assert C.domain == QQ
+
+    D = A.convert_to(ZZ)
+    assert D == A
+    assert D.domain == ZZ
+
+
+def test_SDM_hstack():
+    A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ)
+    AA = SDM({0:{1:ZZ(1), 3:ZZ(1)}}, (2, 4), ZZ)
+    AB = SDM({0:{1:ZZ(1)}, 1:{3:ZZ(1)}}, (2, 4), ZZ)
+    assert SDM.hstack(A) == A
+    assert SDM.hstack(A, A) == AA
+    assert SDM.hstack(A, B) == AB
+
+
+def test_SDM_vstack():
+    A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ)
+    AA = SDM({0:{1:ZZ(1)}, 2:{1:ZZ(1)}}, (4, 2), ZZ)
+    AB = SDM({0:{1:ZZ(1)}, 3:{1:ZZ(1)}}, (4, 2), ZZ)
+    assert SDM.vstack(A) == A
+    assert SDM.vstack(A, A) == AA
+    assert SDM.vstack(A, B) == AB
+
+
+def test_SDM_applyfunc():
+    A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
+    B = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ)
+    assert A.applyfunc(lambda x: 2*x, ZZ) == B
+
+
+def test_SDM_inv():
+    A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+    B = SDM({0:{0:QQ(-2), 1:QQ(1)}, 1:{0:QQ(3, 2), 1:QQ(-1, 2)}}, (2, 2), QQ)
+    assert A.inv() == B
+
+
+def test_SDM_det():
+    A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+    assert A.det() == QQ(-2)
+
+
+def test_SDM_lu():
+    A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+    L = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(1)}}, (2, 2), QQ)
+    #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ)
+    #swaps = []
+    # This doesn't quite work. U has some nonzero elements in the lower part.
+    #assert A.lu() == (L, U, swaps)
+    assert A.lu()[0] == L
+
+
+def test_SDM_lu_solve():
+    A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+    b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
+    x = SDM({1:{0:QQ(1, 2)}}, (2, 1), QQ)
+    assert A.matmul(x) == b
+    assert A.lu_solve(b) == x
+
+
+def test_SDM_charpoly():
+    A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
+    assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)]
+
+
+def test_SDM_nullspace():
+    # More tests are in test_nullspace.py
+    A = SDM({0:{0:QQ(1), 1:QQ(1)}}, (2, 2), QQ)
+    assert A.nullspace()[0] == SDM({0:{0:QQ(-1), 1:QQ(1)}}, (1, 2), QQ)
+
+
+def test_SDM_rref():
+    # More tests are in test_rref.py
+
+    A = SDM({0:{0:QQ(1), 1:QQ(2)},
+             1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
+    A_rref = SDM({0:{0:QQ(1)}, 1:{1:QQ(1)}}, (2, 2), QQ)
+    assert A.rref() == (A_rref, [0, 1])
+
+    A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(2)},
+             1: {0: QQ(3),           2: QQ(4)}}, (2, 3), ZZ)
+    A_rref = SDM({0: {0: QQ(1,1), 2: QQ(4,3)},
+                  1: {1: QQ(1,1), 2: QQ(1,3)}}, (2, 3), QQ)
+    assert A.rref() == (A_rref, [0, 1])
+
+
+def test_SDM_particular():
+    A = SDM({0:{0:QQ(1)}}, (2, 2), QQ)
+    Apart = SDM.zeros((1, 2), QQ)
+    assert A.particular() == Apart
+
+
+def test_SDM_is_zero_matrix():
+    A = SDM({0: {0: QQ(1)}}, (2, 2), QQ)
+    Azero = SDM.zeros((1, 2), QQ)
+    assert A.is_zero_matrix() is False
+    assert Azero.is_zero_matrix() is True
+
+
+def test_SDM_is_upper():
+    A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
+                       1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
+                                 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ)
+    B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
+                       1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
+                       2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ)
+    assert A.is_upper() is True
+    assert B.is_upper() is False
+
+
+def test_SDM_is_lower():
+    A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
+                       1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
+                                 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ
+            ).transpose()
+    B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
+                       1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
+                       2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ
+            ).transpose()
+    assert A.is_lower() is True
+    assert B.is_lower() is False
diff --git a/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_xxm.py b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_xxm.py
new file mode 100644
index 0000000000000000000000000000000000000000..96a660123aa232107258a6f0e0a3e24a0bba07b4
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/matrices/tests/test_xxm.py
@@ -0,0 +1,864 @@
+#
+# Test basic features of DDM, SDM and DFM.
+#
+# These three types are supposed to be interchangeable, so we should use the
+# same tests for all of them for the most part.
+#
+# The tests here cover the basic part of the inerface that the three types
+# should expose and that DomainMatrix should mostly rely on.
+#
+# More in-depth tests of the heavier algorithms like rref etc should go in
+# their own test files.
+#
+# Any new methods added to the DDM, SDM or DFM classes should be tested here
+# and added to all classes.
+#
+
+from sympy.external.gmpy import GROUND_TYPES
+
+from sympy import ZZ, QQ, GF, ZZ_I, symbols
+
+from sympy.polys.matrices.exceptions import (
+    DMBadInputError,
+    DMDomainError,
+    DMNonSquareMatrixError,
+    DMNonInvertibleMatrixError,
+    DMShapeError,
+)
+
+from sympy.polys.matrices.domainmatrix import DM, DomainMatrix, DDM, SDM, DFM
+
+from sympy.testing.pytest import raises, skip
+import pytest
+
+
+def test_XXM_constructors():
+    """Test the DDM, etc constructors."""
+
+    lol = [
+        [ZZ(1), ZZ(2)],
+        [ZZ(3), ZZ(4)],
+        [ZZ(5), ZZ(6)],
+    ]
+    dod = {
+        0: {0: ZZ(1), 1: ZZ(2)},
+        1: {0: ZZ(3), 1: ZZ(4)},
+        2: {0: ZZ(5), 1: ZZ(6)},
+    }
+
+    lol_0x0 = []
+    lol_0x2 = []
+    lol_2x0 = [[], []]
+    dod_0x0 = {}
+    dod_0x2 = {}
+    dod_2x0 = {}
+
+    lol_bad = [
+        [ZZ(1), ZZ(2)],
+        [ZZ(3), ZZ(4)],
+        [ZZ(5), ZZ(6), ZZ(7)],
+    ]
+    dod_bad = {
+        0: {0: ZZ(1), 1: ZZ(2)},
+        1: {0: ZZ(3), 1: ZZ(4)},
+        2: {0: ZZ(5), 1: ZZ(6), 2: ZZ(7)},
+    }
+
+    XDM_dense = [DDM]
+    XDM_sparse = [SDM]
+
+    if GROUND_TYPES == 'flint':
+        XDM_dense.append(DFM)
+
+    for XDM in XDM_dense:
+
+        A = XDM(lol, (3, 2), ZZ)
+        assert A.rows == 3
+        assert A.cols == 2
+        assert A.domain == ZZ
+        assert A.shape == (3, 2)
+        if XDM is not DFM:
+            assert ZZ.of_type(A[0][0]) is True
+        else:
+            assert ZZ.of_type(A.rep[0, 0]) is True
+
+        Adm = DomainMatrix(lol, (3, 2), ZZ)
+        if XDM is DFM:
+            assert Adm.rep == A
+            assert Adm.rep.to_ddm() != A
+        elif GROUND_TYPES == 'flint':
+            assert Adm.rep.to_ddm() == A
+            assert Adm.rep != A
+        else:
+            assert Adm.rep == A
+            assert Adm.rep.to_ddm() == A
+
+        assert XDM(lol_0x0, (0, 0), ZZ).shape == (0, 0)
+        assert XDM(lol_0x2, (0, 2), ZZ).shape == (0, 2)
+        assert XDM(lol_2x0, (2, 0), ZZ).shape == (2, 0)
+        raises(DMBadInputError, lambda: XDM(lol, (2, 3), ZZ))
+        raises(DMBadInputError, lambda: XDM(lol_bad, (3, 2), ZZ))
+        raises(DMBadInputError, lambda: XDM(dod, (3, 2), ZZ))
+
+    for XDM in XDM_sparse:
+
+        A = XDM(dod, (3, 2), ZZ)
+        assert A.rows == 3
+        assert A.cols == 2
+        assert A.domain == ZZ
+        assert A.shape == (3, 2)
+        assert ZZ.of_type(A[0][0]) is True
+
+        assert DomainMatrix(dod, (3, 2), ZZ).rep == A
+
+        assert XDM(dod_0x0, (0, 0), ZZ).shape == (0, 0)
+        assert XDM(dod_0x2, (0, 2), ZZ).shape == (0, 2)
+        assert XDM(dod_2x0, (2, 0), ZZ).shape == (2, 0)
+        raises(DMBadInputError, lambda: XDM(dod, (2, 3), ZZ))
+        raises(DMBadInputError, lambda: XDM(lol, (3, 2), ZZ))
+        raises(DMBadInputError, lambda: XDM(dod_bad, (3, 2), ZZ))
+
+    raises(DMBadInputError, lambda: DomainMatrix(lol, (2, 3), ZZ))
+    raises(DMBadInputError, lambda: DomainMatrix(lol_bad, (3, 2), ZZ))
+    raises(DMBadInputError, lambda: DomainMatrix(dod_bad, (3, 2), ZZ))
+
+
+def test_XXM_eq():
+    """Test equality for DDM, SDM, DFM and DomainMatrix."""
+
+    lol1 = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+    dod1 = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}
+
+    lol2 = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(5)]]
+    dod2 = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(5)}}
+
+    A1_ddm = DDM(lol1, (2, 2), ZZ)
+    A1_sdm = SDM(dod1, (2, 2), ZZ)
+    A1_dm_d = DomainMatrix(lol1, (2, 2), ZZ)
+    A1_dm_s = DomainMatrix(dod1, (2, 2), ZZ)
+
+    A2_ddm = DDM(lol2, (2, 2), ZZ)
+    A2_sdm = SDM(dod2, (2, 2), ZZ)
+    A2_dm_d = DomainMatrix(lol2, (2, 2), ZZ)
+    A2_dm_s = DomainMatrix(dod2, (2, 2), ZZ)
+
+    A1_all = [A1_ddm, A1_sdm, A1_dm_d, A1_dm_s]
+    A2_all = [A2_ddm, A2_sdm, A2_dm_d, A2_dm_s]
+
+    if GROUND_TYPES == 'flint':
+
+        A1_dfm = DFM([[1, 2], [3, 4]], (2, 2), ZZ)
+        A2_dfm = DFM([[1, 2], [3, 5]], (2, 2), ZZ)
+
+        A1_all.append(A1_dfm)
+        A2_all.append(A2_dfm)
+
+    for n, An in enumerate(A1_all):
+        for m, Am in enumerate(A1_all):
+            if n == m:
+                assert (An == Am) is True
+                assert (An != Am) is False
+            else:
+                assert (An == Am) is False
+                assert (An != Am) is True
+
+    for n, An in enumerate(A2_all):
+        for m, Am in enumerate(A2_all):
+            if n == m:
+                assert (An == Am) is True
+                assert (An != Am) is False
+            else:
+                assert (An == Am) is False
+                assert (An != Am) is True
+
+    for n, A1 in enumerate(A1_all):
+        for m, A2 in enumerate(A2_all):
+            assert (A1 == A2) is False
+            assert (A1 != A2) is True
+
+
+def test_to_XXM():
+    """Test to_ddm etc. for DDM, SDM, DFM and DomainMatrix."""
+
+    lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]]
+    dod = {0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}
+
+    A_ddm = DDM(lol, (2, 2), ZZ)
+    A_sdm = SDM(dod, (2, 2), ZZ)
+    A_dm_d = DomainMatrix(lol, (2, 2), ZZ)
+    A_dm_s = DomainMatrix(dod, (2, 2), ZZ)
+
+    A_all = [A_ddm, A_sdm, A_dm_d, A_dm_s]
+
+    if GROUND_TYPES == 'flint':
+        A_dfm = DFM(lol, (2, 2), ZZ)
+        A_all.append(A_dfm)
+
+    for A in A_all:
+        assert A.to_ddm() == A_ddm
+        assert A.to_sdm() == A_sdm
+        if GROUND_TYPES != 'flint':
+            raises(NotImplementedError, lambda: A.to_dfm())
+            assert A.to_dfm_or_ddm() == A_ddm
+
+        # Add e.g. DDM.to_DM()?
+        # assert A.to_DM() == A_dm
+
+    if GROUND_TYPES == 'flint':
+        for A in A_all:
+            assert A.to_dfm() == A_dfm
+            for K in [ZZ, QQ, GF(5), ZZ_I]:
+                if isinstance(A, DFM) and not DFM._supports_domain(K):
+                    raises(NotImplementedError, lambda: A.convert_to(K))
+                else:
+                    A_K = A.convert_to(K)
+                    if DFM._supports_domain(K):
+                        A_dfm_K = A_dfm.convert_to(K)
+                        assert A_K.to_dfm() == A_dfm_K
+                        assert A_K.to_dfm_or_ddm() == A_dfm_K
+                    else:
+                        raises(NotImplementedError, lambda: A_K.to_dfm())
+                        assert A_K.to_dfm_or_ddm() == A_ddm.convert_to(K)
+
+
+def test_DFM_domains():
+    """Test which domains are supported by DFM."""
+
+    x, y = symbols('x, y')
+
+    if GROUND_TYPES in ('python', 'gmpy'):
+
+        supported = []
+        flint_funcs = {}
+        not_supported = [ZZ, QQ, GF(5), QQ[x], QQ[x,y]]
+
+    elif GROUND_TYPES == 'flint':
+
+        import flint
+        supported = [ZZ, QQ]
+        flint_funcs = {
+            ZZ: flint.fmpz_mat,
+            QQ: flint.fmpq_mat,
+        }
+        not_supported = [
+            # This could be supported but not yet implemented in SymPy:
+            GF(5),
+            # Other domains could be supported but not implemented as matrices
+            # in python-flint:
+            QQ[x],
+            QQ[x,y],
+            QQ.frac_field(x,y),
+            # Others would potentially never be supported by python-flint:
+            ZZ_I,
+        ]
+
+    else:
+        assert False, "Unknown GROUND_TYPES: %s" % GROUND_TYPES
+
+    for domain in supported:
+        assert DFM._supports_domain(domain) is True
+        assert DFM._get_flint_func(domain) == flint_funcs[domain]
+    for domain in not_supported:
+        assert DFM._supports_domain(domain) is False
+        raises(NotImplementedError, lambda: DFM._get_flint_func(domain))
+
+
+def _DM(lol, typ, K):
+    """Make a DM of type typ over K from lol."""
+    A = DM(lol, K)
+
+    if typ == 'DDM':
+        return A.to_ddm()
+    elif typ == 'SDM':
+        return A.to_sdm()
+    elif typ == 'DFM':
+        if GROUND_TYPES != 'flint':
+            skip("DFM not supported in this ground type")
+        return A.to_dfm()
+    else:
+        assert False, "Unknown type %s" % typ
+
+
+def _DMZ(lol, typ):
+    """Make a DM of type typ over ZZ from lol."""
+    return _DM(lol, typ, ZZ)
+
+
+def _DMQ(lol, typ):
+    """Make a DM of type typ over QQ from lol."""
+    return _DM(lol, typ, QQ)
+
+
+def DM_ddm(lol, K):
+    """Make a DDM over K from lol."""
+    return _DM(lol, 'DDM', K)
+
+
+def DM_sdm(lol, K):
+    """Make a SDM over K from lol."""
+    return _DM(lol, 'SDM', K)
+
+
+def DM_dfm(lol, K):
+    """Make a DFM over K from lol."""
+    return _DM(lol, 'DFM', K)
+
+
+def DMZ_ddm(lol):
+    """Make a DDM from lol."""
+    return _DMZ(lol, 'DDM')
+
+
+def DMZ_sdm(lol):
+    """Make a SDM from lol."""
+    return _DMZ(lol, 'SDM')
+
+
+def DMZ_dfm(lol):
+    """Make a DFM from lol."""
+    return _DMZ(lol, 'DFM')
+
+
+def DMQ_ddm(lol):
+    """Make a DDM from lol."""
+    return _DMQ(lol, 'DDM')
+
+
+def DMQ_sdm(lol):
+    """Make a SDM from lol."""
+    return _DMQ(lol, 'SDM')
+
+
+def DMQ_dfm(lol):
+    """Make a DFM from lol."""
+    return _DMQ(lol, 'DFM')
+
+
+DM_all = [DM_ddm, DM_sdm, DM_dfm]
+DMZ_all = [DMZ_ddm, DMZ_sdm, DMZ_dfm]
+DMQ_all = [DMQ_ddm, DMQ_sdm, DMQ_dfm]
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XDM_getitem(DM):
+    """Test getitem for DDM, etc."""
+
+    lol = [[0, 1], [2, 0]]
+    A = DM(lol)
+    m, n = A.shape
+
+    indices = [-3, -2, -1, 0, 1, 2]
+
+    for i in indices:
+        for j in indices:
+            if -2 <= i < m and -2 <= j < n:
+                assert A.getitem(i, j) == ZZ(lol[i][j])
+            else:
+                raises(IndexError, lambda: A.getitem(i, j))
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XDM_setitem(DM):
+    """Test setitem for DDM, etc."""
+
+    A = DM([[0, 1, 2], [3, 4, 5]])
+
+    A.setitem(0, 0, ZZ(6))
+    assert A == DM([[6, 1, 2], [3, 4, 5]])
+
+    A.setitem(0, 1, ZZ(7))
+    assert A == DM([[6, 7, 2], [3, 4, 5]])
+
+    A.setitem(0, 2, ZZ(8))
+    assert A == DM([[6, 7, 8], [3, 4, 5]])
+
+    A.setitem(0, -1, ZZ(9))
+    assert A == DM([[6, 7, 9], [3, 4, 5]])
+
+    A.setitem(0, -2, ZZ(10))
+    assert A == DM([[6, 10, 9], [3, 4, 5]])
+
+    A.setitem(0, -3, ZZ(11))
+    assert A == DM([[11, 10, 9], [3, 4, 5]])
+
+    raises(IndexError, lambda: A.setitem(0, 3, ZZ(12)))
+    raises(IndexError, lambda: A.setitem(0, -4, ZZ(13)))
+
+    A.setitem(1, 0, ZZ(14))
+    assert A == DM([[11, 10, 9], [14, 4, 5]])
+
+    A.setitem(1, 1, ZZ(15))
+    assert A == DM([[11, 10, 9], [14, 15, 5]])
+
+    A.setitem(-1, 1, ZZ(16))
+    assert A == DM([[11, 10, 9], [14, 16, 5]])
+
+    A.setitem(-2, 1, ZZ(17))
+    assert A == DM([[11, 17, 9], [14, 16, 5]])
+
+    raises(IndexError, lambda: A.setitem(2, 0, ZZ(18)))
+    raises(IndexError, lambda: A.setitem(-3, 0, ZZ(19)))
+
+    A.setitem(1, 2, ZZ(0))
+    assert A == DM([[11, 17, 9], [14, 16, 0]])
+
+    A.setitem(1, -2, ZZ(0))
+    assert A == DM([[11, 17, 9], [14, 0, 0]])
+
+    A.setitem(1, -3, ZZ(0))
+    assert A == DM([[11, 17, 9], [0, 0, 0]])
+
+    A.setitem(0, 0, ZZ(0))
+    assert A == DM([[0, 17, 9], [0, 0, 0]])
+
+    A.setitem(0, -1, ZZ(0))
+    assert A == DM([[0, 17, 0], [0, 0, 0]])
+
+    A.setitem(0, 0, ZZ(0))
+    assert A == DM([[0, 17, 0], [0, 0, 0]])
+
+    A.setitem(0, -2, ZZ(0))
+    assert A == DM([[0, 0, 0], [0, 0, 0]])
+
+    A.setitem(0, -3, ZZ(1))
+    assert A == DM([[1, 0, 0], [0, 0, 0]])
+
+
+class _Sliced:
+    def __getitem__(self, item):
+        return item
+
+
+_slice = _Sliced()
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_extract_slice(DM):
+    A = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    assert A.extract_slice(*_slice[:,:]) == A
+    assert A.extract_slice(*_slice[1:,:]) == DM([[4, 5, 6], [7, 8, 9]])
+    assert A.extract_slice(*_slice[1:,1:]) == DM([[5, 6], [8, 9]])
+    assert A.extract_slice(*_slice[1:,:-1]) == DM([[4, 5], [7, 8]])
+    assert A.extract_slice(*_slice[1:,:-1:2]) == DM([[4], [7]])
+    assert A.extract_slice(*_slice[:,::2]) == DM([[1, 3], [4, 6], [7, 9]])
+    assert A.extract_slice(*_slice[::2,:]) == DM([[1, 2, 3], [7, 8, 9]])
+    assert A.extract_slice(*_slice[::2,::2]) == DM([[1, 3], [7, 9]])
+    assert A.extract_slice(*_slice[::2,::-2]) == DM([[3, 1], [9, 7]])
+    assert A.extract_slice(*_slice[::-2,::2]) == DM([[7, 9], [1, 3]])
+    assert A.extract_slice(*_slice[::-2,::-2]) == DM([[9, 7], [3, 1]])
+    assert A.extract_slice(*_slice[:,::-1]) == DM([[3, 2, 1], [6, 5, 4], [9, 8, 7]])
+    assert A.extract_slice(*_slice[::-1,:]) == DM([[7, 8, 9], [4, 5, 6], [1, 2, 3]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_extract(DM):
+
+    A = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+
+    assert A.extract([0, 1, 2], [0, 1, 2]) == A
+    assert A.extract([1, 2], [1, 2]) == DM([[5, 6], [8, 9]])
+    assert A.extract([1, 2], [0, 1]) == DM([[4, 5], [7, 8]])
+    assert A.extract([1, 2], [0, 2]) == DM([[4, 6], [7, 9]])
+    assert A.extract([1, 2], [0]) == DM([[4], [7]])
+    assert A.extract([1, 2], []) == DM([[1]]).zeros((2, 0), ZZ)
+    assert A.extract([], [0, 1, 2]) == DM([[1]]).zeros((0, 3), ZZ)
+
+    raises(IndexError, lambda: A.extract([1, 2], [0, 3]))
+    raises(IndexError, lambda: A.extract([1, 2], [0, -4]))
+    raises(IndexError, lambda: A.extract([3, 1], [0, 1]))
+    raises(IndexError, lambda: A.extract([-4, 2], [3, 1]))
+
+    B = DM([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
+    assert B.extract([1, 2], [1, 2]) == DM([[0, 0], [0, 0]])
+
+
+def test_XXM_str():
+
+    A = DomainMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)
+
+    assert str(A) == \
+        'DomainMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)'
+    assert str(A.to_ddm()) == \
+        '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'
+    assert str(A.to_sdm()) == \
+        '{0: {0: 1, 1: 2, 2: 3}, 1: {0: 4, 1: 5, 2: 6}, 2: {0: 7, 1: 8, 2: 9}}'
+
+    assert repr(A) == \
+        'DomainMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)'
+    assert repr(A.to_ddm()) == \
+        'DDM([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)'
+    assert repr(A.to_sdm()) == \
+        'SDM({0: {0: 1, 1: 2, 2: 3}, 1: {0: 4, 1: 5, 2: 6}, 2: {0: 7, 1: 8, 2: 9}}, (3, 3), ZZ)'
+
+    B = DomainMatrix({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3)}}, (2, 2), ZZ)
+
+    assert str(B) == \
+        'DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3}}, (2, 2), ZZ)'
+    assert str(B.to_ddm()) == \
+        '[[1, 2], [3, 0]]'
+    assert str(B.to_sdm()) == \
+        '{0: {0: 1, 1: 2}, 1: {0: 3}}'
+
+    assert repr(B) == \
+        'DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3}}, (2, 2), ZZ)'
+
+    if GROUND_TYPES != 'gmpy':
+        assert repr(B.to_ddm()) == \
+            'DDM([[1, 2], [3, 0]], (2, 2), ZZ)'
+        assert repr(B.to_sdm()) == \
+            'SDM({0: {0: 1, 1: 2}, 1: {0: 3}}, (2, 2), ZZ)'
+    else:
+        assert repr(B.to_ddm()) == \
+            'DDM([[mpz(1), mpz(2)], [mpz(3), mpz(0)]], (2, 2), ZZ)'
+        assert repr(B.to_sdm()) == \
+            'SDM({0: {0: mpz(1), 1: mpz(2)}, 1: {0: mpz(3)}}, (2, 2), ZZ)'
+
+    if GROUND_TYPES == 'flint':
+
+        assert str(A.to_dfm()) == \
+            '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'
+        assert str(B.to_dfm()) == \
+            '[[1, 2], [3, 0]]'
+
+        assert repr(A.to_dfm()) == \
+            'DFM([[1, 2, 3], [4, 5, 6], [7, 8, 9]], (3, 3), ZZ)'
+        assert repr(B.to_dfm()) == \
+            'DFM([[1, 2], [3, 0]], (2, 2), ZZ)'
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_from_list(DM):
+    T = type(DM([[0]]))
+
+    lol = [[1, 2, 4], [4, 5, 6]]
+    lol_ZZ = [[ZZ(1), ZZ(2), ZZ(4)], [ZZ(4), ZZ(5), ZZ(6)]]
+    lol_ZZ_bad = [[ZZ(1), ZZ(2), ZZ(4)], [ZZ(4), ZZ(5), ZZ(6), ZZ(7)]]
+
+    assert T.from_list(lol_ZZ, (2, 3), ZZ) == DM(lol)
+    raises(DMBadInputError, lambda: T.from_list(lol_ZZ_bad, (3, 2), ZZ))
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_to_list(DM):
+    lol = [[1, 2, 4], [4, 5, 6]]
+    assert DM(lol).to_list() == [[ZZ(1), ZZ(2), ZZ(4)], [ZZ(4), ZZ(5), ZZ(6)]]
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_to_list_flat(DM):
+    lol = [[1, 2, 4], [4, 5, 6]]
+    assert DM(lol).to_list_flat() == [ZZ(1), ZZ(2), ZZ(4), ZZ(4), ZZ(5), ZZ(6)]
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_from_list_flat(DM):
+    T = type(DM([[0]]))
+    flat = [ZZ(1), ZZ(2), ZZ(4), ZZ(4), ZZ(5), ZZ(6)]
+    assert T.from_list_flat(flat, (2, 3), ZZ) == DM([[1, 2, 4], [4, 5, 6]])
+    raises(DMBadInputError, lambda: T.from_list_flat(flat, (3, 3), ZZ))
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_to_flat_nz(DM):
+    M = DM([[1, 2, 0], [0, 0, 0], [0, 0, 3]])
+    elements = [ZZ(1), ZZ(2), ZZ(3)]
+    indices = ((0, 0), (0, 1), (2, 2))
+    assert M.to_flat_nz() == (elements, (indices, M.shape))
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_from_flat_nz(DM):
+    T = type(DM([[0]]))
+    elements = [ZZ(1), ZZ(2), ZZ(3)]
+    indices = ((0, 0), (0, 1), (2, 2))
+    data = (indices, (3, 3))
+    result = DM([[1, 2, 0], [0, 0, 0], [0, 0, 3]])
+    assert T.from_flat_nz(elements, data, ZZ) == result
+    raises(DMBadInputError, lambda: T.from_flat_nz(elements, (indices, (2, 3)), ZZ))
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_to_dod(DM):
+    dod = {0: {0: ZZ(1), 2: ZZ(4)}, 1: {0: ZZ(4), 1: ZZ(5), 2: ZZ(6)}}
+    assert DM([[1, 0, 4], [4, 5, 6]]).to_dod() == dod
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_from_dod(DM):
+    T = type(DM([[0]]))
+    dod = {0: {0: ZZ(1), 2: ZZ(4)}, 1: {0: ZZ(4), 1: ZZ(5), 2: ZZ(6)}}
+    assert T.from_dod(dod, (2, 3), ZZ) == DM([[1, 0, 4], [4, 5, 6]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_to_dok(DM):
+    dod = {(0, 0): ZZ(1), (0, 2): ZZ(4),
+           (1, 0): ZZ(4), (1, 1): ZZ(5), (1, 2): ZZ(6)}
+    assert DM([[1, 0, 4], [4, 5, 6]]).to_dok() == dod
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_from_dok(DM):
+    T = type(DM([[0]]))
+    dod = {(0, 0): ZZ(1), (0, 2): ZZ(4),
+           (1, 0): ZZ(4), (1, 1): ZZ(5), (1, 2): ZZ(6)}
+    assert T.from_dok(dod, (2, 3), ZZ) == DM([[1, 0, 4], [4, 5, 6]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_iter_values(DM):
+    values = [ZZ(1), ZZ(4), ZZ(4), ZZ(5), ZZ(6)]
+    assert sorted(DM([[1, 0, 4], [4, 5, 6]]).iter_values()) == values
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_iter_items(DM):
+    items = [((0, 0), ZZ(1)), ((0, 2), ZZ(4)),
+             ((1, 0), ZZ(4)), ((1, 1), ZZ(5)), ((1, 2), ZZ(6))]
+    assert sorted(DM([[1, 0, 4], [4, 5, 6]]).iter_items()) == items
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_from_ddm(DM):
+    T = type(DM([[0]]))
+    ddm = DDM([[1, 2, 4], [4, 5, 6]], (2, 3), ZZ)
+    assert T.from_ddm(ddm) == DM([[1, 2, 4], [4, 5, 6]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_zeros(DM):
+    T = type(DM([[0]]))
+    assert T.zeros((2, 3), ZZ) == DM([[0, 0, 0], [0, 0, 0]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_ones(DM):
+    T = type(DM([[0]]))
+    assert T.ones((2, 3), ZZ) == DM([[1, 1, 1], [1, 1, 1]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_eye(DM):
+    T = type(DM([[0]]))
+    assert T.eye(3, ZZ) == DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+    assert T.eye((3, 2), ZZ) == DM([[1, 0], [0, 1], [0, 0]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_diag(DM):
+    T = type(DM([[0]]))
+    assert T.diag([1, 2, 3], ZZ) == DM([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_transpose(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    assert A.transpose() == DM([[1, 4], [2, 5], [3, 6]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_add(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[1, 2, 3], [4, 5, 6]])
+    C = DM([[2, 4, 6], [8, 10, 12]])
+    assert A.add(B) == C
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_sub(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[1, 2, 3], [4, 5, 6]])
+    C = DM([[0, 0, 0], [0, 0, 0]])
+    assert A.sub(B) == C
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_mul(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    b = ZZ(2)
+    assert A.mul(b) == DM([[2, 4, 6], [8, 10, 12]])
+    assert A.rmul(b) == DM([[2, 4, 6], [8, 10, 12]])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_matmul(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[1, 2], [3, 4], [5, 6]])
+    C = DM([[22, 28], [49, 64]])
+    assert A.matmul(B) == C
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_mul_elementwise(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[1, 2, 3], [4, 5, 6]])
+    C = DM([[1, 4, 9], [16, 25, 36]])
+    assert A.mul_elementwise(B) == C
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_neg(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    C = DM([[-1, -2, -3], [-4, -5, -6]])
+    assert A.neg() == C
+
+
+@pytest.mark.parametrize('DM', DM_all)
+def test_XXM_convert_to(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]], ZZ)
+    B = DM([[1, 2, 3], [4, 5, 6]], QQ)
+    assert A.convert_to(QQ) == B
+    assert B.convert_to(ZZ) == A
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_scc(DM):
+    A = DM([
+        [0, 1, 0, 0, 0, 0],
+        [1, 0, 0, 0, 0, 0],
+        [0, 0, 1, 0, 0, 0],
+        [0, 0, 0, 1, 0, 1],
+        [0, 0, 0, 0, 1, 0],
+        [0, 0, 0, 1, 0, 1]])
+    assert A.scc() == [[0, 1], [2], [3, 5], [4]]
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_hstack(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[7, 8], [9, 10]])
+    C = DM([[1, 2, 3, 7, 8], [4, 5, 6, 9, 10]])
+    ABC = DM([[1, 2, 3, 7, 8, 1, 2, 3, 7, 8],
+              [4, 5, 6, 9, 10, 4, 5, 6, 9, 10]])
+    assert A.hstack(B) == C
+    assert A.hstack(B, C) == ABC
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_vstack(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[7, 8, 9]])
+    C = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    ABC = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    assert A.vstack(B) == C
+    assert A.vstack(B, C) == ABC
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_applyfunc(DM):
+    A = DM([[1, 2, 3], [4, 5, 6]])
+    B = DM([[2, 4, 6], [8, 10, 12]])
+    assert A.applyfunc(lambda x: 2*x, ZZ) == B
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_is_upper(DM):
+    assert DM([[1, 2, 3], [0, 5, 6]]).is_upper() is True
+    assert DM([[1, 2, 3], [4, 5, 6]]).is_upper() is False
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_is_lower(DM):
+    assert DM([[1, 0, 0], [4, 5, 0]]).is_lower() is True
+    assert DM([[1, 2, 3], [4, 5, 6]]).is_lower() is False
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_is_diagonal(DM):
+    assert DM([[1, 0, 0], [0, 5, 0]]).is_diagonal() is True
+    assert DM([[1, 2, 3], [4, 5, 6]]).is_diagonal() is False
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_diagonal(DM):
+    assert DM([[1, 0, 0], [0, 5, 0]]).diagonal() == [1, 5]
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_is_zero_matrix(DM):
+    assert DM([[0, 0, 0], [0, 0, 0]]).is_zero_matrix() is True
+    assert DM([[1, 0, 0], [0, 0, 0]]).is_zero_matrix() is False
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_det_ZZ(DM):
+    assert DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).det() == 0
+    assert DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]]).det() == -3
+
+
+@pytest.mark.parametrize('DM', DMQ_all)
+def test_XXM_det_QQ(DM):
+    dM1 = DM([[(1,2), (2,3)], [(3,4), (4,5)]])
+    assert dM1.det() == QQ(-1,10)
+
+
+@pytest.mark.parametrize('DM', DMQ_all)
+def test_XXM_inv_QQ(DM):
+    dM1 = DM([[(1,2), (2,3)], [(3,4), (4,5)]])
+    dM2 = DM([[(-8,1), (20,3)], [(15,2), (-5,1)]])
+    assert dM1.inv() == dM2
+    assert dM1.matmul(dM2) == DM([[1, 0], [0, 1]])
+
+    dM3 = DM([[(1,2), (2,3)], [(1,4), (1,3)]])
+    raises(DMNonInvertibleMatrixError, lambda: dM3.inv())
+
+    dM4 = DM([[(1,2), (2,3), (3,4)], [(1,4), (1,3), (1,2)]])
+    raises(DMNonSquareMatrixError, lambda: dM4.inv())
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_inv_ZZ(DM):
+    dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
+    # XXX: Maybe this should return a DM over QQ instead?
+    # XXX: Handle unimodular matrices?
+    raises(DMDomainError, lambda: dM1.inv())
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_charpoly_ZZ(DM):
+    dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
+    assert dM1.charpoly() == [1, -16, -12, 3]
+
+
+@pytest.mark.parametrize('DM', DMQ_all)
+def test_XXM_charpoly_QQ(DM):
+    dM1 = DM([[(1,2), (2,3)], [(3,4), (4,5)]])
+    assert dM1.charpoly() == [QQ(1,1), QQ(-13,10), QQ(-1,10)]
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_lu_solve_ZZ(DM):
+    dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
+    dM2 = DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+    raises(DMDomainError, lambda: dM1.lu_solve(dM2))
+
+
+@pytest.mark.parametrize('DM', DMQ_all)
+def test_XXM_lu_solve_QQ(DM):
+    dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
+    dM2 = DM([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+    dM3 = DM([[(-2,3),(-4,3),(1,1)],[(-2,3),(11,3),(-2,1)],[(1,1),(-2,1),(1,1)]])
+    assert dM1.lu_solve(dM2) == dM3 == dM1.inv()
+
+    dM4 = DM([[1, 2, 3], [4, 5, 6]])
+    dM5 = DM([[1, 0], [0, 1], [0, 0]])
+    raises(DMShapeError, lambda: dM4.lu_solve(dM5))
+
+
+@pytest.mark.parametrize('DM', DMQ_all)
+def test_XXM_nullspace_QQ(DM):
+    dM1 = DM([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    # XXX: Change the signature to just return the nullspace. Possibly
+    # returning the rank or nullity makes sense but the list of nonpivots is
+    # not useful.
+    assert dM1.nullspace() == (DM([[1, -2, 1]]), [2])
+
+
+@pytest.mark.parametrize('DM', DMZ_all)
+def test_XXM_lll(DM):
+    M = DM([[1, 2, 3], [4, 5, 20]])
+    M_lll = DM([[1, 2, 3], [-1, -5, 5]])
+    T = DM([[1, 0], [-5, 1]])
+    assert M.lll() == M_lll
+    assert M.lll_transform() == (M_lll, T)
+    assert T.matmul(M) == M_lll
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/__init__.py b/lib/python3.11/site-packages/sympy/polys/numberfields/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..38403fdf80be22d47589a346d1b1878b982c3c93
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/__init__.py
@@ -0,0 +1,27 @@
+"""Computational algebraic field theory. """
+
+__all__ = [
+    'minpoly', 'minimal_polynomial',
+
+    'field_isomorphism', 'primitive_element', 'to_number_field',
+
+    'isolate',
+
+    'round_two',
+
+    'prime_decomp', 'prime_valuation',
+
+    'galois_group',
+]
+
+from .minpoly import minpoly, minimal_polynomial
+
+from .subfield import field_isomorphism, primitive_element, to_number_field
+
+from .utilities import isolate
+
+from .basis import round_two
+
+from .primes import prime_decomp, prime_valuation
+
+from .galoisgroups import galois_group
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/basis.py b/lib/python3.11/site-packages/sympy/polys/numberfields/basis.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c9cb41925973b3a10a80cc6ba1442cf44330971
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/basis.py
@@ -0,0 +1,246 @@
+"""Computing integral bases for number fields. """
+
+from sympy.polys.polytools import Poly
+from sympy.polys.domains.algebraicfield import AlgebraicField
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.domains.rationalfield import QQ
+from sympy.utilities.decorator import public
+from .modules import ModuleEndomorphism, ModuleHomomorphism, PowerBasis
+from .utilities import extract_fundamental_discriminant
+
+
+def _apply_Dedekind_criterion(T, p):
+    r"""
+    Apply the "Dedekind criterion" to test whether the order needs to be
+    enlarged relative to a given prime *p*.
+    """
+    x = T.gen
+    T_bar = Poly(T, modulus=p)
+    lc, fl = T_bar.factor_list()
+    assert lc == 1
+    g_bar = Poly(1, x, modulus=p)
+    for ti_bar, _ in fl:
+        g_bar *= ti_bar
+    h_bar = T_bar // g_bar
+    g = Poly(g_bar, domain=ZZ)
+    h = Poly(h_bar, domain=ZZ)
+    f = (g * h - T) // p
+    f_bar = Poly(f, modulus=p)
+    Z_bar = f_bar
+    for b in [g_bar, h_bar]:
+        Z_bar = Z_bar.gcd(b)
+    U_bar = T_bar // Z_bar
+    m = Z_bar.degree()
+    return U_bar, m
+
+
+def nilradical_mod_p(H, p, q=None):
+    r"""
+    Compute the nilradical mod *p* for a given order *H*, and prime *p*.
+
+    Explanation
+    ===========
+
+    This is the ideal $I$ in $H/pH$ consisting of all elements some positive
+    power of which is zero in this quotient ring, i.e. is a multiple of *p*.
+
+    Parameters
+    ==========
+
+    H : :py:class:`~.Submodule`
+        The given order.
+    p : int
+        The rational prime.
+    q : int, optional
+        If known, the smallest power of *p* that is $>=$ the dimension of *H*.
+        If not provided, we compute it here.
+
+    Returns
+    =======
+
+    :py:class:`~.Module` representing the nilradical mod *p* in *H*.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
+    (See Lemma 6.1.6.)
+
+    """
+    n = H.n
+    if q is None:
+        q = p
+        while q < n:
+            q *= p
+    phi = ModuleEndomorphism(H, lambda x: x**q)
+    return phi.kernel(modulus=p)
+
+
+def _second_enlargement(H, p, q):
+    r"""
+    Perform the second enlargement in the Round Two algorithm.
+    """
+    Ip = nilradical_mod_p(H, p, q=q)
+    B = H.parent.submodule_from_matrix(H.matrix * Ip.matrix, denom=H.denom)
+    C = B + p*H
+    E = C.endomorphism_ring()
+    phi = ModuleHomomorphism(H, E, lambda x: E.inner_endomorphism(x))
+    gamma = phi.kernel(modulus=p)
+    G = H.parent.submodule_from_matrix(H.matrix * gamma.matrix, denom=H.denom * p)
+    H1 = G + H
+    return H1, Ip
+
+
+@public
+def round_two(T, radicals=None):
+    r"""
+    Zassenhaus's "Round 2" algorithm.
+
+    Explanation
+    ===========
+
+    Carry out Zassenhaus's "Round 2" algorithm on an irreducible polynomial
+    *T* over :ref:`ZZ` or :ref:`QQ`. This computes an integral basis and the
+    discriminant for the field $K = \mathbb{Q}[x]/(T(x))$.
+
+    Alternatively, you may pass an :py:class:`~.AlgebraicField` instance, in
+    place of the polynomial *T*, in which case the algorithm is applied to the
+    minimal polynomial for the field's primitive element.
+
+    Ordinarily this function need not be called directly, as one can instead
+    access the :py:meth:`~.AlgebraicField.maximal_order`,
+    :py:meth:`~.AlgebraicField.integral_basis`, and
+    :py:meth:`~.AlgebraicField.discriminant` methods of an
+    :py:class:`~.AlgebraicField`.
+
+    Examples
+    ========
+
+    Working through an AlgebraicField:
+
+    >>> from sympy import Poly, QQ
+    >>> from sympy.abc import x
+    >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
+    >>> K = QQ.alg_field_from_poly(T, "theta")
+    >>> print(K.maximal_order())
+    Submodule[[2, 0, 0], [0, 2, 0], [0, 1, 1]]/2
+    >>> print(K.discriminant())
+    -503
+    >>> print(K.integral_basis(fmt='sympy'))
+    [1, theta, theta/2 + theta**2/2]
+
+    Calling directly:
+
+    >>> from sympy import Poly
+    >>> from sympy.abc import x
+    >>> from sympy.polys.numberfields.basis import round_two
+    >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
+    >>> print(round_two(T))
+    (Submodule[[2, 0, 0], [0, 2, 0], [0, 1, 1]]/2, -503)
+
+    The nilradicals mod $p$ that are sometimes computed during the Round Two
+    algorithm may be useful in further calculations. Pass a dictionary under
+    `radicals` to receive these:
+
+    >>> T = Poly(x**3 + 3*x**2 + 5)
+    >>> rad = {}
+    >>> ZK, dK = round_two(T, radicals=rad)
+    >>> print(rad)
+    {3: Submodule[[-1, 1, 0], [-1, 0, 1]]}
+
+    Parameters
+    ==========
+
+    T : :py:class:`~.Poly`, :py:class:`~.AlgebraicField`
+        Either (1) the irreducible polynomial over :ref:`ZZ` or :ref:`QQ`
+        defining the number field, or (2) an :py:class:`~.AlgebraicField`
+        representing the number field itself.
+
+    radicals : dict, optional
+        This is a way for any $p$-radicals (if computed) to be returned by
+        reference. If desired, pass an empty dictionary. If the algorithm
+        reaches the point where it computes the nilradical mod $p$ of the ring
+        of integers $Z_K$, then an $\mathbb{F}_p$-basis for this ideal will be
+        stored in this dictionary under the key ``p``. This can be useful for
+        other algorithms, such as prime decomposition.
+
+    Returns
+    =======
+
+    Pair ``(ZK, dK)``, where:
+
+        ``ZK`` is a :py:class:`~sympy.polys.numberfields.modules.Submodule`
+        representing the maximal order.
+
+        ``dK`` is the discriminant of the field $K = \mathbb{Q}[x]/(T(x))$.
+
+    See Also
+    ========
+
+    .AlgebraicField.maximal_order
+    .AlgebraicField.integral_basis
+    .AlgebraicField.discriminant
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+
+    """
+    K = None
+    if isinstance(T, AlgebraicField):
+        K, T = T, T.ext.minpoly_of_element()
+    if (   not T.is_univariate
+        or not T.is_irreducible
+        or T.domain not in [ZZ, QQ]):
+        raise ValueError('Round 2 requires an irreducible univariate polynomial over ZZ or QQ.')
+    T, _ = T.make_monic_over_integers_by_scaling_roots()
+    n = T.degree()
+    D = T.discriminant()
+    D_modulus = ZZ.from_sympy(abs(D))
+    # D must be 0 or 1 mod 4 (see Cohen Sec 4.4), which ensures we can write
+    # it in the form D = D_0 * F**2, where D_0 is 1 or a fundamental discriminant.
+    _, F = extract_fundamental_discriminant(D)
+    Ztheta = PowerBasis(K or T)
+    H = Ztheta.whole_submodule()
+    nilrad = None
+    while F:
+        # Next prime:
+        p, e = F.popitem()
+        U_bar, m = _apply_Dedekind_criterion(T, p)
+        if m == 0:
+            continue
+        # For a given prime p, the first enlargement of the order spanned by
+        # the current basis can be done in a simple way:
+        U = Ztheta.element_from_poly(Poly(U_bar, domain=ZZ))
+        # TODO:
+        #  Theory says only first m columns of the U//p*H term below are needed.
+        #  Could be slightly more efficient to use only those. Maybe `Submodule`
+        #  class should support a slice operator?
+        H = H.add(U // p * H, hnf_modulus=D_modulus)
+        if e <= m:
+            continue
+        # A second, and possibly more, enlargements for p will be needed.
+        # These enlargements require a more involved procedure.
+        q = p
+        while q < n:
+            q *= p
+        H1, nilrad = _second_enlargement(H, p, q)
+        while H1 != H:
+            H = H1
+            H1, nilrad = _second_enlargement(H, p, q)
+    # Note: We do not store all nilradicals mod p, only the very last. This is
+    # because, unless computed against the entire integral basis, it might not
+    # be accurate. (In other words, if H was not already equal to ZK when we
+    # passed it to `_second_enlargement`, then we can't trust the nilradical
+    # so computed.) Example: if T(x) = x ** 3 + 15 * x ** 2 - 9 * x + 13, then
+    # F is divisible by 2, 3, and 7, and the nilradical mod 2 as computed above
+    # will not be accurate for the full, maximal order ZK.
+    if nilrad is not None and isinstance(radicals, dict):
+        radicals[p] = nilrad
+    ZK = H
+    # Pre-set expensive boolean properties which we already know to be true:
+    ZK._starts_with_unity = True
+    ZK._is_sq_maxrank_HNF = True
+    dK = (D * ZK.matrix.det() ** 2) // ZK.denom ** (2 * n)
+    return ZK, dK
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/exceptions.py b/lib/python3.11/site-packages/sympy/polys/numberfields/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e0d1ddc23c39295626fa036cf34974f50e4f53a
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/exceptions.py
@@ -0,0 +1,54 @@
+"""Special exception classes for numberfields. """
+
+
+class ClosureFailure(Exception):
+    r"""
+    Signals that a :py:class:`ModuleElement` which we tried to represent in a
+    certain :py:class:`Module` cannot in fact be represented there.
+
+    Examples
+    ========
+
+    >>> from sympy.polys import Poly, cyclotomic_poly, ZZ
+    >>> from sympy.polys.matrices import DomainMatrix
+    >>> from sympy.polys.numberfields.modules import PowerBasis, to_col
+    >>> T = Poly(cyclotomic_poly(5))
+    >>> A = PowerBasis(T)
+    >>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
+
+    Because we are in a cyclotomic field, the power basis ``A`` is an integral
+    basis, and the submodule ``B`` is just the ideal $(2)$. Therefore ``B`` can
+    represent an element having all even coefficients over the power basis:
+
+    >>> a1 = A(to_col([2, 4, 6, 8]))
+    >>> print(B.represent(a1))
+    DomainMatrix([[1], [2], [3], [4]], (4, 1), ZZ)
+
+    but ``B`` cannot represent an element with an odd coefficient:
+
+    >>> a2 = A(to_col([1, 2, 2, 2]))
+    >>> B.represent(a2)
+    Traceback (most recent call last):
+    ...
+    ClosureFailure: Element in QQ-span but not ZZ-span of this basis.
+
+    """
+    pass
+
+
+class StructureError(Exception):
+    r"""
+    Represents cases in which an algebraic structure was expected to have a
+    certain property, or be of a certain type, but was not.
+    """
+    pass
+
+
+class MissingUnityError(StructureError):
+    r"""Structure should contain a unity element but does not."""
+    pass
+
+
+__all__ = [
+    'ClosureFailure', 'StructureError', 'MissingUnityError',
+]
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/galois_resolvents.py b/lib/python3.11/site-packages/sympy/polys/numberfields/galois_resolvents.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d73b56870a498f09102787da3517e7520edb3db
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/galois_resolvents.py
@@ -0,0 +1,676 @@
+r"""
+Galois resolvents
+
+Each of the functions in ``sympy.polys.numberfields.galoisgroups`` that
+computes Galois groups for a particular degree $n$ uses resolvents. Given the
+polynomial $T$ whose Galois group is to be computed, a resolvent is a
+polynomial $R$ whose roots are defined as functions of the roots of $T$.
+
+One way to compute the coefficients of $R$ is by approximating the roots of $T$
+to sufficient precision. This module defines a :py:class:`~.Resolvent` class
+that handles this job, determining the necessary precision, and computing $R$.
+
+In some cases, the coefficients of $R$ are symmetric in the roots of $T$,
+meaning they are equal to fixed functions of the coefficients of $T$. Therefore
+another approach is to compute these functions once and for all, and record
+them in a lookup table. This module defines code that can compute such tables.
+The tables for polynomials $T$ of degrees 4 through 6, produced by this code,
+are recorded in the resolvent_lookup.py module.
+
+"""
+
+from sympy.core.evalf import (
+    evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath,
+)
+from sympy.core.symbol import symbols, Dummy
+from sympy.polys.densetools import dup_eval
+from sympy.polys.domains import ZZ
+from sympy.polys.orderings import lex
+from sympy.polys.polyroots import preprocess_roots
+from sympy.polys.polytools import Poly
+from sympy.polys.rings import xring
+from sympy.polys.specialpolys import symmetric_poly
+from sympy.utilities.lambdify import lambdify
+
+from mpmath import MPContext
+from mpmath.libmp.libmpf import prec_to_dps
+
+
+class GaloisGroupException(Exception):
+    ...
+
+
+class ResolventException(GaloisGroupException):
+    ...
+
+
+class Resolvent:
+    r"""
+    If $G$ is a subgroup of the symmetric group $S_n$,
+    $F$ a multivariate polynomial in $\mathbb{Z}[X_1, \ldots, X_n]$,
+    $H$ the stabilizer of $F$ in $G$ (i.e. the permutations $\sigma$ such that
+    $F(X_{\sigma(1)}, \ldots, X_{\sigma(n)}) = F(X_1, \ldots, X_n)$), and $s$
+    a set of left coset representatives of $H$ in $G$, then the resolvent
+    polynomial $R(Y)$ is the product over $\sigma \in s$ of
+    $Y - F(X_{\sigma(1)}, \ldots, X_{\sigma(n)})$.
+
+    For example, consider the resolvent for the form
+    $$F = X_0 X_2 + X_1 X_3$$
+    and the group $G = S_4$. In this case, the stabilizer $H$ is the dihedral
+    group $D4 = < (0123), (02) >$, and a set of representatives of $G/H$ is
+    $\{I, (01), (03)\}$. The resolvent can be constructed as follows:
+
+    >>> from sympy.combinatorics.permutations import Permutation
+    >>> from sympy.core.symbol import symbols
+    >>> from sympy.polys.numberfields.galoisgroups import Resolvent
+    >>> X = symbols('X0 X1 X2 X3')
+    >>> F = X[0]*X[2] + X[1]*X[3]
+    >>> s = [Permutation([0, 1, 2, 3]), Permutation([1, 0, 2, 3]),
+    ... Permutation([3, 1, 2, 0])]
+    >>> R = Resolvent(F, X, s)
+
+    This resolvent has three roots, which are the conjugates of ``F`` under the
+    three permutations in ``s``:
+
+    >>> R.root_lambdas[0](*X)
+    X0*X2 + X1*X3
+    >>> R.root_lambdas[1](*X)
+    X0*X3 + X1*X2
+    >>> R.root_lambdas[2](*X)
+    X0*X1 + X2*X3
+
+    Resolvents are useful for computing Galois groups. Given a polynomial $T$
+    of degree $n$, we will use a resolvent $R$ where $Gal(T) \leq G \leq S_n$.
+    We will then want to substitute the roots of $T$ for the variables $X_i$
+    in $R$, and study things like the discriminant of $R$, and the way $R$
+    factors over $\mathbb{Q}$.
+
+    From the symmetry in $R$'s construction, and since $Gal(T) \leq G$, we know
+    from Galois theory that the coefficients of $R$ must lie in $\mathbb{Z}$.
+    This allows us to compute the coefficients of $R$ by approximating the
+    roots of $T$ to sufficient precision, plugging these values in for the
+    variables $X_i$ in the coefficient expressions of $R$, and then simply
+    rounding to the nearest integer.
+
+    In order to determine a sufficient precision for the roots of $T$, this
+    ``Resolvent`` class imposes certain requirements on the form ``F``. It
+    could be possible to design a different ``Resolvent`` class, that made
+    different precision estimates, and different assumptions about ``F``.
+
+    ``F`` must be homogeneous, and all terms must have unit coefficient.
+    Furthermore, if $r$ is the number of terms in ``F``, and $t$ the total
+    degree, and if $m$ is the number of conjugates of ``F``, i.e. the number
+    of permutations in ``s``, then we require that $m < r 2^t$. Again, it is
+    not impossible to work with forms ``F`` that violate these assumptions, but
+    this ``Resolvent`` class requires them.
+
+    Since determining the integer coefficients of the resolvent for a given
+    polynomial $T$ is one of the main problems this class solves, we take some
+    time to explain the precision bounds it uses.
+
+    The general problem is:
+    Given a multivariate polynomial $P \in \mathbb{Z}[X_1, \ldots, X_n]$, and a
+    bound $M \in \mathbb{R}_+$, compute an $\varepsilon > 0$ such that for any
+    complex numbers $a_1, \ldots, a_n$ with $|a_i| < M$, if the $a_i$ are
+    approximated to within an accuracy of $\varepsilon$ by $b_i$, that is,
+    $|a_i - b_i| < \varepsilon$ for $i = 1, \ldots, n$, then
+    $|P(a_1, \ldots, a_n) - P(b_1, \ldots, b_n)| < 1/2$. In other words, if it
+    is known that $P(a_1, \ldots, a_n) = c$ for some $c \in \mathbb{Z}$, then
+    $P(b_1, \ldots, b_n)$ can be rounded to the nearest integer in order to
+    determine $c$.
+
+    To derive our error bound, consider the monomial $xyz$. Defining
+    $d_i = b_i - a_i$, our error is
+    $|(a_1 + d_1)(a_2 + d_2)(a_3 + d_3) - a_1 a_2 a_3|$, which is bounded
+    above by $|(M + \varepsilon)^3 - M^3|$. Passing to a general monomial of
+    total degree $t$, this expression is bounded by
+    $M^{t-1}\varepsilon(t + 2^t\varepsilon/M)$ provided $\varepsilon < M$,
+    and by $(t+1)M^{t-1}\varepsilon$ provided $\varepsilon < M/2^t$.
+    But since our goal is to make the error less than $1/2$, we will choose
+    $\varepsilon < 1/(2(t+1)M^{t-1})$, which implies the condition that
+    $\varepsilon < M/2^t$, as long as $M \geq 2$.
+
+    Passing from the general monomial to the general polynomial is easy, by
+    scaling and summing error bounds.
+
+    In our specific case, we are given a homogeneous polynomial $F$ of
+    $r$ terms and total degree $t$, all of whose coefficients are $\pm 1$. We
+    are given the $m$ permutations that make the conjugates of $F$, and
+    we want to bound the error in the coefficients of the monic polynomial
+    $R(Y)$ having $F$ and its conjugates as roots (i.e. the resolvent).
+
+    For $j$ from $1$ to $m$, the coefficient of $Y^{m-j}$ in $R(Y)$ is the
+    $j$th elementary symmetric polynomial in the conjugates of $F$. This sums
+    the products of these conjugates, taken $j$ at a time, in all possible
+    combinations. There are $\binom{m}{j}$ such combinations, and each product
+    of $j$ conjugates of $F$ expands to a sum of $r^j$ terms, each of unit
+    coefficient, and total degree $jt$. An error bound for the $j$th coeff of
+    $R$ is therefore
+    $$\binom{m}{j} r^j (jt + 1) M^{jt - 1} \varepsilon$$
+    When our goal is to evaluate all the coefficients of $R$, we will want to
+    use the maximum of these error bounds. It is clear that this bound is
+    strictly increasing for $j$ up to the ceiling of $m/2$. After that point,
+    the first factor $\binom{m}{j}$ begins to decrease, while the others
+    continue to increase. However, the binomial coefficient never falls by more
+    than a factor of $1/m$ at a time, so our assumptions that $M \geq 2$ and
+    $m < r 2^t$ are enough to tell us that the constant coefficient of $R$,
+    i.e. that where $j = m$, has the largest error bound. Therefore we can use
+    $$r^m (mt + 1) M^{mt - 1} \varepsilon$$
+    as our error bound for all the coefficients.
+
+    Note that this bound is also (more than) adequate to determine whether any
+    of the roots of $R$ is an integer. Each of these roots is a single
+    conjugate of $F$, which contains less error than the trace, i.e. the
+    coefficient of $Y^{m - 1}$. By rounding the roots of $R$ to the nearest
+    integers, we therefore get all the candidates for integer roots of $R$. By
+    plugging these candidates into $R$, we can check whether any of them
+    actually is a root.
+
+    Note: We take the definition of resolvent from Cohen, but the error bound
+    is ours.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
+       (Def 6.3.2)
+
+    """
+
+    def __init__(self, F, X, s):
+        r"""
+        Parameters
+        ==========
+
+        F : :py:class:`~.Expr`
+            polynomial in the symbols in *X*
+        X : list of :py:class:`~.Symbol`
+        s : list of :py:class:`~.Permutation`
+            representing the cosets of the stabilizer of *F* in
+            some subgroup $G$ of $S_n$, where $n$ is the length of *X*.
+        """
+        self.F = F
+        self.X = X
+        self.s = s
+
+        # Number of conjugates:
+        self.m = len(s)
+        # Total degree of F (computed below):
+        self.t = None
+        # Number of terms in F (computed below):
+        self.r = 0
+
+        for monom, coeff in Poly(F).terms():
+            if abs(coeff) != 1:
+                raise ResolventException('Resolvent class expects forms with unit coeffs')
+            t = sum(monom)
+            if t != self.t and self.t is not None:
+                raise ResolventException('Resolvent class expects homogeneous forms')
+            self.t = t
+            self.r += 1
+
+        m, t, r = self.m, self.t, self.r
+        if not m < r * 2**t:
+            raise ResolventException('Resolvent class expects m < r*2^t')
+        M = symbols('M')
+        # Precision sufficient for computing the coeffs of the resolvent:
+        self.coeff_prec_func = Poly(r**m*(m*t + 1)*M**(m*t - 1))
+        # Precision sufficient for checking whether any of the roots of the
+        # resolvent are integers:
+        self.root_prec_func = Poly(r*(t + 1)*M**(t - 1))
+
+        # The conjugates of F are the roots of the resolvent.
+        # For evaluating these to required numerical precisions, we need
+        # lambdified versions.
+        # Note: for a given permutation sigma, the conjugate (sigma F) is
+        # equivalent to lambda [sigma^(-1) X]: F.
+        self.root_lambdas = [
+            lambdify((~s[j])(X), F)
+            for j in range(self.m)
+        ]
+
+        # For evaluating the coeffs, we'll also need lambdified versions of
+        # the elementary symmetric functions for degree m.
+        Y = symbols('Y')
+        R = symbols(' '.join(f'R{i}' for i in range(m)))
+        f = 1
+        for r in R:
+            f *= (Y - r)
+        C = Poly(f, Y).coeffs()
+        self.esf_lambdas = [lambdify(R, c) for c in C]
+
+    def get_prec(self, M, target='coeffs'):
+        r"""
+        For a given upper bound *M* on the magnitude of the complex numbers to
+        be plugged in for this resolvent's symbols, compute a sufficient
+        precision for evaluating those complex numbers, such that the
+        coefficients, or the integer roots, of the resolvent can be determined.
+
+        Parameters
+        ==========
+
+        M : real number
+            Upper bound on magnitude of the complex numbers to be plugged in.
+
+        target : str, 'coeffs' or 'roots', default='coeffs'
+            Name the task for which a sufficient precision is desired.
+            This is either determining the coefficients of the resolvent
+            ('coeffs') or determining its possible integer roots ('roots').
+            The latter may require significantly lower precision.
+
+        Returns
+        =======
+
+        int $m$
+            such that $2^{-m}$ is a sufficient upper bound on the
+            error in approximating the complex numbers to be plugged in.
+
+        """
+        # As explained in the docstring for this class, our precision estimates
+        # require that M be at least 2.
+        M = max(M, 2)
+        f = self.coeff_prec_func if target == 'coeffs' else self.root_prec_func
+        r, _, _, _ = evalf(2*f(M), 1, {})
+        return fastlog(r) + 1
+
+    def approximate_roots_of_poly(self, T, target='coeffs'):
+        """
+        Approximate the roots of a given polynomial *T* to sufficient precision
+        in order to evaluate this resolvent's coefficients, or determine
+        whether the resolvent has an integer root.
+
+        Parameters
+        ==========
+
+        T : :py:class:`~.Poly`
+
+        target : str, 'coeffs' or 'roots', default='coeffs'
+            Set the approximation precision to be sufficient for the desired
+            task, which is either determining the coefficients of the resolvent
+            ('coeffs') or determining its possible integer roots ('roots').
+            The latter may require significantly lower precision.
+
+        Returns
+        =======
+
+        list of elements of :ref:`CC`
+
+        """
+        ctx = MPContext()
+        # Because sympy.polys.polyroots._integer_basis() is called when a CRootOf
+        # is formed, we proactively extract the integer basis now. This means that
+        # when we call T.all_roots(), every root will be a CRootOf, not a Mul
+        # of Integer*CRootOf.
+        coeff, T = preprocess_roots(T)
+        coeff = ctx.mpf(str(coeff))
+
+        scaled_roots = T.all_roots(radicals=False)
+
+        # Since we're going to be approximating the roots of T anyway, we can
+        # get a good upper bound on the magnitude of the roots by starting with
+        # a very low precision approx.
+        approx0 = [coeff * quad_to_mpmath(_evalf_with_bounded_error(r, m=0)) for r in scaled_roots]
+        # Here we add 1 to account for the possible error in our initial approximation.
+        M = max(abs(b) for b in approx0) + 1
+        m = self.get_prec(M, target=target)
+        n = fastlog(M._mpf_) + 1
+        p = m + n + 1
+        ctx.prec = p
+        d = prec_to_dps(p)
+
+        approx1 = [r.eval_approx(d, return_mpmath=True) for r in scaled_roots]
+        approx1 = [coeff*ctx.mpc(r) for r in approx1]
+
+        return approx1
+
+    @staticmethod
+    def round_mpf(a):
+        if isinstance(a, int):
+            return a
+        # If we use python's built-in `round()`, we lose precision.
+        # If we use `ZZ` directly, we may add or subtract 1.
+        #
+        # XXX: We have to convert to int before converting to ZZ because
+        # flint.fmpz cannot convert a mpmath mpf.
+        return ZZ(int(a.context.nint(a)))
+
+    def round_roots_to_integers_for_poly(self, T):
+        """
+        For a given polynomial *T*, round the roots of this resolvent to the
+        nearest integers.
+
+        Explanation
+        ===========
+
+        None of the integers returned by this method is guaranteed to be a
+        root of the resolvent; however, if the resolvent has any integer roots
+        (for the given polynomial *T*), then they must be among these.
+
+        If the coefficients of the resolvent are also desired, then this method
+        should not be used. Instead, use the ``eval_for_poly`` method. This
+        method may be significantly faster than ``eval_for_poly``.
+
+        Parameters
+        ==========
+
+        T : :py:class:`~.Poly`
+
+        Returns
+        =======
+
+        dict
+            Keys are the indices of those permutations in ``self.s`` such that
+            the corresponding root did round to a rational integer.
+
+            Values are :ref:`ZZ`.
+
+
+        """
+        approx_roots_of_T = self.approximate_roots_of_poly(T, target='roots')
+        approx_roots_of_self = [r(*approx_roots_of_T) for r in self.root_lambdas]
+        return {
+            i: self.round_mpf(r.real)
+            for i, r in enumerate(approx_roots_of_self)
+            if self.round_mpf(r.imag) == 0
+        }
+
+    def eval_for_poly(self, T, find_integer_root=False):
+        r"""
+        Compute the integer values of the coefficients of this resolvent, when
+        plugging in the roots of a given polynomial.
+
+        Parameters
+        ==========
+
+        T : :py:class:`~.Poly`
+
+        find_integer_root : ``bool``, default ``False``
+            If ``True``, then also determine whether the resolvent has an
+            integer root, and return the first one found, along with its
+            index, i.e. the index of the permutation ``self.s[i]`` it
+            corresponds to.
+
+        Returns
+        =======
+
+        Tuple ``(R, a, i)``
+
+            ``R`` is this resolvent as a dense univariate polynomial over
+            :ref:`ZZ`, i.e. a list of :ref:`ZZ`.
+
+            If *find_integer_root* was ``True``, then ``a`` and ``i`` are the
+            first integer root found, and its index, if one exists.
+            Otherwise ``a`` and ``i`` are both ``None``.
+
+        """
+        approx_roots_of_T = self.approximate_roots_of_poly(T, target='coeffs')
+        approx_roots_of_self = [r(*approx_roots_of_T) for r in self.root_lambdas]
+        approx_coeffs_of_self = [c(*approx_roots_of_self) for c in self.esf_lambdas]
+
+        R = []
+        for c in approx_coeffs_of_self:
+            if self.round_mpf(c.imag) != 0:
+                # If precision was enough, this should never happen.
+                raise ResolventException(f"Got non-integer coeff for resolvent: {c}")
+            R.append(self.round_mpf(c.real))
+
+        a0, i0 = None, None
+
+        if find_integer_root:
+            for i, r in enumerate(approx_roots_of_self):
+                if self.round_mpf(r.imag) != 0:
+                    continue
+                if not dup_eval(R, (a := self.round_mpf(r.real)), ZZ):
+                    a0, i0 = a, i
+                    break
+
+        return R, a0, i0
+
+
+def wrap(text, width=80):
+    """Line wrap a polynomial expression. """
+    out = ''
+    col = 0
+    for c in text:
+        if c == ' ' and col > width:
+            c, col = '\n', 0
+        else:
+            col += 1
+        out += c
+    return out
+
+
+def s_vars(n):
+    """Form the symbols s1, s2, ..., sn to stand for elem. symm. polys. """
+    return symbols([f's{i + 1}' for i in range(n)])
+
+
+def sparse_symmetrize_resolvent_coeffs(F, X, s, verbose=False):
+    """
+    Compute the coefficients of a resolvent as functions of the coefficients of
+    the associated polynomial.
+
+    F must be a sparse polynomial.
+    """
+    import time, sys
+    # Roots of resolvent as multivariate forms over vars X:
+    root_forms = [
+        F.compose(list(zip(X, sigma(X))))
+        for sigma in s
+    ]
+
+    # Coeffs of resolvent (besides lead coeff of 1) as symmetric forms over vars X:
+    Y = [Dummy(f'Y{i}') for i in range(len(s))]
+    coeff_forms = []
+    for i in range(1, len(s) + 1):
+        if verbose:
+            print('----')
+            print(f'Computing symmetric poly of degree {i}...')
+            sys.stdout.flush()
+        t0 = time.time()
+        G = symmetric_poly(i, *Y)
+        t1 = time.time()
+        if verbose:
+            print(f'took {t1 - t0} seconds')
+            print('lambdifying...')
+            sys.stdout.flush()
+        t0 = time.time()
+        C = lambdify(Y, (-1)**i*G)
+        t1 = time.time()
+        if verbose:
+            print(f'took {t1 - t0} seconds')
+            sys.stdout.flush()
+        coeff_forms.append(C)
+
+    coeffs = []
+    for i, f in enumerate(coeff_forms):
+        if verbose:
+            print('----')
+            print(f'Plugging root forms into elem symm poly {i+1}...')
+            sys.stdout.flush()
+        t0 = time.time()
+        g = f(*root_forms)
+        t1 = time.time()
+        coeffs.append(g)
+        if verbose:
+            print(f'took {t1 - t0} seconds')
+            sys.stdout.flush()
+
+    # Now symmetrize these coeffs. This means recasting them as polynomials in
+    # the elementary symmetric polys over X.
+    symmetrized = []
+    symmetrization_times = []
+    ss = s_vars(len(X))
+    for i, A in list(enumerate(coeffs)):
+        if verbose:
+            print('-----')
+            print(f'Coeff {i+1}...')
+            sys.stdout.flush()
+        t0 = time.time()
+        B, rem, _ = A.symmetrize()
+        t1 = time.time()
+        if rem != 0:
+            msg = f"Got nonzero remainder {rem} for resolvent (F, X, s) = ({F}, {X}, {s})"
+            raise ResolventException(msg)
+        B_str = str(B.as_expr(*ss))
+        symmetrized.append(B_str)
+        symmetrization_times.append(t1 - t0)
+        if verbose:
+            print(wrap(B_str))
+            print(f'took {t1 - t0} seconds')
+            sys.stdout.flush()
+
+    return symmetrized, symmetrization_times
+
+
+def define_resolvents():
+    """Define all the resolvents for polys T of degree 4 through 6. """
+    from sympy.combinatorics.galois import PGL2F5
+    from sympy.combinatorics.permutations import Permutation
+
+    R4, X4 = xring("X0,X1,X2,X3", ZZ, lex)
+    X = X4
+
+    # The one resolvent used in `_galois_group_degree_4_lookup()`:
+    F40 = X[0]*X[1]**2 + X[1]*X[2]**2 + X[2]*X[3]**2 + X[3]*X[0]**2
+    s40 = [
+        Permutation(3),
+        Permutation(3)(0, 1),
+        Permutation(3)(0, 2),
+        Permutation(3)(0, 3),
+        Permutation(3)(1, 2),
+        Permutation(3)(2, 3),
+    ]
+
+    # First resolvent used in `_galois_group_degree_4_root_approx()`:
+    F41 = X[0]*X[2] + X[1]*X[3]
+    s41 = [
+        Permutation(3),
+        Permutation(3)(0, 1),
+        Permutation(3)(0, 3)
+    ]
+
+    R5, X5 = xring("X0,X1,X2,X3,X4", ZZ, lex)
+    X = X5
+
+    # First resolvent used in `_galois_group_degree_5_hybrid()`,
+    # and only one used in `_galois_group_degree_5_lookup_ext_factor()`:
+    F51 = (  X[0]**2*(X[1]*X[4] + X[2]*X[3])
+           + X[1]**2*(X[2]*X[0] + X[3]*X[4])
+           + X[2]**2*(X[3]*X[1] + X[4]*X[0])
+           + X[3]**2*(X[4]*X[2] + X[0]*X[1])
+           + X[4]**2*(X[0]*X[3] + X[1]*X[2]))
+    s51 = [
+        Permutation(4),
+        Permutation(4)(0, 1),
+        Permutation(4)(0, 2),
+        Permutation(4)(0, 3),
+        Permutation(4)(0, 4),
+        Permutation(4)(1, 4)
+    ]
+
+    R6, X6 = xring("X0,X1,X2,X3,X4,X5", ZZ, lex)
+    X = X6
+
+    # First resolvent used in `_galois_group_degree_6_lookup()`:
+    H = PGL2F5()
+    term0 = X[0]**2*X[5]**2*(X[1]*X[4] + X[2]*X[3])
+    terms = {term0.compose(list(zip(X, s(X)))) for s in H.elements}
+    F61 = sum(terms)
+    s61 = [Permutation(5)] + [Permutation(5)(0, n) for n in range(1, 6)]
+
+    # Second resolvent used in `_galois_group_degree_6_lookup()`:
+    F62 = X[0]*X[1]*X[2] + X[3]*X[4]*X[5]
+    s62 = [Permutation(5)] + [
+        Permutation(5)(i, j + 3) for i in range(3) for j in range(3)
+    ]
+
+    return {
+        (4, 0): (F40, X4, s40),
+        (4, 1): (F41, X4, s41),
+        (5, 1): (F51, X5, s51),
+        (6, 1): (F61, X6, s61),
+        (6, 2): (F62, X6, s62),
+    }
+
+
+def generate_lambda_lookup(verbose=False, trial_run=False):
+    """
+    Generate the whole lookup table of coeff lambdas, for all resolvents.
+    """
+    jobs = define_resolvents()
+    lambda_lists = {}
+    total_time = 0
+    time_for_61 = 0
+    time_for_61_last = 0
+    for k, (F, X, s) in jobs.items():
+        symmetrized, times = sparse_symmetrize_resolvent_coeffs(F, X, s, verbose=verbose)
+
+        total_time += sum(times)
+        if k == (6, 1):
+            time_for_61 = sum(times)
+            time_for_61_last = times[-1]
+
+        sv = s_vars(len(X))
+        head = f'lambda {", ".join(str(v) for v in sv)}:'
+        lambda_lists[k] = ',\n        '.join([
+            f'{head} ({wrap(f)})'
+            for f in symmetrized
+        ])
+
+        if trial_run:
+            break
+
+    table = (
+         "# This table was generated by a call to\n"
+         "# `sympy.polys.numberfields.galois_resolvents.generate_lambda_lookup()`.\n"
+        f"# The entire job took {total_time:.2f}s.\n"
+        f"# Of this, Case (6, 1) took {time_for_61:.2f}s.\n"
+        f"# The final polynomial of Case (6, 1) alone took {time_for_61_last:.2f}s.\n"
+         "resolvent_coeff_lambdas = {\n")
+
+    for k, L in lambda_lists.items():
+        table += f"    {k}: [\n"
+        table +=  "        " + L + '\n'
+        table +=  "    ],\n"
+    table += "}\n"
+    return table
+
+
+def get_resolvent_by_lookup(T, number):
+    """
+    Use the lookup table, to return a resolvent (as dup) for a given
+    polynomial *T*.
+
+    Parameters
+    ==========
+
+    T : Poly
+        The polynomial whose resolvent is needed
+
+    number : int
+        For some degrees, there are multiple resolvents.
+        Use this to indicate which one you want.
+
+    Returns
+    =======
+
+    dup
+
+    """
+    from sympy.polys.numberfields.resolvent_lookup import resolvent_coeff_lambdas
+    degree = T.degree()
+    L = resolvent_coeff_lambdas[(degree, number)]
+    T_coeffs = T.rep.to_list()[1:]
+    return [ZZ(1)] + [c(*T_coeffs) for c in L]
+
+
+# Use
+#   (.venv) $ python -m sympy.polys.numberfields.galois_resolvents
+# to reproduce the table found in resolvent_lookup.py
+if __name__ == "__main__":
+    import sys
+    verbose = '-v' in sys.argv[1:]
+    trial_run = '-t' in sys.argv[1:]
+    table = generate_lambda_lookup(verbose=verbose, trial_run=trial_run)
+    print(table)
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/galoisgroups.py b/lib/python3.11/site-packages/sympy/polys/numberfields/galoisgroups.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0e424bf7554c0cedd926902e7322b9640735a8b
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/galoisgroups.py
@@ -0,0 +1,623 @@
+"""
+Compute Galois groups of polynomials.
+
+We use algorithms from [1], with some modifications to use lookup tables for
+resolvents.
+
+References
+==========
+
+.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
+
+"""
+
+from collections import defaultdict
+import random
+
+from sympy.core.symbol import Dummy, symbols
+from sympy.ntheory.primetest import is_square
+from sympy.polys.domains import ZZ
+from sympy.polys.densebasic import dup_random
+from sympy.polys.densetools import dup_eval
+from sympy.polys.euclidtools import dup_discriminant
+from sympy.polys.factortools import dup_factor_list, dup_irreducible_p
+from sympy.polys.numberfields.galois_resolvents import (
+    GaloisGroupException, get_resolvent_by_lookup, define_resolvents,
+    Resolvent,
+)
+from sympy.polys.numberfields.utilities import coeff_search
+from sympy.polys.polytools import (Poly, poly_from_expr,
+                                   PolificationFailed, ComputationFailed)
+from sympy.polys.sqfreetools import dup_sqf_p
+from sympy.utilities import public
+
+
+class MaxTriesException(GaloisGroupException):
+    ...
+
+
+def tschirnhausen_transformation(T, max_coeff=10, max_tries=30, history=None,
+                                 fixed_order=True):
+    r"""
+    Given a univariate, monic, irreducible polynomial over the integers, find
+    another such polynomial defining the same number field.
+
+    Explanation
+    ===========
+
+    See Alg 6.3.4 of [1].
+
+    Parameters
+    ==========
+
+    T : Poly
+        The given polynomial
+    max_coeff : int
+        When choosing a transformation as part of the process,
+        keep the coeffs between plus and minus this.
+    max_tries : int
+        Consider at most this many transformations.
+    history : set, None, optional (default=None)
+        Pass a set of ``Poly.rep``'s in order to prevent any of these
+        polynomials from being returned as the polynomial ``U`` i.e. the
+        transformation of the given polynomial *T*. The given poly *T* will
+        automatically be added to this set, before we try to find a new one.
+    fixed_order : bool, default True
+        If ``True``, work through candidate transformations A(x) in a fixed
+        order, from small coeffs to large, resulting in deterministic behavior.
+        If ``False``, the A(x) are chosen randomly, while still working our way
+        up from small coefficients to larger ones.
+
+    Returns
+    =======
+
+    Pair ``(A, U)``
+
+        ``A`` and ``U`` are ``Poly``, ``A`` is the
+        transformation, and ``U`` is the transformed polynomial that defines
+        the same number field as *T*. The polynomial ``A`` maps the roots of
+        *T* to the roots of ``U``.
+
+    Raises
+    ======
+
+    MaxTriesException
+        if could not find a polynomial before exceeding *max_tries*.
+
+    """
+    X = Dummy('X')
+    n = T.degree()
+    if history is None:
+        history = set()
+    history.add(T.rep)
+
+    if fixed_order:
+        coeff_generators = {}
+        deg_coeff_sum = 3
+        current_degree = 2
+
+    def get_coeff_generator(degree):
+        gen = coeff_generators.get(degree, coeff_search(degree, 1))
+        coeff_generators[degree] = gen
+        return gen
+
+    for i in range(max_tries):
+
+        # We never use linear A(x), since applying a fixed linear transformation
+        # to all roots will only multiply the discriminant of T by a square
+        # integer. This will change nothing important. In particular, if disc(T)
+        # was zero before, it will still be zero now, and typically we apply
+        # the transformation in hopes of replacing T by a squarefree poly.
+
+        if fixed_order:
+            # If d is degree and c max coeff, we move through the dc-space
+            # along lines of constant sum. First d + c = 3 with (d, c) = (2, 1).
+            # Then d + c = 4 with (d, c) = (3, 1), (2, 2). Then d + c = 5 with
+            # (d, c) = (4, 1), (3, 2), (2, 3), and so forth. For a given (d, c)
+            # we go though all sets of coeffs where max = c, before moving on.
+            gen = get_coeff_generator(current_degree)
+            coeffs = next(gen)
+            m = max(abs(c) for c in coeffs)
+            if current_degree + m > deg_coeff_sum:
+                if current_degree == 2:
+                    deg_coeff_sum += 1
+                    current_degree = deg_coeff_sum - 1
+                else:
+                    current_degree -= 1
+                gen = get_coeff_generator(current_degree)
+                coeffs = next(gen)
+            a = [ZZ(1)] + [ZZ(c) for c in coeffs]
+
+        else:
+            # We use a progressive coeff bound, up to the max specified, since it
+            # is preferable to succeed with smaller coeffs.
+            # Give each coeff bound five tries, before incrementing.
+            C = min(i//5 + 1, max_coeff)
+            d = random.randint(2, n - 1)
+            a = dup_random(d, -C, C, ZZ)
+
+        A = Poly(a, T.gen)
+        U = Poly(T.resultant(X - A), X)
+        if U.rep not in history and dup_sqf_p(U.rep.to_list(), ZZ):
+            return A, U
+    raise MaxTriesException
+
+
+def has_square_disc(T):
+    """Convenience to check if a Poly or dup has square discriminant. """
+    d = T.discriminant() if isinstance(T, Poly) else dup_discriminant(T, ZZ)
+    return is_square(d)
+
+
+def _galois_group_degree_3(T, max_tries=30, randomize=False):
+    r"""
+    Compute the Galois group of a polynomial of degree 3.
+
+    Explanation
+    ===========
+
+    Uses Prop 6.3.5 of [1].
+
+    """
+    from sympy.combinatorics.galois import S3TransitiveSubgroups
+    return ((S3TransitiveSubgroups.A3, True) if has_square_disc(T)
+            else (S3TransitiveSubgroups.S3, False))
+
+
+def _galois_group_degree_4_root_approx(T, max_tries=30, randomize=False):
+    r"""
+    Compute the Galois group of a polynomial of degree 4.
+
+    Explanation
+    ===========
+
+    Follows Alg 6.3.7 of [1], using a pure root approximation approach.
+
+    """
+    from sympy.combinatorics.permutations import Permutation
+    from sympy.combinatorics.galois import S4TransitiveSubgroups
+
+    X = symbols('X0 X1 X2 X3')
+    # We start by considering the resolvent for the form
+    #   F = X0*X2 + X1*X3
+    # and the group G = S4. In this case, the stabilizer H is D4 = < (0123), (02) >,
+    # and a set of representatives of G/H is {I, (01), (03)}
+    F1 = X[0]*X[2] + X[1]*X[3]
+    s1 = [
+        Permutation(3),
+        Permutation(3)(0, 1),
+        Permutation(3)(0, 3)
+    ]
+    R1 = Resolvent(F1, X, s1)
+
+    # In the second half of the algorithm (if we reach it), we use another
+    # form and set of coset representatives. However, we may need to permute
+    # them first, so cannot form their resolvent now.
+    F2_pre = X[0]*X[1]**2 + X[1]*X[2]**2 + X[2]*X[3]**2 + X[3]*X[0]**2
+    s2_pre = [
+        Permutation(3),
+        Permutation(3)(0, 2)
+    ]
+
+    history = set()
+    for i in range(max_tries):
+        if i > 0:
+            # If we're retrying, need a new polynomial T.
+            _, T = tschirnhausen_transformation(T, max_tries=max_tries,
+                                                history=history,
+                                                fixed_order=not randomize)
+
+        R_dup, _, i0 = R1.eval_for_poly(T, find_integer_root=True)
+        # If R is not squarefree, must retry.
+        if not dup_sqf_p(R_dup, ZZ):
+            continue
+
+        # By Prop 6.3.1 of [1], Gal(T) is contained in A4 iff disc(T) is square.
+        sq_disc = has_square_disc(T)
+
+        if i0 is None:
+            # By Thm 6.3.3 of [1], Gal(T) is not conjugate to any subgroup of the
+            # stabilizer H = D4 that we chose. This means Gal(T) is either A4 or S4.
+            return ((S4TransitiveSubgroups.A4, True) if sq_disc
+                    else (S4TransitiveSubgroups.S4, False))
+
+        # Gal(T) is conjugate to a subgroup of H = D4, so it is either V, C4
+        # or D4 itself.
+
+        if sq_disc:
+            # Neither C4 nor D4 is contained in A4, so Gal(T) must be V.
+            return (S4TransitiveSubgroups.V, True)
+
+        # Gal(T) can only be D4 or C4.
+        # We will now use our second resolvent, with G being that conjugate of D4 that
+        # Gal(T) is contained in. To determine the right conjugate, we will need
+        # the permutation corresponding to the integer root we found.
+        sigma = s1[i0]
+        # Applying sigma means permuting the args of F, and
+        # conjugating the set of coset representatives.
+        F2 = F2_pre.subs(zip(X, sigma(X)), simultaneous=True)
+        s2 = [sigma*tau*sigma for tau in s2_pre]
+        R2 = Resolvent(F2, X, s2)
+        R_dup, _, _ = R2.eval_for_poly(T)
+        d = dup_discriminant(R_dup, ZZ)
+        # If d is zero (R has a repeated root), must retry.
+        if d == 0:
+            continue
+        if is_square(d):
+            return (S4TransitiveSubgroups.C4, False)
+        else:
+            return (S4TransitiveSubgroups.D4, False)
+
+    raise MaxTriesException
+
+
+def _galois_group_degree_4_lookup(T, max_tries=30, randomize=False):
+    r"""
+    Compute the Galois group of a polynomial of degree 4.
+
+    Explanation
+    ===========
+
+    Based on Alg 6.3.6 of [1], but uses resolvent coeff lookup.
+
+    """
+    from sympy.combinatorics.galois import S4TransitiveSubgroups
+
+    history = set()
+    for i in range(max_tries):
+        R_dup = get_resolvent_by_lookup(T, 0)
+        if dup_sqf_p(R_dup, ZZ):
+            break
+        _, T = tschirnhausen_transformation(T, max_tries=max_tries,
+                                            history=history,
+                                            fixed_order=not randomize)
+    else:
+        raise MaxTriesException
+
+    # Compute list L of degrees of irreducible factors of R, in increasing order:
+    fl = dup_factor_list(R_dup, ZZ)
+    L = sorted(sum([
+        [len(r) - 1] * e for r, e in fl[1]
+    ], []))
+
+    if L == [6]:
+        return ((S4TransitiveSubgroups.A4, True) if has_square_disc(T)
+            else (S4TransitiveSubgroups.S4, False))
+
+    if L == [1, 1, 4]:
+        return (S4TransitiveSubgroups.C4, False)
+
+    if L == [2, 2, 2]:
+        return (S4TransitiveSubgroups.V, True)
+
+    assert L == [2, 4]
+    return (S4TransitiveSubgroups.D4, False)
+
+
+def _galois_group_degree_5_hybrid(T, max_tries=30, randomize=False):
+    r"""
+    Compute the Galois group of a polynomial of degree 5.
+
+    Explanation
+    ===========
+
+    Based on Alg 6.3.9 of [1], but uses a hybrid approach, combining resolvent
+    coeff lookup, with root approximation.
+
+    """
+    from sympy.combinatorics.galois import S5TransitiveSubgroups
+    from sympy.combinatorics.permutations import Permutation
+
+    X5 = symbols("X0,X1,X2,X3,X4")
+    res = define_resolvents()
+    F51, _, s51 = res[(5, 1)]
+    F51 = F51.as_expr(*X5)
+    R51 = Resolvent(F51, X5, s51)
+
+    history = set()
+    reached_second_stage = False
+    for i in range(max_tries):
+        if i > 0:
+            _, T = tschirnhausen_transformation(T, max_tries=max_tries,
+                                                history=history,
+                                                fixed_order=not randomize)
+        R51_dup = get_resolvent_by_lookup(T, 1)
+        if not dup_sqf_p(R51_dup, ZZ):
+            continue
+
+        # First stage
+        # If we have not yet reached the second stage, then the group still
+        # might be S5, A5, or M20, so must test for that.
+        if not reached_second_stage:
+            sq_disc = has_square_disc(T)
+
+            if dup_irreducible_p(R51_dup, ZZ):
+                return ((S5TransitiveSubgroups.A5, True) if sq_disc
+                        else (S5TransitiveSubgroups.S5, False))
+
+            if not sq_disc:
+                return (S5TransitiveSubgroups.M20, False)
+
+        # Second stage
+        reached_second_stage = True
+        # R51 must have an integer root for T.
+        # To choose our second resolvent, we need to know which conjugate of
+        # F51 is a root.
+        rounded_roots = R51.round_roots_to_integers_for_poly(T)
+        # These are integers, and candidates to be roots of R51.
+        # We find the first one that actually is a root.
+        for permutation_index, candidate_root in rounded_roots.items():
+            if not dup_eval(R51_dup, candidate_root, ZZ):
+                break
+
+        X = X5
+        F2_pre = X[0]*X[1]**2 + X[1]*X[2]**2 + X[2]*X[3]**2 + X[3]*X[4]**2 + X[4]*X[0]**2
+        s2_pre = [
+            Permutation(4),
+            Permutation(4)(0, 1)(2, 4)
+        ]
+
+        i0 = permutation_index
+        sigma = s51[i0]
+        F2 = F2_pre.subs(zip(X, sigma(X)), simultaneous=True)
+        s2 = [sigma*tau*sigma for tau in s2_pre]
+        R2 = Resolvent(F2, X, s2)
+        R_dup, _, _ = R2.eval_for_poly(T)
+        d = dup_discriminant(R_dup, ZZ)
+
+        if d == 0:
+            continue
+        if is_square(d):
+            return (S5TransitiveSubgroups.C5, True)
+        else:
+            return (S5TransitiveSubgroups.D5, True)
+
+    raise MaxTriesException
+
+
+def _galois_group_degree_5_lookup_ext_factor(T, max_tries=30, randomize=False):
+    r"""
+    Compute the Galois group of a polynomial of degree 5.
+
+    Explanation
+    ===========
+
+    Based on Alg 6.3.9 of [1], but uses resolvent coeff lookup, plus
+    factorization over an algebraic extension.
+
+    """
+    from sympy.combinatorics.galois import S5TransitiveSubgroups
+
+    _T = T
+
+    history = set()
+    for i in range(max_tries):
+        R_dup = get_resolvent_by_lookup(T, 1)
+        if dup_sqf_p(R_dup, ZZ):
+            break
+        _, T = tschirnhausen_transformation(T, max_tries=max_tries,
+                                            history=history,
+                                            fixed_order=not randomize)
+    else:
+        raise MaxTriesException
+
+    sq_disc = has_square_disc(T)
+
+    if dup_irreducible_p(R_dup, ZZ):
+        return ((S5TransitiveSubgroups.A5, True) if sq_disc
+                else (S5TransitiveSubgroups.S5, False))
+
+    if not sq_disc:
+        return (S5TransitiveSubgroups.M20, False)
+
+    # If we get this far, Gal(T) can only be D5 or C5.
+    # But for Gal(T) to have order 5, T must already split completely in
+    # the extension field obtained by adjoining a single one of its roots.
+    fl = Poly(_T, domain=ZZ.alg_field_from_poly(_T)).factor_list()[1]
+    if len(fl) == 5:
+        return (S5TransitiveSubgroups.C5, True)
+    else:
+        return (S5TransitiveSubgroups.D5, True)
+
+
+def _galois_group_degree_6_lookup(T, max_tries=30, randomize=False):
+    r"""
+    Compute the Galois group of a polynomial of degree 6.
+
+    Explanation
+    ===========
+
+    Based on Alg 6.3.10 of [1], but uses resolvent coeff lookup.
+
+    """
+    from sympy.combinatorics.galois import S6TransitiveSubgroups
+
+    # First resolvent:
+
+    history = set()
+    for i in range(max_tries):
+        R_dup = get_resolvent_by_lookup(T, 1)
+        if dup_sqf_p(R_dup, ZZ):
+            break
+        _, T = tschirnhausen_transformation(T, max_tries=max_tries,
+                                            history=history,
+                                            fixed_order=not randomize)
+    else:
+        raise MaxTriesException
+
+    fl = dup_factor_list(R_dup, ZZ)
+
+    # Group the factors by degree.
+    factors_by_deg = defaultdict(list)
+    for r, _ in fl[1]:
+        factors_by_deg[len(r) - 1].append(r)
+
+    L = sorted(sum([
+        [d] * len(ff) for d, ff in factors_by_deg.items()
+    ], []))
+
+    T_has_sq_disc = has_square_disc(T)
+
+    if L == [1, 2, 3]:
+        f1 = factors_by_deg[3][0]
+        return ((S6TransitiveSubgroups.C6, False) if has_square_disc(f1)
+                else (S6TransitiveSubgroups.D6, False))
+
+    elif L == [3, 3]:
+        f1, f2 = factors_by_deg[3]
+        any_square = has_square_disc(f1) or has_square_disc(f2)
+        return ((S6TransitiveSubgroups.G18, False) if any_square
+                else (S6TransitiveSubgroups.G36m, False))
+
+    elif L == [2, 4]:
+        if T_has_sq_disc:
+            return (S6TransitiveSubgroups.S4p, True)
+        else:
+            f1 = factors_by_deg[4][0]
+            return ((S6TransitiveSubgroups.A4xC2, False) if has_square_disc(f1)
+                    else (S6TransitiveSubgroups.S4xC2, False))
+
+    elif L == [1, 1, 4]:
+        return ((S6TransitiveSubgroups.A4, True) if T_has_sq_disc
+                else (S6TransitiveSubgroups.S4m, False))
+
+    elif L == [1, 5]:
+        return ((S6TransitiveSubgroups.PSL2F5, True) if T_has_sq_disc
+                else (S6TransitiveSubgroups.PGL2F5, False))
+
+    elif L == [1, 1, 1, 3]:
+        return (S6TransitiveSubgroups.S3, False)
+
+    assert L == [6]
+
+    # Second resolvent:
+
+    history = set()
+    for i in range(max_tries):
+        R_dup = get_resolvent_by_lookup(T, 2)
+        if dup_sqf_p(R_dup, ZZ):
+            break
+        _, T = tschirnhausen_transformation(T, max_tries=max_tries,
+                                            history=history,
+                                            fixed_order=not randomize)
+    else:
+        raise MaxTriesException
+
+    T_has_sq_disc = has_square_disc(T)
+
+    if dup_irreducible_p(R_dup, ZZ):
+        return ((S6TransitiveSubgroups.A6, True) if T_has_sq_disc
+                else (S6TransitiveSubgroups.S6, False))
+    else:
+        return ((S6TransitiveSubgroups.G36p, True) if T_has_sq_disc
+                else (S6TransitiveSubgroups.G72, False))
+
+
+@public
+def galois_group(f, *gens, by_name=False, max_tries=30, randomize=False, **args):
+    r"""
+    Compute the Galois group for polynomials *f* up to degree 6.
+
+    Examples
+    ========
+
+    >>> from sympy import galois_group
+    >>> from sympy.abc import x
+    >>> f = x**4 + 1
+    >>> G, alt = galois_group(f)
+    >>> print(G)
+    PermutationGroup([
+    (0 1)(2 3),
+    (0 2)(1 3)])
+
+    The group is returned along with a boolean, indicating whether it is
+    contained in the alternating group $A_n$, where $n$ is the degree of *T*.
+    Along with other group properties, this can help determine which group it
+    is:
+
+    >>> alt
+    True
+    >>> G.order()
+    4
+
+    Alternatively, the group can be returned by name:
+
+    >>> G_name, _ = galois_group(f, by_name=True)
+    >>> print(G_name)
+    S4TransitiveSubgroups.V
+
+    The group itself can then be obtained by calling the name's
+    ``get_perm_group()`` method:
+
+    >>> G_name.get_perm_group()
+    PermutationGroup([
+    (0 1)(2 3),
+    (0 2)(1 3)])
+
+    Group names are values of the enum classes
+    :py:class:`sympy.combinatorics.galois.S1TransitiveSubgroups`,
+    :py:class:`sympy.combinatorics.galois.S2TransitiveSubgroups`,
+    etc.
+
+    Parameters
+    ==========
+
+    f : Expr
+        Irreducible polynomial over :ref:`ZZ` or :ref:`QQ`, whose Galois group
+        is to be determined.
+    gens : optional list of symbols
+        For converting *f* to Poly, and will be passed on to the
+        :py:func:`~.poly_from_expr` function.
+    by_name : bool, default False
+        If ``True``, the Galois group will be returned by name.
+        Otherwise it will be returned as a :py:class:`~.PermutationGroup`.
+    max_tries : int, default 30
+        Make at most this many attempts in those steps that involve
+        generating Tschirnhausen transformations.
+    randomize : bool, default False
+        If ``True``, then use random coefficients when generating Tschirnhausen
+        transformations. Otherwise try transformations in a fixed order. Both
+        approaches start with small coefficients and degrees and work upward.
+    args : optional
+        For converting *f* to Poly, and will be passed on to the
+        :py:func:`~.poly_from_expr` function.
+
+    Returns
+    =======
+
+    Pair ``(G, alt)``
+        The first element ``G`` indicates the Galois group. It is an instance
+        of one of the :py:class:`sympy.combinatorics.galois.S1TransitiveSubgroups`
+        :py:class:`sympy.combinatorics.galois.S2TransitiveSubgroups`, etc. enum
+        classes if *by_name* was ``True``, and a :py:class:`~.PermutationGroup`
+        if ``False``.
+
+        The second element is a boolean, saying whether the group is contained
+        in the alternating group $A_n$ ($n$ the degree of *T*).
+
+    Raises
+    ======
+
+    ValueError
+        if *f* is of an unsupported degree.
+
+    MaxTriesException
+        if could not complete before exceeding *max_tries* in those steps
+        that involve generating Tschirnhausen transformations.
+
+    See Also
+    ========
+
+    .Poly.galois_group
+
+    """
+    gens = gens or []
+    args = args or {}
+
+    try:
+        F, opt = poly_from_expr(f, *gens, **args)
+    except PolificationFailed as exc:
+        raise ComputationFailed('galois_group', 1, exc)
+
+    return F.galois_group(by_name=by_name, max_tries=max_tries,
+                          randomize=randomize)
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/minpoly.py b/lib/python3.11/site-packages/sympy/polys/numberfields/minpoly.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3543339bfbaeb0ec5b3bea1ea66c4f354a0c8af
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/minpoly.py
@@ -0,0 +1,883 @@
+"""Minimal polynomials for algebraic numbers."""
+
+from functools import reduce
+
+from sympy.core.add import Add
+from sympy.core.exprtools import Factors
+from sympy.core.function import expand_mul, expand_multinomial, _mexpand
+from sympy.core.mul import Mul
+from sympy.core.numbers import (I, Rational, pi, _illegal)
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import sympify
+from sympy.core.traversal import preorder_traversal
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt, cbrt
+from sympy.functions.elementary.trigonometric import cos, sin, tan
+from sympy.ntheory.factor_ import divisors
+from sympy.utilities.iterables import subsets
+
+from sympy.polys.domains import ZZ, QQ, FractionField
+from sympy.polys.orthopolys import dup_chebyshevt
+from sympy.polys.polyerrors import (
+    NotAlgebraic,
+    GeneratorsError,
+)
+from sympy.polys.polytools import (
+    Poly, PurePoly, invert, factor_list, groebner, resultant,
+    degree, poly_from_expr, parallel_poly_from_expr, lcm
+)
+from sympy.polys.polyutils import dict_from_expr, expr_from_dict
+from sympy.polys.ring_series import rs_compose_add
+from sympy.polys.rings import ring
+from sympy.polys.rootoftools import CRootOf
+from sympy.polys.specialpolys import cyclotomic_poly
+from sympy.utilities import (
+    numbered_symbols, public, sift
+)
+
+
+def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
+    """
+    Return a factor having root ``v``
+    It is assumed that one of the factors has root ``v``.
+    """
+
+    if isinstance(factors[0], tuple):
+        factors = [f[0] for f in factors]
+    if len(factors) == 1:
+        return factors[0]
+
+    prec1 = 10
+    points = {}
+    symbols = dom.symbols if hasattr(dom, 'symbols') else []
+    while prec1 <= prec:
+        # when dealing with non-Rational numbers we usually evaluate
+        # with `subs` argument but we only need a ballpark evaluation
+        fe = [f.as_expr().xreplace({x:v}) for f in factors]
+        if v.is_number:
+            fe = [f.n(prec) for f in fe]
+
+        # assign integers [0, n) to symbols (if any)
+        for n in subsets(range(bound), k=len(symbols), repetition=True):
+            for s, i in zip(symbols, n):
+                points[s] = i
+
+            # evaluate the expression at these points
+            candidates = [(abs(f.subs(points).n(prec1)), i)
+                for i,f in enumerate(fe)]
+
+            # if we get invalid numbers (e.g. from division by zero)
+            # we try again
+            if any(i in _illegal for i, _ in candidates):
+                continue
+
+            # find the smallest two -- if they differ significantly
+            # then we assume we have found the factor that becomes
+            # 0 when v is substituted into it
+            can = sorted(candidates)
+            (a, ix), (b, _) = can[:2]
+            if b > a * 10**6:  # XXX what to use?
+                return factors[ix]
+
+        prec1 *= 2
+
+    raise NotImplementedError("multiple candidates for the minimal polynomial of %s" % v)
+
+
+def _is_sum_surds(p):
+    args = p.args if p.is_Add else [p]
+    for y in args:
+        if not ((y**2).is_Rational and y.is_extended_real):
+            return False
+    return True
+
+
+def _separate_sq(p):
+    """
+    helper function for ``_minimal_polynomial_sq``
+
+    It selects a rational ``g`` such that the polynomial ``p``
+    consists of a sum of terms whose surds squared have gcd equal to ``g``
+    and a sum of terms with surds squared prime with ``g``;
+    then it takes the field norm to eliminate ``sqrt(g)``
+
+    See simplify.simplify.split_surds and polytools.sqf_norm.
+
+    Examples
+    ========
+
+    >>> from sympy import sqrt
+    >>> from sympy.abc import x
+    >>> from sympy.polys.numberfields.minpoly import _separate_sq
+    >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)
+    >>> p = _separate_sq(p); p
+    -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8
+    >>> p = _separate_sq(p); p
+    -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20
+    >>> p = _separate_sq(p); p
+    -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400
+
+    """
+    def is_sqrt(expr):
+        return expr.is_Pow and expr.exp is S.Half
+    # p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)]
+    a = []
+    for y in p.args:
+        if not y.is_Mul:
+            if is_sqrt(y):
+                a.append((S.One, y**2))
+            elif y.is_Atom:
+                a.append((y, S.One))
+            elif y.is_Pow and y.exp.is_integer:
+                a.append((y, S.One))
+            else:
+                raise NotImplementedError
+        else:
+            T, F = sift(y.args, is_sqrt, binary=True)
+            a.append((Mul(*F), Mul(*T)**2))
+    a.sort(key=lambda z: z[1])
+    if a[-1][1] is S.One:
+        # there are no surds
+        return p
+    surds = [z for y, z in a]
+    for i in range(len(surds)):
+        if surds[i] != 1:
+            break
+    from sympy.simplify.radsimp import _split_gcd
+    g, b1, b2 = _split_gcd(*surds[i:])
+    a1 = []
+    a2 = []
+    for y, z in a:
+        if z in b1:
+            a1.append(y*z**S.Half)
+        else:
+            a2.append(y*z**S.Half)
+    p1 = Add(*a1)
+    p2 = Add(*a2)
+    p = _mexpand(p1**2) - _mexpand(p2**2)
+    return p
+
+def _minimal_polynomial_sq(p, n, x):
+    """
+    Returns the minimal polynomial for the ``nth-root`` of a sum of surds
+    or ``None`` if it fails.
+
+    Parameters
+    ==========
+
+    p : sum of surds
+    n : positive integer
+    x : variable of the returned polynomial
+
+    Examples
+    ========
+
+    >>> from sympy.polys.numberfields.minpoly import _minimal_polynomial_sq
+    >>> from sympy import sqrt
+    >>> from sympy.abc import x
+    >>> q = 1 + sqrt(2) + sqrt(3)
+    >>> _minimal_polynomial_sq(q, 3, x)
+    x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
+
+    """
+    p = sympify(p)
+    n = sympify(n)
+    if not n.is_Integer or not n > 0 or not _is_sum_surds(p):
+        return None
+    pn = p**Rational(1, n)
+    # eliminate the square roots
+    p -= x
+    while 1:
+        p1 = _separate_sq(p)
+        if p1 is p:
+            p = p1.subs({x:x**n})
+            break
+        else:
+            p = p1
+
+    # _separate_sq eliminates field extensions in a minimal way, so that
+    # if n = 1 then `p = constant*(minimal_polynomial(p))`
+    # if n > 1 it contains the minimal polynomial as a factor.
+    if n == 1:
+        p1 = Poly(p)
+        if p.coeff(x**p1.degree(x)) < 0:
+            p = -p
+        p = p.primitive()[1]
+        return p
+    # by construction `p` has root `pn`
+    # the minimal polynomial is the factor vanishing in x = pn
+    factors = factor_list(p)[1]
+
+    result = _choose_factor(factors, x, pn)
+    return result
+
+def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
+    """
+    return the minimal polynomial for ``op(ex1, ex2)``
+
+    Parameters
+    ==========
+
+    op : operation ``Add`` or ``Mul``
+    ex1, ex2 : expressions for the algebraic elements
+    x : indeterminate of the polynomials
+    dom: ground domain
+    mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None
+
+    Examples
+    ========
+
+    >>> from sympy import sqrt, Add, Mul, QQ
+    >>> from sympy.polys.numberfields.minpoly import _minpoly_op_algebraic_element
+    >>> from sympy.abc import x, y
+    >>> p1 = sqrt(sqrt(2) + 1)
+    >>> p2 = sqrt(sqrt(2) - 1)
+    >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)
+    x - 1
+    >>> q1 = sqrt(y)
+    >>> q2 = 1 / y
+    >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))
+    x**2*y**2 - 2*x*y - y**3 + 1
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Resultant
+    .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638
+           "Degrees of sums in a separable field extension".
+
+    """
+    y = Dummy(str(x))
+    if mp1 is None:
+        mp1 = _minpoly_compose(ex1, x, dom)
+    if mp2 is None:
+        mp2 = _minpoly_compose(ex2, y, dom)
+    else:
+        mp2 = mp2.subs({x: y})
+
+    if op is Add:
+        # mp1a = mp1.subs({x: x - y})
+        if dom == QQ:
+            R, X = ring('X', QQ)
+            p1 = R(dict_from_expr(mp1)[0])
+            p2 = R(dict_from_expr(mp2)[0])
+        else:
+            (p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y)
+            r = p1.compose(p2)
+            mp1a = r.as_expr()
+
+    elif op is Mul:
+        mp1a = _muly(mp1, x, y)
+    else:
+        raise NotImplementedError('option not available')
+
+    if op is Mul or dom != QQ:
+        r = resultant(mp1a, mp2, gens=[y, x])
+    else:
+        r = rs_compose_add(p1, p2)
+        r = expr_from_dict(r.as_expr_dict(), x)
+
+    deg1 = degree(mp1, x)
+    deg2 = degree(mp2, y)
+    if op is Mul and deg1 == 1 or deg2 == 1:
+        # if deg1 = 1, then mp1 = x - a; mp1a = x - y - a;
+        # r = mp2(x - a), so that `r` is irreducible
+        return r
+
+    r = Poly(r, x, domain=dom)
+    _, factors = r.factor_list()
+    res = _choose_factor(factors, x, op(ex1, ex2), dom)
+    return res.as_expr()
+
+
+def _invertx(p, x):
+    """
+    Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``
+    """
+    p1 = poly_from_expr(p, x)[0]
+
+    n = degree(p1)
+    a = [c * x**(n - i) for (i,), c in p1.terms()]
+    return Add(*a)
+
+
+def _muly(p, x, y):
+    """
+    Returns ``_mexpand(y**deg*p.subs({x:x / y}))``
+    """
+    p1 = poly_from_expr(p, x)[0]
+
+    n = degree(p1)
+    a = [c * x**i * y**(n - i) for (i,), c in p1.terms()]
+    return Add(*a)
+
+
+def _minpoly_pow(ex, pw, x, dom, mp=None):
+    """
+    Returns ``minpoly(ex**pw, x)``
+
+    Parameters
+    ==========
+
+    ex : algebraic element
+    pw : rational number
+    x : indeterminate of the polynomial
+    dom: ground domain
+    mp : minimal polynomial of ``p``
+
+    Examples
+    ========
+
+    >>> from sympy import sqrt, QQ, Rational
+    >>> from sympy.polys.numberfields.minpoly import _minpoly_pow, minpoly
+    >>> from sympy.abc import x, y
+    >>> p = sqrt(1 + sqrt(2))
+    >>> _minpoly_pow(p, 2, x, QQ)
+    x**2 - 2*x - 1
+    >>> minpoly(p**2, x)
+    x**2 - 2*x - 1
+    >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))
+    x**3 - y
+    >>> minpoly(y**Rational(1, 3), x)
+    x**3 - y
+
+    """
+    pw = sympify(pw)
+    if not mp:
+        mp = _minpoly_compose(ex, x, dom)
+    if not pw.is_rational:
+        raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+    if pw < 0:
+        if mp == x:
+            raise ZeroDivisionError('%s is zero' % ex)
+        mp = _invertx(mp, x)
+        if pw == -1:
+            return mp
+        pw = -pw
+        ex = 1/ex
+
+    y = Dummy(str(x))
+    mp = mp.subs({x: y})
+    n, d = pw.as_numer_denom()
+    res = Poly(resultant(mp, x**d - y**n, gens=[y]), x, domain=dom)
+    _, factors = res.factor_list()
+    res = _choose_factor(factors, x, ex**pw, dom)
+    return res.as_expr()
+
+
+def _minpoly_add(x, dom, *a):
+    """
+    returns ``minpoly(Add(*a), dom, x)``
+    """
+    mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
+    p = a[0] + a[1]
+    for px in a[2:]:
+        mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
+        p = p + px
+    return mp
+
+
+def _minpoly_mul(x, dom, *a):
+    """
+    returns ``minpoly(Mul(*a), dom, x)``
+    """
+    mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
+    p = a[0] * a[1]
+    for px in a[2:]:
+        mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
+        p = p * px
+    return mp
+
+
+def _minpoly_sin(ex, x):
+    """
+    Returns the minimal polynomial of ``sin(ex)``
+    see https://mathworld.wolfram.com/TrigonometryAngles.html
+    """
+    c, a = ex.args[0].as_coeff_Mul()
+    if a is pi:
+        if c.is_rational:
+            n = c.q
+            q = sympify(n)
+            if q.is_prime:
+                # for a = pi*p/q with q odd prime, using chebyshevt
+                # write sin(q*a) = mp(sin(a))*sin(a);
+                # the roots of mp(x) are sin(pi*p/q) for p = 1,..., q - 1
+                a = dup_chebyshevt(n, ZZ)
+                return Add(*[x**(n - i - 1)*a[i] for i in range(n)])
+            if c.p == 1:
+                if q == 9:
+                    return 64*x**6 - 96*x**4 + 36*x**2 - 3
+
+            if n % 2 == 1:
+                # for a = pi*p/q with q odd, use
+                # sin(q*a) = 0 to see that the minimal polynomial must be
+                # a factor of dup_chebyshevt(n, ZZ)
+                a = dup_chebyshevt(n, ZZ)
+                a = [x**(n - i)*a[i] for i in range(n + 1)]
+                r = Add(*a)
+                _, factors = factor_list(r)
+                res = _choose_factor(factors, x, ex)
+                return res
+
+            expr = ((1 - cos(2*c*pi))/2)**S.Half
+            res = _minpoly_compose(expr, x, QQ)
+            return res
+
+    raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+
+
+def _minpoly_cos(ex, x):
+    """
+    Returns the minimal polynomial of ``cos(ex)``
+    see https://mathworld.wolfram.com/TrigonometryAngles.html
+    """
+    c, a = ex.args[0].as_coeff_Mul()
+    if a is pi:
+        if c.is_rational:
+            if c.p == 1:
+                if c.q == 7:
+                    return 8*x**3 - 4*x**2 - 4*x + 1
+                if c.q == 9:
+                    return 8*x**3 - 6*x - 1
+            elif c.p == 2:
+                q = sympify(c.q)
+                if q.is_prime:
+                    s = _minpoly_sin(ex, x)
+                    return _mexpand(s.subs({x:sqrt((1 - x)/2)}))
+
+            # for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
+            n = int(c.q)
+            a = dup_chebyshevt(n, ZZ)
+            a = [x**(n - i)*a[i] for i in range(n + 1)]
+            r = Add(*a) - (-1)**c.p
+            _, factors = factor_list(r)
+            res = _choose_factor(factors, x, ex)
+            return res
+
+    raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+
+
+def _minpoly_tan(ex, x):
+    """
+    Returns the minimal polynomial of ``tan(ex)``
+    see https://github.com/sympy/sympy/issues/21430
+    """
+    c, a = ex.args[0].as_coeff_Mul()
+    if a is pi:
+        if c.is_rational:
+            c = c * 2
+            n = int(c.q)
+            a = n if c.p % 2 == 0 else 1
+            terms = []
+            for k in range((c.p+1)%2, n+1, 2):
+                terms.append(a*x**k)
+                a = -(a*(n-k-1)*(n-k)) // ((k+1)*(k+2))
+
+            r = Add(*terms)
+            _, factors = factor_list(r)
+            res = _choose_factor(factors, x, ex)
+            return res
+
+    raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+
+
+def _minpoly_exp(ex, x):
+    """
+    Returns the minimal polynomial of ``exp(ex)``
+    """
+    c, a = ex.args[0].as_coeff_Mul()
+    if a == I*pi:
+        if c.is_rational:
+            q = sympify(c.q)
+            if c.p == 1 or c.p == -1:
+                if q == 3:
+                    return x**2 - x + 1
+                if q == 4:
+                    return x**4 + 1
+                if q == 6:
+                    return x**4 - x**2 + 1
+                if q == 8:
+                    return x**8 + 1
+                if q == 9:
+                    return x**6 - x**3 + 1
+                if q == 10:
+                    return x**8 - x**6 + x**4 - x**2 + 1
+                if q.is_prime:
+                    s = 0
+                    for i in range(q):
+                        s += (-x)**i
+                    return s
+
+            # x**(2*q) = product(factors)
+            factors = [cyclotomic_poly(i, x) for i in divisors(2*q)]
+            mp = _choose_factor(factors, x, ex)
+            return mp
+        else:
+            raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+    raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+
+
+def _minpoly_rootof(ex, x):
+    """
+    Returns the minimal polynomial of a ``CRootOf`` object.
+    """
+    p = ex.expr
+    p = p.subs({ex.poly.gens[0]:x})
+    _, factors = factor_list(p, x)
+    result = _choose_factor(factors, x, ex)
+    return result
+
+
+def _minpoly_compose(ex, x, dom):
+    """
+    Computes the minimal polynomial of an algebraic element
+    using operations on minimal polynomials
+
+    Examples
+    ========
+
+    >>> from sympy import minimal_polynomial, sqrt, Rational
+    >>> from sympy.abc import x, y
+    >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)
+    x**2 - 2*x - 1
+    >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)
+    x**2*y**2 - 2*x*y - y**3 + 1
+
+    """
+    if ex.is_Rational:
+        return ex.q*x - ex.p
+    if ex is I:
+        _, factors = factor_list(x**2 + 1, x, domain=dom)
+        return x**2 + 1 if len(factors) == 1 else x - I
+
+    if ex is S.GoldenRatio:
+        _, factors = factor_list(x**2 - x - 1, x, domain=dom)
+        if len(factors) == 1:
+            return x**2 - x - 1
+        else:
+            return _choose_factor(factors, x, (1 + sqrt(5))/2, dom=dom)
+
+    if ex is S.TribonacciConstant:
+        _, factors = factor_list(x**3 - x**2 - x - 1, x, domain=dom)
+        if len(factors) == 1:
+            return x**3 - x**2 - x - 1
+        else:
+            fac = (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
+            return _choose_factor(factors, x, fac, dom=dom)
+
+    if hasattr(dom, 'symbols') and ex in dom.symbols:
+        return x - ex
+
+    if dom.is_QQ and _is_sum_surds(ex):
+        # eliminate the square roots
+        ex -= x
+        while 1:
+            ex1 = _separate_sq(ex)
+            if ex1 is ex:
+                return ex
+            else:
+                ex = ex1
+
+    if ex.is_Add:
+        res = _minpoly_add(x, dom, *ex.args)
+    elif ex.is_Mul:
+        f = Factors(ex).factors
+        r = sift(f.items(), lambda itx: itx[0].is_Rational and itx[1].is_Rational)
+        if r[True] and dom == QQ:
+            ex1 = Mul(*[bx**ex for bx, ex in r[False] + r[None]])
+            r1 = dict(r[True])
+            dens = [y.q for y in r1.values()]
+            lcmdens = reduce(lcm, dens, 1)
+            neg1 = S.NegativeOne
+            expn1 = r1.pop(neg1, S.Zero)
+            nums = [base**(y.p*lcmdens // y.q) for base, y in r1.items()]
+            ex2 = Mul(*nums)
+            mp1 = minimal_polynomial(ex1, x)
+            # use the fact that in SymPy canonicalization products of integers
+            # raised to rational powers are organized in relatively prime
+            # bases, and that in ``base**(n/d)`` a perfect power is
+            # simplified with the root
+            # Powers of -1 have to be treated separately to preserve sign.
+            mp2 = ex2.q*x**lcmdens - ex2.p*neg1**(expn1*lcmdens)
+            ex2 = neg1**expn1 * ex2**Rational(1, lcmdens)
+            res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2)
+        else:
+            res = _minpoly_mul(x, dom, *ex.args)
+    elif ex.is_Pow:
+        res = _minpoly_pow(ex.base, ex.exp, x, dom)
+    elif ex.__class__ is sin:
+        res = _minpoly_sin(ex, x)
+    elif ex.__class__ is cos:
+        res = _minpoly_cos(ex, x)
+    elif ex.__class__ is tan:
+        res = _minpoly_tan(ex, x)
+    elif ex.__class__ is exp:
+        res = _minpoly_exp(ex, x)
+    elif ex.__class__ is CRootOf:
+        res = _minpoly_rootof(ex, x)
+    else:
+        raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
+    return res
+
+
+@public
+def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
+    """
+    Computes the minimal polynomial of an algebraic element.
+
+    Parameters
+    ==========
+
+    ex : Expr
+        Element or expression whose minimal polynomial is to be calculated.
+
+    x : Symbol, optional
+        Independent variable of the minimal polynomial
+
+    compose : boolean, optional (default=True)
+        Method to use for computing minimal polynomial. If ``compose=True``
+        (default) then ``_minpoly_compose`` is used, if ``compose=False`` then
+        groebner bases are used.
+
+    polys : boolean, optional (default=False)
+        If ``True`` returns a ``Poly`` object else an ``Expr`` object.
+
+    domain : Domain, optional
+        Ground domain
+
+    Notes
+    =====
+
+    By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``
+    are computed, then the arithmetic operations on them are performed using the resultant
+    and factorization.
+    If ``compose=False``, a bottom-up algorithm is used with ``groebner``.
+    The default algorithm stalls less frequently.
+
+    If no ground domain is given, it will be generated automatically from the expression.
+
+    Examples
+    ========
+
+    >>> from sympy import minimal_polynomial, sqrt, solve, QQ
+    >>> from sympy.abc import x, y
+
+    >>> minimal_polynomial(sqrt(2), x)
+    x**2 - 2
+    >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))
+    x - sqrt(2)
+    >>> minimal_polynomial(sqrt(2) + sqrt(3), x)
+    x**4 - 10*x**2 + 1
+    >>> minimal_polynomial(solve(x**3 + x + 3)[0], x)
+    x**3 + x + 3
+    >>> minimal_polynomial(sqrt(y), x)
+    x**2 - y
+
+    """
+
+    ex = sympify(ex)
+    if ex.is_number:
+        # not sure if it's always needed but try it for numbers (issue 8354)
+        ex = _mexpand(ex, recursive=True)
+    for expr in preorder_traversal(ex):
+        if expr.is_AlgebraicNumber:
+            compose = False
+            break
+
+    if x is not None:
+        x, cls = sympify(x), Poly
+    else:
+        x, cls = Dummy('x'), PurePoly
+
+    if not domain:
+        if ex.free_symbols:
+            domain = FractionField(QQ, list(ex.free_symbols))
+        else:
+            domain = QQ
+    if hasattr(domain, 'symbols') and x in domain.symbols:
+        raise GeneratorsError("the variable %s is an element of the ground "
+                              "domain %s" % (x, domain))
+
+    if compose:
+        result = _minpoly_compose(ex, x, domain)
+        result = result.primitive()[1]
+        c = result.coeff(x**degree(result, x))
+        if c.is_negative:
+            result = expand_mul(-result)
+        return cls(result, x, field=True) if polys else result.collect(x)
+
+    if not domain.is_QQ:
+        raise NotImplementedError("groebner method only works for QQ")
+
+    result = _minpoly_groebner(ex, x, cls)
+    return cls(result, x, field=True) if polys else result.collect(x)
+
+
+def _minpoly_groebner(ex, x, cls):
+    """
+    Computes the minimal polynomial of an algebraic number
+    using Groebner bases
+
+    Examples
+    ========
+
+    >>> from sympy import minimal_polynomial, sqrt, Rational
+    >>> from sympy.abc import x
+    >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)
+    x**2 - 2*x - 1
+
+    """
+
+    generator = numbered_symbols('a', cls=Dummy)
+    mapping, symbols = {}, {}
+
+    def update_mapping(ex, exp, base=None):
+        a = next(generator)
+        symbols[ex] = a
+
+        if base is not None:
+            mapping[ex] = a**exp + base
+        else:
+            mapping[ex] = exp.as_expr(a)
+
+        return a
+
+    def bottom_up_scan(ex):
+        """
+        Transform a given algebraic expression *ex* into a multivariate
+        polynomial, by introducing fresh variables with defining equations.
+
+        Explanation
+        ===========
+
+        The critical elements of the algebraic expression *ex* are root
+        extractions, instances of :py:class:`~.AlgebraicNumber`, and negative
+        powers.
+
+        When we encounter a root extraction or an :py:class:`~.AlgebraicNumber`
+        we replace this expression with a fresh variable ``a_i``, and record
+        the defining polynomial for ``a_i``. For example, if ``a_0**(1/3)``
+        occurs, we will replace it with ``a_1``, and record the new defining
+        polynomial ``a_1**3 - a_0``.
+
+        When we encounter a negative power we transform it into a positive
+        power by algebraically inverting the base. This means computing the
+        minimal polynomial in ``x`` for the base, inverting ``x`` modulo this
+        poly (which generates a new polynomial) and then substituting the
+        original base expression for ``x`` in this last polynomial.
+
+        We return the transformed expression, and we record the defining
+        equations for new symbols using the ``update_mapping()`` function.
+
+        """
+        if ex.is_Atom:
+            if ex is S.ImaginaryUnit:
+                if ex not in mapping:
+                    return update_mapping(ex, 2, 1)
+                else:
+                    return symbols[ex]
+            elif ex.is_Rational:
+                return ex
+        elif ex.is_Add:
+            return Add(*[ bottom_up_scan(g) for g in ex.args ])
+        elif ex.is_Mul:
+            return Mul(*[ bottom_up_scan(g) for g in ex.args ])
+        elif ex.is_Pow:
+            if ex.exp.is_Rational:
+                if ex.exp < 0:
+                    minpoly_base = _minpoly_groebner(ex.base, x, cls)
+                    inverse = invert(x, minpoly_base).as_expr()
+                    base_inv = inverse.subs(x, ex.base).expand()
+
+                    if ex.exp == -1:
+                        return bottom_up_scan(base_inv)
+                    else:
+                        ex = base_inv**(-ex.exp)
+                if not ex.exp.is_Integer:
+                    base, exp = (
+                        ex.base**ex.exp.p).expand(), Rational(1, ex.exp.q)
+                else:
+                    base, exp = ex.base, ex.exp
+                base = bottom_up_scan(base)
+                expr = base**exp
+
+                if expr not in mapping:
+                    if exp.is_Integer:
+                        return expr.expand()
+                    else:
+                        return update_mapping(expr, 1 / exp, -base)
+                else:
+                    return symbols[expr]
+        elif ex.is_AlgebraicNumber:
+            if ex not in mapping:
+                return update_mapping(ex, ex.minpoly_of_element())
+            else:
+                return symbols[ex]
+
+        raise NotAlgebraic("%s does not seem to be an algebraic number" % ex)
+
+    def simpler_inverse(ex):
+        """
+        Returns True if it is more likely that the minimal polynomial
+        algorithm works better with the inverse
+        """
+        if ex.is_Pow:
+            if (1/ex.exp).is_integer and ex.exp < 0:
+                if ex.base.is_Add:
+                    return True
+        if ex.is_Mul:
+            hit = True
+            for p in ex.args:
+                if p.is_Add:
+                    return False
+                if p.is_Pow:
+                    if p.base.is_Add and p.exp > 0:
+                        return False
+
+            if hit:
+                return True
+        return False
+
+    inverted = False
+    ex = expand_multinomial(ex)
+    if ex.is_AlgebraicNumber:
+        return ex.minpoly_of_element().as_expr(x)
+    elif ex.is_Rational:
+        result = ex.q*x - ex.p
+    else:
+        inverted = simpler_inverse(ex)
+        if inverted:
+            ex = ex**-1
+        res = None
+        if ex.is_Pow and (1/ex.exp).is_Integer:
+            n = 1/ex.exp
+            res = _minimal_polynomial_sq(ex.base, n, x)
+
+        elif _is_sum_surds(ex):
+            res = _minimal_polynomial_sq(ex, S.One, x)
+
+        if res is not None:
+            result = res
+
+        if res is None:
+            bus = bottom_up_scan(ex)
+            F = [x - bus] + list(mapping.values())
+            G = groebner(F, list(symbols.values()) + [x], order='lex')
+
+            _, factors = factor_list(G[-1])
+            # by construction G[-1] has root `ex`
+            result = _choose_factor(factors, x, ex)
+    if inverted:
+        result = _invertx(result, x)
+        if result.coeff(x**degree(result, x)) < 0:
+            result = expand_mul(-result)
+
+    return result
+
+
+@public
+def minpoly(ex, x=None, compose=True, polys=False, domain=None):
+    """This is a synonym for :py:func:`~.minimal_polynomial`."""
+    return minimal_polynomial(ex, x=x, compose=compose, polys=polys, domain=domain)
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/modules.py b/lib/python3.11/site-packages/sympy/polys/numberfields/modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..af2e29bcc9cf73d97def0701712f90db58601b86
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/modules.py
@@ -0,0 +1,2114 @@
+r"""Modules in number fields.
+
+The classes defined here allow us to work with finitely generated, free
+modules, whose generators are algebraic numbers.
+
+There is an abstract base class called :py:class:`~.Module`, which has two
+concrete subclasses, :py:class:`~.PowerBasis` and :py:class:`~.Submodule`.
+
+Every module is defined by its basis, or set of generators:
+
+* For a :py:class:`~.PowerBasis`, the generators are the first $n$ powers
+  (starting with the zeroth) of an algebraic integer $\theta$ of degree $n$.
+  The :py:class:`~.PowerBasis` is constructed by passing either the minimal
+  polynomial of $\theta$, or an :py:class:`~.AlgebraicField` having $\theta$
+  as its primitive element.
+
+* For a :py:class:`~.Submodule`, the generators are a set of
+  $\mathbb{Q}$-linear combinations of the generators of another module. That
+  other module is then the "parent" of the :py:class:`~.Submodule`. The
+  coefficients of the $\mathbb{Q}$-linear combinations may be given by an
+  integer matrix, and a positive integer denominator. Each column of the matrix
+  defines a generator.
+
+>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
+>>> from sympy.abc import x
+>>> from sympy.polys.matrices import DomainMatrix, DM
+>>> from sympy.polys.numberfields.modules import PowerBasis
+>>> T = Poly(cyclotomic_poly(5, x))
+>>> A = PowerBasis(T)
+>>> print(A)
+PowerBasis(x**4 + x**3 + x**2 + x + 1)
+>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3)
+>>> print(B)
+Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3
+>>> print(B.parent)
+PowerBasis(x**4 + x**3 + x**2 + x + 1)
+
+Thus, every module is either a :py:class:`~.PowerBasis`,
+or a :py:class:`~.Submodule`, some ancestor of which is a
+:py:class:`~.PowerBasis`. (If ``S`` is a :py:class:`~.Submodule`, then its
+ancestors are ``S.parent``, ``S.parent.parent``, and so on).
+
+The :py:class:`~.ModuleElement` class represents a linear combination of the
+generators of any module. Critically, the coefficients of this linear
+combination are not restricted to be integers, but may be any rational
+numbers. This is necessary so that any and all algebraic integers be
+representable, starting from the power basis in a primitive element $\theta$
+for the number field in question. For example, in a quadratic field
+$\mathbb{Q}(\sqrt{d})$ where $d \equiv 1 \mod{4}$, a denominator of $2$ is
+needed.
+
+A :py:class:`~.ModuleElement` can be constructed from an integer column vector
+and a denominator:
+
+>>> U = Poly(x**2 - 5)
+>>> M = PowerBasis(U)
+>>> e = M(DM([[1], [1]], ZZ), denom=2)
+>>> print(e)
+[1, 1]/2
+>>> print(e.module)
+PowerBasis(x**2 - 5)
+
+The :py:class:`~.PowerBasisElement` class is a subclass of
+:py:class:`~.ModuleElement` that represents elements of a
+:py:class:`~.PowerBasis`, and adds functionality pertinent to elements
+represented directly over powers of the primitive element $\theta$.
+
+
+Arithmetic with module elements
+===============================
+
+While a :py:class:`~.ModuleElement` represents a linear combination over the
+generators of a particular module, recall that every module is either a
+:py:class:`~.PowerBasis` or a descendant (along a chain of
+:py:class:`~.Submodule` objects) thereof, so that in fact every
+:py:class:`~.ModuleElement` represents an algebraic number in some field
+$\mathbb{Q}(\theta)$, where $\theta$ is the defining element of some
+:py:class:`~.PowerBasis`. It thus makes sense to talk about the number field
+to which a given :py:class:`~.ModuleElement` belongs.
+
+This means that any two :py:class:`~.ModuleElement` instances can be added,
+subtracted, multiplied, or divided, provided they belong to the same number
+field. Similarly, since $\mathbb{Q}$ is a subfield of every number field,
+any :py:class:`~.ModuleElement` may be added, multiplied, etc. by any
+rational number.
+
+>>> from sympy import QQ
+>>> from sympy.polys.numberfields.modules import to_col
+>>> T = Poly(cyclotomic_poly(5))
+>>> A = PowerBasis(T)
+>>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
+>>> e = A(to_col([0, 2, 0, 0]), denom=3)
+>>> f = A(to_col([0, 0, 0, 7]), denom=5)
+>>> g = C(to_col([1, 1, 1, 1]))
+>>> e + f
+[0, 10, 0, 21]/15
+>>> e - f
+[0, 10, 0, -21]/15
+>>> e - g
+[-9, -7, -9, -9]/3
+>>> e + QQ(7, 10)
+[21, 20, 0, 0]/30
+>>> e * f
+[-14, -14, -14, -14]/15
+>>> e ** 2
+[0, 0, 4, 0]/9
+>>> f // g
+[7, 7, 7, 7]/15
+>>> f * QQ(2, 3)
+[0, 0, 0, 14]/15
+
+However, care must be taken with arithmetic operations on
+:py:class:`~.ModuleElement`, because the module $C$ to which the result will
+belong will be the nearest common ancestor (NCA) of the modules $A$, $B$ to
+which the two operands belong, and $C$ may be different from either or both
+of $A$ and $B$.
+
+>>> A = PowerBasis(T)
+>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
+>>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
+>>> print((B(0) * C(0)).module == A)
+True
+
+Before the arithmetic operation is performed, copies of the two operands are
+automatically converted into elements of the NCA (the operands themselves are
+not modified). This upward conversion along an ancestor chain is easy: it just
+requires the successive multiplication by the defining matrix of each
+:py:class:`~.Submodule`.
+
+Conversely, downward conversion, i.e. representing a given
+:py:class:`~.ModuleElement` in a submodule, is also supported -- namely by
+the :py:meth:`~sympy.polys.numberfields.modules.Submodule.represent` method
+-- but is not guaranteed to succeed in general, since the given element may
+not belong to the submodule. The main circumstance in which this issue tends
+to arise is with multiplication, since modules, while closed under addition,
+need not be closed under multiplication.
+
+
+Multiplication
+--------------
+
+Generally speaking, a module need not be closed under multiplication, i.e. need
+not form a ring. However, many of the modules we work with in the context of
+number fields are in fact rings, and our classes do support multiplication.
+
+Specifically, any :py:class:`~.Module` can attempt to compute its own
+multiplication table, but this does not happen unless an attempt is made to
+multiply two :py:class:`~.ModuleElement` instances belonging to it.
+
+>>> A = PowerBasis(T)
+>>> print(A._mult_tab is None)
+True
+>>> a = A(0)*A(1)
+>>> print(A._mult_tab is None)
+False
+
+Every :py:class:`~.PowerBasis` is, by its nature, closed under multiplication,
+so instances of :py:class:`~.PowerBasis` can always successfully compute their
+multiplication table.
+
+When a :py:class:`~.Submodule` attempts to compute its multiplication table,
+it converts each of its own generators into elements of its parent module,
+multiplies them there, in every possible pairing, and then tries to
+represent the results in itself, i.e. as $\mathbb{Z}$-linear combinations
+over its own generators. This will succeed if and only if the submodule is
+in fact closed under multiplication.
+
+
+Module Homomorphisms
+====================
+
+Many important number theoretic algorithms require the calculation of the
+kernel of one or more module homomorphisms. Accordingly we have several
+lightweight classes, :py:class:`~.ModuleHomomorphism`,
+:py:class:`~.ModuleEndomorphism`, :py:class:`~.InnerEndomorphism`, and
+:py:class:`~.EndomorphismRing`, which provide the minimal necessary machinery
+to support this.
+
+"""
+
+from sympy.core.intfunc import igcd, ilcm
+from sympy.core.symbol import Dummy
+from sympy.polys.polyclasses import ANP
+from sympy.polys.polytools import Poly
+from sympy.polys.densetools import dup_clear_denoms
+from sympy.polys.domains.algebraicfield import AlgebraicField
+from sympy.polys.domains.finitefield import FF
+from sympy.polys.domains.rationalfield import QQ
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.matrices.domainmatrix import DomainMatrix
+from sympy.polys.matrices.exceptions import DMBadInputError
+from sympy.polys.matrices.normalforms import hermite_normal_form
+from sympy.polys.polyerrors import CoercionFailed, UnificationFailed
+from sympy.polys.polyutils import IntegerPowerable
+from .exceptions import ClosureFailure, MissingUnityError, StructureError
+from .utilities import AlgIntPowers, is_rat, get_num_denom
+
+
+def to_col(coeffs):
+    r"""Transform a list of integer coefficients into a column vector."""
+    return DomainMatrix([[ZZ(c) for c in coeffs]], (1, len(coeffs)), ZZ).transpose()
+
+
+class Module:
+    """
+    Generic finitely-generated module.
+
+    This is an abstract base class, and should not be instantiated directly.
+    The two concrete subclasses are :py:class:`~.PowerBasis` and
+    :py:class:`~.Submodule`.
+
+    Every :py:class:`~.Submodule` is derived from another module, referenced
+    by its ``parent`` attribute. If ``S`` is a submodule, then we refer to
+    ``S.parent``, ``S.parent.parent``, and so on, as the "ancestors" of
+    ``S``. Thus, every :py:class:`~.Module` is either a
+    :py:class:`~.PowerBasis` or a :py:class:`~.Submodule`, some ancestor of
+    which is a :py:class:`~.PowerBasis`.
+    """
+
+    @property
+    def n(self):
+        """The number of generators of this module."""
+        raise NotImplementedError
+
+    def mult_tab(self):
+        """
+        Get the multiplication table for this module (if closed under mult).
+
+        Explanation
+        ===========
+
+        Computes a dictionary ``M`` of dictionaries of lists, representing the
+        upper triangular half of the multiplication table.
+
+        In other words, if ``0 <= i <= j < self.n``, then ``M[i][j]`` is the
+        list ``c`` of coefficients such that
+        ``g[i] * g[j] == sum(c[k]*g[k], k in range(self.n))``,
+        where ``g`` is the list of generators of this module.
+
+        If ``j < i`` then ``M[i][j]`` is undefined.
+
+        Examples
+        ========
+
+        >>> from sympy.polys import Poly, cyclotomic_poly
+        >>> from sympy.polys.numberfields.modules import PowerBasis
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> print(A.mult_tab())  # doctest: +SKIP
+        {0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0],     3: [0, 0, 0, 1]},
+                          1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1],     3: [-1, -1, -1, -1]},
+                                           2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]},
+                                                                3: {3: [0, 1, 0, 0]}}
+
+        Returns
+        =======
+
+        dict of dict of lists
+
+        Raises
+        ======
+
+        ClosureFailure
+            If the module is not closed under multiplication.
+
+        """
+        raise NotImplementedError
+
+    @property
+    def parent(self):
+        """
+        The parent module, if any, for this module.
+
+        Explanation
+        ===========
+
+        For a :py:class:`~.Submodule` this is its ``parent`` attribute; for a
+        :py:class:`~.PowerBasis` this is ``None``.
+
+        Returns
+        =======
+
+        :py:class:`~.Module`, ``None``
+
+        See Also
+        ========
+
+        Module
+
+        """
+        return None
+
+    def represent(self, elt):
+        r"""
+        Represent a module element as an integer-linear combination over the
+        generators of this module.
+
+        Explanation
+        ===========
+
+        In our system, to "represent" always means to write a
+        :py:class:`~.ModuleElement` as a :ref:`ZZ`-linear combination over the
+        generators of the present :py:class:`~.Module`. Furthermore, the
+        incoming :py:class:`~.ModuleElement` must belong to an ancestor of
+        the present :py:class:`~.Module` (or to the present
+        :py:class:`~.Module` itself).
+
+        The most common application is to represent a
+        :py:class:`~.ModuleElement` in a :py:class:`~.Submodule`. For example,
+        this is involved in computing multiplication tables.
+
+        On the other hand, representing in a :py:class:`~.PowerBasis` is an
+        odd case, and one which tends not to arise in practice, except for
+        example when using a :py:class:`~.ModuleEndomorphism` on a
+        :py:class:`~.PowerBasis`.
+
+        In such a case, (1) the incoming :py:class:`~.ModuleElement` must
+        belong to the :py:class:`~.PowerBasis` itself (since the latter has no
+        proper ancestors) and (2) it is "representable" iff it belongs to
+        $\mathbb{Z}[\theta]$ (although generally a
+        :py:class:`~.PowerBasisElement` may represent any element of
+        $\mathbb{Q}(\theta)$, i.e. any algebraic number).
+
+        Examples
+        ========
+
+        >>> from sympy import Poly, cyclotomic_poly
+        >>> from sympy.polys.numberfields.modules import PowerBasis, to_col
+        >>> from sympy.abc import zeta
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> a = A(to_col([2, 4, 6, 8]))
+
+        The :py:class:`~.ModuleElement` ``a`` has all even coefficients.
+        If we represent ``a`` in the submodule ``B = 2*A``, the coefficients in
+        the column vector will be halved:
+
+        >>> B = A.submodule_from_gens([2*A(i) for i in range(4)])
+        >>> b = B.represent(a)
+        >>> print(b.transpose())  # doctest: +SKIP
+        DomainMatrix([[1, 2, 3, 4]], (1, 4), ZZ)
+
+        However, the element of ``B`` so defined still represents the same
+        algebraic number:
+
+        >>> print(a.poly(zeta).as_expr())
+        8*zeta**3 + 6*zeta**2 + 4*zeta + 2
+        >>> print(B(b).over_power_basis().poly(zeta).as_expr())
+        8*zeta**3 + 6*zeta**2 + 4*zeta + 2
+
+        Parameters
+        ==========
+
+        elt : :py:class:`~.ModuleElement`
+            The module element to be represented. Must belong to some ancestor
+            module of this module (including this module itself).
+
+        Returns
+        =======
+
+        :py:class:`~.DomainMatrix` over :ref:`ZZ`
+            This will be a column vector, representing the coefficients of a
+            linear combination of this module's generators, which equals the
+            given element.
+
+        Raises
+        ======
+
+        ClosureFailure
+            If the given element cannot be represented as a :ref:`ZZ`-linear
+            combination over this module.
+
+        See Also
+        ========
+
+        .Submodule.represent
+        .PowerBasis.represent
+
+        """
+        raise NotImplementedError
+
+    def ancestors(self, include_self=False):
+        """
+        Return the list of ancestor modules of this module, from the
+        foundational :py:class:`~.PowerBasis` downward, optionally including
+        ``self``.
+
+        See Also
+        ========
+
+        Module
+
+        """
+        c = self.parent
+        a = [] if c is None else c.ancestors(include_self=True)
+        if include_self:
+            a.append(self)
+        return a
+
+    def power_basis_ancestor(self):
+        """
+        Return the :py:class:`~.PowerBasis` that is an ancestor of this module.
+
+        See Also
+        ========
+
+        Module
+
+        """
+        if isinstance(self, PowerBasis):
+            return self
+        c = self.parent
+        if c is not None:
+            return c.power_basis_ancestor()
+        return None
+
+    def nearest_common_ancestor(self, other):
+        """
+        Locate the nearest common ancestor of this module and another.
+
+        Returns
+        =======
+
+        :py:class:`~.Module`, ``None``
+
+        See Also
+        ========
+
+        Module
+
+        """
+        sA = self.ancestors(include_self=True)
+        oA = other.ancestors(include_self=True)
+        nca = None
+        for sa, oa in zip(sA, oA):
+            if sa == oa:
+                nca = sa
+            else:
+                break
+        return nca
+
+    @property
+    def number_field(self):
+        r"""
+        Return the associated :py:class:`~.AlgebraicField`, if any.
+
+        Explanation
+        ===========
+
+        A :py:class:`~.PowerBasis` can be constructed on a :py:class:`~.Poly`
+        $f$ or on an :py:class:`~.AlgebraicField` $K$. In the latter case, the
+        :py:class:`~.PowerBasis` and all its descendant modules will return $K$
+        as their ``.number_field`` property, while in the former case they will
+        all return ``None``.
+
+        Returns
+        =======
+
+        :py:class:`~.AlgebraicField`, ``None``
+
+        """
+        return self.power_basis_ancestor().number_field
+
+    def is_compat_col(self, col):
+        """Say whether *col* is a suitable column vector for this module."""
+        return isinstance(col, DomainMatrix) and col.shape == (self.n, 1) and col.domain.is_ZZ
+
+    def __call__(self, spec, denom=1):
+        r"""
+        Generate a :py:class:`~.ModuleElement` belonging to this module.
+
+        Examples
+        ========
+
+        >>> from sympy.polys import Poly, cyclotomic_poly
+        >>> from sympy.polys.numberfields.modules import PowerBasis, to_col
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> e = A(to_col([1, 2, 3, 4]), denom=3)
+        >>> print(e)  # doctest: +SKIP
+        [1, 2, 3, 4]/3
+        >>> f = A(2)
+        >>> print(f)  # doctest: +SKIP
+        [0, 0, 1, 0]
+
+        Parameters
+        ==========
+
+        spec : :py:class:`~.DomainMatrix`, int
+            Specifies the numerators of the coefficients of the
+            :py:class:`~.ModuleElement`. Can be either a column vector over
+            :ref:`ZZ`, whose length must equal the number $n$ of generators of
+            this module, or else an integer ``j``, $0 \leq j < n$, which is a
+            shorthand for column $j$ of $I_n$, the $n \times n$ identity
+            matrix.
+        denom : int, optional (default=1)
+            Denominator for the coefficients of the
+            :py:class:`~.ModuleElement`.
+
+        Returns
+        =======
+
+        :py:class:`~.ModuleElement`
+            The coefficients are the entries of the *spec* vector, divided by
+            *denom*.
+
+        """
+        if isinstance(spec, int) and 0 <= spec < self.n:
+            spec = DomainMatrix.eye(self.n, ZZ)[:, spec].to_dense()
+        if not self.is_compat_col(spec):
+            raise ValueError('Compatible column vector required.')
+        return make_mod_elt(self, spec, denom=denom)
+
+    def starts_with_unity(self):
+        """Say whether the module's first generator equals unity."""
+        raise NotImplementedError
+
+    def basis_elements(self):
+        """
+        Get list of :py:class:`~.ModuleElement` being the generators of this
+        module.
+        """
+        return [self(j) for j in range(self.n)]
+
+    def zero(self):
+        """Return a :py:class:`~.ModuleElement` representing zero."""
+        return self(0) * 0
+
+    def one(self):
+        """
+        Return a :py:class:`~.ModuleElement` representing unity,
+        and belonging to the first ancestor of this module (including
+        itself) that starts with unity.
+        """
+        return self.element_from_rational(1)
+
+    def element_from_rational(self, a):
+        """
+        Return a :py:class:`~.ModuleElement` representing a rational number.
+
+        Explanation
+        ===========
+
+        The returned :py:class:`~.ModuleElement` will belong to the first
+        module on this module's ancestor chain (including this module
+        itself) that starts with unity.
+
+        Examples
+        ========
+
+        >>> from sympy.polys import Poly, cyclotomic_poly, QQ
+        >>> from sympy.polys.numberfields.modules import PowerBasis
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> a = A.element_from_rational(QQ(2, 3))
+        >>> print(a)  # doctest: +SKIP
+        [2, 0, 0, 0]/3
+
+        Parameters
+        ==========
+
+        a : int, :ref:`ZZ`, :ref:`QQ`
+
+        Returns
+        =======
+
+        :py:class:`~.ModuleElement`
+
+        """
+        raise NotImplementedError
+
+    def submodule_from_gens(self, gens, hnf=True, hnf_modulus=None):
+        """
+        Form the submodule generated by a list of :py:class:`~.ModuleElement`
+        belonging to this module.
+
+        Examples
+        ========
+
+        >>> from sympy.polys import Poly, cyclotomic_poly
+        >>> from sympy.polys.numberfields.modules import PowerBasis
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> gens = [A(0), 2*A(1), 3*A(2), 4*A(3)//5]
+        >>> B = A.submodule_from_gens(gens)
+        >>> print(B)  # doctest: +SKIP
+        Submodule[[5, 0, 0, 0], [0, 10, 0, 0], [0, 0, 15, 0], [0, 0, 0, 4]]/5
+
+        Parameters
+        ==========
+
+        gens : list of :py:class:`~.ModuleElement` belonging to this module.
+        hnf : boolean, optional (default=True)
+            If True, we will reduce the matrix into Hermite Normal Form before
+            forming the :py:class:`~.Submodule`.
+        hnf_modulus : int, None, optional (default=None)
+            Modulus for use in the HNF reduction algorithm. See
+            :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+
+        See Also
+        ========
+
+        submodule_from_matrix
+
+        """
+        if not all(g.module == self for g in gens):
+            raise ValueError('Generators must belong to this module.')
+        n = len(gens)
+        if n == 0:
+            raise ValueError('Need at least one generator.')
+        m = gens[0].n
+        d = gens[0].denom if n == 1 else ilcm(*[g.denom for g in gens])
+        B = DomainMatrix.zeros((m, 0), ZZ).hstack(*[(d // g.denom) * g.col for g in gens])
+        if hnf:
+            B = hermite_normal_form(B, D=hnf_modulus)
+        return self.submodule_from_matrix(B, denom=d)
+
+    def submodule_from_matrix(self, B, denom=1):
+        """
+        Form the submodule generated by the elements of this module indicated
+        by the columns of a matrix, with an optional denominator.
+
+        Examples
+        ========
+
+        >>> from sympy.polys import Poly, cyclotomic_poly, ZZ
+        >>> from sympy.polys.matrices import DM
+        >>> from sympy.polys.numberfields.modules import PowerBasis
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> B = A.submodule_from_matrix(DM([
+        ...     [0, 10, 0, 0],
+        ...     [0,  0, 7, 0],
+        ... ], ZZ).transpose(), denom=15)
+        >>> print(B)  # doctest: +SKIP
+        Submodule[[0, 10, 0, 0], [0, 0, 7, 0]]/15
+
+        Parameters
+        ==========
+
+        B : :py:class:`~.DomainMatrix` over :ref:`ZZ`
+            Each column gives the numerators of the coefficients of one
+            generator of the submodule. Thus, the number of rows of *B* must
+            equal the number of generators of the present module.
+        denom : int, optional (default=1)
+            Common denominator for all generators of the submodule.
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+
+        Raises
+        ======
+
+        ValueError
+            If the given matrix *B* is not over :ref:`ZZ` or its number of rows
+            does not equal the number of generators of the present module.
+
+        See Also
+        ========
+
+        submodule_from_gens
+
+        """
+        m, n = B.shape
+        if not B.domain.is_ZZ:
+            raise ValueError('Matrix must be over ZZ.')
+        if not m == self.n:
+            raise ValueError('Matrix row count must match base module.')
+        return Submodule(self, B, denom=denom)
+
+    def whole_submodule(self):
+        """
+        Return a submodule equal to this entire module.
+
+        Explanation
+        ===========
+
+        This is useful when you have a :py:class:`~.PowerBasis` and want to
+        turn it into a :py:class:`~.Submodule` (in order to use methods
+        belonging to the latter).
+
+        """
+        B = DomainMatrix.eye(self.n, ZZ)
+        return self.submodule_from_matrix(B)
+
+    def endomorphism_ring(self):
+        """Form the :py:class:`~.EndomorphismRing` for this module."""
+        return EndomorphismRing(self)
+
+
+class PowerBasis(Module):
+    """The module generated by the powers of an algebraic integer."""
+
+    def __init__(self, T):
+        """
+        Parameters
+        ==========
+
+        T : :py:class:`~.Poly`, :py:class:`~.AlgebraicField`
+            Either (1) the monic, irreducible, univariate polynomial over
+            :ref:`ZZ`, a root of which is the generator of the power basis,
+            or (2) an :py:class:`~.AlgebraicField` whose primitive element
+            is the generator of the power basis.
+
+        """
+        K = None
+        if isinstance(T, AlgebraicField):
+            K, T = T, T.ext.minpoly_of_element()
+        # Sometimes incoming Polys are formally over QQ, although all their
+        # coeffs are integral. We want them to be formally over ZZ.
+        T = T.set_domain(ZZ)
+        self.K = K
+        self.T = T
+        self._n = T.degree()
+        self._mult_tab = None
+
+    @property
+    def number_field(self):
+        return self.K
+
+    def __repr__(self):
+        return f'PowerBasis({self.T.as_expr()})'
+
+    def __eq__(self, other):
+        if isinstance(other, PowerBasis):
+            return self.T == other.T
+        return NotImplemented
+
+    @property
+    def n(self):
+        return self._n
+
+    def mult_tab(self):
+        if self._mult_tab is None:
+            self.compute_mult_tab()
+        return self._mult_tab
+
+    def compute_mult_tab(self):
+        theta_pow = AlgIntPowers(self.T)
+        M = {}
+        n = self.n
+        for u in range(n):
+            M[u] = {}
+            for v in range(u, n):
+                M[u][v] = theta_pow[u + v]
+        self._mult_tab = M
+
+    def represent(self, elt):
+        r"""
+        Represent a module element as an integer-linear combination over the
+        generators of this module.
+
+        See Also
+        ========
+
+        .Module.represent
+        .Submodule.represent
+
+        """
+        if elt.module == self and elt.denom == 1:
+            return elt.column()
+        else:
+            raise ClosureFailure('Element not representable in ZZ[theta].')
+
+    def starts_with_unity(self):
+        return True
+
+    def element_from_rational(self, a):
+        return self(0) * a
+
+    def element_from_poly(self, f):
+        """
+        Produce an element of this module, representing *f* after reduction mod
+        our defining minimal polynomial.
+
+        Parameters
+        ==========
+
+        f : :py:class:`~.Poly` over :ref:`ZZ` in same var as our defining poly.
+
+        Returns
+        =======
+
+        :py:class:`~.PowerBasisElement`
+
+        """
+        n, k = self.n, f.degree()
+        if k >= n:
+            f = f % self.T
+        if f == 0:
+            return self.zero()
+        d, c = dup_clear_denoms(f.rep.to_list(), QQ, convert=True)
+        c = list(reversed(c))
+        ell = len(c)
+        z = [ZZ(0)] * (n - ell)
+        col = to_col(c + z)
+        return self(col, denom=d)
+
+    def _element_from_rep_and_mod(self, rep, mod):
+        """
+        Produce a PowerBasisElement representing a given algebraic number.
+
+        Parameters
+        ==========
+
+        rep : list of coeffs
+            Represents the number as polynomial in the primitive element of the
+            field.
+
+        mod : list of coeffs
+            Represents the minimal polynomial of the primitive element of the
+            field.
+
+        Returns
+        =======
+
+        :py:class:`~.PowerBasisElement`
+
+        """
+        if mod != self.T.rep.to_list():
+            raise UnificationFailed('Element does not appear to be in the same field.')
+        return self.element_from_poly(Poly(rep, self.T.gen))
+
+    def element_from_ANP(self, a):
+        """Convert an ANP into a PowerBasisElement. """
+        return self._element_from_rep_and_mod(a.to_list(), a.mod_to_list())
+
+    def element_from_alg_num(self, a):
+        """Convert an AlgebraicNumber into a PowerBasisElement. """
+        return self._element_from_rep_and_mod(a.rep.to_list(), a.minpoly.rep.to_list())
+
+
+class Submodule(Module, IntegerPowerable):
+    """A submodule of another module."""
+
+    def __init__(self, parent, matrix, denom=1, mult_tab=None):
+        """
+        Parameters
+        ==========
+
+        parent : :py:class:`~.Module`
+            The module from which this one is derived.
+        matrix : :py:class:`~.DomainMatrix` over :ref:`ZZ`
+            The matrix whose columns define this submodule's generators as
+            linear combinations over the parent's generators.
+        denom : int, optional (default=1)
+            Denominator for the coefficients given by the matrix.
+        mult_tab : dict, ``None``, optional
+            If already known, the multiplication table for this module may be
+            supplied.
+
+        """
+        self._parent = parent
+        self._matrix = matrix
+        self._denom = denom
+        self._mult_tab = mult_tab
+        self._n = matrix.shape[1]
+        self._QQ_matrix = None
+        self._starts_with_unity = None
+        self._is_sq_maxrank_HNF = None
+
+    def __repr__(self):
+        r = 'Submodule' + repr(self.matrix.transpose().to_Matrix().tolist())
+        if self.denom > 1:
+            r += f'/{self.denom}'
+        return r
+
+    def reduced(self):
+        """
+        Produce a reduced version of this submodule.
+
+        Explanation
+        ===========
+
+        In the reduced version, it is guaranteed that 1 is the only positive
+        integer dividing both the submodule's denominator, and every entry in
+        the submodule's matrix.
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+
+        """
+        if self.denom == 1:
+            return self
+        g = igcd(self.denom, *self.coeffs)
+        if g == 1:
+            return self
+        return type(self)(self.parent, (self.matrix / g).convert_to(ZZ), denom=self.denom // g, mult_tab=self._mult_tab)
+
+    def discard_before(self, r):
+        """
+        Produce a new module by discarding all generators before a given
+        index *r*.
+        """
+        W = self.matrix[:, r:]
+        s = self.n - r
+        M = None
+        mt = self._mult_tab
+        if mt is not None:
+            M = {}
+            for u in range(s):
+                M[u] = {}
+                for v in range(u, s):
+                    M[u][v] = mt[r + u][r + v][r:]
+        return Submodule(self.parent, W, denom=self.denom, mult_tab=M)
+
+    @property
+    def n(self):
+        return self._n
+
+    def mult_tab(self):
+        if self._mult_tab is None:
+            self.compute_mult_tab()
+        return self._mult_tab
+
+    def compute_mult_tab(self):
+        gens = self.basis_element_pullbacks()
+        M = {}
+        n = self.n
+        for u in range(n):
+            M[u] = {}
+            for v in range(u, n):
+                M[u][v] = self.represent(gens[u] * gens[v]).flat()
+        self._mult_tab = M
+
+    @property
+    def parent(self):
+        return self._parent
+
+    @property
+    def matrix(self):
+        return self._matrix
+
+    @property
+    def coeffs(self):
+        return self.matrix.flat()
+
+    @property
+    def denom(self):
+        return self._denom
+
+    @property
+    def QQ_matrix(self):
+        """
+        :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to
+        ``self.matrix / self.denom``, and guaranteed to be dense.
+
+        Explanation
+        ===========
+
+        Depending on how it is formed, a :py:class:`~.DomainMatrix` may have
+        an internal representation that is sparse or dense. We guarantee a
+        dense representation here, so that tests for equivalence of submodules
+        always come out as expected.
+
+        Examples
+        ========
+
+        >>> from sympy.polys import Poly, cyclotomic_poly, ZZ
+        >>> from sympy.abc import x
+        >>> from sympy.polys.matrices import DomainMatrix
+        >>> from sympy.polys.numberfields.modules import PowerBasis
+        >>> T = Poly(cyclotomic_poly(5, x))
+        >>> A = PowerBasis(T)
+        >>> B = A.submodule_from_matrix(3*DomainMatrix.eye(4, ZZ), denom=6)
+        >>> C = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2)
+        >>> print(B.QQ_matrix == C.QQ_matrix)
+        True
+
+        Returns
+        =======
+
+        :py:class:`~.DomainMatrix` over :ref:`QQ`
+
+        """
+        if self._QQ_matrix is None:
+            self._QQ_matrix = (self.matrix / self.denom).to_dense()
+        return self._QQ_matrix
+
+    def starts_with_unity(self):
+        if self._starts_with_unity is None:
+            self._starts_with_unity = self(0).equiv(1)
+        return self._starts_with_unity
+
+    def is_sq_maxrank_HNF(self):
+        if self._is_sq_maxrank_HNF is None:
+            self._is_sq_maxrank_HNF = is_sq_maxrank_HNF(self._matrix)
+        return self._is_sq_maxrank_HNF
+
+    def is_power_basis_submodule(self):
+        return isinstance(self.parent, PowerBasis)
+
+    def element_from_rational(self, a):
+        if self.starts_with_unity():
+            return self(0) * a
+        else:
+            return self.parent.element_from_rational(a)
+
+    def basis_element_pullbacks(self):
+        """
+        Return list of this submodule's basis elements as elements of the
+        submodule's parent module.
+        """
+        return [e.to_parent() for e in self.basis_elements()]
+
+    def represent(self, elt):
+        """
+        Represent a module element as an integer-linear combination over the
+        generators of this module.
+
+        See Also
+        ========
+
+        .Module.represent
+        .PowerBasis.represent
+
+        """
+        if elt.module == self:
+            return elt.column()
+        elif elt.module == self.parent:
+            try:
+                # The given element should be a ZZ-linear combination over our
+                # basis vectors; however, due to the presence of denominators,
+                # we need to solve over QQ.
+                A = self.QQ_matrix
+                b = elt.QQ_col
+                x = A._solve(b)[0].transpose()
+                x = x.convert_to(ZZ)
+            except DMBadInputError:
+                raise ClosureFailure('Element outside QQ-span of this basis.')
+            except CoercionFailed:
+                raise ClosureFailure('Element in QQ-span but not ZZ-span of this basis.')
+            return x
+        elif isinstance(self.parent, Submodule):
+            coeffs_in_parent = self.parent.represent(elt)
+            parent_element = self.parent(coeffs_in_parent)
+            return self.represent(parent_element)
+        else:
+            raise ClosureFailure('Element outside ancestor chain of this module.')
+
+    def is_compat_submodule(self, other):
+        return isinstance(other, Submodule) and other.parent == self.parent
+
+    def __eq__(self, other):
+        if self.is_compat_submodule(other):
+            return other.QQ_matrix == self.QQ_matrix
+        return NotImplemented
+
+    def add(self, other, hnf=True, hnf_modulus=None):
+        """
+        Add this :py:class:`~.Submodule` to another.
+
+        Explanation
+        ===========
+
+        This represents the module generated by the union of the two modules'
+        sets of generators.
+
+        Parameters
+        ==========
+
+        other : :py:class:`~.Submodule`
+        hnf : boolean, optional (default=True)
+            If ``True``, reduce the matrix of the combined module to its
+            Hermite Normal Form.
+        hnf_modulus : :ref:`ZZ`, None, optional
+            If a positive integer is provided, use this as modulus in the
+            HNF reduction. See
+            :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+
+        """
+        d, e = self.denom, other.denom
+        m = ilcm(d, e)
+        a, b = m // d, m // e
+        B = (a * self.matrix).hstack(b * other.matrix)
+        if hnf:
+            B = hermite_normal_form(B, D=hnf_modulus)
+        return self.parent.submodule_from_matrix(B, denom=m)
+
+    def __add__(self, other):
+        if self.is_compat_submodule(other):
+            return self.add(other)
+        return NotImplemented
+
+    __radd__ = __add__
+
+    def mul(self, other, hnf=True, hnf_modulus=None):
+        """
+        Multiply this :py:class:`~.Submodule` by a rational number, a
+        :py:class:`~.ModuleElement`, or another :py:class:`~.Submodule`.
+
+        Explanation
+        ===========
+
+        To multiply by a rational number or :py:class:`~.ModuleElement` means
+        to form the submodule whose generators are the products of this
+        quantity with all the generators of the present submodule.
+
+        To multiply by another :py:class:`~.Submodule` means to form the
+        submodule whose generators are all the products of one generator from
+        the one submodule, and one generator from the other.
+
+        Parameters
+        ==========
+
+        other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`, :py:class:`~.Submodule`
+        hnf : boolean, optional (default=True)
+            If ``True``, reduce the matrix of the product module to its
+            Hermite Normal Form.
+        hnf_modulus : :ref:`ZZ`, None, optional
+            If a positive integer is provided, use this as modulus in the
+            HNF reduction. See
+            :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+
+        """
+        if is_rat(other):
+            a, b = get_num_denom(other)
+            if a == b == 1:
+                return self
+            else:
+                return Submodule(self.parent,
+                             self.matrix * a, denom=self.denom * b,
+                             mult_tab=None).reduced()
+        elif isinstance(other, ModuleElement) and other.module == self.parent:
+            # The submodule is multiplied by an element of the parent module.
+            # We presume this means we want a new submodule of the parent module.
+            gens = [other * e for e in self.basis_element_pullbacks()]
+            return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus)
+        elif self.is_compat_submodule(other):
+            # This case usually means you're multiplying ideals, and want another
+            # ideal, i.e. another submodule of the same parent module.
+            alphas, betas = self.basis_element_pullbacks(), other.basis_element_pullbacks()
+            gens = [a * b for a in alphas for b in betas]
+            return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus)
+        return NotImplemented
+
+    def __mul__(self, other):
+        return self.mul(other)
+
+    __rmul__ = __mul__
+
+    def _first_power(self):
+        return self
+
+    def reduce_element(self, elt):
+        r"""
+        If this submodule $B$ has defining matrix $W$ in square, maximal-rank
+        Hermite normal form, then, given an element $x$ of the parent module
+        $A$, we produce an element $y \in A$ such that $x - y \in B$, and the
+        $i$th coordinate of $y$ satisfies $0 \leq y_i < w_{i,i}$. This
+        representative $y$ is unique, in the sense that every element of
+        the coset $x + B$ reduces to it under this procedure.
+
+        Explanation
+        ===========
+
+        In the special case where $A$ is a power basis for a number field $K$,
+        and $B$ is a submodule representing an ideal $I$, this operation
+        represents one of a few important ways of reducing an element of $K$
+        modulo $I$ to obtain a "small" representative. See [Cohen00]_ Section
+        1.4.3.
+
+        Examples
+        ========
+
+        >>> from sympy import QQ, Poly, symbols
+        >>> t = symbols('t')
+        >>> k = QQ.alg_field_from_poly(Poly(t**3 + t**2 - 2*t + 8))
+        >>> Zk = k.maximal_order()
+        >>> A = Zk.parent
+        >>> B = (A(2) - 3*A(0))*Zk
+        >>> B.reduce_element(A(2))
+        [3, 0, 0]
+
+        Parameters
+        ==========
+
+        elt : :py:class:`~.ModuleElement`
+            An element of this submodule's parent module.
+
+        Returns
+        =======
+
+        elt : :py:class:`~.ModuleElement`
+            An element of this submodule's parent module.
+
+        Raises
+        ======
+
+        NotImplementedError
+            If the given :py:class:`~.ModuleElement` does not belong to this
+            submodule's parent module.
+        StructureError
+            If this submodule's defining matrix is not in square, maximal-rank
+            Hermite normal form.
+
+        References
+        ==========
+
+        .. [Cohen00] Cohen, H. *Advanced Topics in Computational Number
+           Theory.*
+
+        """
+        if not elt.module == self.parent:
+            raise NotImplementedError
+        if not self.is_sq_maxrank_HNF():
+            msg = "Reduction not implemented unless matrix square max-rank HNF"
+            raise StructureError(msg)
+        B = self.basis_element_pullbacks()
+        a = elt
+        for i in range(self.n - 1, -1, -1):
+            b = B[i]
+            q = a.coeffs[i]*b.denom // (b.coeffs[i]*a.denom)
+            a -= q*b
+        return a
+
+
+def is_sq_maxrank_HNF(dm):
+    r"""
+    Say whether a :py:class:`~.DomainMatrix` is in that special case of Hermite
+    Normal Form, in which the matrix is also square and of maximal rank.
+
+    Explanation
+    ===========
+
+    We commonly work with :py:class:`~.Submodule` instances whose matrix is in
+    this form, and it can be useful to be able to check that this condition is
+    satisfied.
+
+    For example this is the case with the :py:class:`~.Submodule` ``ZK``
+    returned by :py:func:`~sympy.polys.numberfields.basis.round_two`, which
+    represents the maximal order in a number field, and with ideals formed
+    therefrom, such as ``2 * ZK``.
+
+    """
+    if dm.domain.is_ZZ and dm.is_square and dm.is_upper:
+        n = dm.shape[0]
+        for i in range(n):
+            d = dm[i, i].element
+            if d <= 0:
+                return False
+            for j in range(i + 1, n):
+                if not (0 <= dm[i, j].element < d):
+                    return False
+        return True
+    return False
+
+
+def make_mod_elt(module, col, denom=1):
+    r"""
+    Factory function which builds a :py:class:`~.ModuleElement`, but ensures
+    that it is a :py:class:`~.PowerBasisElement` if the module is a
+    :py:class:`~.PowerBasis`.
+    """
+    if isinstance(module, PowerBasis):
+        return PowerBasisElement(module, col, denom=denom)
+    else:
+        return ModuleElement(module, col, denom=denom)
+
+
+class ModuleElement(IntegerPowerable):
+    r"""
+    Represents an element of a :py:class:`~.Module`.
+
+    NOTE: Should not be constructed directly. Use the
+    :py:meth:`~.Module.__call__` method or the :py:func:`make_mod_elt()`
+    factory function instead.
+    """
+
+    def __init__(self, module, col, denom=1):
+        """
+        Parameters
+        ==========
+
+        module : :py:class:`~.Module`
+            The module to which this element belongs.
+        col : :py:class:`~.DomainMatrix` over :ref:`ZZ`
+            Column vector giving the numerators of the coefficients of this
+            element.
+        denom : int, optional (default=1)
+            Denominator for the coefficients of this element.
+
+        """
+        self.module = module
+        self.col = col
+        self.denom = denom
+        self._QQ_col = None
+
+    def __repr__(self):
+        r = str([int(c) for c in self.col.flat()])
+        if self.denom > 1:
+            r += f'/{self.denom}'
+        return r
+
+    def reduced(self):
+        """
+        Produce a reduced version of this ModuleElement, i.e. one in which the
+        gcd of the denominator together with all numerator coefficients is 1.
+        """
+        if self.denom == 1:
+            return self
+        g = igcd(self.denom, *self.coeffs)
+        if g == 1:
+            return self
+        return type(self)(self.module,
+                            (self.col / g).convert_to(ZZ),
+                            denom=self.denom // g)
+
+    def reduced_mod_p(self, p):
+        """
+        Produce a version of this :py:class:`~.ModuleElement` in which all
+        numerator coefficients have been reduced mod *p*.
+        """
+        return make_mod_elt(self.module,
+                            self.col.convert_to(FF(p)).convert_to(ZZ),
+                            denom=self.denom)
+
+    @classmethod
+    def from_int_list(cls, module, coeffs, denom=1):
+        """
+        Make a :py:class:`~.ModuleElement` from a list of ints (instead of a
+        column vector).
+        """
+        col = to_col(coeffs)
+        return cls(module, col, denom=denom)
+
+    @property
+    def n(self):
+        """The length of this element's column."""
+        return self.module.n
+
+    def __len__(self):
+        return self.n
+
+    def column(self, domain=None):
+        """
+        Get a copy of this element's column, optionally converting to a domain.
+        """
+        if domain is None:
+            return self.col.copy()
+        else:
+            return self.col.convert_to(domain)
+
+    @property
+    def coeffs(self):
+        return self.col.flat()
+
+    @property
+    def QQ_col(self):
+        """
+        :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to
+        ``self.col / self.denom``, and guaranteed to be dense.
+
+        See Also
+        ========
+
+        .Submodule.QQ_matrix
+
+        """
+        if self._QQ_col is None:
+            self._QQ_col = (self.col / self.denom).to_dense()
+        return self._QQ_col
+
+    def to_parent(self):
+        """
+        Transform into a :py:class:`~.ModuleElement` belonging to the parent of
+        this element's module.
+        """
+        if not isinstance(self.module, Submodule):
+            raise ValueError('Not an element of a Submodule.')
+        return make_mod_elt(
+            self.module.parent, self.module.matrix * self.col,
+            denom=self.module.denom * self.denom)
+
+    def to_ancestor(self, anc):
+        """
+        Transform into a :py:class:`~.ModuleElement` belonging to a given
+        ancestor of this element's module.
+
+        Parameters
+        ==========
+
+        anc : :py:class:`~.Module`
+
+        """
+        if anc == self.module:
+            return self
+        else:
+            return self.to_parent().to_ancestor(anc)
+
+    def over_power_basis(self):
+        """
+        Transform into a :py:class:`~.PowerBasisElement` over our
+        :py:class:`~.PowerBasis` ancestor.
+        """
+        e = self
+        while not isinstance(e.module, PowerBasis):
+            e = e.to_parent()
+        return e
+
+    def is_compat(self, other):
+        """
+        Test whether other is another :py:class:`~.ModuleElement` with same
+        module.
+        """
+        return isinstance(other, ModuleElement) and other.module == self.module
+
+    def unify(self, other):
+        """
+        Try to make a compatible pair of :py:class:`~.ModuleElement`, one
+        equivalent to this one, and one equivalent to the other.
+
+        Explanation
+        ===========
+
+        We search for the nearest common ancestor module for the pair of
+        elements, and represent each one there.
+
+        Returns
+        =======
+
+        Pair ``(e1, e2)``
+            Each ``ei`` is a :py:class:`~.ModuleElement`, they belong to the
+            same :py:class:`~.Module`, ``e1`` is equivalent to ``self``, and
+            ``e2`` is equivalent to ``other``.
+
+        Raises
+        ======
+
+        UnificationFailed
+            If ``self`` and ``other`` have no common ancestor module.
+
+        """
+        if self.module == other.module:
+            return self, other
+        nca = self.module.nearest_common_ancestor(other.module)
+        if nca is not None:
+            return self.to_ancestor(nca), other.to_ancestor(nca)
+        raise UnificationFailed(f"Cannot unify {self} with {other}")
+
+    def __eq__(self, other):
+        if self.is_compat(other):
+            return self.QQ_col == other.QQ_col
+        return NotImplemented
+
+    def equiv(self, other):
+        """
+        A :py:class:`~.ModuleElement` may test as equivalent to a rational
+        number or another :py:class:`~.ModuleElement`, if they represent the
+        same algebraic number.
+
+        Explanation
+        ===========
+
+        This method is intended to check equivalence only in those cases in
+        which it is easy to test; namely, when *other* is either a
+        :py:class:`~.ModuleElement` that can be unified with this one (i.e. one
+        which shares a common :py:class:`~.PowerBasis` ancestor), or else a
+        rational number (which is easy because every :py:class:`~.PowerBasis`
+        represents every rational number).
+
+        Parameters
+        ==========
+
+        other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`
+
+        Returns
+        =======
+
+        bool
+
+        Raises
+        ======
+
+        UnificationFailed
+            If ``self`` and ``other`` do not share a common
+            :py:class:`~.PowerBasis` ancestor.
+
+        """
+        if self == other:
+            return True
+        elif isinstance(other, ModuleElement):
+            a, b = self.unify(other)
+            return a == b
+        elif is_rat(other):
+            if isinstance(self, PowerBasisElement):
+                return self == self.module(0) * other
+            else:
+                return self.over_power_basis().equiv(other)
+        return False
+
+    def __add__(self, other):
+        """
+        A :py:class:`~.ModuleElement` can be added to a rational number, or to
+        another :py:class:`~.ModuleElement`.
+
+        Explanation
+        ===========
+
+        When the other summand is a rational number, it will be converted into
+        a :py:class:`~.ModuleElement` (belonging to the first ancestor of this
+        module that starts with unity).
+
+        In all cases, the sum belongs to the nearest common ancestor (NCA) of
+        the modules of the two summands. If the NCA does not exist, we return
+        ``NotImplemented``.
+        """
+        if self.is_compat(other):
+            d, e = self.denom, other.denom
+            m = ilcm(d, e)
+            u, v = m // d, m // e
+            col = to_col([u * a + v * b for a, b in zip(self.coeffs, other.coeffs)])
+            return type(self)(self.module, col, denom=m).reduced()
+        elif isinstance(other, ModuleElement):
+            try:
+                a, b = self.unify(other)
+            except UnificationFailed:
+                return NotImplemented
+            return a + b
+        elif is_rat(other):
+            return self + self.module.element_from_rational(other)
+        return NotImplemented
+
+    __radd__ = __add__
+
+    def __neg__(self):
+        return self * -1
+
+    def __sub__(self, other):
+        return self + (-other)
+
+    def __rsub__(self, other):
+        return -self + other
+
+    def __mul__(self, other):
+        """
+        A :py:class:`~.ModuleElement` can be multiplied by a rational number,
+        or by another :py:class:`~.ModuleElement`.
+
+        Explanation
+        ===========
+
+        When the multiplier is a rational number, the product is computed by
+        operating directly on the coefficients of this
+        :py:class:`~.ModuleElement`.
+
+        When the multiplier is another :py:class:`~.ModuleElement`, the product
+        will belong to the nearest common ancestor (NCA) of the modules of the
+        two operands, and that NCA must have a multiplication table. If the NCA
+        does not exist, we return ``NotImplemented``. If the NCA does not have
+        a mult. table, ``ClosureFailure`` will be raised.
+        """
+        if self.is_compat(other):
+            M = self.module.mult_tab()
+            A, B = self.col.flat(), other.col.flat()
+            n = self.n
+            C = [0] * n
+            for u in range(n):
+                for v in range(u, n):
+                    c = A[u] * B[v]
+                    if v > u:
+                        c += A[v] * B[u]
+                    if c != 0:
+                        R = M[u][v]
+                        for k in range(n):
+                            C[k] += c * R[k]
+            d = self.denom * other.denom
+            return self.from_int_list(self.module, C, denom=d)
+        elif isinstance(other, ModuleElement):
+            try:
+                a, b = self.unify(other)
+            except UnificationFailed:
+                return NotImplemented
+            return a * b
+        elif is_rat(other):
+            a, b = get_num_denom(other)
+            if a == b == 1:
+                return self
+            else:
+                return make_mod_elt(self.module,
+                                 self.col * a, denom=self.denom * b).reduced()
+        return NotImplemented
+
+    __rmul__ = __mul__
+
+    def _zeroth_power(self):
+        return self.module.one()
+
+    def _first_power(self):
+        return self
+
+    def __floordiv__(self, a):
+        if is_rat(a):
+            a = QQ(a)
+            return self * (1/a)
+        elif isinstance(a, ModuleElement):
+            return self * (1//a)
+        return NotImplemented
+
+    def __rfloordiv__(self, a):
+        return a // self.over_power_basis()
+
+    def __mod__(self, m):
+        r"""
+        Reduce this :py:class:`~.ModuleElement` mod a :py:class:`~.Submodule`.
+
+        Parameters
+        ==========
+
+        m : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.Submodule`
+            If a :py:class:`~.Submodule`, reduce ``self`` relative to this.
+            If an integer or rational, reduce relative to the
+            :py:class:`~.Submodule` that is our own module times this constant.
+
+        See Also
+        ========
+
+        .Submodule.reduce_element
+
+        """
+        if is_rat(m):
+            m = m * self.module.whole_submodule()
+        if isinstance(m, Submodule) and m.parent == self.module:
+            return m.reduce_element(self)
+        return NotImplemented
+
+
+class PowerBasisElement(ModuleElement):
+    r"""
+    Subclass for :py:class:`~.ModuleElement` instances whose module is a
+    :py:class:`~.PowerBasis`.
+    """
+
+    @property
+    def T(self):
+        """Access the defining polynomial of the :py:class:`~.PowerBasis`."""
+        return self.module.T
+
+    def numerator(self, x=None):
+        """Obtain the numerator as a polynomial over :ref:`ZZ`."""
+        x = x or self.T.gen
+        return Poly(reversed(self.coeffs), x, domain=ZZ)
+
+    def poly(self, x=None):
+        """Obtain the number as a polynomial over :ref:`QQ`."""
+        return self.numerator(x=x) // self.denom
+
+    @property
+    def is_rational(self):
+        """Say whether this element represents a rational number."""
+        return self.col[1:, :].is_zero_matrix
+
+    @property
+    def generator(self):
+        """
+        Return a :py:class:`~.Symbol` to be used when expressing this element
+        as a polynomial.
+
+        If we have an associated :py:class:`~.AlgebraicField` whose primitive
+        element has an alias symbol, we use that. Otherwise we use the variable
+        of the minimal polynomial defining the power basis to which we belong.
+        """
+        K = self.module.number_field
+        return K.ext.alias if K and K.ext.is_aliased else self.T.gen
+
+    def as_expr(self, x=None):
+        """Create a Basic expression from ``self``. """
+        return self.poly(x or self.generator).as_expr()
+
+    def norm(self, T=None):
+        """Compute the norm of this number."""
+        T = T or self.T
+        x = T.gen
+        A = self.numerator(x=x)
+        return T.resultant(A) // self.denom ** self.n
+
+    def inverse(self):
+        f = self.poly()
+        f_inv = f.invert(self.T)
+        return self.module.element_from_poly(f_inv)
+
+    def __rfloordiv__(self, a):
+        return self.inverse() * a
+
+    def _negative_power(self, e, modulo=None):
+        return self.inverse() ** abs(e)
+
+    def to_ANP(self):
+        """Convert to an equivalent :py:class:`~.ANP`. """
+        return ANP(list(reversed(self.QQ_col.flat())), QQ.map(self.T.rep.to_list()), QQ)
+
+    def to_alg_num(self):
+        """
+        Try to convert to an equivalent :py:class:`~.AlgebraicNumber`.
+
+        Explanation
+        ===========
+
+        In general, the conversion from an :py:class:`~.AlgebraicNumber` to a
+        :py:class:`~.PowerBasisElement` throws away information, because an
+        :py:class:`~.AlgebraicNumber` specifies a complex embedding, while a
+        :py:class:`~.PowerBasisElement` does not. However, in some cases it is
+        possible to convert a :py:class:`~.PowerBasisElement` back into an
+        :py:class:`~.AlgebraicNumber`, namely when the associated
+        :py:class:`~.PowerBasis` has a reference to an
+        :py:class:`~.AlgebraicField`.
+
+        Returns
+        =======
+
+        :py:class:`~.AlgebraicNumber`
+
+        Raises
+        ======
+
+        StructureError
+            If the :py:class:`~.PowerBasis` to which this element belongs does
+            not have an associated :py:class:`~.AlgebraicField`.
+
+        """
+        K = self.module.number_field
+        if K:
+            return K.to_alg_num(self.to_ANP())
+        raise StructureError("No associated AlgebraicField")
+
+
+class ModuleHomomorphism:
+    r"""A homomorphism from one module to another."""
+
+    def __init__(self, domain, codomain, mapping):
+        r"""
+        Parameters
+        ==========
+
+        domain : :py:class:`~.Module`
+            The domain of the mapping.
+
+        codomain : :py:class:`~.Module`
+            The codomain of the mapping.
+
+        mapping : callable
+            An arbitrary callable is accepted, but should be chosen so as
+            to represent an actual module homomorphism. In particular, should
+            accept elements of *domain* and return elements of *codomain*.
+
+        Examples
+        ========
+
+        >>> from sympy import Poly, cyclotomic_poly
+        >>> from sympy.polys.numberfields.modules import PowerBasis, ModuleHomomorphism
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> A = PowerBasis(T)
+        >>> B = A.submodule_from_gens([2*A(j) for j in range(4)])
+        >>> phi = ModuleHomomorphism(A, B, lambda x: 6*x)
+        >>> print(phi.matrix())  # doctest: +SKIP
+        DomainMatrix([[3, 0, 0, 0], [0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 3]], (4, 4), ZZ)
+
+        """
+        self.domain = domain
+        self.codomain = codomain
+        self.mapping = mapping
+
+    def matrix(self, modulus=None):
+        r"""
+        Compute the matrix of this homomorphism.
+
+        Parameters
+        ==========
+
+        modulus : int, optional
+            A positive prime number $p$ if the matrix should be reduced mod
+            $p$.
+
+        Returns
+        =======
+
+        :py:class:`~.DomainMatrix`
+            The matrix is over :ref:`ZZ`, or else over :ref:`GF(p)` if a
+            modulus was given.
+
+        """
+        basis = self.domain.basis_elements()
+        cols = [self.codomain.represent(self.mapping(elt)) for elt in basis]
+        if not cols:
+            return DomainMatrix.zeros((self.codomain.n, 0), ZZ).to_dense()
+        M = cols[0].hstack(*cols[1:])
+        if modulus:
+            M = M.convert_to(FF(modulus))
+        return M
+
+    def kernel(self, modulus=None):
+        r"""
+        Compute a Submodule representing the kernel of this homomorphism.
+
+        Parameters
+        ==========
+
+        modulus : int, optional
+            A positive prime number $p$ if the kernel should be computed mod
+            $p$.
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+            This submodule's generators span the kernel of this
+            homomorphism over :ref:`ZZ`, or else over :ref:`GF(p)` if a
+            modulus was given.
+
+        """
+        M = self.matrix(modulus=modulus)
+        if modulus is None:
+            M = M.convert_to(QQ)
+        # Note: Even when working over a finite field, what we want here is
+        # the pullback into the integers, so in this case the conversion to ZZ
+        # below is appropriate. When working over ZZ, the kernel should be a
+        # ZZ-submodule, so, while the conversion to QQ above was required in
+        # order for the nullspace calculation to work, conversion back to ZZ
+        # afterward should always work.
+        # TODO:
+        #  Watch , which calls
+        #  for fraction-free algorithms. If this is implemented, we can skip
+        #  the conversion to `QQ` above.
+        K = M.nullspace().convert_to(ZZ).transpose()
+        return self.domain.submodule_from_matrix(K)
+
+
+class ModuleEndomorphism(ModuleHomomorphism):
+    r"""A homomorphism from one module to itself."""
+
+    def __init__(self, domain, mapping):
+        r"""
+        Parameters
+        ==========
+
+        domain : :py:class:`~.Module`
+            The common domain and codomain of the mapping.
+
+        mapping : callable
+            An arbitrary callable is accepted, but should be chosen so as
+            to represent an actual module endomorphism. In particular, should
+            accept and return elements of *domain*.
+
+        """
+        super().__init__(domain, domain, mapping)
+
+
+class InnerEndomorphism(ModuleEndomorphism):
+    r"""
+    An inner endomorphism on a module, i.e. the endomorphism corresponding to
+    multiplication by a fixed element.
+    """
+
+    def __init__(self, domain, multiplier):
+        r"""
+        Parameters
+        ==========
+
+        domain : :py:class:`~.Module`
+            The domain and codomain of the endomorphism.
+
+        multiplier : :py:class:`~.ModuleElement`
+            The element $a$ defining the mapping as $x \mapsto a x$.
+
+        """
+        super().__init__(domain, lambda x: multiplier * x)
+        self.multiplier = multiplier
+
+
+class EndomorphismRing:
+    r"""The ring of endomorphisms on a module."""
+
+    def __init__(self, domain):
+        """
+        Parameters
+        ==========
+
+        domain : :py:class:`~.Module`
+            The domain and codomain of the endomorphisms.
+
+        """
+        self.domain = domain
+
+    def inner_endomorphism(self, multiplier):
+        r"""
+        Form an inner endomorphism belonging to this endomorphism ring.
+
+        Parameters
+        ==========
+
+        multiplier : :py:class:`~.ModuleElement`
+            Element $a$ defining the inner endomorphism $x \mapsto a x$.
+
+        Returns
+        =======
+
+        :py:class:`~.InnerEndomorphism`
+
+        """
+        return InnerEndomorphism(self.domain, multiplier)
+
+    def represent(self, element):
+        r"""
+        Represent an element of this endomorphism ring, as a single column
+        vector.
+
+        Explanation
+        ===========
+
+        Let $M$ be a module, and $E$ its ring of endomorphisms. Let $N$ be
+        another module, and consider a homomorphism $\varphi: N \rightarrow E$.
+        In the event that $\varphi$ is to be represented by a matrix $A$, each
+        column of $A$ must represent an element of $E$. This is possible when
+        the elements of $E$ are themselves representable as matrices, by
+        stacking the columns of such a matrix into a single column.
+
+        This method supports calculating such matrices $A$, by representing
+        an element of this endomorphism ring first as a matrix, and then
+        stacking that matrix's columns into a single column.
+
+        Examples
+        ========
+
+        Note that in these examples we print matrix transposes, to make their
+        columns easier to inspect.
+
+        >>> from sympy import Poly, cyclotomic_poly
+        >>> from sympy.polys.numberfields.modules import PowerBasis
+        >>> from sympy.polys.numberfields.modules import ModuleHomomorphism
+        >>> T = Poly(cyclotomic_poly(5))
+        >>> M = PowerBasis(T)
+        >>> E = M.endomorphism_ring()
+
+        Let $\zeta$ be a primitive 5th root of unity, a generator of our field,
+        and consider the inner endomorphism $\tau$ on the ring of integers,
+        induced by $\zeta$:
+
+        >>> zeta = M(1)
+        >>> tau = E.inner_endomorphism(zeta)
+        >>> tau.matrix().transpose()  # doctest: +SKIP
+        DomainMatrix(
+            [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [-1, -1, -1, -1]],
+            (4, 4), ZZ)
+
+        The matrix representation of $\tau$ is as expected. The first column
+        shows that multiplying by $\zeta$ carries $1$ to $\zeta$, the second
+        column that it carries $\zeta$ to $\zeta^2$, and so forth.
+
+        The ``represent`` method of the endomorphism ring ``E`` stacks these
+        into a single column:
+
+        >>> E.represent(tau).transpose()  # doctest: +SKIP
+        DomainMatrix(
+            [[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1]],
+            (1, 16), ZZ)
+
+        This is useful when we want to consider a homomorphism $\varphi$ having
+        ``E`` as codomain:
+
+        >>> phi = ModuleHomomorphism(M, E, lambda x: E.inner_endomorphism(x))
+
+        and we want to compute the matrix of such a homomorphism:
+
+        >>> phi.matrix().transpose()  # doctest: +SKIP
+        DomainMatrix(
+            [[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
+            [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1],
+            [0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0],
+            [0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0, 0, 1, 0, 0]],
+            (4, 16), ZZ)
+
+        Note that the stacked matrix of $\tau$ occurs as the second column in
+        this example. This is because $\zeta$ is the second basis element of
+        ``M``, and $\varphi(\zeta) = \tau$.
+
+        Parameters
+        ==========
+
+        element : :py:class:`~.ModuleEndomorphism` belonging to this ring.
+
+        Returns
+        =======
+
+        :py:class:`~.DomainMatrix`
+            Column vector equalling the vertical stacking of all the columns
+            of the matrix that represents the given *element* as a mapping.
+
+        """
+        if isinstance(element, ModuleEndomorphism) and element.domain == self.domain:
+            M = element.matrix()
+            # Transform the matrix into a single column, which should reproduce
+            # the original columns, one after another.
+            m, n = M.shape
+            if n == 0:
+                return M
+            return M[:, 0].vstack(*[M[:, j] for j in range(1, n)])
+        raise NotImplementedError
+
+
+def find_min_poly(alpha, domain, x=None, powers=None):
+    r"""
+    Find a polynomial of least degree (not necessarily irreducible) satisfied
+    by an element of a finitely-generated ring with unity.
+
+    Examples
+    ========
+
+    For the $n$th cyclotomic field, $n$ an odd prime, consider the quadratic
+    equation whose roots are the two periods of length $(n-1)/2$. Article 356
+    of Gauss tells us that we should get $x^2 + x - (n-1)/4$ or
+    $x^2 + x + (n+1)/4$ according to whether $n$ is 1 or 3 mod 4, respectively.
+
+    >>> from sympy import Poly, cyclotomic_poly, primitive_root, QQ
+    >>> from sympy.abc import x
+    >>> from sympy.polys.numberfields.modules import PowerBasis, find_min_poly
+    >>> n = 13
+    >>> g = primitive_root(n)
+    >>> C = PowerBasis(Poly(cyclotomic_poly(n, x)))
+    >>> ee = [g**(2*k+1) % n for k in range((n-1)//2)]
+    >>> eta = sum(C(e) for e in ee)
+    >>> print(find_min_poly(eta, QQ, x=x).as_expr())
+    x**2 + x - 3
+    >>> n = 19
+    >>> g = primitive_root(n)
+    >>> C = PowerBasis(Poly(cyclotomic_poly(n, x)))
+    >>> ee = [g**(2*k+2) % n for k in range((n-1)//2)]
+    >>> eta = sum(C(e) for e in ee)
+    >>> print(find_min_poly(eta, QQ, x=x).as_expr())
+    x**2 + x + 5
+
+    Parameters
+    ==========
+
+    alpha : :py:class:`~.ModuleElement`
+        The element whose min poly is to be found, and whose module has
+        multiplication and starts with unity.
+
+    domain : :py:class:`~.Domain`
+        The desired domain of the polynomial.
+
+    x : :py:class:`~.Symbol`, optional
+        The desired variable for the polynomial.
+
+    powers : list, optional
+        If desired, pass an empty list. The powers of *alpha* (as
+        :py:class:`~.ModuleElement` instances) from the zeroth up to the degree
+        of the min poly will be recorded here, as we compute them.
+
+    Returns
+    =======
+
+    :py:class:`~.Poly`, ``None``
+        The minimal polynomial for alpha, or ``None`` if no polynomial could be
+        found over the desired domain.
+
+    Raises
+    ======
+
+    MissingUnityError
+        If the module to which alpha belongs does not start with unity.
+    ClosureFailure
+        If the module to which alpha belongs is not closed under
+        multiplication.
+
+    """
+    R = alpha.module
+    if not R.starts_with_unity():
+        raise MissingUnityError("alpha must belong to finitely generated ring with unity.")
+    if powers is None:
+        powers = []
+    one = R(0)
+    powers.append(one)
+    powers_matrix = one.column(domain=domain)
+    ak = alpha
+    m = None
+    for k in range(1, R.n + 1):
+        powers.append(ak)
+        ak_col = ak.column(domain=domain)
+        try:
+            X = powers_matrix._solve(ak_col)[0]
+        except DMBadInputError:
+            # This means alpha^k still isn't in the domain-span of the lower powers.
+            powers_matrix = powers_matrix.hstack(ak_col)
+            ak *= alpha
+        else:
+            # alpha^k is in the domain-span of the lower powers, so we have found a
+            # minimal-degree poly for alpha.
+            coeffs = [1] + [-c for c in reversed(X.to_list_flat())]
+            x = x or Dummy('x')
+            if domain.is_FF:
+                m = Poly(coeffs, x, modulus=domain.mod)
+            else:
+                m = Poly(coeffs, x, domain=domain)
+            break
+    return m
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/primes.py b/lib/python3.11/site-packages/sympy/polys/numberfields/primes.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f28f13d94f33ed59cded8eabd05e9cf7d0f103f
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/primes.py
@@ -0,0 +1,784 @@
+"""Prime ideals in number fields. """
+
+from sympy.polys.polytools import Poly
+from sympy.polys.domains.finitefield import FF
+from sympy.polys.domains.rationalfield import QQ
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.matrices.domainmatrix import DomainMatrix
+from sympy.polys.polyerrors import CoercionFailed
+from sympy.polys.polyutils import IntegerPowerable
+from sympy.utilities.decorator import public
+from .basis import round_two, nilradical_mod_p
+from .exceptions import StructureError
+from .modules import ModuleEndomorphism, find_min_poly
+from .utilities import coeff_search, supplement_a_subspace
+
+
+def _check_formal_conditions_for_maximal_order(submodule):
+    r"""
+    Several functions in this module accept an argument which is to be a
+    :py:class:`~.Submodule` representing the maximal order in a number field,
+    such as returned by the :py:func:`~sympy.polys.numberfields.basis.round_two`
+    algorithm.
+
+    We do not attempt to check that the given ``Submodule`` actually represents
+    a maximal order, but we do check a basic set of formal conditions that the
+    ``Submodule`` must satisfy, at a minimum. The purpose is to catch an
+    obviously ill-formed argument.
+    """
+    prefix = 'The submodule representing the maximal order should '
+    cond = None
+    if not submodule.is_power_basis_submodule():
+        cond = 'be a direct submodule of a power basis.'
+    elif not submodule.starts_with_unity():
+        cond = 'have 1 as its first generator.'
+    elif not submodule.is_sq_maxrank_HNF():
+        cond = 'have square matrix, of maximal rank, in Hermite Normal Form.'
+    if cond is not None:
+        raise StructureError(prefix + cond)
+
+
+class PrimeIdeal(IntegerPowerable):
+    r"""
+    A prime ideal in a ring of algebraic integers.
+    """
+
+    def __init__(self, ZK, p, alpha, f, e=None):
+        """
+        Parameters
+        ==========
+
+        ZK : :py:class:`~.Submodule`
+            The maximal order where this ideal lives.
+        p : int
+            The rational prime this ideal divides.
+        alpha : :py:class:`~.PowerBasisElement`
+            Such that the ideal is equal to ``p*ZK + alpha*ZK``.
+        f : int
+            The inertia degree.
+        e : int, ``None``, optional
+            The ramification index, if already known. If ``None``, we will
+            compute it here.
+
+        """
+        _check_formal_conditions_for_maximal_order(ZK)
+        self.ZK = ZK
+        self.p = p
+        self.alpha = alpha
+        self.f = f
+        self._test_factor = None
+        self.e = e if e is not None else self.valuation(p * ZK)
+
+    def __str__(self):
+        if self.is_inert:
+            return f'({self.p})'
+        return f'({self.p}, {self.alpha.as_expr()})'
+
+    @property
+    def is_inert(self):
+        """
+        Say whether the rational prime we divide is inert, i.e. stays prime in
+        our ring of integers.
+        """
+        return self.f == self.ZK.n
+
+    def repr(self, field_gen=None, just_gens=False):
+        """
+        Print a representation of this prime ideal.
+
+        Examples
+        ========
+
+        >>> from sympy import cyclotomic_poly, QQ
+        >>> from sympy.abc import x, zeta
+        >>> T = cyclotomic_poly(7, x)
+        >>> K = QQ.algebraic_field((T, zeta))
+        >>> P = K.primes_above(11)
+        >>> print(P[0].repr())
+        [ (11, x**3 + 5*x**2 + 4*x - 1) e=1, f=3 ]
+        >>> print(P[0].repr(field_gen=zeta))
+        [ (11, zeta**3 + 5*zeta**2 + 4*zeta - 1) e=1, f=3 ]
+        >>> print(P[0].repr(field_gen=zeta, just_gens=True))
+        (11, zeta**3 + 5*zeta**2 + 4*zeta - 1)
+
+        Parameters
+        ==========
+
+        field_gen : :py:class:`~.Symbol`, ``None``, optional (default=None)
+            The symbol to use for the generator of the field. This will appear
+            in our representation of ``self.alpha``. If ``None``, we use the
+            variable of the defining polynomial of ``self.ZK``.
+        just_gens : bool, optional (default=False)
+            If ``True``, just print the "(p, alpha)" part, showing "just the
+            generators" of the prime ideal. Otherwise, print a string of the
+            form "[ (p, alpha) e=..., f=... ]", giving the ramification index
+            and inertia degree, along with the generators.
+
+        """
+        field_gen = field_gen or self.ZK.parent.T.gen
+        p, alpha, e, f = self.p, self.alpha, self.e, self.f
+        alpha_rep = str(alpha.numerator(x=field_gen).as_expr())
+        if alpha.denom > 1:
+            alpha_rep = f'({alpha_rep})/{alpha.denom}'
+        gens = f'({p}, {alpha_rep})'
+        if just_gens:
+            return gens
+        return f'[ {gens} e={e}, f={f} ]'
+
+    def __repr__(self):
+        return self.repr()
+
+    def as_submodule(self):
+        r"""
+        Represent this prime ideal as a :py:class:`~.Submodule`.
+
+        Explanation
+        ===========
+
+        The :py:class:`~.PrimeIdeal` class serves to bundle information about
+        a prime ideal, such as its inertia degree, ramification index, and
+        two-generator representation, as well as to offer helpful methods like
+        :py:meth:`~.PrimeIdeal.valuation` and
+        :py:meth:`~.PrimeIdeal.test_factor`.
+
+        However, in order to be added and multiplied by other ideals or
+        rational numbers, it must first be converted into a
+        :py:class:`~.Submodule`, which is a class that supports these
+        operations.
+
+        In many cases, the user need not perform this conversion deliberately,
+        since it is automatically performed by the arithmetic operator methods
+        :py:meth:`~.PrimeIdeal.__add__` and :py:meth:`~.PrimeIdeal.__mul__`.
+
+        Raising a :py:class:`~.PrimeIdeal` to a non-negative integer power is
+        also supported.
+
+        Examples
+        ========
+
+        >>> from sympy import Poly, cyclotomic_poly, prime_decomp
+        >>> T = Poly(cyclotomic_poly(7))
+        >>> P0 = prime_decomp(7, T)[0]
+        >>> print(P0**6 == 7*P0.ZK)
+        True
+
+        Note that, on both sides of the equation above, we had a
+        :py:class:`~.Submodule`. In the next equation we recall that adding
+        ideals yields their GCD. This time, we need a deliberate conversion
+        to :py:class:`~.Submodule` on the right:
+
+        >>> print(P0 + 7*P0.ZK == P0.as_submodule())
+        True
+
+        Returns
+        =======
+
+        :py:class:`~.Submodule`
+            Will be equal to ``self.p * self.ZK + self.alpha * self.ZK``.
+
+        See Also
+        ========
+
+        __add__
+        __mul__
+
+        """
+        M = self.p * self.ZK + self.alpha * self.ZK
+        # Pre-set expensive boolean properties whose value we already know:
+        M._starts_with_unity = False
+        M._is_sq_maxrank_HNF = True
+        return M
+
+    def __eq__(self, other):
+        if isinstance(other, PrimeIdeal):
+            return self.as_submodule() == other.as_submodule()
+        return NotImplemented
+
+    def __add__(self, other):
+        """
+        Convert to a :py:class:`~.Submodule` and add to another
+        :py:class:`~.Submodule`.
+
+        See Also
+        ========
+
+        as_submodule
+
+        """
+        return self.as_submodule() + other
+
+    __radd__ = __add__
+
+    def __mul__(self, other):
+        """
+        Convert to a :py:class:`~.Submodule` and multiply by another
+        :py:class:`~.Submodule` or a rational number.
+
+        See Also
+        ========
+
+        as_submodule
+
+        """
+        return self.as_submodule() * other
+
+    __rmul__ = __mul__
+
+    def _zeroth_power(self):
+        return self.ZK
+
+    def _first_power(self):
+        return self
+
+    def test_factor(self):
+        r"""
+        Compute a test factor for this prime ideal.
+
+        Explanation
+        ===========
+
+        Write $\mathfrak{p}$ for this prime ideal, $p$ for the rational prime
+        it divides. Then, for computing $\mathfrak{p}$-adic valuations it is
+        useful to have a number $\beta \in \mathbb{Z}_K$ such that
+        $p/\mathfrak{p} = p \mathbb{Z}_K + \beta \mathbb{Z}_K$.
+
+        Essentially, this is the same as the number $\Psi$ (or the "reagent")
+        from Kummer's 1847 paper (*Ueber die Zerlegung...*, Crelle vol. 35) in
+        which ideal divisors were invented.
+        """
+        if self._test_factor is None:
+            self._test_factor = _compute_test_factor(self.p, [self.alpha], self.ZK)
+        return self._test_factor
+
+    def valuation(self, I):
+        r"""
+        Compute the $\mathfrak{p}$-adic valuation of integral ideal I at this
+        prime ideal.
+
+        Parameters
+        ==========
+
+        I : :py:class:`~.Submodule`
+
+        See Also
+        ========
+
+        prime_valuation
+
+        """
+        return prime_valuation(I, self)
+
+    def reduce_element(self, elt):
+        """
+        Reduce a :py:class:`~.PowerBasisElement` to a "small representative"
+        modulo this prime ideal.
+
+        Parameters
+        ==========
+
+        elt : :py:class:`~.PowerBasisElement`
+            The element to be reduced.
+
+        Returns
+        =======
+
+        :py:class:`~.PowerBasisElement`
+            The reduced element.
+
+        See Also
+        ========
+
+        reduce_ANP
+        reduce_alg_num
+        .Submodule.reduce_element
+
+        """
+        return self.as_submodule().reduce_element(elt)
+
+    def reduce_ANP(self, a):
+        """
+        Reduce an :py:class:`~.ANP` to a "small representative" modulo this
+        prime ideal.
+
+        Parameters
+        ==========
+
+        elt : :py:class:`~.ANP`
+            The element to be reduced.
+
+        Returns
+        =======
+
+        :py:class:`~.ANP`
+            The reduced element.
+
+        See Also
+        ========
+
+        reduce_element
+        reduce_alg_num
+        .Submodule.reduce_element
+
+        """
+        elt = self.ZK.parent.element_from_ANP(a)
+        red = self.reduce_element(elt)
+        return red.to_ANP()
+
+    def reduce_alg_num(self, a):
+        """
+        Reduce an :py:class:`~.AlgebraicNumber` to a "small representative"
+        modulo this prime ideal.
+
+        Parameters
+        ==========
+
+        elt : :py:class:`~.AlgebraicNumber`
+            The element to be reduced.
+
+        Returns
+        =======
+
+        :py:class:`~.AlgebraicNumber`
+            The reduced element.
+
+        See Also
+        ========
+
+        reduce_element
+        reduce_ANP
+        .Submodule.reduce_element
+
+        """
+        elt = self.ZK.parent.element_from_alg_num(a)
+        red = self.reduce_element(elt)
+        return a.field_element(list(reversed(red.QQ_col.flat())))
+
+
+def _compute_test_factor(p, gens, ZK):
+    r"""
+    Compute the test factor for a :py:class:`~.PrimeIdeal` $\mathfrak{p}$.
+
+    Parameters
+    ==========
+
+    p : int
+        The rational prime $\mathfrak{p}$ divides
+
+    gens : list of :py:class:`PowerBasisElement`
+        A complete set of generators for $\mathfrak{p}$ over *ZK*, EXCEPT that
+        an element equivalent to rational *p* can and should be omitted (since
+        it has no effect except to waste time).
+
+    ZK : :py:class:`~.Submodule`
+        The maximal order where the prime ideal $\mathfrak{p}$ lives.
+
+    Returns
+    =======
+
+    :py:class:`~.PowerBasisElement`
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+    (See Proposition 4.8.15.)
+
+    """
+    _check_formal_conditions_for_maximal_order(ZK)
+    E = ZK.endomorphism_ring()
+    matrices = [E.inner_endomorphism(g).matrix(modulus=p) for g in gens]
+    B = DomainMatrix.zeros((0, ZK.n), FF(p)).vstack(*matrices)
+    # A nonzero element of the nullspace of B will represent a
+    # lin comb over the omegas which (i) is not a multiple of p
+    # (since it is nonzero over FF(p)), while (ii) is such that
+    # its product with each g in gens _is_ a multiple of p (since
+    # B represents multiplication by these generators). Theory
+    # predicts that such an element must exist, so nullspace should
+    # be non-trivial.
+    x = B.nullspace()[0, :].transpose()
+    beta = ZK.parent(ZK.matrix * x.convert_to(ZZ), denom=ZK.denom)
+    return beta
+
+
+@public
+def prime_valuation(I, P):
+    r"""
+    Compute the *P*-adic valuation for an integral ideal *I*.
+
+    Examples
+    ========
+
+    >>> from sympy import QQ
+    >>> from sympy.polys.numberfields import prime_valuation
+    >>> K = QQ.cyclotomic_field(5)
+    >>> P = K.primes_above(5)
+    >>> ZK = K.maximal_order()
+    >>> print(prime_valuation(25*ZK, P[0]))
+    8
+
+    Parameters
+    ==========
+
+    I : :py:class:`~.Submodule`
+        An integral ideal whose valuation is desired.
+
+    P : :py:class:`~.PrimeIdeal`
+        The prime at which to compute the valuation.
+
+    Returns
+    =======
+
+    int
+
+    See Also
+    ========
+
+    .PrimeIdeal.valuation
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+       (See Algorithm 4.8.17.)
+
+    """
+    p, ZK = P.p, P.ZK
+    n, W, d = ZK.n, ZK.matrix, ZK.denom
+
+    A = W.convert_to(QQ).inv() * I.matrix * d / I.denom
+    # Although A must have integer entries, given that I is an integral ideal,
+    # as a DomainMatrix it will still be over QQ, so we convert back:
+    A = A.convert_to(ZZ)
+    D = A.det()
+    if D % p != 0:
+        return 0
+
+    beta = P.test_factor()
+
+    f = d ** n // W.det()
+    need_complete_test = (f % p == 0)
+    v = 0
+    while True:
+        # Entering the loop, the cols of A represent lin combs of omegas.
+        # Turn them into lin combs of thetas:
+        A = W * A
+        # And then one column at a time...
+        for j in range(n):
+            c = ZK.parent(A[:, j], denom=d)
+            c *= beta
+            # ...turn back into lin combs of omegas, after multiplying by beta:
+            c = ZK.represent(c).flat()
+            for i in range(n):
+                A[i, j] = c[i]
+        if A[n - 1, n - 1].element % p != 0:
+            break
+        A = A / p
+        # As noted above, domain converts to QQ even when division goes evenly.
+        # So must convert back, even when we don't "need_complete_test".
+        if need_complete_test:
+            # In this case, having a non-integer entry is actually just our
+            # halting condition.
+            try:
+                A = A.convert_to(ZZ)
+            except CoercionFailed:
+                break
+        else:
+            # In this case theory says we should not have any non-integer entries.
+            A = A.convert_to(ZZ)
+        v += 1
+    return v
+
+
+def _two_elt_rep(gens, ZK, p, f=None, Np=None):
+    r"""
+    Given a set of *ZK*-generators of a prime ideal, compute a set of just two
+    *ZK*-generators for the same ideal, one of which is *p* itself.
+
+    Parameters
+    ==========
+
+    gens : list of :py:class:`PowerBasisElement`
+        Generators for the prime ideal over *ZK*, the ring of integers of the
+        field $K$.
+
+    ZK : :py:class:`~.Submodule`
+        The maximal order in $K$.
+
+    p : int
+        The rational prime divided by the prime ideal.
+
+    f : int, optional
+        The inertia degree of the prime ideal, if known.
+
+    Np : int, optional
+        The norm $p^f$ of the prime ideal, if known.
+        NOTE: There is no reason to supply both *f* and *Np*. Either one will
+        save us from having to compute the norm *Np* ourselves. If both are known,
+        *Np* is preferred since it saves one exponentiation.
+
+    Returns
+    =======
+
+    :py:class:`~.PowerBasisElement` representing a single algebraic integer
+    alpha such that the prime ideal is equal to ``p*ZK + alpha*ZK``.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+    (See Algorithm 4.7.10.)
+
+    """
+    _check_formal_conditions_for_maximal_order(ZK)
+    pb = ZK.parent
+    T = pb.T
+    # Detect the special cases in which either (a) all generators are multiples
+    # of p, or (b) there are no generators (so `all` is vacuously true):
+    if all((g % p).equiv(0) for g in gens):
+        return pb.zero()
+
+    if Np is None:
+        if f is not None:
+            Np = p**f
+        else:
+            Np = abs(pb.submodule_from_gens(gens).matrix.det())
+
+    omega = ZK.basis_element_pullbacks()
+    beta = [p*om for om in omega[1:]]  # note: we omit omega[0] == 1
+    beta += gens
+    search = coeff_search(len(beta), 1)
+    for c in search:
+        alpha = sum(ci*betai for ci, betai in zip(c, beta))
+        # Note: It may be tempting to reduce alpha mod p here, to try to work
+        # with smaller numbers, but must not do that, as it can result in an
+        # infinite loop! E.g. try factoring 2 in Q(sqrt(-7)).
+        n = alpha.norm(T) // Np
+        if n % p != 0:
+            # Now can reduce alpha mod p.
+            return alpha % p
+
+
+def _prime_decomp_easy_case(p, ZK):
+    r"""
+    Compute the decomposition of rational prime *p* in the ring of integers
+    *ZK* (given as a :py:class:`~.Submodule`), in the "easy case", i.e. the
+    case where *p* does not divide the index of $\theta$ in *ZK*, where
+    $\theta$ is the generator of the ``PowerBasis`` of which *ZK* is a
+    ``Submodule``.
+    """
+    T = ZK.parent.T
+    T_bar = Poly(T, modulus=p)
+    lc, fl = T_bar.factor_list()
+    if len(fl) == 1 and fl[0][1] == 1:
+        return [PrimeIdeal(ZK, p, ZK.parent.zero(), ZK.n, 1)]
+    return [PrimeIdeal(ZK, p,
+                       ZK.parent.element_from_poly(Poly(t, domain=ZZ)),
+                       t.degree(), e)
+            for t, e in fl]
+
+
+def _prime_decomp_compute_kernel(I, p, ZK):
+    r"""
+    Parameters
+    ==========
+
+    I : :py:class:`~.Module`
+        An ideal of ``ZK/pZK``.
+    p : int
+        The rational prime being factored.
+    ZK : :py:class:`~.Submodule`
+        The maximal order.
+
+    Returns
+    =======
+
+    Pair ``(N, G)``, where:
+
+        ``N`` is a :py:class:`~.Module` representing the kernel of the map
+        ``a |--> a**p - a`` on ``(O/pO)/I``, guaranteed to be a module with
+        unity.
+
+        ``G`` is a :py:class:`~.Module` representing a basis for the separable
+        algebra ``A = O/I`` (see Cohen).
+
+    """
+    W = I.matrix
+    n, r = W.shape
+    # Want to take the Fp-basis given by the columns of I, adjoin (1, 0, ..., 0)
+    # (which we know is not already in there since I is a basis for a prime ideal)
+    # and then supplement this with additional columns to make an invertible n x n
+    # matrix. This will then represent a full basis for ZK, whose first r columns
+    # are pullbacks of the basis for I.
+    if r == 0:
+        B = W.eye(n, ZZ)
+    else:
+        B = W.hstack(W.eye(n, ZZ)[:, 0])
+    if B.shape[1] < n:
+        B = supplement_a_subspace(B.convert_to(FF(p))).convert_to(ZZ)
+
+    G = ZK.submodule_from_matrix(B)
+    # Must compute G's multiplication table _before_ discarding the first r
+    # columns. (See Step 9 in Alg 6.2.9 in Cohen, where the betas are actually
+    # needed in order to represent each product of gammas. However, once we've
+    # found the representations, then we can ignore the betas.)
+    G.compute_mult_tab()
+    G = G.discard_before(r)
+
+    phi = ModuleEndomorphism(G, lambda x: x**p - x)
+    N = phi.kernel(modulus=p)
+    assert N.starts_with_unity()
+    return N, G
+
+
+def _prime_decomp_maximal_ideal(I, p, ZK):
+    r"""
+    We have reached the case where we have a maximal (hence prime) ideal *I*,
+    which we know because the quotient ``O/I`` is a field.
+
+    Parameters
+    ==========
+
+    I : :py:class:`~.Module`
+        An ideal of ``O/pO``.
+    p : int
+        The rational prime being factored.
+    ZK : :py:class:`~.Submodule`
+        The maximal order.
+
+    Returns
+    =======
+
+    :py:class:`~.PrimeIdeal` instance representing this prime
+
+    """
+    m, n = I.matrix.shape
+    f = m - n
+    G = ZK.matrix * I.matrix
+    gens = [ZK.parent(G[:, j], denom=ZK.denom) for j in range(G.shape[1])]
+    alpha = _two_elt_rep(gens, ZK, p, f=f)
+    return PrimeIdeal(ZK, p, alpha, f)
+
+
+def _prime_decomp_split_ideal(I, p, N, G, ZK):
+    r"""
+    Perform the step in the prime decomposition algorithm where we have determined
+    the quotient ``ZK/I`` is _not_ a field, and we want to perform a non-trivial
+    factorization of *I* by locating an idempotent element of ``ZK/I``.
+    """
+    assert I.parent == ZK and G.parent is ZK and N.parent is G
+    # Since ZK/I is not a field, the kernel computed in the previous step contains
+    # more than just the prime field Fp, and our basis N for the nullspace therefore
+    # contains at least a second column (which represents an element outside Fp).
+    # Let alpha be such an element:
+    alpha = N(1).to_parent()
+    assert alpha.module is G
+
+    alpha_powers = []
+    m = find_min_poly(alpha, FF(p), powers=alpha_powers)
+    # TODO (future work):
+    #  We don't actually need full factorization, so might use a faster method
+    #  to just break off a single non-constant factor m1?
+    lc, fl = m.factor_list()
+    m1 = fl[0][0]
+    m2 = m.quo(m1)
+    U, V, g = m1.gcdex(m2)
+    # Sanity check: theory says m is squarefree, so m1, m2 should be coprime:
+    assert g == 1
+    E = list(reversed(Poly(U * m1, domain=ZZ).rep.to_list()))
+    eps1 = sum(E[i]*alpha_powers[i] for i in range(len(E)))
+    eps2 = 1 - eps1
+    idemps = [eps1, eps2]
+    factors = []
+    for eps in idemps:
+        e = eps.to_parent()
+        assert e.module is ZK
+        D = I.matrix.convert_to(FF(p)).hstack(*[
+            (e * om).column(domain=FF(p)) for om in ZK.basis_elements()
+        ])
+        W = D.columnspace().convert_to(ZZ)
+        H = ZK.submodule_from_matrix(W)
+        factors.append(H)
+    return factors
+
+
+@public
+def prime_decomp(p, T=None, ZK=None, dK=None, radical=None):
+    r"""
+    Compute the decomposition of rational prime *p* in a number field.
+
+    Explanation
+    ===========
+
+    Ordinarily this should be accessed through the
+    :py:meth:`~.AlgebraicField.primes_above` method of an
+    :py:class:`~.AlgebraicField`.
+
+    Examples
+    ========
+
+    >>> from sympy import Poly, QQ
+    >>> from sympy.abc import x, theta
+    >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
+    >>> K = QQ.algebraic_field((T, theta))
+    >>> print(K.primes_above(2))
+    [[ (2, x**2 + 1) e=1, f=1 ], [ (2, (x**2 + 3*x + 2)/2) e=1, f=1 ],
+     [ (2, (3*x**2 + 3*x)/2) e=1, f=1 ]]
+
+    Parameters
+    ==========
+
+    p : int
+        The rational prime whose decomposition is desired.
+
+    T : :py:class:`~.Poly`, optional
+        Monic irreducible polynomial defining the number field $K$ in which to
+        factor. NOTE: at least one of *T* or *ZK* must be provided.
+
+    ZK : :py:class:`~.Submodule`, optional
+        The maximal order for $K$, if already known.
+        NOTE: at least one of *T* or *ZK* must be provided.
+
+    dK : int, optional
+        The discriminant of the field $K$, if already known.
+
+    radical : :py:class:`~.Submodule`, optional
+        The nilradical mod *p* in the integers of $K$, if already known.
+
+    Returns
+    =======
+
+    List of :py:class:`~.PrimeIdeal` instances.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+       (See Algorithm 6.2.9.)
+
+    """
+    if T is None and ZK is None:
+        raise ValueError('At least one of T or ZK must be provided.')
+    if ZK is not None:
+        _check_formal_conditions_for_maximal_order(ZK)
+    if T is None:
+        T = ZK.parent.T
+    radicals = {}
+    if dK is None or ZK is None:
+        ZK, dK = round_two(T, radicals=radicals)
+    dT = T.discriminant()
+    f_squared = dT // dK
+    if f_squared % p != 0:
+        return _prime_decomp_easy_case(p, ZK)
+    radical = radical or radicals.get(p) or nilradical_mod_p(ZK, p)
+    stack = [radical]
+    primes = []
+    while stack:
+        I = stack.pop()
+        N, G = _prime_decomp_compute_kernel(I, p, ZK)
+        if N.n == 1:
+            P = _prime_decomp_maximal_ideal(I, p, ZK)
+            primes.append(P)
+        else:
+            I1, I2 = _prime_decomp_split_ideal(I, p, N, G, ZK)
+            stack.extend([I1, I2])
+    return primes
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/resolvent_lookup.py b/lib/python3.11/site-packages/sympy/polys/numberfields/resolvent_lookup.py
new file mode 100644
index 0000000000000000000000000000000000000000..71812c0d7aec6501039eefe4f3602b1916628071
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/resolvent_lookup.py
@@ -0,0 +1,456 @@
+"""Lookup table for Galois resolvents for polys of degree 4 through 6. """
+# This table was generated by a call to
+# `sympy.polys.numberfields.galois_resolvents.generate_lambda_lookup()`.
+# The entire job took 543.23s.
+# Of this, Case (6, 1) took 539.03s.
+# The final polynomial of Case (6, 1) alone took 455.09s.
+resolvent_coeff_lambdas = {
+    (4, 0): [
+        lambda s1, s2, s3, s4: (-2*s1*s2 + 6*s3),
+        lambda s1, s2, s3, s4: (2*s1**3*s3 + s1**2*s2**2 + s1**2*s4 - 17*s1*s2*s3 + 2*s2**3 - 8*s2*s4 + 24*s3**2),
+        lambda s1, s2, s3, s4: (-2*s1**5*s4 - 2*s1**4*s2*s3 + 10*s1**3*s2*s4 + 8*s1**3*s3**2 + 10*s1**2*s2**2*s3 -
+12*s1**2*s3*s4 - 2*s1*s2**4 - 54*s1*s2*s3**2 + 32*s1*s4**2 + 8*s2**3*s3 - 32*s2*s3*s4
++ 56*s3**3),
+        lambda s1, s2, s3, s4: (2*s1**6*s2*s4 + s1**6*s3**2 - 5*s1**5*s3*s4 - 11*s1**4*s2**2*s4 - 13*s1**4*s2*s3**2
++ 7*s1**4*s4**2 + 3*s1**3*s2**3*s3 + 30*s1**3*s2*s3*s4 + 22*s1**3*s3**3 + 10*s1**2*s2**3*s4
++ 33*s1**2*s2**2*s3**2 - 72*s1**2*s2*s4**2 - 36*s1**2*s3**2*s4 - 13*s1*s2**4*s3 +
+48*s1*s2**2*s3*s4 - 116*s1*s2*s3**3 + 144*s1*s3*s4**2 + s2**6 - 12*s2**4*s4 + 22*s2**3*s3**2
++ 48*s2**2*s4**2 - 120*s2*s3**2*s4 + 96*s3**4 - 64*s4**3),
+        lambda s1, s2, s3, s4: (-2*s1**8*s3*s4 - s1**7*s4**2 + 22*s1**6*s2*s3*s4 + 2*s1**6*s3**3 - 2*s1**5*s2**3*s4
+- s1**5*s2**2*s3**2 - 29*s1**5*s3**2*s4 - 60*s1**4*s2**2*s3*s4 - 19*s1**4*s2*s3**3
++ 38*s1**4*s3*s4**2 + 9*s1**3*s2**4*s4 + 10*s1**3*s2**3*s3**2 + 24*s1**3*s2**2*s4**2
++ 134*s1**3*s2*s3**2*s4 + 28*s1**3*s3**4 + 16*s1**3*s4**3 - s1**2*s2**5*s3 - 4*s1**2*s2**3*s3*s4
++ 34*s1**2*s2**2*s3**3 - 288*s1**2*s2*s3*s4**2 - 104*s1**2*s3**3*s4 - 19*s1*s2**4*s3**2
++ 120*s1*s2**2*s3**2*s4 - 128*s1*s2*s3**4 + 336*s1*s3**2*s4**2 + 2*s2**6*s3 - 24*s2**4*s3*s4
++ 28*s2**3*s3**3 + 96*s2**2*s3*s4**2 - 176*s2*s3**3*s4 + 96*s3**5 - 128*s3*s4**3),
+        lambda s1, s2, s3, s4: (s1**10*s4**2 - 11*s1**8*s2*s4**2 - 2*s1**8*s3**2*s4 + s1**7*s2**2*s3*s4 + 15*s1**7*s3*s4**2
++ 45*s1**6*s2**2*s4**2 + 17*s1**6*s2*s3**2*s4 + s1**6*s3**4 - 5*s1**6*s4**3 - 12*s1**5*s2**3*s3*s4
+- 133*s1**5*s2*s3*s4**2 - 22*s1**5*s3**3*s4 + s1**4*s2**5*s4 - 76*s1**4*s2**3*s4**2
+- 6*s1**4*s2**2*s3**2*s4 - 12*s1**4*s2*s3**4 + 32*s1**4*s2*s4**3 + 128*s1**4*s3**2*s4**2
++ 29*s1**3*s2**4*s3*s4 + 2*s1**3*s2**3*s3**3 + 344*s1**3*s2**2*s3*s4**2 + 48*s1**3*s2*s3**3*s4
++ 16*s1**3*s3**5 - 48*s1**3*s3*s4**3 - 4*s1**2*s2**6*s4 + 32*s1**2*s2**4*s4**2 - 134*s1**2*s2**3*s3**2*s4
++ 36*s1**2*s2**2*s3**4 - 64*s1**2*s2**2*s4**3 - 648*s1**2*s2*s3**2*s4**2 - 48*s1**2*s3**4*s4
++ 16*s1*s2**5*s3*s4 - 12*s1*s2**4*s3**3 - 128*s1*s2**3*s3*s4**2 + 296*s1*s2**2*s3**3*s4
+- 96*s1*s2*s3**5 + 256*s1*s2*s3*s4**3 + 416*s1*s3**3*s4**2 + s2**6*s3**2 - 28*s2**4*s3**2*s4
++ 16*s2**3*s3**4 + 176*s2**2*s3**2*s4**2 - 224*s2*s3**4*s4 + 64*s3**6 - 320*s3**2*s4**3)
+    ],
+    (4, 1): [
+        lambda s1, s2, s3, s4: (-s2),
+        lambda s1, s2, s3, s4: (s1*s3 - 4*s4),
+        lambda s1, s2, s3, s4: (-s1**2*s4 + 4*s2*s4 - s3**2)
+    ],
+    (5, 1): [
+        lambda s1, s2, s3, s4, s5: (-2*s1*s3 + 8*s4),
+        lambda s1, s2, s3, s4, s5: (-8*s1**3*s5 + 2*s1**2*s2*s4 + s1**2*s3**2 + 30*s1*s2*s5 - 14*s1*s3*s4 - 6*s2**2*s4
++ 2*s2*s3**2 - 50*s3*s5 + 40*s4**2),
+        lambda s1, s2, s3, s4, s5: (16*s1**4*s3*s5 - 2*s1**4*s4**2 - 2*s1**3*s2**2*s5 - 2*s1**3*s2*s3*s4 - 44*s1**3*s4*s5
+- 66*s1**2*s2*s3*s5 + 21*s1**2*s2*s4**2 + 6*s1**2*s3**2*s4 - 50*s1**2*s5**2 + 9*s1*s2**3*s5
++ 5*s1*s2**2*s3*s4 - 2*s1*s2*s3**3 + 190*s1*s2*s4*s5 + 120*s1*s3**2*s5 - 80*s1*s3*s4**2
+- 15*s2**2*s3*s5 - 40*s2**2*s4**2 + 21*s2*s3**2*s4 + 125*s2*s5**2 - 2*s3**4 - 400*s3*s4*s5
++ 160*s4**3),
+        lambda s1, s2, s3, s4, s5: (16*s1**6*s5**2 - 8*s1**5*s2*s4*s5 - 8*s1**5*s3**2*s5 + 2*s1**5*s3*s4**2 + 2*s1**4*s2**2*s3*s5
++ s1**4*s2**2*s4**2 - 120*s1**4*s2*s5**2 + 68*s1**4*s3*s4*s5 - 8*s1**4*s4**3 + 46*s1**3*s2**2*s4*s5
++ 28*s1**3*s2*s3**2*s5 - 19*s1**3*s2*s3*s4**2 + 250*s1**3*s3*s5**2 - 144*s1**3*s4**2*s5
+- 9*s1**2*s2**3*s3*s5 - 6*s1**2*s2**3*s4**2 + 3*s1**2*s2**2*s3**2*s4 + 225*s1**2*s2**2*s5**2
+- 354*s1**2*s2*s3*s4*s5 + 76*s1**2*s2*s4**3 - 70*s1**2*s3**3*s5 + 41*s1**2*s3**2*s4**2
+- 200*s1**2*s4*s5**2 - 54*s1*s2**3*s4*s5 + 45*s1*s2**2*s3**2*s5 + 30*s1*s2**2*s3*s4**2
+- 19*s1*s2*s3**3*s4 - 875*s1*s2*s3*s5**2 + 640*s1*s2*s4**2*s5 + 2*s1*s3**5 + 630*s1*s3**2*s4*s5
+- 264*s1*s3*s4**3 + 9*s2**4*s4**2 - 6*s2**3*s3**2*s4 + s2**2*s3**4 + 90*s2**2*s3*s4*s5
+- 136*s2**2*s4**3 - 50*s2*s3**3*s5 + 76*s2*s3**2*s4**2 + 500*s2*s4*s5**2 - 8*s3**4*s4
++ 625*s3**2*s5**2 - 1400*s3*s4**2*s5 + 400*s4**4),
+        lambda s1, s2, s3, s4, s5: (-32*s1**7*s3*s5**2 + 8*s1**7*s4**2*s5 + 8*s1**6*s2**2*s5**2 + 8*s1**6*s2*s3*s4*s5
+- 2*s1**6*s2*s4**3 + 48*s1**6*s4*s5**2 - 2*s1**5*s2**3*s4*s5 + 264*s1**5*s2*s3*s5**2
+- 94*s1**5*s2*s4**2*s5 - 24*s1**5*s3**2*s4*s5 + 6*s1**5*s3*s4**3 - 56*s1**5*s5**3
+- 66*s1**4*s2**3*s5**2 - 50*s1**4*s2**2*s3*s4*s5 + 19*s1**4*s2**2*s4**3 + 8*s1**4*s2*s3**3*s5
+- 2*s1**4*s2*s3**2*s4**2 - 318*s1**4*s2*s4*s5**2 - 352*s1**4*s3**2*s5**2 + 166*s1**4*s3*s4**2*s5
++ 3*s1**4*s4**4 + 15*s1**3*s2**4*s4*s5 - 2*s1**3*s2**3*s3**2*s5 - s1**3*s2**3*s3*s4**2
+- 574*s1**3*s2**2*s3*s5**2 + 347*s1**3*s2**2*s4**2*s5 + 194*s1**3*s2*s3**2*s4*s5 -
+89*s1**3*s2*s3*s4**3 + 350*s1**3*s2*s5**3 - 8*s1**3*s3**4*s5 + 4*s1**3*s3**3*s4**2
++ 1090*s1**3*s3*s4*s5**2 - 364*s1**3*s4**3*s5 + 162*s1**2*s2**4*s5**2 + 33*s1**2*s2**3*s3*s4*s5
+- 51*s1**2*s2**3*s4**3 - 32*s1**2*s2**2*s3**3*s5 + 28*s1**2*s2**2*s3**2*s4**2 + 305*s1**2*s2**2*s4*s5**2
+- 2*s1**2*s2*s3**4*s4 + 1340*s1**2*s2*s3**2*s5**2 - 901*s1**2*s2*s3*s4**2*s5 + 76*s1**2*s2*s4**4
+- 234*s1**2*s3**3*s4*s5 + 102*s1**2*s3**2*s4**3 - 750*s1**2*s3*s5**3 - 550*s1**2*s4**2*s5**2
+- 27*s1*s2**5*s4*s5 + 9*s1*s2**4*s3**2*s5 + 3*s1*s2**4*s3*s4**2 - s1*s2**3*s3**3*s4
++ 180*s1*s2**3*s3*s5**2 - 366*s1*s2**3*s4**2*s5 - 231*s1*s2**2*s3**2*s4*s5 + 212*s1*s2**2*s3*s4**3
+- 375*s1*s2**2*s5**3 + 112*s1*s2*s3**4*s5 - 89*s1*s2*s3**3*s4**2 - 3075*s1*s2*s3*s4*s5**2
++ 1640*s1*s2*s4**3*s5 + 6*s1*s3**5*s4 - 850*s1*s3**3*s5**2 + 1220*s1*s3**2*s4**2*s5
+- 384*s1*s3*s4**4 + 2500*s1*s4*s5**3 - 108*s2**5*s5**2 + 117*s2**4*s3*s4*s5 + 32*s2**4*s4**3
+- 31*s2**3*s3**3*s5 - 51*s2**3*s3**2*s4**2 + 525*s2**3*s4*s5**2 + 19*s2**2*s3**4*s4
+- 325*s2**2*s3**2*s5**2 + 260*s2**2*s3*s4**2*s5 - 256*s2**2*s4**4 - 2*s2*s3**6 + 105*s2*s3**3*s4*s5
++ 76*s2*s3**2*s4**3 + 625*s2*s3*s5**3 - 500*s2*s4**2*s5**2 - 58*s3**5*s5 + 3*s3**4*s4**2
++ 2750*s3**2*s4*s5**2 - 2400*s3*s4**3*s5 + 512*s4**5 - 3125*s5**4),
+        lambda s1, s2, s3, s4, s5: (16*s1**8*s3**2*s5**2 - 8*s1**8*s3*s4**2*s5 + s1**8*s4**4 - 8*s1**7*s2**2*s3*s5**2
++ 2*s1**7*s2**2*s4**2*s5 - 48*s1**7*s3*s4*s5**2 + 12*s1**7*s4**3*s5 + s1**6*s2**4*s5**2
++ 12*s1**6*s2**2*s4*s5**2 - 144*s1**6*s2*s3**2*s5**2 + 88*s1**6*s2*s3*s4**2*s5 - 13*s1**6*s2*s4**4
++ 56*s1**6*s3*s5**3 + 86*s1**6*s4**2*s5**2 + 72*s1**5*s2**3*s3*s5**2 - 22*s1**5*s2**3*s4**2*s5
+- 4*s1**5*s2**2*s3**2*s4*s5 + s1**5*s2**2*s3*s4**3 - 14*s1**5*s2**2*s5**3 + 304*s1**5*s2*s3*s4*s5**2
+- 148*s1**5*s2*s4**3*s5 + 152*s1**5*s3**3*s5**2 - 54*s1**5*s3**2*s4**2*s5 + 5*s1**5*s3*s4**4
+- 468*s1**5*s4*s5**3 - 9*s1**4*s2**5*s5**2 + s1**4*s2**4*s3*s4*s5 - 76*s1**4*s2**3*s4*s5**2
++ 370*s1**4*s2**2*s3**2*s5**2 - 287*s1**4*s2**2*s3*s4**2*s5 + 65*s1**4*s2**2*s4**4
+- 28*s1**4*s2*s3**3*s4*s5 + 5*s1**4*s2*s3**2*s4**3 - 200*s1**4*s2*s3*s5**3 - 294*s1**4*s2*s4**2*s5**2
++ 8*s1**4*s3**5*s5 - 2*s1**4*s3**4*s4**2 - 676*s1**4*s3**2*s4*s5**2 + 180*s1**4*s3*s4**3*s5
++ 17*s1**4*s4**5 + 625*s1**4*s5**4 - 210*s1**3*s2**4*s3*s5**2 + 76*s1**3*s2**4*s4**2*s5
++ 43*s1**3*s2**3*s3**2*s4*s5 - 15*s1**3*s2**3*s3*s4**3 + 50*s1**3*s2**3*s5**3 - 6*s1**3*s2**2*s3**4*s5
++ 2*s1**3*s2**2*s3**3*s4**2 - 397*s1**3*s2**2*s3*s4*s5**2 + 514*s1**3*s2**2*s4**3*s5
+- 700*s1**3*s2*s3**3*s5**2 + 447*s1**3*s2*s3**2*s4**2*s5 - 118*s1**3*s2*s3*s4**4 +
+2300*s1**3*s2*s4*s5**3 - 12*s1**3*s3**4*s4*s5 + 6*s1**3*s3**3*s4**3 + 250*s1**3*s3**2*s5**3
++ 1470*s1**3*s3*s4**2*s5**2 - 276*s1**3*s4**4*s5 + 27*s1**2*s2**6*s5**2 - 9*s1**2*s2**5*s3*s4*s5
++ s1**2*s2**5*s4**3 + s1**2*s2**4*s3**3*s5 + 141*s1**2*s2**4*s4*s5**2 - 185*s1**2*s2**3*s3**2*s5**2
++ 168*s1**2*s2**3*s3*s4**2*s5 - 128*s1**2*s2**3*s4**4 + 93*s1**2*s2**2*s3**3*s4*s5
++ 19*s1**2*s2**2*s3**2*s4**3 - 125*s1**2*s2**2*s3*s5**3 - 610*s1**2*s2**2*s4**2*s5**2
+- 36*s1**2*s2*s3**5*s5 + 5*s1**2*s2*s3**4*s4**2 + 1995*s1**2*s2*s3**2*s4*s5**2 - 1174*s1**2*s2*s3*s4**3*s5
+- 16*s1**2*s2*s4**5 - 3125*s1**2*s2*s5**4 + 375*s1**2*s3**4*s5**2 - 172*s1**2*s3**3*s4**2*s5
++ 82*s1**2*s3**2*s4**4 - 3500*s1**2*s3*s4*s5**3 - 1450*s1**2*s4**3*s5**2 + 198*s1*s2**5*s3*s5**2
+- 78*s1*s2**5*s4**2*s5 - 95*s1*s2**4*s3**2*s4*s5 + 44*s1*s2**4*s3*s4**3 + 25*s1*s2**3*s3**4*s5
+- 15*s1*s2**3*s3**3*s4**2 + 15*s1*s2**3*s3*s4*s5**2 - 384*s1*s2**3*s4**3*s5 + s1*s2**2*s3**5*s4
++ 525*s1*s2**2*s3**3*s5**2 - 528*s1*s2**2*s3**2*s4**2*s5 + 384*s1*s2**2*s3*s4**4 -
+1750*s1*s2**2*s4*s5**3 - 29*s1*s2*s3**4*s4*s5 - 118*s1*s2*s3**3*s4**3 + 625*s1*s2*s3**2*s5**3
+- 850*s1*s2*s3*s4**2*s5**2 + 1760*s1*s2*s4**4*s5 + 38*s1*s3**6*s5 + 5*s1*s3**5*s4**2
+- 2050*s1*s3**3*s4*s5**2 + 780*s1*s3**2*s4**3*s5 - 192*s1*s3*s4**5 + 3125*s1*s3*s5**4
++ 7500*s1*s4**2*s5**3 - 27*s2**7*s5**2 + 18*s2**6*s3*s4*s5 - 4*s2**6*s4**3 - 4*s2**5*s3**3*s5
++ s2**5*s3**2*s4**2 - 99*s2**5*s4*s5**2 - 150*s2**4*s3**2*s5**2 + 196*s2**4*s3*s4**2*s5
++ 48*s2**4*s4**4 + 12*s2**3*s3**3*s4*s5 - 128*s2**3*s3**2*s4**3 + 1200*s2**3*s4**2*s5**2
+- 12*s2**2*s3**5*s5 + 65*s2**2*s3**4*s4**2 - 725*s2**2*s3**2*s4*s5**2 - 160*s2**2*s3*s4**3*s5
+- 192*s2**2*s4**5 + 3125*s2**2*s5**4 - 13*s2*s3**6*s4 - 125*s2*s3**4*s5**2 + 590*s2*s3**3*s4**2*s5
+- 16*s2*s3**2*s4**4 - 1250*s2*s3*s4*s5**3 - 2000*s2*s4**3*s5**2 + s3**8 - 124*s3**5*s4*s5
++ 17*s3**4*s4**3 + 3250*s3**2*s4**2*s5**2 - 1600*s3*s4**4*s5 + 256*s4**6 - 9375*s4*s5**4)
+    ],
+    (6, 1): [
+        lambda s1, s2, s3, s4, s5, s6: (8*s1*s5 - 2*s2*s4 - 18*s6),
+        lambda s1, s2, s3, s4, s5, s6: (-50*s1**2*s4*s6 + 40*s1**2*s5**2 + 30*s1*s2*s3*s6 - 14*s1*s2*s4*s5 - 6*s1*s3**2*s5
++ 2*s1*s3*s4**2 - 30*s1*s5*s6 - 8*s2**3*s6 + 2*s2**2*s3*s5 + s2**2*s4**2 + 114*s2*s4*s6
+- 50*s2*s5**2 - 54*s3**2*s6 + 30*s3*s4*s5 - 8*s4**3 - 135*s6**2),
+        lambda s1, s2, s3, s4, s5, s6: (125*s1**3*s3*s6**2 - 400*s1**3*s4*s5*s6 + 160*s1**3*s5**3 - 50*s1**2*s2**2*s6**2 +
+190*s1**2*s2*s3*s5*s6 + 120*s1**2*s2*s4**2*s6 - 80*s1**2*s2*s4*s5**2 - 15*s1**2*s3**2*s4*s6
+- 40*s1**2*s3**2*s5**2 + 21*s1**2*s3*s4**2*s5 - 2*s1**2*s4**4 + 900*s1**2*s4*s6**2
+- 80*s1**2*s5**2*s6 - 44*s1*s2**3*s5*s6 - 66*s1*s2**2*s3*s4*s6 + 21*s1*s2**2*s3*s5**2
++ 6*s1*s2**2*s4**2*s5 + 9*s1*s2*s3**3*s6 + 5*s1*s2*s3**2*s4*s5 - 2*s1*s2*s3*s4**3
+- 990*s1*s2*s3*s6**2 + 920*s1*s2*s4*s5*s6 - 400*s1*s2*s5**3 - 135*s1*s3**2*s5*s6 -
+126*s1*s3*s4**2*s6 + 190*s1*s3*s4*s5**2 - 44*s1*s4**3*s5 - 2070*s1*s5*s6**2 + 16*s2**4*s4*s6
+- 2*s2**4*s5**2 - 2*s2**3*s3**2*s6 - 2*s2**3*s3*s4*s5 + 304*s2**3*s6**2 - 126*s2**2*s3*s5*s6
+- 232*s2**2*s4**2*s6 + 120*s2**2*s4*s5**2 + 198*s2*s3**2*s4*s6 - 15*s2*s3**2*s5**2
+- 66*s2*s3*s4**2*s5 + 16*s2*s4**4 - 1440*s2*s4*s6**2 + 900*s2*s5**2*s6 - 27*s3**4*s6
++ 9*s3**3*s4*s5 - 2*s3**2*s4**3 + 1350*s3**2*s6**2 - 990*s3*s4*s5*s6 + 125*s3*s5**3
++ 304*s4**3*s6 - 50*s4**2*s5**2 + 3240*s6**3),
+        lambda s1, s2, s3, s4, s5, s6: (500*s1**4*s3*s5*s6**2 + 625*s1**4*s4**2*s6**2 - 1400*s1**4*s4*s5**2*s6 + 400*s1**4*s5**4
+- 200*s1**3*s2**2*s5*s6**2 - 875*s1**3*s2*s3*s4*s6**2 + 640*s1**3*s2*s3*s5**2*s6 +
+630*s1**3*s2*s4**2*s5*s6 - 264*s1**3*s2*s4*s5**3 + 90*s1**3*s3**2*s4*s5*s6 - 136*s1**3*s3**2*s5**3
+- 50*s1**3*s3*s4**3*s6 + 76*s1**3*s3*s4**2*s5**2 - 1125*s1**3*s3*s6**3 - 8*s1**3*s4**4*s5
++ 2550*s1**3*s4*s5*s6**2 - 200*s1**3*s5**3*s6 + 250*s1**2*s2**3*s4*s6**2 - 144*s1**2*s2**3*s5**2*s6
++ 225*s1**2*s2**2*s3**2*s6**2 - 354*s1**2*s2**2*s3*s4*s5*s6 + 76*s1**2*s2**2*s3*s5**3
+- 70*s1**2*s2**2*s4**3*s6 + 41*s1**2*s2**2*s4**2*s5**2 + 450*s1**2*s2**2*s6**3 - 54*s1**2*s2*s3**3*s5*s6
++ 45*s1**2*s2*s3**2*s4**2*s6 + 30*s1**2*s2*s3**2*s4*s5**2 - 19*s1**2*s2*s3*s4**3*s5
+- 2880*s1**2*s2*s3*s5*s6**2 + 2*s1**2*s2*s4**5 - 3480*s1**2*s2*s4**2*s6**2 + 4692*s1**2*s2*s4*s5**2*s6
+- 1400*s1**2*s2*s5**4 + 9*s1**2*s3**4*s5**2 - 6*s1**2*s3**3*s4**2*s5 + s1**2*s3**2*s4**4
++ 1485*s1**2*s3**2*s4*s6**2 - 522*s1**2*s3**2*s5**2*s6 - 1257*s1**2*s3*s4**2*s5*s6
++ 640*s1**2*s3*s4*s5**3 + 218*s1**2*s4**4*s6 - 144*s1**2*s4**3*s5**2 + 1350*s1**2*s4*s6**3
+- 5175*s1**2*s5**2*s6**2 - 120*s1*s2**4*s3*s6**2 + 68*s1*s2**4*s4*s5*s6 - 8*s1*s2**4*s5**3
++ 46*s1*s2**3*s3**2*s5*s6 + 28*s1*s2**3*s3*s4**2*s6 - 19*s1*s2**3*s3*s4*s5**2 + 868*s1*s2**3*s5*s6**2
+- 9*s1*s2**2*s3**3*s4*s6 - 6*s1*s2**2*s3**3*s5**2 + 3*s1*s2**2*s3**2*s4**2*s5 + 2484*s1*s2**2*s3*s4*s6**2
+- 1257*s1*s2**2*s3*s5**2*s6 - 1356*s1*s2**2*s4**2*s5*s6 + 630*s1*s2**2*s4*s5**3 -
+891*s1*s2*s3**3*s6**2 + 882*s1*s2*s3**2*s4*s5*s6 + 90*s1*s2*s3**2*s5**3 + 84*s1*s2*s3*s4**3*s6
+- 354*s1*s2*s3*s4**2*s5**2 + 3240*s1*s2*s3*s6**3 + 68*s1*s2*s4**4*s5 - 4392*s1*s2*s4*s5*s6**2
++ 2550*s1*s2*s5**3*s6 + 54*s1*s3**4*s5*s6 - 54*s1*s3**3*s4**2*s6 - 54*s1*s3**3*s4*s5**2
++ 46*s1*s3**2*s4**3*s5 + 2727*s1*s3**2*s5*s6**2 - 8*s1*s3*s4**5 + 756*s1*s3*s4**2*s6**2
+- 2880*s1*s3*s4*s5**2*s6 + 500*s1*s3*s5**4 + 868*s1*s4**3*s5*s6 - 200*s1*s4**2*s5**3
++ 8100*s1*s5*s6**3 + 16*s2**6*s6**2 - 8*s2**5*s3*s5*s6 - 8*s2**5*s4**2*s6 + 2*s2**5*s4*s5**2
++ 2*s2**4*s3**2*s4*s6 + s2**4*s3**2*s5**2 - 688*s2**4*s4*s6**2 + 218*s2**4*s5**2*s6
++ 234*s2**3*s3**2*s6**2 + 84*s2**3*s3*s4*s5*s6 - 50*s2**3*s3*s5**3 + 168*s2**3*s4**3*s6
+- 70*s2**3*s4**2*s5**2 - 1224*s2**3*s6**3 - 54*s2**2*s3**3*s5*s6 - 144*s2**2*s3**2*s4**2*s6
++ 45*s2**2*s3**2*s4*s5**2 + 28*s2**2*s3*s4**3*s5 + 756*s2**2*s3*s5*s6**2 - 8*s2**2*s4**5
++ 4320*s2**2*s4**2*s6**2 - 3480*s2**2*s4*s5**2*s6 + 625*s2**2*s5**4 + 27*s2*s3**4*s4*s6
+- 9*s2*s3**3*s4**2*s5 + 2*s2*s3**2*s4**4 - 4752*s2*s3**2*s4*s6**2 + 1485*s2*s3**2*s5**2*s6
++ 2484*s2*s3*s4**2*s5*s6 - 875*s2*s3*s4*s5**3 - 688*s2*s4**4*s6 + 250*s2*s4**3*s5**2
+- 4536*s2*s4*s6**3 + 1350*s2*s5**2*s6**2 + 972*s3**4*s6**2 - 891*s3**3*s4*s5*s6 +
+234*s3**2*s4**3*s6 + 225*s3**2*s4**2*s5**2 - 1944*s3**2*s6**3 - 120*s3*s4**4*s5 +
+3240*s3*s4*s5*s6**2 - 1125*s3*s5**3*s6 + 16*s4**6 - 1224*s4**3*s6**2 + 450*s4**2*s5**2*s6),
+        lambda s1, s2, s3, s4, s5, s6: (-3125*s1**6*s6**4 + 2500*s1**5*s2*s5*s6**3 + 625*s1**5*s3*s4*s6**3 - 500*s1**5*s3*s5**2*s6**2
++ 2750*s1**5*s4**2*s5*s6**2 - 2400*s1**5*s4*s5**3*s6 + 512*s1**5*s5**5 - 750*s1**4*s2**2*s4*s6**3
+- 550*s1**4*s2**2*s5**2*s6**2 - 375*s1**4*s2*s3**2*s6**3 - 3075*s1**4*s2*s3*s4*s5*s6**2
++ 1640*s1**4*s2*s3*s5**3*s6 - 850*s1**4*s2*s4**3*s6**2 + 1220*s1**4*s2*s4**2*s5**2*s6
+- 384*s1**4*s2*s4*s5**4 + 22500*s1**4*s2*s6**4 + 525*s1**4*s3**3*s5*s6**2 - 325*s1**4*s3**2*s4**2*s6**2
++ 260*s1**4*s3**2*s4*s5**2*s6 - 256*s1**4*s3**2*s5**4 + 105*s1**4*s3*s4**3*s5*s6 +
+76*s1**4*s3*s4**2*s5**3 + 375*s1**4*s3*s5*s6**3 - 58*s1**4*s4**5*s6 + 3*s1**4*s4**4*s5**2
+- 12750*s1**4*s4**2*s6**3 + 3700*s1**4*s4*s5**2*s6**2 + 640*s1**4*s5**4*s6 + 350*s1**3*s2**3*s3*s6**3
++ 1090*s1**3*s2**3*s4*s5*s6**2 - 364*s1**3*s2**3*s5**3*s6 + 305*s1**3*s2**2*s3**2*s5*s6**2
++ 1340*s1**3*s2**2*s3*s4**2*s6**2 - 901*s1**3*s2**2*s3*s4*s5**2*s6 + 76*s1**3*s2**2*s3*s5**4
+- 234*s1**3*s2**2*s4**3*s5*s6 + 102*s1**3*s2**2*s4**2*s5**3 - 16650*s1**3*s2**2*s5*s6**3
++ 180*s1**3*s2*s3**3*s4*s6**2 - 366*s1**3*s2*s3**3*s5**2*s6 - 231*s1**3*s2*s3**2*s4**2*s5*s6
++ 212*s1**3*s2*s3**2*s4*s5**3 + 112*s1**3*s2*s3*s4**4*s6 - 89*s1**3*s2*s3*s4**3*s5**2
++ 10950*s1**3*s2*s3*s4*s6**3 + 1555*s1**3*s2*s3*s5**2*s6**2 + 6*s1**3*s2*s4**5*s5
+- 9540*s1**3*s2*s4**2*s5*s6**2 + 9016*s1**3*s2*s4*s5**3*s6 - 2400*s1**3*s2*s5**5 -
+108*s1**3*s3**5*s6**2 + 117*s1**3*s3**4*s4*s5*s6 + 32*s1**3*s3**4*s5**3 - 31*s1**3*s3**3*s4**3*s6
+- 51*s1**3*s3**3*s4**2*s5**2 - 2025*s1**3*s3**3*s6**3 + 19*s1**3*s3**2*s4**4*s5 +
+2955*s1**3*s3**2*s4*s5*s6**2 - 1436*s1**3*s3**2*s5**3*s6 - 2*s1**3*s3*s4**6 + 2770*s1**3*s3*s4**3*s6**2
+- 5123*s1**3*s3*s4**2*s5**2*s6 + 1640*s1**3*s3*s4*s5**4 - 40500*s1**3*s3*s6**4 + 914*s1**3*s4**4*s5*s6
+- 364*s1**3*s4**3*s5**3 + 53550*s1**3*s4*s5*s6**3 - 17930*s1**3*s5**3*s6**2 - 56*s1**2*s2**5*s6**3
+- 318*s1**2*s2**4*s3*s5*s6**2 - 352*s1**2*s2**4*s4**2*s6**2 + 166*s1**2*s2**4*s4*s5**2*s6
++ 3*s1**2*s2**4*s5**4 - 574*s1**2*s2**3*s3**2*s4*s6**2 + 347*s1**2*s2**3*s3**2*s5**2*s6
++ 194*s1**2*s2**3*s3*s4**2*s5*s6 - 89*s1**2*s2**3*s3*s4*s5**3 - 8*s1**2*s2**3*s4**4*s6
++ 4*s1**2*s2**3*s4**3*s5**2 + 560*s1**2*s2**3*s4*s6**3 + 3662*s1**2*s2**3*s5**2*s6**2
++ 162*s1**2*s2**2*s3**4*s6**2 + 33*s1**2*s2**2*s3**3*s4*s5*s6 - 51*s1**2*s2**2*s3**3*s5**3
+- 32*s1**2*s2**2*s3**2*s4**3*s6 + 28*s1**2*s2**2*s3**2*s4**2*s5**2 + 270*s1**2*s2**2*s3**2*s6**3
+- 2*s1**2*s2**2*s3*s4**4*s5 + 4872*s1**2*s2**2*s3*s4*s5*s6**2 - 5123*s1**2*s2**2*s3*s5**3*s6
++ 2144*s1**2*s2**2*s4**3*s6**2 - 2812*s1**2*s2**2*s4**2*s5**2*s6 + 1220*s1**2*s2**2*s4*s5**4
+- 37800*s1**2*s2**2*s6**4 - 27*s1**2*s2*s3**5*s5*s6 + 9*s1**2*s2*s3**4*s4**2*s6 +
+3*s1**2*s2*s3**4*s4*s5**2 - s1**2*s2*s3**3*s4**3*s5 - 3078*s1**2*s2*s3**3*s5*s6**2
+- 4014*s1**2*s2*s3**2*s4**2*s6**2 + 5412*s1**2*s2*s3**2*s4*s5**2*s6 + 260*s1**2*s2*s3**2*s5**4
+- 310*s1**2*s2*s3*s4**3*s5*s6 - 901*s1**2*s2*s3*s4**2*s5**3 - 3780*s1**2*s2*s3*s5*s6**3
++ 166*s1**2*s2*s4**4*s5**2 + 40320*s1**2*s2*s4**2*s6**3 - 25344*s1**2*s2*s4*s5**2*s6**2
++ 3700*s1**2*s2*s5**4*s6 + 918*s1**2*s3**4*s4*s6**2 + 27*s1**2*s3**4*s5**2*s6 - 342*s1**2*s3**3*s4**2*s5*s6
+- 366*s1**2*s3**3*s4*s5**3 + 32*s1**2*s3**2*s4**4*s6 + 347*s1**2*s3**2*s4**3*s5**2
+- 4590*s1**2*s3**2*s4*s6**3 + 594*s1**2*s3**2*s5**2*s6**2 - 94*s1**2*s3*s4**5*s5 +
+3618*s1**2*s3*s4**2*s5*s6**2 + 1555*s1**2*s3*s4*s5**3*s6 - 500*s1**2*s3*s5**5 + 8*s1**2*s4**7
+- 7192*s1**2*s4**4*s6**2 + 3662*s1**2*s4**3*s5**2*s6 - 550*s1**2*s4**2*s5**4 - 48600*s1**2*s4*s6**4
++ 1080*s1**2*s5**2*s6**3 + 48*s1*s2**6*s5*s6**2 + 264*s1*s2**5*s3*s4*s6**2 - 94*s1*s2**5*s3*s5**2*s6
+- 24*s1*s2**5*s4**2*s5*s6 + 6*s1*s2**5*s4*s5**3 - 66*s1*s2**4*s3**3*s6**2 - 50*s1*s2**4*s3**2*s4*s5*s6
++ 19*s1*s2**4*s3**2*s5**3 + 8*s1*s2**4*s3*s4**3*s6 - 2*s1*s2**4*s3*s4**2*s5**2 - 552*s1*s2**4*s3*s6**3
+- 2560*s1*s2**4*s4*s5*s6**2 + 914*s1*s2**4*s5**3*s6 + 15*s1*s2**3*s3**4*s5*s6 - 2*s1*s2**3*s3**3*s4**2*s6
+- s1*s2**3*s3**3*s4*s5**2 + 1602*s1*s2**3*s3**2*s5*s6**2 - 608*s1*s2**3*s3*s4**2*s6**2
+- 310*s1*s2**3*s3*s4*s5**2*s6 + 105*s1*s2**3*s3*s5**4 + 600*s1*s2**3*s4**3*s5*s6 -
+234*s1*s2**3*s4**2*s5**3 + 31368*s1*s2**3*s5*s6**3 + 756*s1*s2**2*s3**3*s4*s6**2 -
+342*s1*s2**2*s3**3*s5**2*s6 + 216*s1*s2**2*s3**2*s4**2*s5*s6 - 231*s1*s2**2*s3**2*s4*s5**3
+- 192*s1*s2**2*s3*s4**4*s6 + 194*s1*s2**2*s3*s4**3*s5**2 - 39096*s1*s2**2*s3*s4*s6**3
++ 3618*s1*s2**2*s3*s5**2*s6**2 - 24*s1*s2**2*s4**5*s5 + 9408*s1*s2**2*s4**2*s5*s6**2
+- 9540*s1*s2**2*s4*s5**3*s6 + 2750*s1*s2**2*s5**5 - 162*s1*s2*s3**5*s6**2 - 378*s1*s2*s3**4*s4*s5*s6
++ 117*s1*s2*s3**4*s5**3 + 150*s1*s2*s3**3*s4**3*s6 + 33*s1*s2*s3**3*s4**2*s5**2 +
+10044*s1*s2*s3**3*s6**3 - 50*s1*s2*s3**2*s4**4*s5 - 8640*s1*s2*s3**2*s4*s5*s6**2 +
+2955*s1*s2*s3**2*s5**3*s6 + 8*s1*s2*s3*s4**6 + 6144*s1*s2*s3*s4**3*s6**2 + 4872*s1*s2*s3*s4**2*s5**2*s6
+- 3075*s1*s2*s3*s4*s5**4 + 174960*s1*s2*s3*s6**4 - 2560*s1*s2*s4**4*s5*s6 + 1090*s1*s2*s4**3*s5**3
+- 148824*s1*s2*s4*s5*s6**3 + 53550*s1*s2*s5**3*s6**2 + 81*s1*s3**6*s5*s6 - 27*s1*s3**5*s4**2*s6
+- 27*s1*s3**5*s4*s5**2 + 15*s1*s3**4*s4**3*s5 + 2430*s1*s3**4*s5*s6**2 - 2*s1*s3**3*s4**5
+- 2052*s1*s3**3*s4**2*s6**2 - 3078*s1*s3**3*s4*s5**2*s6 + 525*s1*s3**3*s5**4 + 1602*s1*s3**2*s4**3*s5*s6
++ 305*s1*s3**2*s4**2*s5**3 + 18144*s1*s3**2*s5*s6**3 - 104*s1*s3*s4**5*s6 - 318*s1*s3*s4**4*s5**2
+- 33696*s1*s3*s4**2*s6**3 - 3780*s1*s3*s4*s5**2*s6**2 + 375*s1*s3*s5**4*s6 + 48*s1*s4**6*s5
++ 31368*s1*s4**3*s5*s6**2 - 16650*s1*s4**2*s5**3*s6 + 2500*s1*s4*s5**5 + 77760*s1*s5*s6**4
+- 32*s2**7*s4*s6**2 + 8*s2**7*s5**2*s6 + 8*s2**6*s3**2*s6**2 + 8*s2**6*s3*s4*s5*s6
+- 2*s2**6*s3*s5**3 + 96*s2**6*s6**3 - 2*s2**5*s3**3*s5*s6 - 104*s2**5*s3*s5*s6**2
++ 416*s2**5*s4**2*s6**2 - 58*s2**5*s5**4 - 312*s2**4*s3**2*s4*s6**2 + 32*s2**4*s3**2*s5**2*s6
+- 192*s2**4*s3*s4**2*s5*s6 + 112*s2**4*s3*s4*s5**3 - 8*s2**4*s4**3*s5**2 + 4224*s2**4*s4*s6**3
+- 7192*s2**4*s5**2*s6**2 + 54*s2**3*s3**4*s6**2 + 150*s2**3*s3**3*s4*s5*s6 - 31*s2**3*s3**3*s5**3
+- 32*s2**3*s3**2*s4**2*s5**2 - 864*s2**3*s3**2*s6**3 + 8*s2**3*s3*s4**4*s5 + 6144*s2**3*s3*s4*s5*s6**2
++ 2770*s2**3*s3*s5**3*s6 - 4032*s2**3*s4**3*s6**2 + 2144*s2**3*s4**2*s5**2*s6 - 850*s2**3*s4*s5**4
+- 16416*s2**3*s6**4 - 27*s2**2*s3**5*s5*s6 + 9*s2**2*s3**4*s4*s5**2 - 2*s2**2*s3**3*s4**3*s5
+- 2052*s2**2*s3**3*s5*s6**2 + 2376*s2**2*s3**2*s4**2*s6**2 - 4014*s2**2*s3**2*s4*s5**2*s6
+- 325*s2**2*s3**2*s5**4 - 608*s2**2*s3*s4**3*s5*s6 + 1340*s2**2*s3*s4**2*s5**3 - 33696*s2**2*s3*s5*s6**3
++ 416*s2**2*s4**5*s6 - 352*s2**2*s4**4*s5**2 - 6048*s2**2*s4**2*s6**3 + 40320*s2**2*s4*s5**2*s6**2
+- 12750*s2**2*s5**4*s6 - 324*s2*s3**4*s4*s6**2 + 918*s2*s3**4*s5**2*s6 + 756*s2*s3**3*s4**2*s5*s6
++ 180*s2*s3**3*s4*s5**3 - 312*s2*s3**2*s4**4*s6 - 574*s2*s3**2*s4**3*s5**2 + 43416*s2*s3**2*s4*s6**3
+- 4590*s2*s3**2*s5**2*s6**2 + 264*s2*s3*s4**5*s5 - 39096*s2*s3*s4**2*s5*s6**2 + 10950*s2*s3*s4*s5**3*s6
++ 625*s2*s3*s5**5 - 32*s2*s4**7 + 4224*s2*s4**4*s6**2 + 560*s2*s4**3*s5**2*s6 - 750*s2*s4**2*s5**4
++ 85536*s2*s4*s6**4 - 48600*s2*s5**2*s6**3 - 162*s3**5*s4*s5*s6 - 108*s3**5*s5**3
++ 54*s3**4*s4**3*s6 + 162*s3**4*s4**2*s5**2 - 11664*s3**4*s6**3 - 66*s3**3*s4**4*s5
++ 10044*s3**3*s4*s5*s6**2 - 2025*s3**3*s5**3*s6 + 8*s3**2*s4**6 - 864*s3**2*s4**3*s6**2
++ 270*s3**2*s4**2*s5**2*s6 - 375*s3**2*s4*s5**4 - 163296*s3**2*s6**4 - 552*s3*s4**4*s5*s6
++ 350*s3*s4**3*s5**3 + 174960*s3*s4*s5*s6**3 - 40500*s3*s5**3*s6**2 + 96*s4**6*s6
+- 56*s4**5*s5**2 - 16416*s4**3*s6**3 - 37800*s4**2*s5**2*s6**2 + 22500*s4*s5**4*s6
+- 3125*s5**6 - 93312*s6**5),
+        lambda s1, s2, s3, s4, s5, s6: (-9375*s1**7*s5*s6**4 + 3125*s1**6*s2*s4*s6**4 + 7500*s1**6*s2*s5**2*s6**3 + 3125*s1**6*s3**2*s6**4
+- 1250*s1**6*s3*s4*s5*s6**3 - 2000*s1**6*s3*s5**3*s6**2 + 3250*s1**6*s4**2*s5**2*s6**2
+- 1600*s1**6*s4*s5**4*s6 + 256*s1**6*s5**6 + 40625*s1**6*s6**5 - 3125*s1**5*s2**2*s3*s6**4
+- 3500*s1**5*s2**2*s4*s5*s6**3 - 1450*s1**5*s2**2*s5**3*s6**2 - 1750*s1**5*s2*s3**2*s5*s6**3
++ 625*s1**5*s2*s3*s4**2*s6**3 - 850*s1**5*s2*s3*s4*s5**2*s6**2 + 1760*s1**5*s2*s3*s5**4*s6
+- 2050*s1**5*s2*s4**3*s5*s6**2 + 780*s1**5*s2*s4**2*s5**3*s6 - 192*s1**5*s2*s4*s5**5
++ 35000*s1**5*s2*s5*s6**4 + 1200*s1**5*s3**3*s5**2*s6**2 - 725*s1**5*s3**2*s4**2*s5*s6**2
+- 160*s1**5*s3**2*s4*s5**3*s6 - 192*s1**5*s3**2*s5**5 - 125*s1**5*s3*s4**4*s6**2 +
+590*s1**5*s3*s4**3*s5**2*s6 - 16*s1**5*s3*s4**2*s5**4 - 20625*s1**5*s3*s4*s6**4 +
+17250*s1**5*s3*s5**2*s6**3 - 124*s1**5*s4**5*s5*s6 + 17*s1**5*s4**4*s5**3 - 20250*s1**5*s4**2*s5*s6**3
++ 1900*s1**5*s4*s5**3*s6**2 + 1344*s1**5*s5**5*s6 + 625*s1**4*s2**4*s6**4 + 2300*s1**4*s2**3*s3*s5*s6**3
++ 250*s1**4*s2**3*s4**2*s6**3 + 1470*s1**4*s2**3*s4*s5**2*s6**2 - 276*s1**4*s2**3*s5**4*s6
+- 125*s1**4*s2**2*s3**2*s4*s6**3 - 610*s1**4*s2**2*s3**2*s5**2*s6**2 + 1995*s1**4*s2**2*s3*s4**2*s5*s6**2
+- 1174*s1**4*s2**2*s3*s4*s5**3*s6 - 16*s1**4*s2**2*s3*s5**5 + 375*s1**4*s2**2*s4**4*s6**2
+- 172*s1**4*s2**2*s4**3*s5**2*s6 + 82*s1**4*s2**2*s4**2*s5**4 - 7750*s1**4*s2**2*s4*s6**4
+- 46650*s1**4*s2**2*s5**2*s6**3 + 15*s1**4*s2*s3**3*s4*s5*s6**2 - 384*s1**4*s2*s3**3*s5**3*s6
++ 525*s1**4*s2*s3**2*s4**3*s6**2 - 528*s1**4*s2*s3**2*s4**2*s5**2*s6 + 384*s1**4*s2*s3**2*s4*s5**4
+- 10125*s1**4*s2*s3**2*s6**4 - 29*s1**4*s2*s3*s4**4*s5*s6 - 118*s1**4*s2*s3*s4**3*s5**3
++ 36700*s1**4*s2*s3*s4*s5*s6**3 + 2410*s1**4*s2*s3*s5**3*s6**2 + 38*s1**4*s2*s4**6*s6
++ 5*s1**4*s2*s4**5*s5**2 + 5550*s1**4*s2*s4**3*s6**3 - 10040*s1**4*s2*s4**2*s5**2*s6**2
++ 5800*s1**4*s2*s4*s5**4*s6 - 1600*s1**4*s2*s5**6 - 292500*s1**4*s2*s6**5 - 99*s1**4*s3**5*s5*s6**2
+- 150*s1**4*s3**4*s4**2*s6**2 + 196*s1**4*s3**4*s4*s5**2*s6 + 48*s1**4*s3**4*s5**4
++ 12*s1**4*s3**3*s4**3*s5*s6 - 128*s1**4*s3**3*s4**2*s5**3 - 6525*s1**4*s3**3*s5*s6**3
+- 12*s1**4*s3**2*s4**5*s6 + 65*s1**4*s3**2*s4**4*s5**2 + 225*s1**4*s3**2*s4**2*s6**3
++ 80*s1**4*s3**2*s4*s5**2*s6**2 - 13*s1**4*s3*s4**6*s5 + 5145*s1**4*s3*s4**3*s5*s6**2
+- 6746*s1**4*s3*s4**2*s5**3*s6 + 1760*s1**4*s3*s4*s5**5 - 103500*s1**4*s3*s5*s6**4
++ s1**4*s4**8 + 954*s1**4*s4**5*s6**2 + 449*s1**4*s4**4*s5**2*s6 - 276*s1**4*s4**3*s5**4
++ 70125*s1**4*s4**2*s6**4 + 58900*s1**4*s4*s5**2*s6**3 - 23310*s1**4*s5**4*s6**2 -
+468*s1**3*s2**5*s5*s6**3 - 200*s1**3*s2**4*s3*s4*s6**3 - 294*s1**3*s2**4*s3*s5**2*s6**2
+- 676*s1**3*s2**4*s4**2*s5*s6**2 + 180*s1**3*s2**4*s4*s5**3*s6 + 17*s1**3*s2**4*s5**5
++ 50*s1**3*s2**3*s3**3*s6**3 - 397*s1**3*s2**3*s3**2*s4*s5*s6**2 + 514*s1**3*s2**3*s3**2*s5**3*s6
+- 700*s1**3*s2**3*s3*s4**3*s6**2 + 447*s1**3*s2**3*s3*s4**2*s5**2*s6 - 118*s1**3*s2**3*s3*s4*s5**4
++ 11700*s1**3*s2**3*s3*s6**4 - 12*s1**3*s2**3*s4**4*s5*s6 + 6*s1**3*s2**3*s4**3*s5**3
++ 10360*s1**3*s2**3*s4*s5*s6**3 + 11404*s1**3*s2**3*s5**3*s6**2 + 141*s1**3*s2**2*s3**4*s5*s6**2
+- 185*s1**3*s2**2*s3**3*s4**2*s6**2 + 168*s1**3*s2**2*s3**3*s4*s5**2*s6 - 128*s1**3*s2**2*s3**3*s5**4
++ 93*s1**3*s2**2*s3**2*s4**3*s5*s6 + 19*s1**3*s2**2*s3**2*s4**2*s5**3 + 5895*s1**3*s2**2*s3**2*s5*s6**3
+- 36*s1**3*s2**2*s3*s4**5*s6 + 5*s1**3*s2**2*s3*s4**4*s5**2 - 12020*s1**3*s2**2*s3*s4**2*s6**3
+- 5698*s1**3*s2**2*s3*s4*s5**2*s6**2 - 6746*s1**3*s2**2*s3*s5**4*s6 + 5064*s1**3*s2**2*s4**3*s5*s6**2
+- 762*s1**3*s2**2*s4**2*s5**3*s6 + 780*s1**3*s2**2*s4*s5**5 + 93900*s1**3*s2**2*s5*s6**4
++ 198*s1**3*s2*s3**5*s4*s6**2 - 78*s1**3*s2*s3**5*s5**2*s6 - 95*s1**3*s2*s3**4*s4**2*s5*s6
++ 44*s1**3*s2*s3**4*s4*s5**3 + 25*s1**3*s2*s3**3*s4**4*s6 - 15*s1**3*s2*s3**3*s4**3*s5**2
++ 1935*s1**3*s2*s3**3*s4*s6**3 - 2808*s1**3*s2*s3**3*s5**2*s6**2 + s1**3*s2*s3**2*s4**5*s5
+- 4844*s1**3*s2*s3**2*s4**2*s5*s6**2 + 8996*s1**3*s2*s3**2*s4*s5**3*s6 - 160*s1**3*s2*s3**2*s5**5
+- 3616*s1**3*s2*s3*s4**4*s6**2 + 500*s1**3*s2*s3*s4**3*s5**2*s6 - 1174*s1**3*s2*s3*s4**2*s5**4
++ 72900*s1**3*s2*s3*s4*s6**4 - 55665*s1**3*s2*s3*s5**2*s6**3 + 128*s1**3*s2*s4**5*s5*s6
++ 180*s1**3*s2*s4**4*s5**3 + 16240*s1**3*s2*s4**2*s5*s6**3 - 9330*s1**3*s2*s4*s5**3*s6**2
++ 1900*s1**3*s2*s5**5*s6 - 27*s1**3*s3**7*s6**2 + 18*s1**3*s3**6*s4*s5*s6 - 4*s1**3*s3**6*s5**3
+- 4*s1**3*s3**5*s4**3*s6 + s1**3*s3**5*s4**2*s5**2 + 54*s1**3*s3**5*s6**3 + 1143*s1**3*s3**4*s4*s5*s6**2
+- 820*s1**3*s3**4*s5**3*s6 + 923*s1**3*s3**3*s4**3*s6**2 + 57*s1**3*s3**3*s4**2*s5**2*s6
+- 384*s1**3*s3**3*s4*s5**4 + 29700*s1**3*s3**3*s6**4 - 547*s1**3*s3**2*s4**4*s5*s6
++ 514*s1**3*s3**2*s4**3*s5**3 - 10305*s1**3*s3**2*s4*s5*s6**3 - 7405*s1**3*s3**2*s5**3*s6**2
++ 108*s1**3*s3*s4**6*s6 - 148*s1**3*s3*s4**5*s5**2 - 11360*s1**3*s3*s4**3*s6**3 +
+22209*s1**3*s3*s4**2*s5**2*s6**2 + 2410*s1**3*s3*s4*s5**4*s6 - 2000*s1**3*s3*s5**6
++ 432000*s1**3*s3*s6**5 + 12*s1**3*s4**7*s5 - 22624*s1**3*s4**4*s5*s6**2 + 11404*s1**3*s4**3*s5**3*s6
+- 1450*s1**3*s4**2*s5**5 - 242100*s1**3*s4*s5*s6**4 + 58430*s1**3*s5**3*s6**3 + 56*s1**2*s2**6*s4*s6**3
++ 86*s1**2*s2**6*s5**2*s6**2 - 14*s1**2*s2**5*s3**2*s6**3 + 304*s1**2*s2**5*s3*s4*s5*s6**2
+- 148*s1**2*s2**5*s3*s5**3*s6 + 152*s1**2*s2**5*s4**3*s6**2 - 54*s1**2*s2**5*s4**2*s5**2*s6
++ 5*s1**2*s2**5*s4*s5**4 - 2472*s1**2*s2**5*s6**4 - 76*s1**2*s2**4*s3**3*s5*s6**2
++ 370*s1**2*s2**4*s3**2*s4**2*s6**2 - 287*s1**2*s2**4*s3**2*s4*s5**2*s6 + 65*s1**2*s2**4*s3**2*s5**4
+- 28*s1**2*s2**4*s3*s4**3*s5*s6 + 5*s1**2*s2**4*s3*s4**2*s5**3 - 8092*s1**2*s2**4*s3*s5*s6**3
++ 8*s1**2*s2**4*s4**5*s6 - 2*s1**2*s2**4*s4**4*s5**2 + 1096*s1**2*s2**4*s4**2*s6**3
+- 5144*s1**2*s2**4*s4*s5**2*s6**2 + 449*s1**2*s2**4*s5**4*s6 - 210*s1**2*s2**3*s3**4*s4*s6**2
++ 76*s1**2*s2**3*s3**4*s5**2*s6 + 43*s1**2*s2**3*s3**3*s4**2*s5*s6 - 15*s1**2*s2**3*s3**3*s4*s5**3
+- 6*s1**2*s2**3*s3**2*s4**4*s6 + 2*s1**2*s2**3*s3**2*s4**3*s5**2 + 1962*s1**2*s2**3*s3**2*s4*s6**3
++ 3181*s1**2*s2**3*s3**2*s5**2*s6**2 + 1684*s1**2*s2**3*s3*s4**2*s5*s6**2 + 500*s1**2*s2**3*s3*s4*s5**3*s6
++ 590*s1**2*s2**3*s3*s5**5 - 168*s1**2*s2**3*s4**4*s6**2 - 494*s1**2*s2**3*s4**3*s5**2*s6
+- 172*s1**2*s2**3*s4**2*s5**4 - 22080*s1**2*s2**3*s4*s6**4 + 58894*s1**2*s2**3*s5**2*s6**3
++ 27*s1**2*s2**2*s3**6*s6**2 - 9*s1**2*s2**2*s3**5*s4*s5*s6 + s1**2*s2**2*s3**5*s5**3
++ s1**2*s2**2*s3**4*s4**3*s6 - 486*s1**2*s2**2*s3**4*s6**3 + 1071*s1**2*s2**2*s3**3*s4*s5*s6**2
++ 57*s1**2*s2**2*s3**3*s5**3*s6 + 2262*s1**2*s2**2*s3**2*s4**3*s6**2 - 2742*s1**2*s2**2*s3**2*s4**2*s5**2*s6
+- 528*s1**2*s2**2*s3**2*s4*s5**4 - 29160*s1**2*s2**2*s3**2*s6**4 + 772*s1**2*s2**2*s3*s4**4*s5*s6
++ 447*s1**2*s2**2*s3*s4**3*s5**3 - 96732*s1**2*s2**2*s3*s4*s5*s6**3 + 22209*s1**2*s2**2*s3*s5**3*s6**2
+- 160*s1**2*s2**2*s4**6*s6 - 54*s1**2*s2**2*s4**5*s5**2 - 7992*s1**2*s2**2*s4**3*s6**3
++ 8634*s1**2*s2**2*s4**2*s5**2*s6**2 - 10040*s1**2*s2**2*s4*s5**4*s6 + 3250*s1**2*s2**2*s5**6
++ 529200*s1**2*s2**2*s6**5 - 351*s1**2*s2*s3**5*s5*s6**2 - 1215*s1**2*s2*s3**4*s4**2*s6**2
+- 360*s1**2*s2*s3**4*s4*s5**2*s6 + 196*s1**2*s2*s3**4*s5**4 + 741*s1**2*s2*s3**3*s4**3*s5*s6
++ 168*s1**2*s2*s3**3*s4**2*s5**3 + 11718*s1**2*s2*s3**3*s5*s6**3 - 106*s1**2*s2*s3**2*s4**5*s6
+- 287*s1**2*s2*s3**2*s4**4*s5**2 + 22572*s1**2*s2*s3**2*s4**2*s6**3 - 8892*s1**2*s2*s3**2*s4*s5**2*s6**2
++ 80*s1**2*s2*s3**2*s5**4*s6 + 88*s1**2*s2*s3*s4**6*s5 + 22144*s1**2*s2*s3*s4**3*s5*s6**2
+- 5698*s1**2*s2*s3*s4**2*s5**3*s6 - 850*s1**2*s2*s3*s4*s5**5 + 169560*s1**2*s2*s3*s5*s6**4
+- 8*s1**2*s2*s4**8 + 3032*s1**2*s2*s4**5*s6**2 - 5144*s1**2*s2*s4**4*s5**2*s6 + 1470*s1**2*s2*s4**3*s5**4
+- 249480*s1**2*s2*s4**2*s6**4 - 105390*s1**2*s2*s4*s5**2*s6**3 + 58900*s1**2*s2*s5**4*s6**2
++ 162*s1**2*s3**6*s4*s6**2 + 216*s1**2*s3**6*s5**2*s6 - 216*s1**2*s3**5*s4**2*s5*s6
+- 78*s1**2*s3**5*s4*s5**3 + 36*s1**2*s3**4*s4**4*s6 + 76*s1**2*s3**4*s4**3*s5**2 -
+3564*s1**2*s3**4*s4*s6**3 + 8802*s1**2*s3**4*s5**2*s6**2 - 22*s1**2*s3**3*s4**5*s5
+- 11475*s1**2*s3**3*s4**2*s5*s6**2 - 2808*s1**2*s3**3*s4*s5**3*s6 + 1200*s1**2*s3**3*s5**5
++ 2*s1**2*s3**2*s4**7 + 222*s1**2*s3**2*s4**4*s6**2 + 3181*s1**2*s3**2*s4**3*s5**2*s6
+- 610*s1**2*s3**2*s4**2*s5**4 - 165240*s1**2*s3**2*s4*s6**4 + 118260*s1**2*s3**2*s5**2*s6**3
++ 572*s1**2*s3*s4**5*s5*s6 - 294*s1**2*s3*s4**4*s5**3 - 32616*s1**2*s3*s4**2*s5*s6**3
+- 55665*s1**2*s3*s4*s5**3*s6**2 + 17250*s1**2*s3*s5**5*s6 - 232*s1**2*s4**7*s6 + 86*s1**2*s4**6*s5**2
++ 48408*s1**2*s4**4*s6**3 + 58894*s1**2*s4**3*s5**2*s6**2 - 46650*s1**2*s4**2*s5**4*s6
++ 7500*s1**2*s4*s5**6 - 129600*s1**2*s4*s6**5 + 41040*s1**2*s5**2*s6**4 - 48*s1*s2**7*s4*s5*s6**2
++ 12*s1*s2**7*s5**3*s6 + 12*s1*s2**6*s3**2*s5*s6**2 - 144*s1*s2**6*s3*s4**2*s6**2
++ 88*s1*s2**6*s3*s4*s5**2*s6 - 13*s1*s2**6*s3*s5**4 + 1680*s1*s2**6*s5*s6**3 + 72*s1*s2**5*s3**3*s4*s6**2
+- 22*s1*s2**5*s3**3*s5**2*s6 - 4*s1*s2**5*s3**2*s4**2*s5*s6 + s1*s2**5*s3**2*s4*s5**3
+- 144*s1*s2**5*s3*s4*s6**3 + 572*s1*s2**5*s3*s5**2*s6**2 + 736*s1*s2**5*s4**2*s5*s6**2
++ 128*s1*s2**5*s4*s5**3*s6 - 124*s1*s2**5*s5**5 - 9*s1*s2**4*s3**5*s6**2 + s1*s2**4*s3**4*s4*s5*s6
++ 36*s1*s2**4*s3**3*s6**3 - 2028*s1*s2**4*s3**2*s4*s5*s6**2 - 547*s1*s2**4*s3**2*s5**3*s6
+- 480*s1*s2**4*s3*s4**3*s6**2 + 772*s1*s2**4*s3*s4**2*s5**2*s6 - 29*s1*s2**4*s3*s4*s5**4
++ 6336*s1*s2**4*s3*s6**4 - 12*s1*s2**4*s4**3*s5**3 + 4368*s1*s2**4*s4*s5*s6**3 - 22624*s1*s2**4*s5**3*s6**2
++ 441*s1*s2**3*s3**4*s5*s6**2 + 336*s1*s2**3*s3**3*s4**2*s6**2 + 741*s1*s2**3*s3**3*s4*s5**2*s6
++ 12*s1*s2**3*s3**3*s5**4 - 868*s1*s2**3*s3**2*s4**3*s5*s6 + 93*s1*s2**3*s3**2*s4**2*s5**3
++ 11016*s1*s2**3*s3**2*s5*s6**3 + 176*s1*s2**3*s3*s4**5*s6 - 28*s1*s2**3*s3*s4**4*s5**2
++ 14784*s1*s2**3*s3*s4**2*s6**3 + 22144*s1*s2**3*s3*s4*s5**2*s6**2 + 5145*s1*s2**3*s3*s5**4*s6
+- 11344*s1*s2**3*s4**3*s5*s6**2 + 5064*s1*s2**3*s4**2*s5**3*s6 - 2050*s1*s2**3*s4*s5**5
+- 346896*s1*s2**3*s5*s6**4 - 54*s1*s2**2*s3**5*s4*s6**2 - 216*s1*s2**2*s3**5*s5**2*s6
++ 324*s1*s2**2*s3**4*s4**2*s5*s6 - 95*s1*s2**2*s3**4*s4*s5**3 - 80*s1*s2**2*s3**3*s4**4*s6
++ 43*s1*s2**2*s3**3*s4**3*s5**2 - 12204*s1*s2**2*s3**3*s4*s6**3 - 11475*s1*s2**2*s3**3*s5**2*s6**2
+- 4*s1*s2**2*s3**2*s4**5*s5 - 3888*s1*s2**2*s3**2*s4**2*s5*s6**2 - 4844*s1*s2**2*s3**2*s4*s5**3*s6
+- 725*s1*s2**2*s3**2*s5**5 - 1312*s1*s2**2*s3*s4**4*s6**2 + 1684*s1*s2**2*s3*s4**3*s5**2*s6
++ 1995*s1*s2**2*s3*s4**2*s5**4 + 139104*s1*s2**2*s3*s4*s6**4 - 32616*s1*s2**2*s3*s5**2*s6**3
++ 736*s1*s2**2*s4**5*s5*s6 - 676*s1*s2**2*s4**4*s5**3 + 131040*s1*s2**2*s4**2*s5*s6**3
++ 16240*s1*s2**2*s4*s5**3*s6**2 - 20250*s1*s2**2*s5**5*s6 - 27*s1*s2*s3**6*s4*s5*s6
++ 18*s1*s2*s3**6*s5**3 + 9*s1*s2*s3**5*s4**3*s6 - 9*s1*s2*s3**5*s4**2*s5**2 + 1944*s1*s2*s3**5*s6**3
++ s1*s2*s3**4*s4**4*s5 + 6156*s1*s2*s3**4*s4*s5*s6**2 + 1143*s1*s2*s3**4*s5**3*s6
++ 324*s1*s2*s3**3*s4**3*s6**2 + 1071*s1*s2*s3**3*s4**2*s5**2*s6 + 15*s1*s2*s3**3*s4*s5**4
+- 7776*s1*s2*s3**3*s6**4 - 2028*s1*s2*s3**2*s4**4*s5*s6 - 397*s1*s2*s3**2*s4**3*s5**3
++ 112860*s1*s2*s3**2*s4*s5*s6**3 - 10305*s1*s2*s3**2*s5**3*s6**2 + 336*s1*s2*s3*s4**6*s6
++ 304*s1*s2*s3*s4**5*s5**2 - 68976*s1*s2*s3*s4**3*s6**3 - 96732*s1*s2*s3*s4**2*s5**2*s6**2
++ 36700*s1*s2*s3*s4*s5**4*s6 - 1250*s1*s2*s3*s5**6 - 1477440*s1*s2*s3*s6**5 - 48*s1*s2*s4**7*s5
++ 4368*s1*s2*s4**4*s5*s6**2 + 10360*s1*s2*s4**3*s5**3*s6 - 3500*s1*s2*s4**2*s5**5
++ 935280*s1*s2*s4*s5*s6**4 - 242100*s1*s2*s5**3*s6**3 - 972*s1*s3**6*s5*s6**2 - 351*s1*s3**5*s4*s5**2*s6
+- 99*s1*s3**5*s5**4 + 441*s1*s3**4*s4**3*s5*s6 + 141*s1*s3**4*s4**2*s5**3 - 36936*s1*s3**4*s5*s6**3
+- 84*s1*s3**3*s4**5*s6 - 76*s1*s3**3*s4**4*s5**2 + 17496*s1*s3**3*s4**2*s6**3 + 11718*s1*s3**3*s4*s5**2*s6**2
+- 6525*s1*s3**3*s5**4*s6 + 12*s1*s3**2*s4**6*s5 + 11016*s1*s3**2*s4**3*s5*s6**2 +
+5895*s1*s3**2*s4**2*s5**3*s6 - 1750*s1*s3**2*s4*s5**5 - 252720*s1*s3**2*s5*s6**4 -
+2544*s1*s3*s4**5*s6**2 - 8092*s1*s3*s4**4*s5**2*s6 + 2300*s1*s3*s4**3*s5**4 + 536544*s1*s3*s4**2*s6**4
++ 169560*s1*s3*s4*s5**2*s6**3 - 103500*s1*s3*s5**4*s6**2 + 1680*s1*s4**6*s5*s6 - 468*s1*s4**5*s5**3
+- 346896*s1*s4**3*s5*s6**3 + 93900*s1*s4**2*s5**3*s6**2 + 35000*s1*s4*s5**5*s6 - 9375*s1*s5**7
++ 108864*s1*s5*s6**5 + 16*s2**8*s4**2*s6**2 - 8*s2**8*s4*s5**2*s6 + s2**8*s5**4 -
+8*s2**7*s3**2*s4*s6**2 + 2*s2**7*s3**2*s5**2*s6 - 96*s2**7*s4*s6**3 - 232*s2**7*s5**2*s6**2
++ s2**6*s3**4*s6**2 + 24*s2**6*s3**2*s6**3 + 336*s2**6*s3*s4*s5*s6**2 + 108*s2**6*s3*s5**3*s6
+- 32*s2**6*s4**3*s6**2 - 160*s2**6*s4**2*s5**2*s6 + 38*s2**6*s4*s5**4 + 144*s2**6*s6**4
+- 84*s2**5*s3**3*s5*s6**2 + 8*s2**5*s3**2*s4**2*s6**2 - 106*s2**5*s3**2*s4*s5**2*s6
+- 12*s2**5*s3**2*s5**4 + 176*s2**5*s3*s4**3*s5*s6 - 36*s2**5*s3*s4**2*s5**3 - 2544*s2**5*s3*s5*s6**3
+- 32*s2**5*s4**5*s6 + 8*s2**5*s4**4*s5**2 - 3072*s2**5*s4**2*s6**3 + 3032*s2**5*s4*s5**2*s6**2
++ 954*s2**5*s5**4*s6 + 36*s2**4*s3**4*s5**2*s6 - 80*s2**4*s3**3*s4**2*s5*s6 + 25*s2**4*s3**3*s4*s5**3
++ 16*s2**4*s3**2*s4**4*s6 - 6*s2**4*s3**2*s4**3*s5**2 + 2520*s2**4*s3**2*s4*s6**3
++ 222*s2**4*s3**2*s5**2*s6**2 - 1312*s2**4*s3*s4**2*s5*s6**2 - 3616*s2**4*s3*s4*s5**3*s6
+- 125*s2**4*s3*s5**5 + 1296*s2**4*s4**4*s6**2 - 168*s2**4*s4**3*s5**2*s6 + 375*s2**4*s4**2*s5**4
++ 19296*s2**4*s4*s6**4 + 48408*s2**4*s5**2*s6**3 + 9*s2**3*s3**5*s4*s5*s6 - 4*s2**3*s3**5*s5**3
+- 2*s2**3*s3**4*s4**3*s6 + s2**3*s3**4*s4**2*s5**2 - 432*s2**3*s3**4*s6**3 + 324*s2**3*s3**3*s4*s5*s6**2
++ 923*s2**3*s3**3*s5**3*s6 - 752*s2**3*s3**2*s4**3*s6**2 + 2262*s2**3*s3**2*s4**2*s5**2*s6
++ 525*s2**3*s3**2*s4*s5**4 - 9936*s2**3*s3**2*s6**4 - 480*s2**3*s3*s4**4*s5*s6 - 700*s2**3*s3*s4**3*s5**3
+- 68976*s2**3*s3*s4*s5*s6**3 - 11360*s2**3*s3*s5**3*s6**2 - 32*s2**3*s4**6*s6 + 152*s2**3*s4**5*s5**2
++ 6912*s2**3*s4**3*s6**3 - 7992*s2**3*s4**2*s5**2*s6**2 + 5550*s2**3*s4*s5**4*s6 -
+29376*s2**3*s6**5 + 108*s2**2*s3**4*s4**2*s6**2 - 1215*s2**2*s3**4*s4*s5**2*s6 - 150*s2**2*s3**4*s5**4
++ 336*s2**2*s3**3*s4**3*s5*s6 - 185*s2**2*s3**3*s4**2*s5**3 + 17496*s2**2*s3**3*s5*s6**3
++ 8*s2**2*s3**2*s4**5*s6 + 370*s2**2*s3**2*s4**4*s5**2 - 864*s2**2*s3**2*s4**2*s6**3
++ 22572*s2**2*s3**2*s4*s5**2*s6**2 + 225*s2**2*s3**2*s5**4*s6 - 144*s2**2*s3*s4**6*s5
++ 14784*s2**2*s3*s4**3*s5*s6**2 - 12020*s2**2*s3*s4**2*s5**3*s6 + 625*s2**2*s3*s4*s5**5
++ 536544*s2**2*s3*s5*s6**4 + 16*s2**2*s4**8 - 3072*s2**2*s4**5*s6**2 + 1096*s2**2*s4**4*s5**2*s6
++ 250*s2**2*s4**3*s5**4 - 93744*s2**2*s4**2*s6**4 - 249480*s2**2*s4*s5**2*s6**3 +
+70125*s2**2*s5**4*s6**2 + 162*s2*s3**6*s5**2*s6 - 54*s2*s3**5*s4**2*s5*s6 + 198*s2*s3**5*s4*s5**3
+- 210*s2*s3**4*s4**3*s5**2 - 3564*s2*s3**4*s5**2*s6**2 + 72*s2*s3**3*s4**5*s5 - 12204*s2*s3**3*s4**2*s5*s6**2
++ 1935*s2*s3**3*s4*s5**3*s6 - 8*s2*s3**2*s4**7 + 2520*s2*s3**2*s4**4*s6**2 + 1962*s2*s3**2*s4**3*s5**2*s6
+- 125*s2*s3**2*s4**2*s5**4 - 178848*s2*s3**2*s4*s6**4 - 165240*s2*s3**2*s5**2*s6**3
+- 144*s2*s3*s4**5*s5*s6 - 200*s2*s3*s4**4*s5**3 + 139104*s2*s3*s4**2*s5*s6**3 + 72900*s2*s3*s4*s5**3*s6**2
+- 20625*s2*s3*s5**5*s6 - 96*s2*s4**7*s6 + 56*s2*s4**6*s5**2 + 19296*s2*s4**4*s6**3
+- 22080*s2*s4**3*s5**2*s6**2 - 7750*s2*s4**2*s5**4*s6 + 3125*s2*s4*s5**6 + 248832*s2*s4*s6**5
+- 129600*s2*s5**2*s6**4 - 27*s3**7*s5**3 + 27*s3**6*s4**2*s5**2 - 9*s3**5*s4**4*s5
++ 1944*s3**5*s4*s5*s6**2 + 54*s3**5*s5**3*s6 + s3**4*s4**6 - 432*s3**4*s4**3*s6**2
+- 486*s3**4*s4**2*s5**2*s6 + 46656*s3**4*s6**4 + 36*s3**3*s4**4*s5*s6 + 50*s3**3*s4**3*s5**3
+- 7776*s3**3*s4*s5*s6**3 + 29700*s3**3*s5**3*s6**2 + 24*s3**2*s4**6*s6 - 14*s3**2*s4**5*s5**2
+- 9936*s3**2*s4**3*s6**3 - 29160*s3**2*s4**2*s5**2*s6**2 - 10125*s3**2*s4*s5**4*s6
++ 3125*s3**2*s5**6 + 1026432*s3**2*s6**5 + 6336*s3*s4**4*s5*s6**2 + 11700*s3*s4**3*s5**3*s6
+- 3125*s3*s4**2*s5**5 - 1477440*s3*s4*s5*s6**4 + 432000*s3*s5**3*s6**3 + 144*s4**6*s6**2
+- 2472*s4**5*s5**2*s6 + 625*s4**4*s5**4 - 29376*s4**3*s6**4 + 529200*s4**2*s5**2*s6**3
+- 292500*s4*s5**4*s6**2 + 40625*s5**6*s6 - 186624*s6**6)
+    ],
+    (6, 2): [
+        lambda s1, s2, s3, s4, s5, s6: (-s3),
+        lambda s1, s2, s3, s4, s5, s6: (-s1*s5 + s2*s4 - 9*s6),
+        lambda s1, s2, s3, s4, s5, s6: (s1*s2*s6 + 2*s1*s3*s5 - s1*s4**2 - s2**2*s5 + 6*s3*s6 + s4*s5),
+        lambda s1, s2, s3, s4, s5, s6: (s1**2*s4*s6 - s1**2*s5**2 - 3*s1*s2*s3*s6 + s1*s2*s4*s5 + 9*s1*s5*s6 + s2**3*s6 -
+9*s2*s4*s6 + s2*s5**2 + 3*s3**2*s6 - 3*s3*s4*s5 + s4**3 + 27*s6**2),
+        lambda s1, s2, s3, s4, s5, s6: (-2*s1**3*s6**2 + 2*s1**2*s2*s5*s6 + 2*s1**2*s3*s4*s6 - s1**2*s3*s5**2 - s1*s2**2*s4*s6
+- 3*s1*s2*s6**2 - 16*s1*s3*s5*s6 + 4*s1*s4**2*s6 + 2*s1*s4*s5**2 + 4*s2**2*s5*s6 +
+s2*s3*s4*s6 + 2*s2*s3*s5**2 - s2*s4**2*s5 - 9*s3*s6**2 - 3*s4*s5*s6 - 2*s5**3),
+        lambda s1, s2, s3, s4, s5, s6: (s1**3*s3*s6**2 - 3*s1**3*s4*s5*s6 + s1**3*s5**3 - s1**2*s2**2*s6**2 + s1**2*s2*s3*s5*s6
+- 2*s1**2*s4*s6**2 + 6*s1**2*s5**2*s6 + 16*s1*s2*s3*s6**2 - 3*s1*s2*s5**3 - s1*s3**2*s5*s6
+- 2*s1*s3*s4**2*s6 + s1*s3*s4*s5**2 - 30*s1*s5*s6**2 - 4*s2**3*s6**2 - 2*s2**2*s3*s5*s6
++ s2**2*s4**2*s6 + 18*s2*s4*s6**2 - 2*s2*s5**2*s6 - 15*s3**2*s6**2 + 16*s3*s4*s5*s6
++ s3*s5**3 - 4*s4**3*s6 - s4**2*s5**2 - 27*s6**3),
+        lambda s1, s2, s3, s4, s5, s6: (s1**4*s5*s6**2 + 2*s1**3*s2*s4*s6**2 - s1**3*s2*s5**2*s6 - s1**3*s3**2*s6**2 + 9*s1**3*s6**3
+- 14*s1**2*s2*s5*s6**2 - 11*s1**2*s3*s4*s6**2 + 6*s1**2*s3*s5**2*s6 + 3*s1**2*s4**2*s5*s6
+- s1**2*s4*s5**3 + 3*s1*s2**2*s5**2*s6 + 3*s1*s2*s3**2*s6**2 - s1*s2*s3*s4*s5*s6 +
+39*s1*s3*s5*s6**2 - 14*s1*s4*s5**2*s6 + s1*s5**4 - 11*s2*s3*s5**2*s6 + 2*s2*s4*s5**3
+- 3*s3**3*s6**2 + 3*s3**2*s4*s5*s6 - s3**2*s5**3 + 9*s5**3*s6),
+        lambda s1, s2, s3, s4, s5, s6: (-s1**4*s2*s6**3 + s1**4*s3*s5*s6**2 - 4*s1**3*s3*s6**3 + 10*s1**3*s4*s5*s6**2 - 4*s1**3*s5**3*s6
++ 8*s1**2*s2**2*s6**3 - 8*s1**2*s2*s3*s5*s6**2 - 2*s1**2*s2*s4**2*s6**2 + s1**2*s2*s4*s5**2*s6
++ s1**2*s3**2*s4*s6**2 - 6*s1**2*s4*s6**3 - 7*s1**2*s5**2*s6**2 - 24*s1*s2*s3*s6**3
+- 4*s1*s2*s4*s5*s6**2 + 10*s1*s2*s5**3*s6 + 8*s1*s3**2*s5*s6**2 + 8*s1*s3*s4**2*s6**2
+- 8*s1*s3*s4*s5**2*s6 + s1*s3*s5**4 + 36*s1*s5*s6**3 + 8*s2**2*s3*s5*s6**2 - 2*s2**2*s4*s5**2*s6
+- 2*s2*s3**2*s4*s6**2 + s2*s3**2*s5**2*s6 - 6*s2*s5**2*s6**2 + 18*s3**2*s6**3 - 24*s3*s4*s5*s6**2
+- 4*s3*s5**3*s6 + 8*s4**2*s5**2*s6 - s4*s5**4),
+        lambda s1, s2, s3, s4, s5, s6: (-s1**5*s4*s6**3 - 2*s1**4*s5*s6**3 + 3*s1**3*s2*s5**2*s6**2 + 3*s1**3*s3**2*s6**3
+- s1**3*s3*s4*s5*s6**2 - 8*s1**3*s6**4 + 16*s1**2*s2*s5*s6**3 + 8*s1**2*s3*s4*s6**3
+- 6*s1**2*s3*s5**2*s6**2 - 8*s1**2*s4**2*s5*s6**2 + 3*s1**2*s4*s5**3*s6 - 8*s1*s2**2*s5**2*s6**2
+- 8*s1*s2*s3**2*s6**3 + 8*s1*s2*s3*s4*s5*s6**2 - s1*s2*s3*s5**3*s6 - s1*s3**3*s5*s6**2
+- 24*s1*s3*s5*s6**3 + 16*s1*s4*s5**2*s6**2 - 2*s1*s5**4*s6 + 8*s2*s3*s5**2*s6**2 -
+s2*s5**5 + 8*s3**3*s6**3 - 8*s3**2*s4*s5*s6**2 + 3*s3**2*s5**3*s6 - 8*s5**3*s6**2),
+        lambda s1, s2, s3, s4, s5, s6: (s1**6*s6**4 - 4*s1**4*s2*s6**4 - 2*s1**4*s3*s5*s6**3 + s1**4*s4**2*s6**3 + 8*s1**3*s3*s6**4
+- 4*s1**3*s4*s5*s6**3 + 2*s1**3*s5**3*s6**2 + 8*s1**2*s2*s3*s5*s6**3 - 2*s1**2*s2*s4*s5**2*s6**2
+- 2*s1**2*s3**2*s4*s6**3 + s1**2*s3**2*s5**2*s6**2 - 4*s1*s2*s5**3*s6**2 - 12*s1*s3**2*s5*s6**3
++ 8*s1*s3*s4*s5**2*s6**2 - 2*s1*s3*s5**4*s6 + s2**2*s5**4*s6 - 2*s2*s3**2*s5**2*s6**2
++ s3**4*s6**3 + 8*s3*s5**3*s6**2 - 4*s4*s5**4*s6 + s5**6)
+    ],
+}
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/subfield.py b/lib/python3.11/site-packages/sympy/polys/numberfields/subfield.py
new file mode 100644
index 0000000000000000000000000000000000000000..b959ddeb27a6bc5719dc4fc567bd20a3fd936798
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/subfield.py
@@ -0,0 +1,507 @@
+r"""
+Functions in ``polys.numberfields.subfield`` solve the "Subfield Problem" and
+allied problems, for algebraic number fields.
+
+Following Cohen (see [Cohen93]_ Section 4.5), we can define the main problem as
+follows:
+
+* **Subfield Problem:**
+
+  Given two number fields $\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$
+  via the minimal polynomials for their generators $\alpha$ and $\beta$, decide
+  whether one field is isomorphic to a subfield of the other.
+
+From a solution to this problem flow solutions to the following problems as
+well:
+
+* **Primitive Element Problem:**
+
+  Given several algebraic numbers
+  $\alpha_1, \ldots, \alpha_m$, compute a single algebraic number $\theta$
+  such that $\mathbb{Q}(\alpha_1, \ldots, \alpha_m) = \mathbb{Q}(\theta)$.
+
+* **Field Isomorphism Problem:**
+
+  Decide whether two number fields
+  $\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$ are isomorphic.
+
+* **Field Membership Problem:**
+
+  Given two algebraic numbers $\alpha$,
+  $\beta$, decide whether $\alpha \in \mathbb{Q}(\beta)$, and if so write
+  $\alpha = f(\beta)$ for some $f(x) \in \mathbb{Q}[x]$.
+"""
+
+from sympy.core.add import Add
+from sympy.core.numbers import AlgebraicNumber
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import sympify, _sympify
+from sympy.ntheory import sieve
+from sympy.polys.densetools import dup_eval
+from sympy.polys.domains import QQ
+from sympy.polys.numberfields.minpoly import _choose_factor, minimal_polynomial
+from sympy.polys.polyerrors import IsomorphismFailed
+from sympy.polys.polytools import Poly, PurePoly, factor_list
+from sympy.utilities import public
+
+from mpmath import MPContext
+
+
+def is_isomorphism_possible(a, b):
+    """Necessary but not sufficient test for isomorphism. """
+    n = a.minpoly.degree()
+    m = b.minpoly.degree()
+
+    if m % n != 0:
+        return False
+
+    if n == m:
+        return True
+
+    da = a.minpoly.discriminant()
+    db = b.minpoly.discriminant()
+
+    i, k, half = 1, m//n, db//2
+
+    while True:
+        p = sieve[i]
+        P = p**k
+
+        if P > half:
+            break
+
+        if ((da % p) % 2) and not (db % P):
+            return False
+
+        i += 1
+
+    return True
+
+
+def field_isomorphism_pslq(a, b):
+    """Construct field isomorphism using PSLQ algorithm. """
+    if not a.root.is_real or not b.root.is_real:
+        raise NotImplementedError("PSLQ doesn't support complex coefficients")
+
+    f = a.minpoly
+    g = b.minpoly.replace(f.gen)
+
+    n, m, prev = 100, b.minpoly.degree(), None
+    ctx = MPContext()
+
+    for i in range(1, 5):
+        A = a.root.evalf(n)
+        B = b.root.evalf(n)
+
+        basis = [1, B] + [ B**i for i in range(2, m) ] + [-A]
+
+        ctx.dps = n
+        coeffs = ctx.pslq(basis, maxcoeff=10**10, maxsteps=1000)
+
+        if coeffs is None:
+            # PSLQ can't find an integer linear combination. Give up.
+            break
+
+        if coeffs != prev:
+            prev = coeffs
+        else:
+            # Increasing precision didn't produce anything new. Give up.
+            break
+
+        # We have
+        #   c0 + c1*B + c2*B^2 + ... + cm-1*B^(m-1) - cm*A ~ 0.
+        # So bring cm*A to the other side, and divide through by cm,
+        # for an approximate representation of A as a polynomial in B.
+        # (We know cm != 0 since `b.minpoly` is irreducible.)
+        coeffs = [S(c)/coeffs[-1] for c in coeffs[:-1]]
+
+        # Throw away leading zeros.
+        while not coeffs[-1]:
+            coeffs.pop()
+
+        coeffs = list(reversed(coeffs))
+        h = Poly(coeffs, f.gen, domain='QQ')
+
+        # We only have A ~ h(B). We must check whether the relation is exact.
+        if f.compose(h).rem(g).is_zero:
+            # Now we know that h(b) is in fact equal to _some conjugate of_ a.
+            # But from the very precise approximation A ~ h(B) we can assume
+            # the conjugate is a itself.
+            return coeffs
+        else:
+            n *= 2
+
+    return None
+
+
+def field_isomorphism_factor(a, b):
+    """Construct field isomorphism via factorization. """
+    _, factors = factor_list(a.minpoly, extension=b)
+    for f, _ in factors:
+        if f.degree() == 1:
+            # Any linear factor f(x) represents some conjugate of a in QQ(b).
+            # We want to know whether this linear factor represents a itself.
+            # Let f = x - c
+            c = -f.rep.TC()
+            # Write c as polynomial in b
+            coeffs = c.to_sympy_list()
+            d, terms = len(coeffs) - 1, []
+            for i, coeff in enumerate(coeffs):
+                terms.append(coeff*b.root**(d - i))
+            r = Add(*terms)
+            # Check whether we got the number a
+            if a.minpoly.same_root(r, a):
+                return coeffs
+
+    # If none of the linear factors represented a in QQ(b), then in fact a is
+    # not an element of QQ(b).
+    return None
+
+
+@public
+def field_isomorphism(a, b, *, fast=True):
+    r"""
+    Find an embedding of one number field into another.
+
+    Explanation
+    ===========
+
+    This function looks for an isomorphism from $\mathbb{Q}(a)$ onto some
+    subfield of $\mathbb{Q}(b)$. Thus, it solves the Subfield Problem.
+
+    Examples
+    ========
+
+    >>> from sympy import sqrt, field_isomorphism, I
+    >>> print(field_isomorphism(3, sqrt(2)))  # doctest: +SKIP
+    [3]
+    >>> print(field_isomorphism( I*sqrt(3), I*sqrt(3)/2))  # doctest: +SKIP
+    [2, 0]
+
+    Parameters
+    ==========
+
+    a : :py:class:`~.Expr`
+        Any expression representing an algebraic number.
+    b : :py:class:`~.Expr`
+        Any expression representing an algebraic number.
+    fast : boolean, optional (default=True)
+        If ``True``, we first attempt a potentially faster way of computing the
+        isomorphism, falling back on a slower method if this fails. If
+        ``False``, we go directly to the slower method, which is guaranteed to
+        return a result.
+
+    Returns
+    =======
+
+    List of rational numbers, or None
+        If $\mathbb{Q}(a)$ is not isomorphic to some subfield of
+        $\mathbb{Q}(b)$, then return ``None``. Otherwise, return a list of
+        rational numbers representing an element of $\mathbb{Q}(b)$ to which
+        $a$ may be mapped, in order to define a monomorphism, i.e. an
+        isomorphism from $\mathbb{Q}(a)$ to some subfield of $\mathbb{Q}(b)$.
+        The elements of the list are the coefficients of falling powers of $b$.
+
+    """
+    a, b = sympify(a), sympify(b)
+
+    if not a.is_AlgebraicNumber:
+        a = AlgebraicNumber(a)
+
+    if not b.is_AlgebraicNumber:
+        b = AlgebraicNumber(b)
+
+    a = a.to_primitive_element()
+    b = b.to_primitive_element()
+
+    if a == b:
+        return a.coeffs()
+
+    n = a.minpoly.degree()
+    m = b.minpoly.degree()
+
+    if n == 1:
+        return [a.root]
+
+    if m % n != 0:
+        return None
+
+    if fast:
+        try:
+            result = field_isomorphism_pslq(a, b)
+
+            if result is not None:
+                return result
+        except NotImplementedError:
+            pass
+
+    return field_isomorphism_factor(a, b)
+
+
+def _switch_domain(g, K):
+    # An algebraic relation f(a, b) = 0 over Q can also be written
+    # g(b) = 0 where g is in Q(a)[x] and h(a) = 0 where h is in Q(b)[x].
+    # This function transforms g into h where Q(b) = K.
+    frep = g.rep.inject()
+    hrep = frep.eject(K, front=True)
+
+    return g.new(hrep, g.gens[0])
+
+
+def _linsolve(p):
+    # Compute root of linear polynomial.
+    c, d = p.rep.to_list()
+    return -d/c
+
+
+@public
+def primitive_element(extension, x=None, *, ex=False, polys=False):
+    r"""
+    Find a single generator for a number field given by several generators.
+
+    Explanation
+    ===========
+
+    The basic problem is this: Given several algebraic numbers
+    $\alpha_1, \alpha_2, \ldots, \alpha_n$, find a single algebraic number
+    $\theta$ such that
+    $\mathbb{Q}(\alpha_1, \alpha_2, \ldots, \alpha_n) = \mathbb{Q}(\theta)$.
+
+    This function actually guarantees that $\theta$ will be a linear
+    combination of the $\alpha_i$, with non-negative integer coefficients.
+
+    Furthermore, if desired, this function will tell you how to express each
+    $\alpha_i$ as a $\mathbb{Q}$-linear combination of the powers of $\theta$.
+
+    Examples
+    ========
+
+    >>> from sympy import primitive_element, sqrt, S, minpoly, simplify
+    >>> from sympy.abc import x
+    >>> f, lincomb, reps = primitive_element([sqrt(2), sqrt(3)], x, ex=True)
+
+    Then ``lincomb`` tells us the primitive element as a linear combination of
+    the given generators ``sqrt(2)`` and ``sqrt(3)``.
+
+    >>> print(lincomb)
+    [1, 1]
+
+    This means the primtiive element is $\sqrt{2} + \sqrt{3}$.
+    Meanwhile ``f`` is the minimal polynomial for this primitive element.
+
+    >>> print(f)
+    x**4 - 10*x**2 + 1
+    >>> print(minpoly(sqrt(2) + sqrt(3), x))
+    x**4 - 10*x**2 + 1
+
+    Finally, ``reps`` (which was returned only because we set keyword arg
+    ``ex=True``) tells us how to recover each of the generators $\sqrt{2}$ and
+    $\sqrt{3}$ as $\mathbb{Q}$-linear combinations of the powers of the
+    primitive element $\sqrt{2} + \sqrt{3}$.
+
+    >>> print([S(r) for r in reps[0]])
+    [1/2, 0, -9/2, 0]
+    >>> theta = sqrt(2) + sqrt(3)
+    >>> print(simplify(theta**3/2 - 9*theta/2))
+    sqrt(2)
+    >>> print([S(r) for r in reps[1]])
+    [-1/2, 0, 11/2, 0]
+    >>> print(simplify(-theta**3/2 + 11*theta/2))
+    sqrt(3)
+
+    Parameters
+    ==========
+
+    extension : list of :py:class:`~.Expr`
+        Each expression must represent an algebraic number $\alpha_i$.
+    x : :py:class:`~.Symbol`, optional (default=None)
+        The desired symbol to appear in the computed minimal polynomial for the
+        primitive element $\theta$. If ``None``, we use a dummy symbol.
+    ex : boolean, optional (default=False)
+        If and only if ``True``, compute the representation of each $\alpha_i$
+        as a $\mathbb{Q}$-linear combination over the powers of $\theta$.
+    polys : boolean, optional (default=False)
+        If ``True``, return the minimal polynomial as a :py:class:`~.Poly`.
+        Otherwise return it as an :py:class:`~.Expr`.
+
+    Returns
+    =======
+
+    Pair (f, coeffs) or triple (f, coeffs, reps), where:
+        ``f`` is the minimal polynomial for the primitive element.
+        ``coeffs`` gives the primitive element as a linear combination of the
+        given generators.
+        ``reps`` is present if and only if argument ``ex=True`` was passed,
+        and is a list of lists of rational numbers. Each list gives the
+        coefficients of falling powers of the primitive element, to recover
+        one of the original, given generators.
+
+    """
+    if not extension:
+        raise ValueError("Cannot compute primitive element for empty extension")
+    extension = [_sympify(ext) for ext in extension]
+
+    if x is not None:
+        x, cls = sympify(x), Poly
+    else:
+        x, cls = Dummy('x'), PurePoly
+
+    if not ex:
+        gen, coeffs = extension[0], [1]
+        g = minimal_polynomial(gen, x, polys=True)
+        for ext in extension[1:]:
+            if ext.is_Rational:
+                coeffs.append(0)
+                continue
+            _, factors = factor_list(g, extension=ext)
+            g = _choose_factor(factors, x, gen)
+            [s], _, g = g.sqf_norm()
+            gen += s*ext
+            coeffs.append(s)
+
+        if not polys:
+            return g.as_expr(), coeffs
+        else:
+            return cls(g), coeffs
+
+    gen, coeffs = extension[0], [1]
+    f = minimal_polynomial(gen, x, polys=True)
+    K = QQ.algebraic_field((f, gen))  # incrementally constructed field
+    reps = [K.unit]  # representations of extension elements in K
+    for ext in extension[1:]:
+        if ext.is_Rational:
+            coeffs.append(0)    # rational ext is not included in the expression of a primitive element
+            reps.append(K.convert(ext))    # but it is included in reps
+            continue
+        p = minimal_polynomial(ext, x, polys=True)
+        L = QQ.algebraic_field((p, ext))
+        _, factors = factor_list(f, domain=L)
+        f = _choose_factor(factors, x, gen)
+        [s], g, f = f.sqf_norm()
+        gen += s*ext
+        coeffs.append(s)
+        K = QQ.algebraic_field((f, gen))
+        h = _switch_domain(g, K)
+        erep = _linsolve(h.gcd(p))  # ext as element of K
+        ogen = K.unit - s*erep  # old gen as element of K
+        reps = [dup_eval(_.to_list(), ogen, K) for _ in reps] + [erep]
+
+    if K.ext.root.is_Rational:  # all extensions are rational
+        H = [K.convert(_).rep for _ in extension]
+        coeffs = [0]*len(extension)
+        f = cls(x, domain=QQ)
+    else:
+        H = [_.to_list() for _ in reps]
+    if not polys:
+        return f.as_expr(), coeffs, H
+    else:
+        return f, coeffs, H
+
+
+@public
+def to_number_field(extension, theta=None, *, gen=None, alias=None):
+    r"""
+    Express one algebraic number in the field generated by another.
+
+    Explanation
+    ===========
+
+    Given two algebraic numbers $\eta, \theta$, this function either expresses
+    $\eta$ as an element of $\mathbb{Q}(\theta)$, or else raises an exception
+    if $\eta \not\in \mathbb{Q}(\theta)$.
+
+    This function is essentially just a convenience, utilizing
+    :py:func:`~.field_isomorphism` (our solution of the Subfield Problem) to
+    solve this, the Field Membership Problem.
+
+    As an additional convenience, this function allows you to pass a list of
+    algebraic numbers $\alpha_1, \alpha_2, \ldots, \alpha_n$ instead of $\eta$.
+    It then computes $\eta$ for you, as a solution of the Primitive Element
+    Problem, using :py:func:`~.primitive_element` on the list of $\alpha_i$.
+
+    Examples
+    ========
+
+    >>> from sympy import sqrt, to_number_field
+    >>> eta = sqrt(2)
+    >>> theta = sqrt(2) + sqrt(3)
+    >>> a = to_number_field(eta, theta)
+    >>> print(type(a))
+    
+    >>> a.root
+    sqrt(2) + sqrt(3)
+    >>> print(a)
+    sqrt(2)
+    >>> a.coeffs()
+    [1/2, 0, -9/2, 0]
+
+    We get an :py:class:`~.AlgebraicNumber`, whose ``.root`` is $\theta$, whose
+    value is $\eta$, and whose ``.coeffs()`` show how to write $\eta$ as a
+    $\mathbb{Q}$-linear combination in falling powers of $\theta$.
+
+    Parameters
+    ==========
+
+    extension : :py:class:`~.Expr` or list of :py:class:`~.Expr`
+        Either the algebraic number that is to be expressed in the other field,
+        or else a list of algebraic numbers, a primitive element for which is
+        to be expressed in the other field.
+    theta : :py:class:`~.Expr`, None, optional (default=None)
+        If an :py:class:`~.Expr` representing an algebraic number, behavior is
+        as described under **Explanation**. If ``None``, then this function
+        reduces to a shorthand for calling :py:func:`~.primitive_element` on
+        ``extension`` and turning the computed primitive element into an
+        :py:class:`~.AlgebraicNumber`.
+    gen : :py:class:`~.Symbol`, None, optional (default=None)
+        If provided, this will be used as the generator symbol for the minimal
+        polynomial in the returned :py:class:`~.AlgebraicNumber`.
+    alias : str, :py:class:`~.Symbol`, None, optional (default=None)
+        If provided, this will be used as the alias symbol for the returned
+        :py:class:`~.AlgebraicNumber`.
+
+    Returns
+    =======
+
+    AlgebraicNumber
+        Belonging to $\mathbb{Q}(\theta)$ and equaling $\eta$.
+
+    Raises
+    ======
+
+    IsomorphismFailed
+        If $\eta \not\in \mathbb{Q}(\theta)$.
+
+    See Also
+    ========
+
+    field_isomorphism
+    primitive_element
+
+    """
+    if hasattr(extension, '__iter__'):
+        extension = list(extension)
+    else:
+        extension = [extension]
+
+    if len(extension) == 1 and isinstance(extension[0], tuple):
+        return AlgebraicNumber(extension[0], alias=alias)
+
+    minpoly, coeffs = primitive_element(extension, gen, polys=True)
+    root = sum(coeff*ext for coeff, ext in zip(coeffs, extension))
+
+    if theta is None:
+        return AlgebraicNumber((minpoly, root), alias=alias)
+    else:
+        theta = sympify(theta)
+
+        if not theta.is_AlgebraicNumber:
+            theta = AlgebraicNumber(theta, gen=gen, alias=alias)
+
+        coeffs = field_isomorphism(root, theta)
+
+        if coeffs is not None:
+            return AlgebraicNumber(theta, coeffs, alias=alias)
+        else:
+            raise IsomorphismFailed(
+                "%s is not in a subfield of %s" % (root, theta.root))
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/tests/__init__.py b/lib/python3.11/site-packages/sympy/polys/numberfields/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/lib/python3.11/site-packages/sympy/polys/numberfields/utilities.py b/lib/python3.11/site-packages/sympy/polys/numberfields/utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe583efb440f02f1b16c38fb7d03621c1f97e83d
--- /dev/null
+++ b/lib/python3.11/site-packages/sympy/polys/numberfields/utilities.py
@@ -0,0 +1,474 @@
+"""Utilities for algebraic number theory. """
+
+from sympy.core.sympify import sympify
+from sympy.ntheory.factor_ import factorint
+from sympy.polys.domains.rationalfield import QQ
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.matrices.exceptions import DMRankError
+from sympy.polys.numberfields.minpoly import minpoly
+from sympy.printing.lambdarepr import IntervalPrinter
+from sympy.utilities.decorator import public
+from sympy.utilities.lambdify import lambdify
+
+from mpmath import mp
+
+
+def is_rat(c):
+    r"""
+    Test whether an argument is of an acceptable type to be used as a rational
+    number.
+
+    Explanation
+    ===========
+
+    Returns ``True`` on any argument of type ``int``, :ref:`ZZ`, or :ref:`QQ`.
+
+    See Also
+    ========
+
+    is_int
+
+    """
+    # ``c in QQ`` is too accepting (e.g. ``3.14 in QQ`` is ``True``),
+    # ``QQ.of_type(c)`` is too demanding (e.g. ``QQ.of_type(3)`` is ``False``).
+    #
+    # Meanwhile, if gmpy2 is installed then ``ZZ.of_type()`` accepts only
+    # ``mpz``, not ``int``, so we need another clause to ensure ``int`` is
+    # accepted.
+    return isinstance(c, int) or ZZ.of_type(c) or QQ.of_type(c)
+
+
+def is_int(c):
+    r"""
+    Test whether an argument is of an acceptable type to be used as an integer.
+
+    Explanation
+    ===========
+
+    Returns ``True`` on any argument of type ``int`` or :ref:`ZZ`.
+
+    See Also
+    ========
+
+    is_rat
+
+    """
+    # If gmpy2 is installed then ``ZZ.of_type()`` accepts only
+    # ``mpz``, not ``int``, so we need another clause to ensure ``int`` is
+    # accepted.
+    return isinstance(c, int) or ZZ.of_type(c)
+
+
+def get_num_denom(c):
+    r"""
+    Given any argument on which :py:func:`~.is_rat` is ``True``, return the
+    numerator and denominator of this number.
+
+    See Also
+    ========
+
+    is_rat
+
+    """
+    r = QQ(c)
+    return r.numerator, r.denominator
+
+
+@public
+def extract_fundamental_discriminant(a):
+    r"""
+    Extract a fundamental discriminant from an integer *a*.
+
+    Explanation
+    ===========
+
+    Given any rational integer *a* that is 0 or 1 mod 4, write $a = d f^2$,
+    where $d$ is either 1 or a fundamental discriminant, and return a pair
+    of dictionaries ``(D, F)`` giving the prime factorizations of $d$ and $f$
+    respectively, in the same format returned by :py:func:`~.factorint`.
+
+    A fundamental discriminant $d$ is different from unity, and is either
+    1 mod 4 and squarefree, or is 0 mod 4 and such that $d/4$ is squarefree
+    and 2 or 3 mod 4. This is the same as being the discriminant of some
+    quadratic field.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.numberfields.utilities import extract_fundamental_discriminant
+    >>> print(extract_fundamental_discriminant(-432))
+    ({3: 1, -1: 1}, {2: 2, 3: 1})
+
+    For comparison:
+
+    >>> from sympy import factorint
+    >>> print(factorint(-432))
+    {2: 4, 3: 3, -1: 1}
+
+    Parameters
+    ==========
+
+    a: int, must be 0 or 1 mod 4
+
+    Returns
+    =======
+
+    Pair ``(D, F)``  of dictionaries.
+
+    Raises
+    ======
+
+    ValueError
+        If *a* is not 0 or 1 mod 4.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+       (See Prop. 5.1.3)
+
+    """
+    if a % 4 not in [0, 1]:
+        raise ValueError('To extract fundamental discriminant, number must be 0 or 1 mod 4.')
+    if a == 0:
+        return {}, {0: 1}
+    if a == 1:
+        return {}, {}
+    a_factors = factorint(a)
+    D = {}
+    F = {}
+    # First pass: just make d squarefree, and a/d a perfect square.
+    # We'll count primes (and units! i.e. -1) that are 3 mod 4 and present in d.
+    num_3_mod_4 = 0
+    for p, e in a_factors.items():
+        if e % 2 == 1:
+            D[p] = 1
+            if p % 4 == 3:
+                num_3_mod_4 += 1
+            if e >= 3:
+                F[p] = (e - 1) // 2
+        else:
+            F[p] = e // 2
+    # Second pass: if d is cong. to 2 or 3 mod 4, then we must steal away
+    # another factor of 4 from f**2 and give it to d.
+    even = 2 in D
+    if even or num_3_mod_4 % 2 == 1:
+        e2 = F[2]
+        assert e2 > 0
+        if e2 == 1:
+            del F[2]
+        else:
+            F[2] = e2 - 1
+        D[2] = 3 if even else 2
+    return D, F
+
+
+@public
+class AlgIntPowers:
+    r"""
+    Compute the powers of an algebraic integer.
+
+    Explanation
+    ===========
+
+    Given an algebraic integer $\theta$ by its monic irreducible polynomial
+    ``T`` over :ref:`ZZ`, this class computes representations of arbitrarily
+    high powers of $\theta$, as :ref:`ZZ`-linear combinations over
+    $\{1, \theta, \ldots, \theta^{n-1}\}$, where $n = \deg(T)$.
+
+    The representations are computed using the linear recurrence relations for
+    powers of $\theta$, derived from the polynomial ``T``. See [1], Sec. 4.2.2.
+
+    Optionally, the representations may be reduced with respect to a modulus.
+
+    Examples
+    ========
+
+    >>> from sympy import Poly, cyclotomic_poly
+    >>> from sympy.polys.numberfields.utilities import AlgIntPowers
+    >>> T = Poly(cyclotomic_poly(5))
+    >>> zeta_pow = AlgIntPowers(T)
+    >>> print(zeta_pow[0])
+    [1, 0, 0, 0]
+    >>> print(zeta_pow[1])
+    [0, 1, 0, 0]
+    >>> print(zeta_pow[4])  # doctest: +SKIP
+    [-1, -1, -1, -1]
+    >>> print(zeta_pow[24])  # doctest: +SKIP
+    [-1, -1, -1, -1]
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
+
+    """
+
+    def __init__(self, T, modulus=None):
+        """
+        Parameters
+        ==========
+
+        T : :py:class:`~.Poly`
+            The monic irreducible polynomial over :ref:`ZZ` defining the
+            algebraic integer.
+
+        modulus : int, None, optional
+            If not ``None``, all representations will be reduced w.r.t. this.
+
+        """
+        self.T = T
+        self.modulus = modulus
+        self.n = T.degree()
+        self.powers_n_and_up = [[-c % self for c in reversed(T.rep.to_list())][:-1]]
+        self.max_so_far = self.n
+
+    def red(self, exp):
+        return exp if self.modulus is None else exp % self.modulus
+
+    def __rmod__(self, other):
+        return self.red(other)
+
+    def compute_up_through(self, e):
+        m = self.max_so_far
+        if e <= m: return
+        n = self.n
+        r = self.powers_n_and_up
+        c = r[0]
+        for k in range(m+1, e+1):
+            b = r[k-1-n][n-1]
+            r.append(
+                [c[0]*b % self] + [
+                    (r[k-1-n][i-1] + c[i]*b) % self for i in range(1, n)
+                ]
+            )
+        self.max_so_far = e
+
+    def get(self, e):
+        n = self.n
+        if e < 0:
+            raise ValueError('Exponent must be non-negative.')
+        elif e < n:
+            return [1 if i == e else 0 for i in range(n)]
+        else:
+            self.compute_up_through(e)
+            return self.powers_n_and_up[e - n]
+
+    def __getitem__(self, item):
+        return self.get(item)
+
+
+@public
+def coeff_search(m, R):
+    r"""
+    Generate coefficients for searching through polynomials.
+
+    Explanation
+    ===========
+
+    Lead coeff is always non-negative. Explore all combinations with coeffs
+    bounded in absolute value before increasing the bound. Skip the all-zero
+    list, and skip any repeats. See examples.
+
+    Examples
+    ========
+
+    >>> from sympy.polys.numberfields.utilities import coeff_search
+    >>> cs = coeff_search(2, 1)
+    >>> C = [next(cs) for i in range(13)]
+    >>> print(C)
+    [[1, 1], [1, 0], [1, -1], [0, 1], [2, 2], [2, 1], [2, 0], [2, -1], [2, -2],
+     [1, 2], [1, -2], [0, 2], [3, 3]]
+
+    Parameters
+    ==========
+
+    m : int
+        Length of coeff list.
+    R : int
+        Initial max abs val for coeffs (will increase as search proceeds).
+
+    Returns
+    =======
+
+    generator
+        Infinite generator of lists of coefficients.
+
+    """
+    R0 = R
+    c = [R] * m
+    while True:
+        if R == R0 or R in c or -R in c:
+            yield c[:]
+        j = m - 1
+        while c[j] == -R:
+            j -= 1
+        c[j] -= 1
+        for i in range(j + 1, m):
+            c[i] = R
+        for j in range(m):
+            if c[j] != 0:
+                break
+        else:
+            R += 1
+            c = [R] * m
+
+
+def supplement_a_subspace(M):
+    r"""
+    Extend a basis for a subspace to a basis for the whole space.
+
+    Explanation
+    ===========
+
+    Given an $n \times r$ matrix *M* of rank $r$ (so $r \leq n$), this function
+    computes an invertible $n \times n$ matrix $B$ such that the first $r$
+    columns of $B$ equal *M*.
+
+    This operation can be interpreted as a way of extending a basis for a
+    subspace, to give a basis for the whole space.
+
+    To be precise, suppose you have an $n$-dimensional vector space $V$, with
+    basis $\{v_1, v_2, \ldots, v_n\}$, and an $r$-dimensional subspace $W$ of
+    $V$, spanned by a basis $\{w_1, w_2, \ldots, w_r\}$, where the $w_j$ are
+    given as linear combinations of the $v_i$. If the columns of *M* represent
+    the $w_j$ as such linear combinations, then the columns of the matrix $B$
+    computed by this function give a new basis $\{u_1, u_2, \ldots, u_n\}$ for
+    $V$, again relative to the $\{v_i\}$ basis, and such that $u_j = w_j$
+    for $1 \leq j \leq r$.
+
+    Examples
+    ========
+
+    Note: The function works in terms of columns, so in these examples we
+    print matrix transposes in order to make the columns easier to inspect.
+
+    >>> from sympy.polys.matrices import DM
+    >>> from sympy import QQ, FF
+    >>> from sympy.polys.numberfields.utilities import supplement_a_subspace
+    >>> M = DM([[1, 7, 0], [2, 3, 4]], QQ).transpose()
+    >>> print(supplement_a_subspace(M).to_Matrix().transpose())
+    Matrix([[1, 7, 0], [2, 3, 4], [1, 0, 0]])
+
+    >>> M2 = M.convert_to(FF(7))
+    >>> print(M2.to_Matrix().transpose())
+    Matrix([[1, 0, 0], [2, 3, -3]])
+    >>> print(supplement_a_subspace(M2).to_Matrix().transpose())
+    Matrix([[1, 0, 0], [2, 3, -3], [0, 1, 0]])
+
+    Parameters
+    ==========
+
+    M : :py:class:`~.DomainMatrix`
+        The columns give the basis for the subspace.
+
+    Returns
+    =======
+
+    :py:class:`~.DomainMatrix`
+        This matrix is invertible and its first $r$ columns equal *M*.
+
+    Raises
+    ======
+
+    DMRankError
+        If *M* was not of maximal rank.
+
+    References
+    ==========
+
+    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*
+       (See Sec. 2.3.2.)
+
+    """
+    n, r = M.shape
+    # Let In be the n x n identity matrix.
+    # Form the augmented matrix [M | In] and compute RREF.
+    Maug = M.hstack(M.eye(n, M.domain))
+    R, pivots = Maug.rref()
+    if pivots[:r] != tuple(range(r)):
+        raise DMRankError('M was not of maximal rank')
+    # Let J be the n x r matrix equal to the first r columns of In.
+    # Since M is of rank r, RREF reduces [M | In] to [J | A], where A is the product of
+    # elementary matrices Ei corresp. to the row ops performed by RREF. Since the Ei are
+    # invertible, so is A. Let B = A^(-1).
+    A = R[:, r:]
+    B = A.inv()
+    # Then B is the desired matrix. It is invertible, since B^(-1) == A.
+    # And A * [M | In] == [J | A]
+    #  => A * M == J
+    #  => M == B * J == the first r columns of B.
+    return B
+
+
+@public
+def isolate(alg, eps=None, fast=False):
+    """
+    Find a rational isolating interval for a real algebraic number.
+
+    Examples
+    ========
+
+    >>> from sympy import isolate, sqrt, Rational
+    >>> print(isolate(sqrt(2)))  # doctest: +SKIP
+    (1, 2)
+    >>> print(isolate(sqrt(2), eps=Rational(1, 100)))
+    (24/17, 17/12)
+
+    Parameters
+    ==========
+
+    alg : str, int, :py:class:`~.Expr`
+        The algebraic number to be isolated. Must be a real number, to use this
+        particular function. However, see also :py:meth:`.Poly.intervals`,
+        which isolates complex roots when you pass ``all=True``.
+    eps : positive element of :ref:`QQ`, None, optional (default=None)
+        Precision to be passed to :py:meth:`.Poly.refine_root`
+    fast : boolean, optional (default=False)
+        Say whether fast refinement procedure should be used.
+        (Will be passed to :py:meth:`.Poly.refine_root`.)
+
+    Returns
+    =======
+
+    Pair of rational numbers defining an isolating interval for the given
+    algebraic number.
+
+    See Also
+    ========
+
+    .Poly.intervals
+
+    """
+    alg = sympify(alg)
+
+    if alg.is_Rational:
+        return (alg, alg)
+    elif not alg.is_real:
+        raise NotImplementedError(
+            "complex algebraic numbers are not supported")
+
+    func = lambdify((), alg, modules="mpmath", printer=IntervalPrinter())
+
+    poly = minpoly(alg, polys=True)
+    intervals = poly.intervals(sqf=True)
+
+    dps, done = mp.dps, False
+
+    try:
+        while not done:
+            alg = func()
+
+            for a, b in intervals:
+                if a <= alg.a and alg.b <= b:
+                    done = True
+                    break
+            else:
+                mp.dps *= 2
+    finally:
+        mp.dps = dps
+
+    if eps is not None:
+        a, b = poly.refine_root(a, b, eps=eps, fast=fast)
+
+    return (a, b)

' : '\U0001d4ab', + '\\' : '\U0001d4ac', + '\\' : '\U0000211b', + '\\' : '\U0001d4ae', + '\\' : '\U0001d4af', + '\\' : '\U0001d4b0', + '\\' : '\U0001d4b1', + '\\' : '\U0001d4b2', + '\\' : '\U0001d4b3', + '\\' : '\U0001d4b4', + '\\' : '\U0001d4b5', + '\\' : '\U0001d5ba', + '\\' : '\U0001d5bb', + '\\' : '\U0001d5bc', + '\\' : '\U0001d5bd', + '\\' : '\U0001d5be', + '\\' : '\U0001d5bf', + '\\' : '\U0001d5c0', + '\\' : '\U0001d5c1', + '\\' : '\U0001d5c2', + '\\' : '\U0001d5c3', + '\\' : '\U0001d5c4', + '\\' : '\U0001d5c5', + '\\' : '\U0001d5c6', + '\\' : '\U0001d5c7', + '\\' : '\U0001d5c8', + '\\