Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. ย See raw diff
Files changed (50)
- .cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet-1.4.3.dist-info/METADATAAdded+87
- .cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet-1.4.3.dist-info/RECORDAdded+7
- .cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet-1.4.3.dist-info/WHEELAdded+5
- .cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet/__init__.pyAdded+5
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/METADATAAdded+202
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/RECORDAdded+17
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/WHEELAdded+5
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/licenses/LICENSE.txtAdded+22
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/top_level.txtAdded+1
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/__init__.pyAdded+62
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_abnf.pyAdded+132
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_connection.pyAdded+659
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_events.pyAdded+369
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_headers.pyAdded+282
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_readers.pyAdded+250
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_receivebuffer.pyAdded+153
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_state.pyAdded+365
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_util.pyAdded+135
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_version.pyAdded+16
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_writers.pyAdded+145
- .cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/py.typedAdded+1
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/cddl.pyAdded+172
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/chapel.pyAdded+139
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/clean.pyAdded+180
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/codeql.pyAdded+80
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/comal.pyAdded+81
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/compiled.pyAdded+35
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/configs.pyAdded+1433
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/console.pyAdded+114
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/cplint.pyAdded+43
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/crystal.pyAdded+364
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/csound.pyAdded+466
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/css.pyAdded+632
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/d.pyAdded+259
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dalvik.pyAdded+126
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/data.pyAdded+763
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dax.pyAdded+135
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/devicetree.pyAdded+120
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/diff.pyAdded+169
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dns.pyAdded+109
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dotnet.pyAdded+873
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dsls.pyAdded+970
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dylan.pyAdded+279
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/ecl.pyAdded+144
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/eiffel.pyAdded+68
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/elm.pyAdded+123
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/elpi.pyAdded+201
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/email.pyAdded+132
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/erlang.pyAdded+526
- .cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/esoteric.pyAdded+300
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687Metadata-Version: 2.4Name: hf-xetVersion: 1.4.3Classifier: Development Status :: 5 - Production/StableClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Programming Language :: RustClassifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Free ThreadingClassifier: Programming Language :: Python :: Free Threading :: 2 - BetaClassifier: Topic :: Scientific/Engineering :: Artificial IntelligenceRequires-Dist: pytest ; extra == 'tests'Provides-Extra: testsLicense-File: LICENSESummary: Fast transfer of large files with the Hugging Face Hub.Maintainer-email: Rajat Arya <rajat@rajatarya.com>, Jared Sulzdorf <j.sulzdorf@gmail.com>, Di Xiao <di@huggingface.co>, Assaf Vayner <assaf@huggingface.co>, Hoyt Koepke <hoytak@gmail.com>License-Expression: Apache-2.0Requires-Python: >=3.8Description-Content-Type: text/markdown; charset=UTF-8; variant=GFMProject-URL: Documentation, https://huggingface.co/docs/hub/xet/indexProject-URL: Homepage, https://github.com/huggingface/xet-coreProject-URL: Issues, https://github.com/huggingface/xet-core/issuesProject-URL: Repository, https://github.com/huggingface/xet-core.git
<!---Copyright 2024 The HuggingFace Team. 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, softwaredistributed 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 andlimitations under the License.--><p align="center"> <a href="https://github.com/huggingface/xet-core/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/xet-core.svg?color=blue"></a> <a href="https://github.com/huggingface/xet-core/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/xet-core.svg"></a> <a href="https://github.com/huggingface/xet-core/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a></p>
<h3 align="center"> <p>๐ค hf-xet - xet client tech, used in <a target="_blank" href="https://github.com/huggingface/huggingface_hub/">huggingface_hub</a></p></h3>
## Welcome
`hf-xet` enables `huggingface_hub` to utilize xet storage for uploading and downloading to HF Hub. Xet storage provides chunk-based deduplication, efficient storage/retrieval with local disk caching, and backwards compatibility with Git LFS. This library is not meant to be used directly, and is instead intended to be used from [huggingface_hub](https://pypi.org/project/huggingface-hub).
## Key features
โป **chunk-based deduplication implementation**: avoid transferring and storing chunks that are shared across binary files (models, datasets, etc).
๐ค **Python bindings**: bindings for [huggingface_hub](https://github.com/huggingface/huggingface_hub/) package.
โ **network communications**: concurrent communication to HF Hub Xet backend services (CAS).
๐ **local disk caching**: chunk-based cache that sits alongside the existing [huggingface_hub disk cache](https://huggingface.co/docs/huggingface_hub/guides/manage-cache).
## Installation
Install the `hf_xet` package with [pip](https://pypi.org/project/hf-xet/):
```bashpip install hf_xet```
## Quick Start
`hf_xet` is not intended to be run independently as it is expected to be used from `huggingface_hub`, so to get started with `huggingface_hub` check out the documentation [here]("https://hf.co/docs/huggingface_hub").
## Contributions (feature requests, bugs, etc.) are encouraged & appreciated ๐๐๐๐๐งกโค๏ธ
Please join us in making hf-xet better. We value everyone's contributions. Code is not the only way to help. Answering questions, helping each other, improving documentation, filing issues all help immensely. If you are interested in contributing (please do!), check out the [contribution guide](https://github.com/huggingface/xet-core/blob/main/CONTRIBUTING.md) for this repository.1234567hf_xet/__init__.py,sha256=E8UDdyQ8glZ_nve9hHEf22bPang8-RKx4VuApXYeQUo,107hf_xet/hf_xet.abi3.so,sha256=SwT1a-zZLMNfCnvhiSNIbxvfZ8uSJ0yHlxaMNoXLBHk,10705480hf_xet-1.4.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357hf_xet-1.4.3.dist-info/sboms/hf_xet.cyclonedx.json,sha256=4mTyJZO-hy5XZfX_3Ls0Oy63jI80kjeFloXJL3XHiFE,396786hf_xet-1.4.3.dist-info/METADATA,sha256=7hxekaCV9twusR2dzpAwSnG_8104pGIwbZXqfiar-eA,4882hf_xet-1.4.3.dist-info/WHEEL,sha256=1pgehMgoLQR1FJVAn1ncNPArAkOOjDbju-Tmx-fP9xs,143hf_xet-1.4.3.dist-info/RECORD,,12345Wheel-Version: 1.0Generator: maturin (1.12.6)Root-Is-Purelib: falseTag: cp37-abi3-manylinux_2_17_x86_64Tag: cp37-abi3-manylinux2014_x86_6412345from .hf_xet import *
__doc__ = hf_xet.__doc__if hasattr(hf_xet, "__all__"): __all__ = hf_xet.__all__123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202Metadata-Version: 2.4Name: h11Version: 0.16.0Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1Home-page: https://github.com/python-hyper/h11Author: Nathaniel J. SmithAuthor-email: njs@pobox.comLicense: MITClassifier: Development Status :: 3 - AlphaClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Topic :: Internet :: WWW/HTTPClassifier: Topic :: System :: NetworkingRequires-Python: >=3.8License-File: LICENSE.txtDynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: requires-pythonDynamic: summary
h11===
.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master :target: https://travis-ci.org/python-hyper/h11 :alt: Automated test status
.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-hyper/h11 :alt: Test coverage
.. image:: https://readthedocs.org/projects/h11/badge/?version=latest :target: http://h11.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status
This is a little HTTP/1.1 library written from scratch in Python,heavily inspired by `hyper-h2 <https://hyper-h2.readthedocs.io/>`_.
It's a "bring-your-own-I/O" library; h11 contains no IO codewhatsoever. This means you can hook h11 up to your favorite networkAPI, and that could be anything you want: synchronous, threaded,asynchronous, or your own implementation of `RFC 6214<https://tools.ietf.org/html/rfc6214>`_ -- h11 won't judge you.(Compare this to the current state of the art, where every time a `newnetwork API <https://trio.readthedocs.io/>`_ comes along then someonegets to start over reimplementing the entire HTTP protocol fromscratch.) Cory Benfield made an `excellent blog post describing thebenefits of this approach<https://lukasa.co.uk/2015/10/The_New_Hyper/>`_, or if you like videothen here's his `PyCon 2016 talk on the same theme<https://www.youtube.com/watch?v=7cC3_jGwl_U>`_.
This also means that h11 is not immediately useful out of the box:it's a toolkit for building programs that speak HTTP, not somethingthat could directly replace ``requests`` or ``twisted.web`` orwhatever. But h11 makes it much easier to implement something like``requests`` or ``twisted.web``.
At a high level, working with h11 goes like this:
1) First, create an ``h11.Connection`` object to track the state of a single HTTP/1.1 connection.
2) When you read data off the network, pass it to ``conn.receive_data(...)``; you'll get back a list of objects representing high-level HTTP "events".
3) When you want to send a high-level HTTP event, create the corresponding "event" object and pass it to ``conn.send(...)``; this will give you back some bytes that you can then push out through the network.
For example, a client might instantiate and then send a``h11.Request`` object, then zero or more ``h11.Data`` objects for therequest body (e.g., if this is a POST), and then a``h11.EndOfMessage`` to indicate the end of the message. Then theserver would then send back a ``h11.Response``, some ``h11.Data``, andits own ``h11.EndOfMessage``. If either side violates the protocol,you'll get a ``h11.ProtocolError`` exception.
h11 is suitable for implementing both servers and clients, and has apleasantly symmetric API: the events you send as a client are exactlythe ones that you receive as a server and vice-versa.
`Here's an example of a tiny HTTP client<https://github.com/python-hyper/h11/blob/master/examples/basic-client.py>`_
It also has `a fine manual <https://h11.readthedocs.io/>`_.
FAQ---
*Whyyyyy?*
I wanted to play with HTTP in `Curio<https://curio.readthedocs.io/en/latest/tutorial.html>`__ and `Trio<https://trio.readthedocs.io>`__, which at the time didn't have anyHTTP libraries. So I thought, no big deal, Python has, like, a dozendifferent implementations of HTTP, surely I can find one that'sreusable. I didn't find one, but I did find Cory's call-to-armsblog-post. So I figured, well, fine, if I have to implement HTTP fromscratch, at least I can make sure no-one *else* has to ever again.
*Should I use it?*
Maybe. You should be aware that it's a very young project. But, it'sfeature complete and has an exhaustive test-suite and complete docs,so the next step is for people to try using it and see how it goes:-). If you do then please let us know -- if nothing else we'll wantto talk to you before making any incompatible changes!
*What are the features/limitations?*
Roughly speaking, it's trying to be a robust, complete, and non-hackyimplementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:HTTP/1.1 Message Syntax and Routing<https://tools.ietf.org/html/rfc7230>`_. That is, it mostly focuses onimplementing HTTP at the level of taking bytes on and off the wire,and the headers related to that, and tries to be anal about specconformance. It doesn't know about higher-level concerns like URLrouting, conditional GETs, cross-origin cookie policies, or contentnegotiation. But it does know how to take care of framing,cross-version differences in keep-alive handling, and the "obsoleteline folding" rule, so you can focus your energies on the hard /interesting parts for your application, and it tries to support thefull specification in the sense that any useful HTTP/1.1 conformantapplication should be able to use h11.
It's pure Python, and has no dependencies outside of the standardlibrary.
It has a test suite with 100.0% coverage for both statements andbranches.
Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.The last Python 2-compatible version was h11 0.11.x.(Originally it had a Cython wrapper for `http-parser<https://github.com/nodejs/http-parser>`_ and a beautiful nested statemachine implemented with ``yield from`` to postprocess the output. ButI had to take these out -- the new *parser* needs fewer lines-of-codethan the old *parser wrapper*, is written in pure Python, uses noexotic language syntax, and has more features. It's sad, really; thatold state machine was really slick. I just need a few sentences hereto mourn that.)
I don't know how fast it is. I haven't benchmarked or profiled it yet,so it's probably got a few pointless hot spots, and I've been tryingto err on the side of simplicity and robustness instead ofmicro-optimization. But at the architectural level I tried hard toavoid fundamentally bad decisions, e.g., I believe that all theparsing algorithms remain linear-time even in the face of pathologicalinput like slowloris, and there are no byte-by-byte loops. (I alsobelieve that it maintains bounded memory usage in the face ofarbitrary/pathological input.)
The whole library is ~800 lines-of-code. You can read and understandthe whole thing in less than an hour. Most of the energy invested inthis so far has been spent on trying to keep things simple byminimizing special-cases and ad hoc state manipulation; even though itis now quite small and simple, I'm still annoyed that I haven'tfigured out how to make it even smaller and simpler. (Unfortunately,HTTP does not lend itself to simplicity.)
The API is ~feature complete and I don't expect the general outlinesto change much, but you can't judge an API's ergonomics until youactually document and use it, so I'd expect some changes in thedetails.
*How do I try it?*
.. code-block:: sh
$ pip install h11 $ git clone git@github.com:python-hyper/h11 $ cd h11/examples $ python basic-client.py
and go from there.
*License?*
MIT
*Code of conduct?*
Contributors are requested to follow our `code of conduct<https://github.com/python-hyper/h11/blob/master/CODE_OF_CONDUCT.md>`_ inall project spaces.1234567891011121314151617h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4h11-0.16.0.dist-info/RECORD,,12345Wheel-Version: 1.0Generator: setuptools (78.1.0)Root-Is-Purelib: trueTag: py3-none-any
12345678910111213141516171819202122The MIT License (MIT)
Copyright (c) 2016 Nathaniel J. Smith <njs@pobox.com> and other contributors
Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded 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 OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTIONOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIONWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.1h111234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230),# containing no networking code at all, loosely modelled on hyper-h2's generic# implementation of HTTP/2 (and in particular the h2.connection.H2Connection# class). There's still a bunch of subtle details you need to get right if you# want to make this actually useful, because it doesn't implement all the# semantics to check that what you're asking to write to the wire is sensible,# but at least it gets you out of dealing with the wire itself.
from h11._connection import Connection, NEED_DATA, PAUSEDfrom h11._events import ( ConnectionClosed, Data, EndOfMessage, Event, InformationalResponse, Request, Response,)from h11._state import ( CLIENT, CLOSED, DONE, ERROR, IDLE, MIGHT_SWITCH_PROTOCOL, MUST_CLOSE, SEND_BODY, SEND_RESPONSE, SERVER, SWITCHED_PROTOCOL,)from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolErrorfrom h11._version import __version__
PRODUCT_ID = "python-h11/" + __version__
__all__ = ( "Connection", "NEED_DATA", "PAUSED", "ConnectionClosed", "Data", "EndOfMessage", "Event", "InformationalResponse", "Request", "Response", "CLIENT", "CLOSED", "DONE", "ERROR", "IDLE", "MUST_CLOSE", "SEND_BODY", "SEND_RESPONSE", "SERVER", "SWITCHED_PROTOCOL", "ProtocolError", "LocalProtocolError", "RemoteProtocolError",)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# We use native strings for all the re patterns, to take advantage of string# formatting, and then convert to bytestrings when compiling the final re# objects.
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace# OWS = *( SP / HTAB )# ; optional whitespaceOWS = r"[ \t]*"
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators# token = 1*tchar## tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"# / DIGIT / ALPHA# ; any VCHAR, except delimiterstoken = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields# field-name = tokenfield_name = token
# The standard says:## field-value = *( field-content / obs-fold )# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]# field-vchar = VCHAR / obs-text# obs-fold = CRLF 1*( SP / HTAB )# ; obsolete line folding# ; see Section 3.2.4## https://tools.ietf.org/html/rfc5234#appendix-B.1## VCHAR = %x21-7E# ; visible (printing) characters## https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string# obs-text = %x80-FF## However, the standard definition of field-content is WRONG! It disallows# fields containing a single visible character surrounded by whitespace,# e.g. "foo a bar".## See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189## So our definition of field_content attempts to fix it up...## Also, we allow lots of control characters, because apparently people assume# that they're legal in practice (e.g., google analytics makes cookies with# \x01 in them!):# https://github.com/python-hyper/h11/issues/57# We still don't allow NUL or whitespace, because those are often treated as# meta-characters and letting them through can lead to nasty issues like SSRF.vchar = r"[\x21-\x7e]"vchar_or_obs_text = r"[^\x00\s]"field_vchar = vchar_or_obs_textfield_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
# We handle obs-fold at a different level, and our fixed-up field_content# already grows to swallow the whole value, so ? instead of *field_value = r"({field_content})?".format(**globals())
# header-field = field-name ":" OWS field-value OWSheader_field = ( r"(?P<field_name>{field_name})" r":" r"{OWS}" r"(?P<field_value>{field_value})" r"{OWS}".format(**globals()))
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line## request-line = method SP request-target SP HTTP-version CRLF# method = token# HTTP-version = HTTP-name "/" DIGIT "." DIGIT# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive## request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full# URL, host+port (for connect), or even "*", but in any case we are guaranteed# that it contists of the visible printing characters.method = tokenrequest_target = r"{vchar}+".format(**globals())http_version = r"HTTP/(?P<http_version>[0-9]\.[0-9])"request_line = ( r"(?P<method>{method})" r" " r"(?P<target>{request_target})" r" " r"{http_version}".format(**globals()))
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line## status-line = HTTP-version SP status-code SP reason-phrase CRLF# status-code = 3DIGIT# reason-phrase = *( HTAB / SP / VCHAR / obs-text )status_code = r"[0-9]{3}"reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())status_line = ( r"{http_version}" r" " r"(?P<status_code>{status_code})" # However, there are apparently a few too many servers out there that just # leave out the reason phrase: # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 # https://github.com/seanmonstar/httparse/issues/29 # so make it optional. ?: is a non-capturing group. r"(?: (?P<reason>{reason_phrase}))?".format(**globals()))
HEXDIG = r"[0-9A-Fa-f]"# Actually## chunk-size = 1*HEXDIG## but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())# Actually## chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )## but we aren't parsing the things so we don't really care.chunk_ext = r";.*"chunk_header = ( r"(?P<chunk_size>{chunk_size})" r"(?P<chunk_ext>{chunk_ext})?" r"{OWS}\r\n".format( **globals() ) # Even though the specification does not allow for extra whitespaces, # we are lenient with trailing whitespaces because some servers on the wild use it.)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659# This contains the main Connection class. Everything in h11 revolves around# this.from typing import ( Any, Callable, cast, Dict, List, Optional, overload, Tuple, Type, Union,)
from ._events import ( ConnectionClosed, Data, EndOfMessage, Event, InformationalResponse, Request, Response,)from ._headers import get_comma_header, has_expect_100_continue, set_comma_headerfrom ._readers import READERS, ReadersTypefrom ._receivebuffer import ReceiveBufferfrom ._state import ( _SWITCH_CONNECT, _SWITCH_UPGRADE, CLIENT, ConnectionState, DONE, ERROR, MIGHT_SWITCH_PROTOCOL, SEND_BODY, SERVER, SWITCHED_PROTOCOL,)from ._util import ( # Import the internal things we need LocalProtocolError, RemoteProtocolError, Sentinel,)from ._writers import WRITERS, WritersType
# Everything in __all__ gets re-exported as part of the h11 public API.__all__ = ["Connection", "NEED_DATA", "PAUSED"]
class NEED_DATA(Sentinel, metaclass=Sentinel): pass
class PAUSED(Sentinel, metaclass=Sentinel): pass
# If we ever have this much buffered without it making a complete parseable# event, we error out. The only time we really buffer is when reading the# request/response line + headers together, so this is effectively the limit on# the size of that.## Some precedents for defaults:# - node.js: 80 * 1024# - tomcat: 8 * 1024# - IIS: 16 * 1024# - Apache: <8 KiB per line>DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024
# RFC 7230's rules for connection lifecycles:# - If either side says they want to close the connection, then the connection# must close.# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive# (and even this is a mess -- e.g. if you're implementing a proxy then# sending Connection: keep-alive is forbidden).## We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So# our rule is:# - If someone says Connection: close, we will close# - If someone uses HTTP/1.0, we will close.def _keep_alive(event: Union[Request, Response]) -> bool: connection = get_comma_header(event.headers, b"connection") if b"close" in connection: return False if getattr(event, "http_version", b"1.1") < b"1.1": return False return True
def _body_framing( request_method: bytes, event: Union[Request, Response]) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: # Called when we enter SEND_BODY to figure out framing information for # this body. # # These are the only two events that can trigger a SEND_BODY state: assert type(event) in (Request, Response) # Returns one of: # # ("content-length", count) # ("chunked", ()) # ("http/1.0", ()) # # which are (lookup key, *args) for constructing body reader/writer # objects. # # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 # # Step 1: some responses always have an empty body, regardless of what the # headers say. if type(event) is Response: if ( event.status_code in (204, 304) or request_method == b"HEAD" or (request_method == b"CONNECT" and 200 <= event.status_code < 300) ): return ("content-length", (0,)) # Section 3.3.3 also lists another case -- responses with status_code # < 200. For us these are InformationalResponses, not Responses, so # they can't get into this function in the first place. assert event.status_code >= 200
# Step 2: check for Transfer-Encoding (T-E beats C-L): transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") if transfer_encodings: assert transfer_encodings == [b"chunked"] return ("chunked", ())
# Step 3: check for Content-Length content_lengths = get_comma_header(event.headers, b"content-length") if content_lengths: return ("content-length", (int(content_lengths[0]),))
# Step 4: no applicable headers; fallback/default depends on type if type(event) is Request: return ("content-length", (0,)) else: return ("http/1.0", ())
################################################################## The main Connection class#################################################################
class Connection: """An object encapsulating the state of an HTTP connection.
Args: our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If you're implementing a server, pass :data:`h11.SERVER`.
max_incomplete_event_size (int): The maximum number of bytes we're willing to buffer of an incomplete event. In practice this mostly sets a limit on the maximum size of the request/response line + headers. If this is exceeded, then :meth:`next_event` will raise :exc:`RemoteProtocolError`.
"""
def __init__( self, our_role: Type[Sentinel], max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, ) -> None: self._max_incomplete_event_size = max_incomplete_event_size # State and role tracking if our_role not in (CLIENT, SERVER): raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}") self.our_role = our_role self.their_role: Type[Sentinel] if our_role is CLIENT: self.their_role = SERVER else: self.their_role = CLIENT self._cstate = ConnectionState()
# Callables for converting data->events or vice-versa given the # current state self._writer = self._get_io_object(self.our_role, None, WRITERS) self._reader = self._get_io_object(self.their_role, None, READERS)
# Holds any unprocessed received data self._receive_buffer = ReceiveBuffer() # If this is true, then it indicates that the incoming connection was # closed *after* the end of whatever's in self._receive_buffer: self._receive_buffer_closed = False
# Extra bits of state that don't fit into the state machine. # # These two are only used to interpret framing headers for figuring # out how to read/write response bodies. their_http_version is also # made available as a convenient public API. self.their_http_version: Optional[bytes] = None self._request_method: Optional[bytes] = None # This is pure flow-control and doesn't at all affect the set of legal # transitions, so no need to bother ConnectionState with it: self.client_is_waiting_for_100_continue = False
@property def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: """A dictionary like::
{CLIENT: <client state>, SERVER: <server state>}
See :ref:`state-machine` for details.
""" return dict(self._cstate.states)
@property def our_state(self) -> Type[Sentinel]: """The current state of whichever role we are playing. See :ref:`state-machine` for details. """ return self._cstate.states[self.our_role]
@property def their_state(self) -> Type[Sentinel]: """The current state of whichever role we are NOT playing. See :ref:`state-machine` for details. """ return self._cstate.states[self.their_role]
@property def they_are_waiting_for_100_continue(self) -> bool: return self.their_role is CLIENT and self.client_is_waiting_for_100_continue
def start_next_cycle(self) -> None: """Attempt to reset our connection state for a new request/response cycle.
If both client and server are in :data:`DONE` state, then resets them both to :data:`IDLE` state in preparation for a new request/response cycle on this same connection. Otherwise, raises a :exc:`LocalProtocolError`.
See :ref:`keepalive-and-pipelining`.
""" old_states = dict(self._cstate.states) self._cstate.start_next_cycle() self._request_method = None # self.their_http_version gets left alone, since it presumably lasts # beyond a single request/response cycle assert not self.client_is_waiting_for_100_continue self._respond_to_state_changes(old_states)
def _process_error(self, role: Type[Sentinel]) -> None: old_states = dict(self._cstate.states) self._cstate.process_error(role) self._respond_to_state_changes(old_states)
def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: if type(event) is InformationalResponse and event.status_code == 101: return _SWITCH_UPGRADE if type(event) is Response: if ( _SWITCH_CONNECT in self._cstate.pending_switch_proposals and 200 <= event.status_code < 300 ): return _SWITCH_CONNECT return None
# All events go through here def _process_event(self, role: Type[Sentinel], event: Event) -> None: # First, pass the event through the state machine to make sure it # succeeds. old_states = dict(self._cstate.states) if role is CLIENT and type(event) is Request: if event.method == b"CONNECT": self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) if get_comma_header(event.headers, b"upgrade"): self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) server_switch_event = None if role is SERVER: server_switch_event = self._server_switch_event(event) self._cstate.process_event(role, type(event), server_switch_event)
# Then perform the updates triggered by it.
if type(event) is Request: self._request_method = event.method
if role is self.their_role and type(event) in ( Request, Response, InformationalResponse, ): event = cast(Union[Request, Response, InformationalResponse], event) self.their_http_version = event.http_version
# Keep alive handling # # RFC 7230 doesn't really say what one should do if Connection: close # shows up on a 1xx InformationalResponse. I think the idea is that # this is not supposed to happen. In any case, if it does happen, we # ignore it. if type(event) in (Request, Response) and not _keep_alive( cast(Union[Request, Response], event) ): self._cstate.process_keep_alive_disabled()
# 100-continue if type(event) is Request and has_expect_100_continue(event): self.client_is_waiting_for_100_continue = True if type(event) in (InformationalResponse, Response): self.client_is_waiting_for_100_continue = False if role is CLIENT and type(event) in (Data, EndOfMessage): self.client_is_waiting_for_100_continue = False
self._respond_to_state_changes(old_states, event)
def _get_io_object( self, role: Type[Sentinel], event: Optional[Event], io_dict: Union[ReadersType, WritersType], ) -> Optional[Callable[..., Any]]: # event may be None; it's only used when entering SEND_BODY state = self._cstate.states[role] if state is SEND_BODY: # Special case: the io_dict has a dict of reader/writer factories # that depend on the request/response framing. framing_type, args = _body_framing( cast(bytes, self._request_method), cast(Union[Request, Response], event) ) return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] else: # General case: the io_dict just has the appropriate reader/writer # for this state return io_dict.get((role, state)) # type: ignore[return-value]
# This must be called after any action that might have caused # self._cstate.states to change. def _respond_to_state_changes( self, old_states: Dict[Type[Sentinel], Type[Sentinel]], event: Optional[Event] = None, ) -> None: # Update reader/writer if self.our_state != old_states[self.our_role]: self._writer = self._get_io_object(self.our_role, event, WRITERS) if self.their_state != old_states[self.their_role]: self._reader = self._get_io_object(self.their_role, event, READERS)
@property def trailing_data(self) -> Tuple[bytes, bool]: """Data that has been received, but not yet processed, represented as a tuple with two elements, where the first is a byte-string containing the unprocessed data itself, and the second is a bool that is True if the receive connection was closed.
See :ref:`switching-protocols` for discussion of why you'd want this. """ return (bytes(self._receive_buffer), self._receive_buffer_closed)
def receive_data(self, data: bytes) -> None: """Add data to our internal receive buffer.
This does not actually do any processing on the data, just stores it. To trigger processing, you have to call :meth:`next_event`.
Args: data (:term:`bytes-like object`): The new data that was just received.
Special case: If *data* is an empty byte-string like ``b""``, then this indicates that the remote side has closed the connection (end of file). Normally this is convenient, because standard Python APIs like :meth:`file.read` or :meth:`socket.recv` use ``b""`` to indicate end-of-file, while other failures to read are indicated using other mechanisms like raising :exc:`TimeoutError`. When using such an API you can just blindly pass through whatever you get from ``read`` to :meth:`receive_data`, and everything will work.
But, if you have an API where reading an empty string is a valid non-EOF condition, then you need to be aware of this and make sure to check for such strings and avoid passing them to :meth:`receive_data`.
Returns: Nothing, but after calling this you should call :meth:`next_event` to parse the newly received data.
Raises: RuntimeError: Raised if you pass an empty *data*, indicating EOF, and then pass a non-empty *data*, indicating more data that somehow arrived after the EOF.
(Calling ``receive_data(b"")`` multiple times is fine, and equivalent to calling it once.)
""" if data: if self._receive_buffer_closed: raise RuntimeError("received close, then received more data?") self._receive_buffer += data else: self._receive_buffer_closed = True
def _extract_next_receive_event( self, ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: state = self.their_state # We don't pause immediately when they enter DONE, because even in # DONE state we can still process a ConnectionClosed() event. But # if we have data in our buffer, then we definitely aren't getting # a ConnectionClosed() immediately and we need to pause. if state is DONE and self._receive_buffer: return PAUSED if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: return PAUSED assert self._reader is not None event = self._reader(self._receive_buffer) if event is None: if not self._receive_buffer and self._receive_buffer_closed: # In some unusual cases (basically just HTTP/1.0 bodies), EOF # triggers an actual protocol event; in that case, we want to # return that event, and then the state will change and we'll # get called again to generate the actual ConnectionClosed(). if hasattr(self._reader, "read_eof"): event = self._reader.read_eof() else: event = ConnectionClosed() if event is None: event = NEED_DATA return event # type: ignore[no-any-return]
def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: """Parse the next event out of our receive buffer, update our internal state, and return it.
This is a mutating operation -- think of it like calling :func:`next` on an iterator.
Returns: : One of three things:
1) An event object -- see :ref:`events`.
2) The special constant :data:`NEED_DATA`, which indicates that you need to read more data from your socket and pass it to :meth:`receive_data` before this method will be able to return any more events.
3) The special constant :data:`PAUSED`, which indicates that we are not in a state where we can process incoming data (usually because the peer has finished their part of the current request/response cycle, and you have not yet called :meth:`start_next_cycle`). See :ref:`flow-control` for details.
Raises: RemoteProtocolError: The peer has misbehaved. You should close the connection (possibly after sending some kind of 4xx response).
Once this method returns :class:`ConnectionClosed` once, then all subsequent calls will also return :class:`ConnectionClosed`.
If this method raises any exception besides :exc:`RemoteProtocolError` then that's a bug -- if it happens please file a bug report!
If this method raises any exception then it also sets :attr:`Connection.their_state` to :data:`ERROR` -- see :ref:`error-handling` for discussion.
"""
if self.their_state is ERROR: raise RemoteProtocolError("Can't receive data when peer state is ERROR") try: event = self._extract_next_receive_event() if event not in [NEED_DATA, PAUSED]: self._process_event(self.their_role, cast(Event, event)) if event is NEED_DATA: if len(self._receive_buffer) > self._max_incomplete_event_size: # 431 is "Request header fields too large" which is pretty # much the only situation where we can get here raise RemoteProtocolError( "Receive buffer too long", error_status_hint=431 ) if self._receive_buffer_closed: # We're still trying to complete some event, but that's # never going to happen because no more data is coming raise RemoteProtocolError("peer unexpectedly closed connection") return event except BaseException as exc: self._process_error(self.their_role) if isinstance(exc, LocalProtocolError): exc._reraise_as_remote_protocol_error() else: raise
@overload def send(self, event: ConnectionClosed) -> None: ...
@overload def send( self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage] ) -> bytes: ...
@overload def send(self, event: Event) -> Optional[bytes]: ...
def send(self, event: Event) -> Optional[bytes]: """Convert a high-level event into bytes that can be sent to the peer, while updating our internal state machine.
Args: event: The :ref:`event <events>` to send.
Returns: If ``type(event) is ConnectionClosed``, then returns ``None``. Otherwise, returns a :term:`bytes-like object`.
Raises: LocalProtocolError: Sending this event at this time would violate our understanding of the HTTP/1.1 protocol.
If this method raises any exception then it also sets :attr:`Connection.our_state` to :data:`ERROR` -- see :ref:`error-handling` for discussion.
""" data_list = self.send_with_data_passthrough(event) if data_list is None: return None else: return b"".join(data_list)
def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: """Identical to :meth:`send`, except that in situations where :meth:`send` returns a single :term:`bytes-like object`, this instead returns a list of them -- and when sending a :class:`Data` event, this list is guaranteed to contain the exact object you passed in as :attr:`Data.data`. See :ref:`sendfile` for discussion.
""" if self.our_state is ERROR: raise LocalProtocolError("Can't send data when our state is ERROR") try: if type(event) is Response: event = self._clean_up_response_headers_for_sending(event) # We want to call _process_event before calling the writer, # because if someone tries to do something invalid then this will # give a sensible error message, while our writers all just assume # they will only receive valid events. But, _process_event might # change self._writer. So we have to do a little dance: writer = self._writer self._process_event(self.our_role, event) if type(event) is ConnectionClosed: return None else: # In any situation where writer is None, process_event should # have raised ProtocolError assert writer is not None data_list: List[bytes] = [] writer(event, data_list.append) return data_list except: self._process_error(self.our_role) raise
def send_failed(self) -> None: """Notify the state machine that we failed to send the data it gave us.
This causes :attr:`Connection.our_state` to immediately become :data:`ERROR` -- see :ref:`error-handling` for discussion.
""" self._process_error(self.our_role)
# When sending a Response, we take responsibility for a few things: # # - Sometimes you MUST set Connection: close. We take care of those # times. (You can also set it yourself if you want, and if you do then # we'll respect that and close the connection at the right time. But you # don't have to worry about that unless you want to.) # # - The user has to set Content-Length if they want it. Otherwise, for # responses that have bodies (e.g. not HEAD), then we will automatically # select the right mechanism for streaming a body of unknown length, # which depends on depending on the peer's HTTP version. # # This function's *only* responsibility is making sure headers are set up # right -- everything downstream just looks at the headers. There are no # side channels. def _clean_up_response_headers_for_sending(self, response: Response) -> Response: assert type(response) is Response
headers = response.headers need_close = False
# HEAD requests need some special handling: they always act like they # have Content-Length: 0, and that's how _body_framing treats # them. But their headers are supposed to match what we would send if # the request was a GET. (Technically there is one deviation allowed: # we're allowed to leave out the framing headers -- see # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as # easy to get them right.) method_for_choosing_headers = cast(bytes, self._request_method) if method_for_choosing_headers == b"HEAD": method_for_choosing_headers = b"GET" framing_type, _ = _body_framing(method_for_choosing_headers, response) if framing_type in ("chunked", "http/1.0"): # This response has a body of unknown length. # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked # If our peer is HTTP/1.0, we use no framing headers, and close the # connection afterwards. # # Make sure to clear Content-Length (in principle user could have # set both and then we ignored Content-Length b/c # Transfer-Encoding overwrote it -- this would be naughty of them, # but the HTTP spec says that if our peer does this then we have # to fix it instead of erroring out, so we'll accord the user the # same respect). headers = set_comma_header(headers, b"content-length", []) if self.their_http_version is None or self.their_http_version < b"1.1": # Either we never got a valid request and are sending back an # error (their_http_version is None), so we assume the worst; # or else we did get a valid HTTP/1.0 request, so we know that # they don't understand chunked encoding. headers = set_comma_header(headers, b"transfer-encoding", []) # This is actually redundant ATM, since currently we # unconditionally disable keep-alive when talking to HTTP/1.0 # peers. But let's be defensive just in case we add # Connection: keep-alive support later: if self._request_method != b"HEAD": need_close = True else: headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"])
if not self._cstate.keep_alive or need_close: # Make sure Connection: close is set connection = set(get_comma_header(headers, b"connection")) connection.discard(b"keep-alive") connection.add(b"close") headers = set_comma_header(headers, b"connection", sorted(connection))
return Response( headers=headers, status_code=response.status_code, http_version=response.http_version, reason=response.reason, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369# High level events that make up HTTP/1.1 conversations. Loosely inspired by# the corresponding events in hyper-h2:## http://python-hyper.org/h2/en/stable/api.html#events## Don't subclass these. Stuff will break.
import refrom abc import ABCfrom dataclasses import dataclassfrom typing import List, Tuple, Union
from ._abnf import method, request_targetfrom ._headers import Headers, normalize_and_validatefrom ._util import bytesify, LocalProtocolError, validate
# Everything in __all__ gets re-exported as part of the h11 public API.__all__ = [ "Event", "Request", "InformationalResponse", "Response", "Data", "EndOfMessage", "ConnectionClosed",]
method_re = re.compile(method.encode("ascii"))request_target_re = re.compile(request_target.encode("ascii"))
class Event(ABC): """ Base class for h11 events. """
__slots__ = ()
@dataclass(init=False, frozen=True)class Request(Event): """The beginning of an HTTP request.
Fields:
.. attribute:: method
An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte string. :term:`Bytes-like objects <bytes-like object>` and native strings containing only ascii characters will be automatically converted to byte strings.
.. attribute:: target
The target of an HTTP request, e.g. ``b"/index.html"``, or one of the more exotic formats described in `RFC 7320, section 5.3 <https://tools.ietf.org/html/rfc7230#section-5.3>`_. Always a byte string. :term:`Bytes-like objects <bytes-like object>` and native strings containing only ascii characters will be automatically converted to byte strings.
.. attribute:: headers
Request headers, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
.. attribute:: http_version
The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details.
"""
__slots__ = ("method", "headers", "target", "http_version")
method: bytes headers: Headers target: bytes http_version: bytes
def __init__( self, *, method: Union[bytes, str], headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], target: Union[bytes, str], http_version: Union[bytes, str] = b"1.1", _parsed: bool = False, ) -> None: super().__init__() if isinstance(headers, Headers): object.__setattr__(self, "headers", headers) else: object.__setattr__( self, "headers", normalize_and_validate(headers, _parsed=_parsed) ) if not _parsed: object.__setattr__(self, "method", bytesify(method)) object.__setattr__(self, "target", bytesify(target)) object.__setattr__(self, "http_version", bytesify(http_version)) else: object.__setattr__(self, "method", method) object.__setattr__(self, "target", target) object.__setattr__(self, "http_version", http_version)
# "A server MUST respond with a 400 (Bad Request) status code to any # HTTP/1.1 request message that lacks a Host header field and to any # request message that contains more than one Host header field or a # Host header field with an invalid field-value." # -- https://tools.ietf.org/html/rfc7230#section-5.4 host_count = 0 for name, value in self.headers: if name == b"host": host_count += 1 if self.http_version == b"1.1" and host_count == 0: raise LocalProtocolError("Missing mandatory Host: header") if host_count > 1: raise LocalProtocolError("Found multiple Host: headers")
validate(method_re, self.method, "Illegal method characters") validate(request_target_re, self.target, "Illegal target characters")
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class _ResponseBase(Event): __slots__ = ("headers", "http_version", "reason", "status_code")
headers: Headers http_version: bytes reason: bytes status_code: int
def __init__( self, *, headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], status_code: int, http_version: Union[bytes, str] = b"1.1", reason: Union[bytes, str] = b"", _parsed: bool = False, ) -> None: super().__init__() if isinstance(headers, Headers): object.__setattr__(self, "headers", headers) else: object.__setattr__( self, "headers", normalize_and_validate(headers, _parsed=_parsed) ) if not _parsed: object.__setattr__(self, "reason", bytesify(reason)) object.__setattr__(self, "http_version", bytesify(http_version)) if not isinstance(status_code, int): raise LocalProtocolError("status code must be integer") # Because IntEnum objects are instances of int, but aren't # duck-compatible (sigh), see gh-72. object.__setattr__(self, "status_code", int(status_code)) else: object.__setattr__(self, "reason", reason) object.__setattr__(self, "http_version", http_version) object.__setattr__(self, "status_code", status_code)
self.__post_init__()
def __post_init__(self) -> None: pass
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class InformationalResponse(_ResponseBase): """An HTTP informational response.
Fields:
.. attribute:: status_code
The status code of this response, as an integer. For an :class:`InformationalResponse`, this is always in the range [100, 200).
.. attribute:: headers
Request headers, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
.. attribute:: http_version
The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details.
.. attribute:: reason
The reason phrase of this response, as a byte string. For example: ``b"OK"``, or ``b"Not Found"``.
"""
def __post_init__(self) -> None: if not (100 <= self.status_code < 200): raise LocalProtocolError( "InformationalResponse status_code should be in range " "[100, 200), not {}".format(self.status_code) )
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class Response(_ResponseBase): """The beginning of an HTTP response.
Fields:
.. attribute:: status_code
The status code of this response, as an integer. For an :class:`Response`, this is always in the range [200, 1000).
.. attribute:: headers
Request headers, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
.. attribute:: http_version
The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details.
.. attribute:: reason
The reason phrase of this response, as a byte string. For example: ``b"OK"``, or ``b"Not Found"``.
"""
def __post_init__(self) -> None: if not (200 <= self.status_code < 1000): raise LocalProtocolError( "Response status_code should be in range [200, 1000), not {}".format( self.status_code ) )
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class Data(Event): """Part of an HTTP message body.
Fields:
.. attribute:: data
A :term:`bytes-like object` containing part of a message body. Or, if using the ``combine=False`` argument to :meth:`Connection.send`, then any object that your socket writing code knows what to do with, and for which calling :func:`len` returns the number of bytes that will be written -- see :ref:`sendfile` for details.
.. attribute:: chunk_start
A marker that indicates whether this data object is from the start of a chunked transfer encoding chunk. This field is ignored when when a Data event is provided to :meth:`Connection.send`: it is only valid on events emitted from :meth:`Connection.next_event`. You probably shouldn't use this attribute at all; see :ref:`chunk-delimiters-are-bad` for details.
.. attribute:: chunk_end
A marker that indicates whether this data object is the last for a given chunked transfer encoding chunk. This field is ignored when when a Data event is provided to :meth:`Connection.send`: it is only valid on events emitted from :meth:`Connection.next_event`. You probably shouldn't use this attribute at all; see :ref:`chunk-delimiters-are-bad` for details.
"""
__slots__ = ("data", "chunk_start", "chunk_end")
data: bytes chunk_start: bool chunk_end: bool
def __init__( self, data: bytes, chunk_start: bool = False, chunk_end: bool = False ) -> None: object.__setattr__(self, "data", data) object.__setattr__(self, "chunk_start", chunk_start) object.__setattr__(self, "chunk_end", chunk_end)
# This is an unhashable type. __hash__ = None # type: ignore
# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that# are forbidden to be sent in a trailer, since processing them as if they were# present in the header section might bypass external security filters."# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part# Unfortunately, the list of forbidden fields is long and vague :-/@dataclass(init=False, frozen=True)class EndOfMessage(Event): """The end of an HTTP message.
Fields:
.. attribute:: headers
Default value: ``[]``
Any trailing headers attached to this message, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
Must be empty unless ``Transfer-Encoding: chunked`` is in use.
"""
__slots__ = ("headers",)
headers: Headers
def __init__( self, *, headers: Union[ Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None ] = None, _parsed: bool = False, ) -> None: super().__init__() if headers is None: headers = Headers([]) elif not isinstance(headers, Headers): headers = normalize_and_validate(headers, _parsed=_parsed)
object.__setattr__(self, "headers", headers)
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(frozen=True)class ConnectionClosed(Event): """This event indicates that the sender has closed their outgoing connection.
Note that this does not necessarily mean that they can't *receive* further data, because TCP connections are composed to two one-way channels which can be closed independently. See :ref:`closing` for details.
No fields. """
pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282import refrom typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_valuefrom ._util import bytesify, LocalProtocolError, validate
if TYPE_CHECKING: from ._events import Request
try: from typing import Literalexcept ImportError: from typing_extensions import Literal # type: ignore
CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1
# Facts# -----## Headers are:# keys: case-insensitive ascii# values: mixture of ascii and raw bytes## "Historically, HTTP has allowed field content with text in the ISO-8859-1# charset [ISO-8859-1], supporting other charsets only through use of# [RFC2047] encoding. In practice, most HTTP header field values use only a# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD# limit their field values to US-ASCII octets. A recipient SHOULD treat other# octets in field content (obs-text) as opaque data."# And it deprecates all non-ascii values## Leading/trailing whitespace in header names is forbidden## Values get leading/trailing whitespace stripped## Content-Disposition actually needs to contain unicode semantically; to# accomplish this it has a terrifically weird way of encoding the filename# itself as ascii (and even this still has lots of cross-browser# incompatibilities)## Order is important:# "a proxy MUST NOT change the order of these field values when forwarding a# message"# (and there are several headers where the order indicates a preference)## Multiple occurences of the same header:# "A sender MUST NOT generate multiple header fields with the same field name# in a message unless either the entire field value for that header field is# defined as a comma-separated list [or the header is Set-Cookie which gets a# special exception]" - RFC 7230. (cookies are in RFC 6265)## So every header aside from Set-Cookie can be merged by b", ".join if it# occurs repeatedly. But, of course, they can't necessarily be split by# .split(b","), because quoting.## Given all this mess (case insensitive, duplicates allowed, order is# important, ...), there doesn't appear to be any standard way to handle# headers in Python -- they're almost like dicts, but... actually just# aren't. For now we punt and just use a super simple representation: headers# are a list of pairs## [(name1, value1), (name2, value2), ...]## where all entries are bytestrings, names are lowercase and have no# leading/trailing whitespace, and values are bytestrings with no# leading/trailing whitespace. Searching and updating are done via naive O(n)# methods.## Maybe a dict-of-lists would be better?
_content_length_re = re.compile(rb"[0-9]+")_field_name_re = re.compile(field_name.encode("ascii"))_field_value_re = re.compile(field_value.encode("ascii"))
class Headers(Sequence[Tuple[bytes, bytes]]): """ A list-like interface that allows iterating over headers as byte-pairs of (lowercased-name, value).
Internally we actually store the representation as three-tuples, including both the raw original casing, in order to preserve casing over-the-wire, and the lowercased name, for case-insensitive comparisions.
r = Request( method="GET", target="/", headers=[("Host", "example.org"), ("Connection", "keep-alive")], http_version="1.1", ) assert r.headers == [ (b"host", b"example.org"), (b"connection", b"keep-alive") ] assert r.headers.raw_items() == [ (b"Host", b"example.org"), (b"Connection", b"keep-alive") ] """
__slots__ = "_full_items"
def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: self._full_items = full_items
def __bool__(self) -> bool: return bool(self._full_items)
def __eq__(self, other: object) -> bool: return list(self) == list(other) # type: ignore
def __len__(self) -> int: return len(self._full_items)
def __repr__(self) -> str: return "<Headers(%s)>" % repr(list(self))
def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override] _, name, value = self._full_items[idx] return (name, value)
def raw_items(self) -> List[Tuple[bytes, bytes]]: return [(raw_name, value) for raw_name, _, value in self._full_items]
HeaderTypes = Union[ List[Tuple[bytes, bytes]], List[Tuple[bytes, str]], List[Tuple[str, bytes]], List[Tuple[str, str]],]
@overloaddef normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: ...
@overloaddef normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: ...
@overloaddef normalize_and_validate( headers: Union[Headers, HeaderTypes], _parsed: bool = False) -> Headers: ...
def normalize_and_validate( headers: Union[Headers, HeaderTypes], _parsed: bool = False) -> Headers: new_headers = [] seen_content_length = None saw_transfer_encoding = False for name, value in headers: # For headers coming out of the parser, we can safely skip some steps, # because it always returns bytes and has already run these regexes # over the data: if not _parsed: name = bytesify(name) value = bytesify(value) validate(_field_name_re, name, "Illegal header name {!r}", name) validate(_field_value_re, value, "Illegal header value {!r}", value) assert isinstance(name, bytes) assert isinstance(value, bytes)
raw_name = name name = name.lower() if name == b"content-length": lengths = {length.strip() for length in value.split(b",")} if len(lengths) != 1: raise LocalProtocolError("conflicting Content-Length headers") value = lengths.pop() validate(_content_length_re, value, "bad Content-Length") if len(value) > CONTENT_LENGTH_MAX_DIGITS: raise LocalProtocolError("bad Content-Length") if seen_content_length is None: seen_content_length = value new_headers.append((raw_name, name, value)) elif seen_content_length != value: raise LocalProtocolError("conflicting Content-Length headers") elif name == b"transfer-encoding": # "A server that receives a request message with a transfer coding # it does not understand SHOULD respond with 501 (Not # Implemented)." # https://tools.ietf.org/html/rfc7230#section-3.3.1 if saw_transfer_encoding: raise LocalProtocolError( "multiple Transfer-Encoding headers", error_status_hint=501 ) # "All transfer-coding names are case-insensitive" # -- https://tools.ietf.org/html/rfc7230#section-4 value = value.lower() if value != b"chunked": raise LocalProtocolError( "Only Transfer-Encoding: chunked is supported", error_status_hint=501, ) saw_transfer_encoding = True new_headers.append((raw_name, name, value)) else: new_headers.append((raw_name, name, value)) return Headers(new_headers)
def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: # Should only be used for headers whose value is a list of # comma-separated, case-insensitive values. # # The header name `name` is expected to be lower-case bytes. # # Connection: meets these criteria (including cast insensitivity). # # Content-Length: technically is just a single value (1*DIGIT), but the # standard makes reference to implementations that do multiple values, and # using this doesn't hurt. Ditto, case insensitivity doesn't things either # way. # # Transfer-Encoding: is more complex (allows for quoted strings), so # splitting on , is actually wrong. For example, this is legal: # # Transfer-Encoding: foo; options="1,2", chunked # # and should be parsed as # # foo; options="1,2" # chunked # # but this naive function will parse it as # # foo; options="1 # 2" # chunked # # However, this is okay because the only thing we are going to do with # any Transfer-Encoding is reject ones that aren't just "chunked", so # both of these will be treated the same anyway. # # Expect: the only legal value is the literal string # "100-continue". Splitting on commas is harmless. Case insensitive. # out: List[bytes] = [] for _, found_name, found_raw_value in headers._full_items: if found_name == name: found_raw_value = found_raw_value.lower() for found_split_value in found_raw_value.split(b","): found_split_value = found_split_value.strip() if found_split_value: out.append(found_split_value) return out
def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers: # The header name `name` is expected to be lower-case bytes. # # Note that when we store the header we use title casing for the header # names, in order to match the conventional HTTP header style. # # Simply calling `.title()` is a blunt approach, but it's correct # here given the cases where we're using `set_comma_header`... # # Connection, Content-Length, Transfer-Encoding. new_headers: List[Tuple[bytes, bytes]] = [] for found_raw_name, found_name, found_raw_value in headers._full_items: if found_name != name: new_headers.append((found_raw_name, found_raw_value)) for new_value in new_values: new_headers.append((name.title(), new_value)) return normalize_and_validate(new_headers)
def has_expect_100_continue(request: "Request") -> bool: # https://tools.ietf.org/html/rfc7231#section-5.1.1 # "A server that receives a 100-continue expectation in an HTTP/1.0 request # MUST ignore that expectation." if request.http_version < b"1.1": return False expect = get_comma_header(request.headers, b"expect") return b"100-continue" in expect123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# Code to read HTTP data## Strategy: each reader is a callable which takes a ReceiveBuffer object, and# either:# 1) consumes some of it and returns an Event# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate()# and it might raise a LocalProtocolError, so simpler just to always use# this)# 3) returns None, meaning "I need more data"## If they have a .read_eof attribute, then this will be called if an EOF is# received -- but this is optional. Either way, the actual ConnectionClosed# event will be generated afterwards.## READERS is a dict describing how to pick a reader. It maps states to either:# - a reader# - or, for body readers, a dict of per-framing reader factories
import refrom typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union
from ._abnf import chunk_header, header_field, request_line, status_linefrom ._events import Data, EndOfMessage, InformationalResponse, Request, Responsefrom ._receivebuffer import ReceiveBufferfrom ._state import ( CLIENT, CLOSED, DONE, IDLE, MUST_CLOSE, SEND_BODY, SEND_RESPONSE, SERVER,)from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate
__all__ = ["READERS"]
header_field_re = re.compile(header_field.encode("ascii"))obs_fold_re = re.compile(rb"[ \t]+")
def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]: it = iter(lines) last: Optional[bytes] = None for line in it: match = obs_fold_re.match(line) if match: if last is None: raise LocalProtocolError("continuation line at start of headers") if not isinstance(last, bytearray): # Cast to a mutable type, avoiding copy on append to ensure O(n) time last = bytearray(last) last += b" " last += line[match.end() :] else: if last is not None: yield last last = line if last is not None: yield last
def _decode_header_lines( lines: Iterable[bytes],) -> Iterable[Tuple[bytes, bytes]]: for line in _obsolete_line_fold(lines): matches = validate(header_field_re, line, "illegal header line: {!r}", line) yield (matches["field_name"], matches["field_value"])
request_line_re = re.compile(request_line.encode("ascii"))
def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]: lines = buf.maybe_extract_lines() if lines is None: if buf.is_next_line_obviously_invalid_request_line(): raise LocalProtocolError("illegal request line") return None if not lines: raise LocalProtocolError("no request line received") matches = validate( request_line_re, lines[0], "illegal request line: {!r}", lines[0] ) return Request( headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches )
status_line_re = re.compile(status_line.encode("ascii"))
def maybe_read_from_SEND_RESPONSE_server( buf: ReceiveBuffer,) -> Union[InformationalResponse, Response, None]: lines = buf.maybe_extract_lines() if lines is None: if buf.is_next_line_obviously_invalid_request_line(): raise LocalProtocolError("illegal request line") return None if not lines: raise LocalProtocolError("no response line received") matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0]) http_version = ( b"1.1" if matches["http_version"] is None else matches["http_version"] ) reason = b"" if matches["reason"] is None else matches["reason"] status_code = int(matches["status_code"]) class_: Union[Type[InformationalResponse], Type[Response]] = ( InformationalResponse if status_code < 200 else Response ) return class_( headers=list(_decode_header_lines(lines[1:])), _parsed=True, status_code=status_code, reason=reason, http_version=http_version, )
class ContentLengthReader: def __init__(self, length: int) -> None: self._length = length self._remaining = length
def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: if self._remaining == 0: return EndOfMessage() data = buf.maybe_extract_at_most(self._remaining) if data is None: return None self._remaining -= len(data) return Data(data=data)
def read_eof(self) -> NoReturn: raise RemoteProtocolError( "peer closed connection without sending complete message body " "(received {} bytes, expected {})".format( self._length - self._remaining, self._length ) )
chunk_header_re = re.compile(chunk_header.encode("ascii"))
class ChunkedReader: def __init__(self) -> None: self._bytes_in_chunk = 0 # After reading a chunk, we have to throw away the trailing \r\n. # This tracks the bytes that we need to match and throw away. self._bytes_to_discard = b"" self._reading_trailer = False
def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: if self._reading_trailer: lines = buf.maybe_extract_lines() if lines is None: return None return EndOfMessage(headers=list(_decode_header_lines(lines))) if self._bytes_to_discard: data = buf.maybe_extract_at_most(len(self._bytes_to_discard)) if data is None: return None if data != self._bytes_to_discard[: len(data)]: raise LocalProtocolError( f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})" ) self._bytes_to_discard = self._bytes_to_discard[len(data) :] if self._bytes_to_discard: return None # else, fall through and read some more assert self._bytes_to_discard == b"" if self._bytes_in_chunk == 0: # We need to refill our chunk count chunk_header = buf.maybe_extract_next_line() if chunk_header is None: return None matches = validate( chunk_header_re, chunk_header, "illegal chunk header: {!r}", chunk_header, ) # XX FIXME: we discard chunk extensions. Does anyone care? self._bytes_in_chunk = int(matches["chunk_size"], base=16) if self._bytes_in_chunk == 0: self._reading_trailer = True return self(buf) chunk_start = True else: chunk_start = False assert self._bytes_in_chunk > 0 data = buf.maybe_extract_at_most(self._bytes_in_chunk) if data is None: return None self._bytes_in_chunk -= len(data) if self._bytes_in_chunk == 0: self._bytes_to_discard = b"\r\n" chunk_end = True else: chunk_end = False return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)
def read_eof(self) -> NoReturn: raise RemoteProtocolError( "peer closed connection without sending complete message body " "(incomplete chunked read)" )
class Http10Reader: def __call__(self, buf: ReceiveBuffer) -> Optional[Data]: data = buf.maybe_extract_at_most(999999999) if data is None: return None return Data(data=data)
def read_eof(self) -> EndOfMessage: return EndOfMessage()
def expect_nothing(buf: ReceiveBuffer) -> None: if buf: raise LocalProtocolError("Got data when expecting EOF") return None
ReadersType = Dict[ Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]], Union[Callable[..., Any], Dict[str, Callable[..., Any]]],]
READERS: ReadersType = { (CLIENT, IDLE): maybe_read_from_IDLE_client, (SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server, (SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server, (CLIENT, DONE): expect_nothing, (CLIENT, MUST_CLOSE): expect_nothing, (CLIENT, CLOSED): expect_nothing, (SERVER, DONE): expect_nothing, (SERVER, MUST_CLOSE): expect_nothing, (SERVER, CLOSED): expect_nothing, SEND_BODY: { "chunked": ChunkedReader, "content-length": ContentLengthReader, "http/1.0": Http10Reader, },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import reimport sysfrom typing import List, Optional, Union
__all__ = ["ReceiveBuffer"]
# Operations we want to support:# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable),# or wait until there is one# - read at-most-N bytes# Goals:# - on average, do this fast# - worst case, do this in O(n) where n is the number of bytes processed# Plan:# - store bytearray, offset, how far we've searched for a separator token# - use the how-far-we've-searched data to avoid rescanning# - while doing a stream of uninterrupted processing, advance offset instead# of constantly copying# WARNING:# - I haven't benchmarked or profiled any of this yet.## Note that starting in Python 3.4, deleting the initial n bytes from a# bytearray is amortized O(n), thanks to some excellent work by Antoine# Martin:## https://bugs.python.org/issue19087## This means that if we only supported 3.4+, we could get rid of the code here# involving self._start and self.compress, because it's doing exactly the same# thing that bytearray now does internally.## BUT unfortunately, we still support 2.7, and reading short segments out of a# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually# delete this code. Yet:## https://pythonclock.org/## (Two things to double-check first though: make sure PyPy also has the# optimization, and benchmark to make sure it's a win, since we do have a# slightly clever thing where we delay calling compress() until we've# processed a whole event, which could in theory be slightly more efficient# than the internal bytearray support.)blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE)
class ReceiveBuffer: def __init__(self) -> None: self._data = bytearray() self._next_line_search = 0 self._multiple_lines_search = 0
def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": self._data += byteslike return self
def __bool__(self) -> bool: return bool(len(self))
def __len__(self) -> int: return len(self._data)
# for @property unprocessed_data def __bytes__(self) -> bytes: return bytes(self._data)
def _extract(self, count: int) -> bytearray: # extracting an initial slice of the data buffer and return it out = self._data[:count] del self._data[:count]
self._next_line_search = 0 self._multiple_lines_search = 0
return out
def maybe_extract_at_most(self, count: int) -> Optional[bytearray]: """ Extract a fixed number of bytes from the buffer. """ out = self._data[:count] if not out: return None
return self._extract(count)
def maybe_extract_next_line(self) -> Optional[bytearray]: """ Extract the first line, if it is completed in the buffer. """ # Only search in buffer space that we've not already looked at. search_start_index = max(0, self._next_line_search - 1) partial_idx = self._data.find(b"\r\n", search_start_index)
if partial_idx == -1: self._next_line_search = len(self._data) return None
# + 2 is to compensate len(b"\r\n") idx = partial_idx + 2
return self._extract(idx)
def maybe_extract_lines(self) -> Optional[List[bytearray]]: """ Extract everything up to the first blank line, and return a list of lines. """ # Handle the case where we have an immediate empty line. if self._data[:1] == b"\n": self._extract(1) return []
if self._data[:2] == b"\r\n": self._extract(2) return []
# Only search in buffer space that we've not already looked at. match = blank_line_regex.search(self._data, self._multiple_lines_search) if match is None: self._multiple_lines_search = max(0, len(self._data) - 2) return None
# Truncate the buffer and return it. idx = match.span(0)[-1] out = self._extract(idx) lines = out.split(b"\n")
for line in lines: if line.endswith(b"\r"): del line[-1]
assert lines[-2] == lines[-1] == b""
del lines[-2:]
return lines
# In theory we should wait until `\r\n` before starting to validate # incoming data. However it's interesting to detect (very) invalid data # early given they might not even contain `\r\n` at all (hence only # timeout will get rid of them). # This is not a 100% effective detection but more of a cheap sanity check # allowing for early abort in some useful cases. # This is especially interesting when peer is messing up with HTTPS and # sent us a TLS stream where we were expecting plain HTTP given all # versions of TLS so far start handshake with a 0x16 message type code. def is_next_line_obviously_invalid_request_line(self) -> bool: try: # HTTP header line must not contain non-printable characters # and should not start with a space return self._data[0] < 0x21 except IndexError: return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365################################################################# The core state machine################################################################## Rule 1: everything that affects the state machine and state transitions must# live here in this file. As much as possible goes into the table-based# representation, but for the bits that don't quite fit, the actual code and# state must nonetheless live here.## Rule 2: this file does not know about what role we're playing; it only knows# about HTTP request/response cycles in the abstract. This ensures that we# don't cheat and apply different rules to local and remote parties.### Theory of operation# ===================## Possibly the simplest way to think about this is that we actually have 5# different state machines here. Yes, 5. These are:## 1) The client state, with its complicated automaton (see the docs)# 2) The server state, with its complicated automaton (see the docs)# 3) The keep-alive state, with possible states {True, False}# 4) The SWITCH_CONNECT state, with possible states {False, True}# 5) The SWITCH_UPGRADE state, with possible states {False, True}## For (3)-(5), the first state listed is the initial state.## (1)-(3) are stored explicitly in member variables. The last# two are stored implicitly in the pending_switch_proposals set as:# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals)# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals)## And each of these machines has two different kinds of transitions:## a) Event-triggered# b) State-triggered## Event triggered is the obvious thing that you'd think it is: some event# happens, and if it's the right event at the right time then a transition# happens. But there are somewhat complicated rules for which machines can# "see" which events. (As a rule of thumb, if a machine "sees" an event, this# means two things: the event can affect the machine, and if the machine is# not in a state where it expects that event then it's an error.) These rules# are:## 1) The client machine sees all h11.events objects emitted by the client.## 2) The server machine sees all h11.events objects emitted by the server.## It also sees the client's Request event.## And sometimes, server events are annotated with a _SWITCH_* event. For# example, we can have a (Response, _SWITCH_CONNECT) event, which is# different from a regular Response event.## 3) The keep-alive machine sees the process_keep_alive_disabled() event# (which is derived from Request/Response events), and this event# transitions it from True -> False, or from False -> False. There's no way# to transition back.## 4&5) The _SWITCH_* machines transition from False->True when we get a# Request that proposes the relevant type of switch (via# process_client_switch_proposals), and they go from True->False when we# get a Response that has no _SWITCH_* annotation.## So that's event-triggered transitions.## State-triggered transitions are less standard. What they do here is couple# the machines together. The way this works is, when certain *joint*# configurations of states are achieved, then we automatically transition to a# new *joint* state. So, for example, if we're ever in a joint state with## client: DONE# keep-alive: False## then the client state immediately transitions to:## client: MUST_CLOSE## This is fundamentally different from an event-based transition, because it# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive# transitioned True -> False. Either way, once this precondition is satisfied,# this transition is immediately triggered.## What if two conflicting state-based transitions get enabled at the same# time? In practice there's only one case where this arises (client DONE -># MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition.## Implementation# --------------## The event-triggered transitions for the server and client machines are all# stored explicitly in a table. Ditto for the state-triggered transitions that# involve just the server and client state.## The transitions for the other machines, and the state-triggered transitions# that involve the other machines, are written out as explicit Python code.## It'd be nice if there were some cleaner way to do all this. This isn't# *too* terrible, but I feel like it could probably be better.## WARNING# -------## The script that generates the state machine diagrams for the docs knows how# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS# tables. But it can't automatically read the transitions that are written# directly in Python code. So if you touch those, you need to also update the# script to keep it in sync!from typing import cast, Dict, Optional, Set, Tuple, Type, Union
from ._events import *from ._util import LocalProtocolError, Sentinel
# Everything in __all__ gets re-exported as part of the h11 public API.__all__ = [ "CLIENT", "SERVER", "IDLE", "SEND_RESPONSE", "SEND_BODY", "DONE", "MUST_CLOSE", "CLOSED", "MIGHT_SWITCH_PROTOCOL", "SWITCHED_PROTOCOL", "ERROR",]
class CLIENT(Sentinel, metaclass=Sentinel): pass
class SERVER(Sentinel, metaclass=Sentinel): pass
# Statesclass IDLE(Sentinel, metaclass=Sentinel): pass
class SEND_RESPONSE(Sentinel, metaclass=Sentinel): pass
class SEND_BODY(Sentinel, metaclass=Sentinel): pass
class DONE(Sentinel, metaclass=Sentinel): pass
class MUST_CLOSE(Sentinel, metaclass=Sentinel): pass
class CLOSED(Sentinel, metaclass=Sentinel): pass
class ERROR(Sentinel, metaclass=Sentinel): pass
# Switch typesclass MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel): pass
class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel): pass
class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel): pass
class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel): pass
EventTransitionType = Dict[ Type[Sentinel], Dict[ Type[Sentinel], Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]], ],]
EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = { CLIENT: { IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED}, SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, DONE: {ConnectionClosed: CLOSED}, MUST_CLOSE: {ConnectionClosed: CLOSED}, CLOSED: {ConnectionClosed: CLOSED}, MIGHT_SWITCH_PROTOCOL: {}, SWITCHED_PROTOCOL: {}, ERROR: {}, }, SERVER: { IDLE: { ConnectionClosed: CLOSED, Response: SEND_BODY, # Special case: server sees client Request events, in this form (Request, CLIENT): SEND_RESPONSE, }, SEND_RESPONSE: { InformationalResponse: SEND_RESPONSE, Response: SEND_BODY, (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL, (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL, }, SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, DONE: {ConnectionClosed: CLOSED}, MUST_CLOSE: {ConnectionClosed: CLOSED}, CLOSED: {ConnectionClosed: CLOSED}, SWITCHED_PROTOCOL: {}, ERROR: {}, },}
StateTransitionType = Dict[ Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]]]
# NB: there are also some special-case state-triggered transitions hard-coded# into _fire_state_triggered_transitions below.STATE_TRIGGERED_TRANSITIONS: StateTransitionType = { # (Client state, Server state) -> new states # Protocol negotiation (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL}, # Socket shutdown (CLOSED, DONE): {SERVER: MUST_CLOSE}, (CLOSED, IDLE): {SERVER: MUST_CLOSE}, (ERROR, DONE): {SERVER: MUST_CLOSE}, (DONE, CLOSED): {CLIENT: MUST_CLOSE}, (IDLE, CLOSED): {CLIENT: MUST_CLOSE}, (DONE, ERROR): {CLIENT: MUST_CLOSE},}
class ConnectionState: def __init__(self) -> None: # Extra bits of state that don't quite fit into the state model.
# If this is False then it enables the automatic DONE -> MUST_CLOSE # transition. Don't set this directly; call .keep_alive_disabled() self.keep_alive = True
# This is a subset of {UPGRADE, CONNECT}, containing the proposals # made by the client for switching protocols. self.pending_switch_proposals: Set[Type[Sentinel]] = set()
self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE}
def process_error(self, role: Type[Sentinel]) -> None: self.states[role] = ERROR self._fire_state_triggered_transitions()
def process_keep_alive_disabled(self) -> None: self.keep_alive = False self._fire_state_triggered_transitions()
def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: self.pending_switch_proposals.add(switch_event) self._fire_state_triggered_transitions()
def process_event( self, role: Type[Sentinel], event_type: Type[Event], server_switch_event: Optional[Type[Sentinel]] = None, ) -> None: _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type if server_switch_event is not None: assert role is SERVER if server_switch_event not in self.pending_switch_proposals: raise LocalProtocolError( "Received server _SWITCH_UPGRADE event without a pending proposal" ) _event_type = (event_type, server_switch_event) if server_switch_event is None and _event_type is Response: self.pending_switch_proposals = set() self._fire_event_triggered_transitions(role, _event_type) # Special case: the server state does get to see Request # events. if _event_type is Request: assert role is CLIENT self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) self._fire_state_triggered_transitions()
def _fire_event_triggered_transitions( self, role: Type[Sentinel], event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], ) -> None: state = self.states[role] try: new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type] except KeyError: event_type = cast(Type[Event], event_type) raise LocalProtocolError( "can't handle event type {} when role={} and state={}".format( event_type.__name__, role, self.states[role] ) ) from None self.states[role] = new_state
def _fire_state_triggered_transitions(self) -> None: # We apply these rules repeatedly until converging on a fixed point while True: start_states = dict(self.states)
# It could happen that both these special-case transitions are # enabled at the same time: # # DONE -> MIGHT_SWITCH_PROTOCOL # DONE -> MUST_CLOSE # # For example, this will always be true of a HTTP/1.0 client # requesting CONNECT. If this happens, the protocol switch takes # priority. From there the client will either go to # SWITCHED_PROTOCOL, in which case it's none of our business when # they close the connection, or else the server will deny the # request, in which case the client will go back to DONE and then # from there to MUST_CLOSE. if self.pending_switch_proposals: if self.states[CLIENT] is DONE: self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL
if not self.pending_switch_proposals: if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL: self.states[CLIENT] = DONE
if not self.keep_alive: for role in (CLIENT, SERVER): if self.states[role] is DONE: self.states[role] = MUST_CLOSE
# Tabular state-triggered transitions joint_state = (self.states[CLIENT], self.states[SERVER]) changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {}) self.states.update(changes)
if self.states == start_states: # Fixed point reached return
def start_next_cycle(self) -> None: if self.states != {CLIENT: DONE, SERVER: DONE}: raise LocalProtocolError( f"not in a reusable state. self.states={self.states}" ) # Can't reach DONE/DONE with any of these active, but still, let's be # sure. assert self.keep_alive assert not self.pending_switch_proposals self.states = {CLIENT: IDLE, SERVER: IDLE}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union
__all__ = [ "ProtocolError", "LocalProtocolError", "RemoteProtocolError", "validate", "bytesify",]
class ProtocolError(Exception): """Exception indicating a violation of the HTTP/1.1 protocol.
This as an abstract base class, with two concrete base classes: :exc:`LocalProtocolError`, which indicates that you tried to do something that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which indicates that the remote peer tried to do something that HTTP/1.1 says is illegal. See :ref:`error-handling` for details.
In addition to the normal :exc:`Exception` features, it has one attribute:
.. attribute:: error_status_hint
This gives a suggestion as to what status code a server might use if this error occurred as part of a request.
For a :exc:`RemoteProtocolError`, this is useful as a suggestion for how you might want to respond to a misbehaving peer, if you're implementing a server.
For a :exc:`LocalProtocolError`, this can be taken as a suggestion for how your peer might have responded to *you* if h11 had allowed you to continue.
The default is 400 Bad Request, a generic catch-all for protocol violations.
"""
def __init__(self, msg: str, error_status_hint: int = 400) -> None: if type(self) is ProtocolError: raise TypeError("tried to directly instantiate ProtocolError") Exception.__init__(self, msg) self.error_status_hint = error_status_hint
# Strategy: there are a number of public APIs where a LocalProtocolError can# be raised (send(), all the different event constructors, ...), and only one# public API where RemoteProtocolError can be raised# (receive_data()). Therefore we always raise LocalProtocolError internally,# and then receive_data will translate this into a RemoteProtocolError.## Internally:# LocalProtocolError is the generic "ProtocolError".# Externally:# LocalProtocolError is for local errors and RemoteProtocolError is for# remote errors.class LocalProtocolError(ProtocolError): def _reraise_as_remote_protocol_error(self) -> NoReturn: # After catching a LocalProtocolError, use this method to re-raise it # as a RemoteProtocolError. This method must be called from inside an # except: block. # # An easy way to get an equivalent RemoteProtocolError is just to # modify 'self' in place. self.__class__ = RemoteProtocolError # type: ignore # But the re-raising is somewhat non-trivial -- you might think that # now that we've modified the in-flight exception object, that just # doing 'raise' to re-raise it would be enough. But it turns out that # this doesn't work, because Python tracks the exception type # (exc_info[0]) separately from the exception object (exc_info[1]), # and we only modified the latter. So we really do need to re-raise # the new type explicitly. # On py3, the traceback is part of the exception object, so our # in-place modification preserved it and we can just re-raise: raise self
class RemoteProtocolError(ProtocolError): pass
def validate( regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any) -> Dict[str, bytes]: match = regex.fullmatch(data) if not match: if format_args: msg = msg.format(*format_args) raise LocalProtocolError(msg) return match.groupdict()
# Sentinel values## - Inherit identity-based comparison and hashing from object# - Have a nice repr# - Have a *bonus property*: type(sentinel) is sentinel## The bonus property is useful if you want to take the return value from# next_event() and do some sort of dispatch based on type(event).
_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel")
class Sentinel(type): def __new__( cls: Type[_T_Sentinel], name: str, bases: Tuple[type, ...], namespace: Dict[str, Any], **kwds: Any ) -> _T_Sentinel: assert bases == (Sentinel,) v = super().__new__(cls, name, bases, namespace, **kwds) v.__class__ = v # type: ignore return v
def __repr__(self) -> str: return self.__name__
# Used for methods, request targets, HTTP versions, header names, and header# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always# returns bytes.def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes: # Fast-path: if type(s) is bytes: return s if isinstance(s, str): s = s.encode("ascii") if isinstance(s, int): raise TypeError("expected bytes-like object, not int") return bytes(s)12345678910111213141516# This file must be kept very simple, because it is consumed from several# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
# We use a simple scheme:# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev# where the +dev versions are never released into the wild, they're just what# we stick into the VCS in between releases.## This is compatible with PEP 440:# http://legacy.python.org/dev/peps/pep-0440/# via the use of the "local suffix" "+dev", which is disallowed on index# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before*# 1.0.0.)
__version__ = "0.16.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145# Code to read HTTP data## Strategy: each writer takes an event + a write-some-bytes function, which is# calls.## WRITERS is a dict describing how to pick a reader. It maps states to either:# - a writer# - or, for body writers, a dict of framin-dependent writer factories
from typing import Any, Callable, Dict, List, Tuple, Type, Union
from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Responsefrom ._headers import Headersfrom ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVERfrom ._util import LocalProtocolError, Sentinel
__all__ = ["WRITERS"]
Writer = Callable[[bytes], Any]
def write_headers(headers: Headers, write: Writer) -> None: # "Since the Host field-value is critical information for handling a # request, a user agent SHOULD generate Host as the first header field # following the request-line." - RFC 7230 raw_items = headers._full_items for raw_name, name, value in raw_items: if name == b"host": write(b"%s: %s\r\n" % (raw_name, value)) for raw_name, name, value in raw_items: if name != b"host": write(b"%s: %s\r\n" % (raw_name, value)) write(b"\r\n")
def write_request(request: Request, write: Writer) -> None: if request.http_version != b"1.1": raise LocalProtocolError("I only send HTTP/1.1") write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target)) write_headers(request.headers, write)
# Shared between InformationalResponse and Responsedef write_any_response( response: Union[InformationalResponse, Response], write: Writer) -> None: if response.http_version != b"1.1": raise LocalProtocolError("I only send HTTP/1.1") status_bytes = str(response.status_code).encode("ascii") # We don't bother sending ascii status messages like "OK"; they're # optional and ignored by the protocol. (But the space after the numeric # status code is mandatory.) # # XX FIXME: could at least make an effort to pull out the status message # from stdlib's http.HTTPStatus table. Or maybe just steal their enums # (either by import or copy/paste). We already accept them as status codes # since they're of type IntEnum < int. write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason)) write_headers(response.headers, write)
class BodyWriter: def __call__(self, event: Event, write: Writer) -> None: if type(event) is Data: self.send_data(event.data, write) elif type(event) is EndOfMessage: self.send_eom(event.headers, write) else: # pragma: no cover assert False
def send_data(self, data: bytes, write: Writer) -> None: pass
def send_eom(self, headers: Headers, write: Writer) -> None: pass
## These are all careful not to do anything to 'data' except call len(data) and# write(data). This allows us to transparently pass-through funny objects,# like placeholder objects referring to files on disk that will be sent via# sendfile(2).#class ContentLengthWriter(BodyWriter): def __init__(self, length: int) -> None: self._length = length
def send_data(self, data: bytes, write: Writer) -> None: self._length -= len(data) if self._length < 0: raise LocalProtocolError("Too much data for declared Content-Length") write(data)
def send_eom(self, headers: Headers, write: Writer) -> None: if self._length != 0: raise LocalProtocolError("Too little data for declared Content-Length") if headers: raise LocalProtocolError("Content-Length and trailers don't mix")
class ChunkedWriter(BodyWriter): def send_data(self, data: bytes, write: Writer) -> None: # if we encoded 0-length data in the naive way, it would look like an # end-of-message. if not data: return write(b"%x\r\n" % len(data)) write(data) write(b"\r\n")
def send_eom(self, headers: Headers, write: Writer) -> None: write(b"0\r\n") write_headers(headers, write)
class Http10Writer(BodyWriter): def send_data(self, data: bytes, write: Writer) -> None: write(data)
def send_eom(self, headers: Headers, write: Writer) -> None: if headers: raise LocalProtocolError("can't send trailers to HTTP/1.0 client") # no need to close the socket ourselves, that will be taken care of by # Connection: close machinery
WritersType = Dict[ Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]], Union[ Dict[str, Type[BodyWriter]], Callable[[Union[InformationalResponse, Response], Writer], None], Callable[[Request, Writer], None], ],]
WRITERS: WritersType = { (CLIENT, IDLE): write_request, (SERVER, IDLE): write_any_response, (SERVER, SEND_RESPONSE): write_any_response, SEND_BODY: { "chunked": ChunkedWriter, "content-length": ContentLengthWriter, "http/1.0": Http10Writer, },}1Marker123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172""" pygments.lexers.cddl ~~~~~~~~~~~~~~~~~~~~
Lexer for the Concise data definition language (CDDL), a notational convention to express CBOR and JSON data structures.
More information: https://datatracker.ietf.org/doc/rfc8610/
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, wordsfrom pygments.token import Comment, Error, Keyword, Name, Number, Operator, \ Punctuation, String, Whitespace
__all__ = ['CddlLexer']
class CddlLexer(RegexLexer): """ Lexer for CDDL definitions. """ name = "CDDL" url = 'https://datatracker.ietf.org/doc/rfc8610/' aliases = ["cddl"] filenames = ["*.cddl"] mimetypes = ["text/x-cddl"] version_added = '2.8'
_prelude_types = [ "any", "b64legacy", "b64url", "bigfloat", "bigint", "bignint", "biguint", "bool", "bstr", "bytes", "cbor-any", "decfrac", "eb16", "eb64legacy", "eb64url", "encoded-cbor", "false", "float", "float16", "float16-32", "float32", "float32-64", "float64", "int", "integer", "mime-message", "nil", "nint", "null", "number", "regexp", "tdate", "text", "time", "true", "tstr", "uint", "undefined", "unsigned", "uri", ]
_controls = [ ".and", ".bits", ".cbor", ".cborseq", ".default", ".eq", ".ge", ".gt", ".le", ".lt", ".ne", ".regexp", ".size", ".within", ]
_re_id = ( r"[$@A-Z_a-z]" r"(?:[\-\.]+(?=[$@0-9A-Z_a-z])|[$@0-9A-Z_a-z])*"
)
# While the spec reads more like "an int must not start with 0" we use a # lookahead here that says "after a 0 there must be no digit". This makes the # '0' the invalid character in '01', which looks nicer when highlighted. _re_uint = r"(?:0b[01]+|0x[0-9a-fA-F]+|[1-9]\d*|0(?!\d))" _re_int = r"-?" + _re_uint
tokens = { "commentsandwhitespace": [(r"\s+", Whitespace), (r";.+$", Comment.Single)], "root": [ include("commentsandwhitespace"), # tag types (rf"#(\d\.{_re_uint})?", Keyword.Type), # type or any # occurrence ( rf"({_re_uint})?(\*)({_re_uint})?", bygroups(Number, Operator, Number), ), (r"\?|\+", Operator), # occurrence (r"\^", Operator), # cuts (r"(\.\.\.|\.\.)", Operator), # rangeop (words(_controls, suffix=r"\b"), Operator.Word), # ctlops # into choice op (rf"&(?=\s*({_re_id}|\())", Operator), (rf"~(?=\s*{_re_id})", Operator), # unwrap op (r"//|/(?!/)", Operator), # double und single slash (r"=>|/==|/=|=", Operator), (r"[\[\]{}\(\),<>:]", Punctuation), # Bytestrings (r"(b64)(')", bygroups(String.Affix, String.Single), "bstrb64url"), (r"(h)(')", bygroups(String.Affix, String.Single), "bstrh"), (r"'", String.Single, "bstr"), # Barewords as member keys (must be matched before values, types, typenames, # groupnames). # Token type is String as barewords are always interpreted as such. (rf"({_re_id})(\s*)(:)", bygroups(String, Whitespace, Punctuation)), # predefined types (words(_prelude_types, prefix=r"(?![\-_$@])\b", suffix=r"\b(?![\-_$@])"), Name.Builtin), # user-defined groupnames, typenames (_re_id, Name.Class), # values (r"0b[01]+", Number.Bin), (r"0o[0-7]+", Number.Oct), (r"0x[0-9a-fA-F]+(\.[0-9a-fA-F]+)?p[+-]?\d+", Number.Hex), # hexfloat (r"0x[0-9a-fA-F]+", Number.Hex), # hex # Float (rf"{_re_int}(?=(\.\d|e[+-]?\d))(?:\.\d+)?(?:e[+-]?\d+)?", Number.Float), # Int (_re_int, Number.Integer), (r'"(\\\\|\\"|[^"])*"', String.Double), ], "bstrb64url": [ (r"'", String.Single, "#pop"), include("commentsandwhitespace"), (r"\\.", String.Escape), (r"[0-9a-zA-Z\-_=]+", String.Single), (r".", Error), # (r";.+$", Token.Other), ], "bstrh": [ (r"'", String.Single, "#pop"), include("commentsandwhitespace"), (r"\\.", String.Escape), (r"[0-9a-fA-F]+", String.Single), (r".", Error), ], "bstr": [ (r"'", String.Single, "#pop"), (r"\\.", String.Escape), (r"[^'\\]+", String.Single), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139""" pygments.lexers.chapel ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Chapel language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, wordsfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ChapelLexer']
class ChapelLexer(RegexLexer): """ For Chapel source. """ name = 'Chapel' url = 'https://chapel-lang.org/' filenames = ['*.chpl'] aliases = ['chapel', 'chpl'] version_added = '2.0' # mimetypes = ['text/x-chapel']
known_types = ('bool', 'bytes', 'complex', 'imag', 'int', 'locale', 'nothing', 'opaque', 'range', 'real', 'string', 'uint', 'void')
type_modifiers_par = ('atomic', 'single', 'sync') type_modifiers_mem = ('borrowed', 'owned', 'shared', 'unmanaged') type_modifiers = (*type_modifiers_par, *type_modifiers_mem)
declarations = ('config', 'const', 'in', 'inout', 'out', 'param', 'ref', 'type', 'var')
constants = ('false', 'nil', 'none', 'true')
other_keywords = ('align', 'as', 'begin', 'break', 'by', 'catch', 'cobegin', 'coforall', 'continue', 'defer', 'delete', 'dmapped', 'do', 'domain', 'else', 'enum', 'except', 'export', 'extern', 'for', 'forall', 'foreach', 'forwarding', 'if', 'implements', 'import', 'index', 'init', 'inline', 'label', 'lambda', 'let', 'lifetime', 'local', 'new', 'noinit', 'on', 'only', 'otherwise', 'override', 'pragma', 'primitive', 'private', 'prototype', 'public', 'reduce', 'require', 'return', 'scan', 'select', 'serial', 'sparse', 'subdomain', 'then', 'this', 'throw', 'throws', 'try', 'use', 'when', 'where', 'while', 'with', 'yield', 'zip')
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'\\\n', Text),
(r'//(.*?)\n', Comment.Single), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
(words(declarations, suffix=r'\b'), Keyword.Declaration), (words(constants, suffix=r'\b'), Keyword.Constant), (words(known_types, suffix=r'\b'), Keyword.Type), (words((*type_modifiers, *other_keywords), suffix=r'\b'), Keyword),
(r'@', Keyword, 'attributename'), (r'(iter)(\s+)', bygroups(Keyword, Whitespace), 'procname'), (r'(proc)(\s+)', bygroups(Keyword, Whitespace), 'procname'), (r'(operator)(\s+)', bygroups(Keyword, Whitespace), 'procname'), (r'(class|interface|module|record|union)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
# imaginary integers (r'\d+i', Number), (r'\d+\.\d*([Ee][-+]\d+)?i', Number), (r'\.\d+([Ee][-+]\d+)?i', Number), (r'\d+[Ee][-+]\d+i', Number),
# reals cannot end with a period due to lexical ambiguity with # .. operator. See reference for rationale. (r'(\d*\.\d+)([eE][+-]?[0-9]+)?i?', Number.Float), (r'\d+[eE][+-]?[0-9]+i?', Number.Float),
# integer literals # -- binary (r'0[bB][01]+', Number.Bin), # -- hex (r'0[xX][0-9a-fA-F]+', Number.Hex), # -- octal (r'0[oO][0-7]+', Number.Oct), # -- decimal (r'[0-9]+', Number.Integer),
# strings (r'"(\\\\|\\"|[^"])*"', String), (r"'(\\\\|\\'|[^'])*'", String),
# tokens (r'(=|\+=|-=|\*=|/=|\*\*=|%=|&=|\|=|\^=|&&=|\|\|=|<<=|>>=|' r'<=>|<~>|\.\.|by|#|\.\.\.|' r'&&|\|\||!|&|\||\^|~|<<|>>|' r'==|!=|<=|>=|<|>|' r'[+\-*/%]|\*\*)', Operator), (r'[:;,.?()\[\]{}]', Punctuation),
# identifiers (r'[a-zA-Z_][\w$]*', Name.Other), ], 'classname': [ (r'[a-zA-Z_][\w$]*', Name.Class, '#pop'), ], 'procname': [ (r'([a-zA-Z_][.\w$]*|' # regular function name, including secondary r'\~[a-zA-Z_][.\w$]*|' # support for legacy destructors r'[+*/!~%<>=&^|\-:]{1,2})', # operators Name.Function, '#pop'),
# allow `proc (atomic T).foo` (r'\(', Punctuation, "receivertype"), (r'\)+\.', Punctuation), ], 'receivertype': [ (words(type_modifiers, suffix=r'\b'), Keyword), (words(known_types, suffix=r'\b'), Keyword.Type), (r'[^()]*', Name.Other, '#pop'), ], 'attributename': [ (r'[a-zA-Z_][.\w$]*', Name.Decorator, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180""" pygments.lexers.clean ~~~~~~~~~~~~~~~~~~~~~
Lexer for the Clean language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import ExtendedRegexLexer, words, default, include, bygroupsfrom pygments.token import Comment, Error, Keyword, Literal, Name, Number, \ Operator, Punctuation, String, Whitespace
__all__ = ['CleanLexer']
class CleanLexer(ExtendedRegexLexer): """ Lexer for the general purpose, state-of-the-art, pure and lazy functional programming language Clean.
.. versionadded: 2.2 """ name = 'Clean' url = 'http://clean.cs.ru.nl/Clean' aliases = ['clean'] filenames = ['*.icl', '*.dcl'] version_added = ''
keywords = ( 'case', 'ccall', 'class', 'code', 'code inline', 'derive', 'export', 'foreign', 'generic', 'if', 'in', 'infix', 'infixl', 'infixr', 'instance', 'let', 'of', 'otherwise', 'special', 'stdcall', 'where', 'with')
modulewords = ('implementation', 'definition', 'system')
lowerId = r'[a-z`][\w`]*' upperId = r'[A-Z`][\w`]*' funnyId = r'[~@#$%\^?!+\-*<>\\/|&=:]+' scoreUpperId = r'_' + upperId scoreLowerId = r'_' + lowerId moduleId = r'[a-zA-Z_][a-zA-Z0-9_.`]+' classId = '|'.join([lowerId, upperId, funnyId])
tokens = { 'root': [ include('comments'), include('keywords'), include('module'), include('import'), include('whitespace'), include('literals'), include('operators'), include('delimiters'), include('names'), ], 'whitespace': [ (r'\s+', Whitespace), ], 'comments': [ (r'//.*\n', Comment.Single), (r'/\*', Comment.Multiline, 'comments.in'), (r'/\*\*', Comment.Special, 'comments.in'), ], 'comments.in': [ (r'\*\/', Comment.Multiline, '#pop'), (r'/\*', Comment.Multiline, '#push'), (r'[^*/]+', Comment.Multiline), (r'\*(?!/)', Comment.Multiline), (r'/', Comment.Multiline), ], 'keywords': [ (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), ], 'module': [ (words(modulewords, prefix=r'\b', suffix=r'\b'), Keyword.Namespace), (r'\bmodule\b', Keyword.Namespace, 'module.name'), ], 'module.name': [ include('whitespace'), (moduleId, Name.Class, '#pop'), ], 'import': [ (r'\b(import)\b(\s*)', bygroups(Keyword, Whitespace), 'import.module'), (r'\b(from)\b(\s*)\b(' + moduleId + r')\b(\s*)\b(import)\b', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Keyword), 'import.what'), ], 'import.module': [ (r'\b(qualified)\b(\s*)', bygroups(Keyword, Whitespace)), (r'(\s*)\b(as)\b', bygroups(Whitespace, Keyword), ('#pop', 'import.module.as')), (moduleId, Name.Class), (r'(\s*)(,)(\s*)', bygroups(Whitespace, Punctuation, Whitespace)), (r'\s+', Whitespace), default('#pop'), ], 'import.module.as': [ include('whitespace'), (lowerId, Name.Class, '#pop'), (upperId, Name.Class, '#pop'), ], 'import.what': [ (r'\b(class)\b(\s+)(' + classId + r')', bygroups(Keyword, Whitespace, Name.Class), 'import.what.class'), (r'\b(instance)(\s+)(' + classId + r')(\s+)', bygroups(Keyword, Whitespace, Name.Class, Whitespace), 'import.what.instance'), (r'(::)(\s*)\b(' + upperId + r')\b', bygroups(Punctuation, Whitespace, Name.Class), 'import.what.type'), (r'\b(generic)\b(\s+)\b(' + lowerId + '|' + upperId + r')\b', bygroups(Keyword, Whitespace, Name)), include('names'), (r'(,)(\s+)', bygroups(Punctuation, Whitespace)), (r'$', Whitespace, '#pop'), include('whitespace'), ], 'import.what.class': [ (r',', Punctuation, '#pop'), (r'\(', Punctuation, 'import.what.class.members'), (r'$', Whitespace, '#pop:2'), include('whitespace'), ], 'import.what.class.members': [ (r',', Punctuation), (r'\.\.', Punctuation), (r'\)', Punctuation, '#pop'), include('names'), ], 'import.what.instance': [ (r'[,)]', Punctuation, '#pop'), (r'\(', Punctuation, 'import.what.instance'), (r'$', Whitespace, '#pop:2'), include('whitespace'), include('names'), ], 'import.what.type': [ (r',', Punctuation, '#pop'), (r'[({]', Punctuation, 'import.what.type.consesandfields'), (r'$', Whitespace, '#pop:2'), include('whitespace'), ], 'import.what.type.consesandfields': [ (r',', Punctuation), (r'\.\.', Punctuation), (r'[)}]', Punctuation, '#pop'), include('names'), ], 'literals': [ (r'\'([^\'\\]|\\(x[\da-fA-F]+|\d+|.))\'', Literal.Char), (r'[+~-]?0[0-7]+\b', Number.Oct), (r'[+~-]?\d+\.\d+(E[+-]?\d+)?', Number.Float), (r'[+~-]?\d+\b', Number.Integer), (r'[+~-]?0x[\da-fA-F]+\b', Number.Hex), (r'True|False', Literal), (r'"', String.Double, 'literals.stringd'), ], 'literals.stringd': [ (r'[^\\"\n]+', String.Double), (r'"', String.Double, '#pop'), (r'\\.', String.Double), (r'[$\n]', Error, '#pop'), ], 'operators': [ (r'[-~@#$%\^?!+*<>\\/|&=:.]+', Operator), (r'\b_+\b', Operator), ], 'delimiters': [ (r'[,;(){}\[\]]', Punctuation), (r'(\')([\w`.]+)(\')', bygroups(Punctuation, Name.Class, Punctuation)), ], 'names': [ (lowerId, Name), (scoreLowerId, Name), (funnyId, Name.Function), (upperId, Name.Class), (scoreUpperId, Name.Class), ] }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980""" pygments.lexers.codeql ~~~~~~~~~~~~~~~~~~~~~~
Lexer for CodeQL query language.
The grammar is originating from: https://github.com/github/vscode-codeql/blob/main/syntaxes/README.md
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
__all__ = ['CodeQLLexer']
import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
class CodeQLLexer(RegexLexer): name = 'CodeQL' aliases = ['codeql', 'ql'] filenames = ['*.ql', '*.qll'] mimetypes = [] url = 'https://github.com/github/codeql' version_added = '2.19'
flags = re.MULTILINE | re.UNICODE
tokens = { 'root': [ # Whitespace and comments (r'\s+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*', Comment.Multiline, 'multiline-comments'),
# Keywords (words(( 'module', 'import', 'class', 'extends', 'implements', 'predicate', 'select', 'where', 'from', 'as', 'and', 'or', 'not', 'in', 'if', 'then', 'else', 'exists', 'forall', 'instanceof', 'private', 'predicate', 'abstract', 'cached', 'external', 'final', 'library', 'override', 'query' ), suffix=r'\b'), Keyword.Builtin),
# Special Keywords (words(('this'), # class related keywords prefix=r'\b', suffix=r'\b\??:?'), Name.Builtin.Pseudo),
# Types (words(( 'boolean', 'date', 'float', 'int', 'string' ), suffix=r'\b'), Keyword.Type),
# Literals (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r'[0-9]+\.[0-9]+', Number.Float), (r'[0-9]+', Number.Integer), # Operators (r'<=|>=|<|>|=|!=|\+|-|\*|/', Operator),
# Punctuation (r'[.,;:\[\]{}()]+', Punctuation),
# Identifiers (r'@[a-zA-Z_]\w*', Name.Variable), # Variables with @ prefix (r'[A-Z][a-zA-Z0-9_]*', Name.Class), # Types and classes (r'[a-z][a-zA-Z0-9_]*', Name.Variable), # Variables and predicates ], 'multiline-comments': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ],
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081""" pygments.lexers.comal ~~~~~~~~~~~~~~~~~~~~~
Lexer for COMAL-80.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Whitespace, Operator, Keyword, String, \ Number, Name, Punctuation
__all__ = ["Comal80Lexer"]
class Comal80Lexer(RegexLexer): """ For COMAL-80 source code. """
name = 'COMAL-80' url = 'https://en.wikipedia.org/wiki/COMAL' aliases = ['comal', 'comal80'] filenames = ['*.cml', '*.comal'] version_added = '' flags = re.IGNORECASE # # COMAL allows for some strange characters in names which we list here so # keywords and word operators will not be recognized at the start of an # identifier. # _suffix = r"\b(?!['\[\]โยฃ\\])" _identifier = r"[a-z]['\[\]โยฃ\\\w]*"
tokens = { 'root': [ (r'//.*\n', Comment.Single), (r'\s+', Whitespace), (r':[=+-]|\<\>|[-+*/^โ<>=]', Operator), (r'(and +then|or +else)' + _suffix, Operator.Word), (words([ 'and', 'bitand', 'bitor', 'bitxor', 'div', 'in', 'mod', 'not', 'or'], suffix=_suffix,), Operator.Word), (words([ 'append', 'at', 'case', 'chain', 'close', 'copy', 'create', 'cursor', 'data', 'delete', 'dir', 'do', 'elif', 'else', 'end', 'endcase', 'endif', 'endfor', 'endloop', 'endtrap', 'endwhile', 'exec', 'exit', 'file', 'for', 'goto', 'handler', 'if', 'input', 'let', 'loop', 'mount', 'null', 'of', 'open', 'otherwise', 'output', 'page', 'pass', 'poke', 'print', 'random', 'read', 'repeat', 'report', 'return', 'rename', 'restore', 'select', 'step', 'stop', 'sys', 'then', 'to', 'trap', 'unit', 'unit$', 'until', 'using', 'when', 'while', 'write', 'zone'], suffix=_suffix), Keyword.Reserved), (words([ 'closed', 'dim', 'endfunc', 'endproc', 'external', 'func', 'import', 'proc', 'ref', 'use'], suffix=_suffix), Keyword.Declaration), (words([ 'abs', 'atn', 'chr$', 'cos', 'eod', 'eof', 'err', 'errfile', 'errtext', 'esc', 'exp', 'int', 'key$', 'len', 'log', 'ord', 'peek', 'randomize', 'rnd', 'sgn', 'sin', 'spc$', 'sqr', 'status$', 'str$', 'tab', 'tan', 'time', 'val'], suffix=_suffix), Name.Builtin), (words(['false', 'pi', 'true'], suffix=_suffix), Keyword.Constant), (r'"', String, 'string'), (_identifier + r":(?=[ \n/])", Name.Label), (_identifier + r"[$#]?", Name), (r'%[01]+', Number.Bin), (r'\$[0-9a-f]+', Number.Hex), (r'\d*\.\d*(e[-+]?\d+)?', Number.Float), (r'\d+', Number.Integer), (r'[(),:;]', Punctuation), ], 'string': [ (r'[^"]+', String), (r'"[0-9]*"', String.Escape), (r'"', String, '#pop'), ], }1234567891011121314151617181920212223242526272829303132333435""" pygments.lexers.compiled ~~~~~~~~~~~~~~~~~~~~~~~~
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: F401from pygments.lexers.jvm import JavaLexer, ScalaLexerfrom pygments.lexers.c_cpp import CLexer, CppLexerfrom pygments.lexers.d import DLexerfrom pygments.lexers.objective import ObjectiveCLexer, \ ObjectiveCppLexer, LogosLexerfrom pygments.lexers.go import GoLexerfrom pygments.lexers.rust import RustLexerfrom pygments.lexers.c_like import ECLexer, ValaLexer, CudaLexerfrom pygments.lexers.pascal import DelphiLexer, PortugolLexer, Modula2Lexerfrom pygments.lexers.ada import AdaLexerfrom pygments.lexers.business import CobolLexer, CobolFreeformatLexerfrom pygments.lexers.fortran import FortranLexerfrom pygments.lexers.prolog import PrologLexerfrom pygments.lexers.python import CythonLexerfrom pygments.lexers.graphics import GLShaderLexerfrom pygments.lexers.ml import OcamlLexerfrom pygments.lexers.basic import BlitzBasicLexer, BlitzMaxLexer, MonkeyLexerfrom pygments.lexers.dylan import DylanLexer, DylanLidLexer, DylanConsoleLexerfrom pygments.lexers.ooc import OocLexerfrom pygments.lexers.felix import FelixLexerfrom pygments.lexers.nimrod import NimrodLexerfrom pygments.lexers.crystal import CrystalLexer
__all__ = []12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433""" pygments.lexers.configs ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for configuration file formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, default, words, \ bygroups, include, using, line_refrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace, Literal, Error, Genericfrom pygments.lexers.shell import BashLexerfrom pygments.lexers.data import JsonLexer
__all__ = ['IniLexer', 'SystemdLexer', 'DesktopLexer', 'RegeditLexer', 'PropertiesLexer', 'KconfigLexer', 'Cfengine3Lexer', 'ApacheConfLexer', 'SquidConfLexer', 'NginxConfLexer', 'LighttpdConfLexer', 'DockerLexer', 'TerraformLexer', 'TermcapLexer', 'TerminfoLexer', 'PkgConfigLexer', 'PacmanConfLexer', 'AugeasLexer', 'TOMLLexer', 'NestedTextLexer', 'SingularityLexer', 'UnixConfigLexer']
class IniLexer(RegexLexer): """ Lexer for configuration files in INI style. """
name = 'INI' aliases = ['ini', 'cfg', 'dosini'] filenames = [ '*.ini', '*.cfg', '*.inf', '.editorconfig', ] mimetypes = ['text/x-ini', 'text/inf'] url = 'https://en.wikipedia.org/wiki/INI_file' version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace), (r'[;#].*', Comment.Single), (r'(\[.*?\])([ \t]*)$', bygroups(Keyword, Whitespace)), (r'''(.*?)([ \t]*)([=:])([ \t]*)(["'])''', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String), "quoted_value"), (r'(.*?)([ \t]*)([=:])([ \t]*)([^;#\n]*)(\\)(\s+)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Text, Whitespace), "value"), (r'(.*?)([ \t]*)([=:])([ \t]*)([^ ;#\n]*(?: +[^ ;#\n]+)*)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), # standalone option, supported by some INI parsers (r'(.+?)$', Name.Attribute), ], 'quoted_value': [ (r'''([^"'\n]*)(["'])(\s*)''', bygroups(String, String, Whitespace), "#pop"), (r'[;#].*', Comment.Single), (r'$', String, "#pop"), ], 'value': [ # line continuation (r'\s+', Whitespace), (r'(\s*)(.*)(\\)([ \t]*)', bygroups(Whitespace, String, Text, Whitespace)), (r'.*$', String, "#pop"), ], }
def analyse_text(text): npos = text.find('\n') if npos < 3: return False if text[0] == '[' and text[npos-1] == ']': return 0.8 return False
class DesktopLexer(RegexLexer): """ Lexer for .desktop files. """
name = 'Desktop file' url = "https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html" aliases = ['desktop'] filenames = ['*.desktop'] mimetypes = ['application/x-desktop'] version_added = '2.16'
tokens = { 'root': [ (r'^[ \t]*\n', Whitespace), (r'^(#.*)(\n)', bygroups(Comment.Single, Whitespace)), (r'(\[[^\]\n]+\])(\n)', bygroups(Keyword, Whitespace)), (r'([-A-Za-z0-9]+)(\[[^\] \t=]+\])?([ \t]*)(=)([ \t]*)([^\n]*)([ \t\n]*\n)', bygroups(Name.Attribute, Name.Namespace, Whitespace, Operator, Whitespace, String, Whitespace)), ], }
def analyse_text(text): if text.startswith("[Desktop Entry]"): return 1.0 if re.search(r"^\[Desktop Entry\][ \t]*$", text[:500], re.MULTILINE) is not None: return 0.9 return 0.0
class SystemdLexer(RegexLexer): """ Lexer for systemd unit files. """
name = 'Systemd' url = "https://www.freedesktop.org/software/systemd/man/systemd.syntax.html" aliases = ['systemd'] filenames = [ '*.service', '*.socket', '*.device', '*.mount', '*.automount', '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope', ] version_added = '2.16'
tokens = { 'root': [ (r'^[ \t]*\n', Whitespace), (r'^([;#].*)(\n)', bygroups(Comment.Single, Whitespace)), (r'(\[[^\]\n]+\])(\n)', bygroups(Keyword, Whitespace)), (r'([^=]+)([ \t]*)(=)([ \t]*)([^\n]*)(\\)(\n)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Text, Whitespace), "value"), (r'([^=]+)([ \t]*)(=)([ \t]*)([^\n]*)(\n)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String, Whitespace)), ], 'value': [ # line continuation (r'^([;#].*)(\n)', bygroups(Comment.Single, Whitespace)), (r'([ \t]*)([^\n]*)(\\)(\n)', bygroups(Whitespace, String, Text, Whitespace)), (r'([ \t]*)([^\n]*)(\n)', bygroups(Whitespace, String, Whitespace), "#pop"), ], }
def analyse_text(text): if text.startswith("[Unit]"): return 1.0 if re.search(r"^\[Unit\][ \t]*$", text[:500], re.MULTILINE) is not None: return 0.9 return 0.0
class RegeditLexer(RegexLexer): """ Lexer for Windows Registry files produced by regedit. """
name = 'reg' url = 'http://en.wikipedia.org/wiki/Windows_Registry#.REG_files' aliases = ['registry'] filenames = ['*.reg'] mimetypes = ['text/x-windows-registry'] version_added = '1.6'
tokens = { 'root': [ (r'Windows Registry Editor.*', Text), (r'\s+', Whitespace), (r'[;#].*', Comment.Single), (r'(\[)(-?)(HKEY_[A-Z_]+)(.*?\])$', bygroups(Keyword, Operator, Name.Builtin, Keyword)), # String keys, which obey somewhat normal escaping (r'("(?:\\"|\\\\|[^"])+")([ \t]*)(=)([ \t]*)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace), 'value'), # Bare keys (includes @) (r'(.*?)([ \t]*)(=)([ \t]*)', bygroups(Name.Attribute, Whitespace, Operator, Whitespace), 'value'), ], 'value': [ (r'-', Operator, '#pop'), # delete value (r'(dword|hex(?:\([0-9a-fA-F]\))?)(:)([0-9a-fA-F,]+)', bygroups(Name.Variable, Punctuation, Number), '#pop'), # As far as I know, .reg files do not support line continuation. (r'.+', String, '#pop'), default('#pop'), ] }
def analyse_text(text): return text.startswith('Windows Registry Editor')
class PropertiesLexer(RegexLexer): """ Lexer for configuration files in Java's properties format.
Note: trailing whitespace counts as part of the value as per spec """
name = 'Properties' aliases = ['properties', 'jproperties'] filenames = ['*.properties'] mimetypes = ['text/x-java-properties'] url = 'https://en.wikipedia.org/wiki/.properties' version_added = '1.4'
tokens = { 'root': [ # comments (r'[!#].*|/{2}.*', Comment.Single), # ending a comment or whitespace-only line (r'\n', Whitespace), # eat whitespace at the beginning of a line (r'^[^\S\n]+', Whitespace), # start lexing a key default('key'), ], 'key': [ # non-escaped key characters (r'[^\\:=\s]+', Name.Attribute), # escapes include('escapes'), # separator is the first non-escaped whitespace or colon or '=' on the line; # if it's whitespace, = and : are gobbled after it (r'([^\S\n]*)([:=])([^\S\n]*)', bygroups(Whitespace, Operator, Whitespace), ('#pop', 'value')), (r'[^\S\n]+', Whitespace, ('#pop', 'value')), # maybe we got no value after all (r'\n', Whitespace, '#pop'), ], 'value': [ # non-escaped value characters (r'[^\\\n]+', String), # escapes include('escapes'), # end the value on an unescaped newline (r'\n', Whitespace, '#pop'), ], 'escapes': [ # line continuations; these gobble whitespace at the beginning of the next line (r'(\\\n)([^\S\n]*)', bygroups(String.Escape, Whitespace)), # other escapes (r'\\(.|\n)', String.Escape), ], }
def _rx_indent(level): # Kconfig *always* interprets a tab as 8 spaces, so this is the default. # Edit this if you are in an environment where KconfigLexer gets expanded # input (tabs expanded to spaces) and the expansion tab width is != 8, # e.g. in connection with Trac (trac.ini, [mimeviewer], tab_width). # Value range here is 2 <= {tab_width} <= 8. tab_width = 8 # Regex matching a given indentation {level}, assuming that indentation is # a multiple of {tab_width}. In other cases there might be problems. if tab_width == 2: space_repeat = '+' else: space_repeat = '{1,%d}' % (tab_width - 1) if level == 1: level_repeat = '' else: level_repeat = f'{{{level}}}' return rf'(?:\t| {space_repeat}\t| {{{tab_width}}}){level_repeat}.*\n'
class KconfigLexer(RegexLexer): """ For Linux-style Kconfig files. """
name = 'Kconfig' aliases = ['kconfig', 'menuconfig', 'linux-config', 'kernel-config'] version_added = '1.6' # Adjust this if new kconfig file names appear in your environment filenames = ['Kconfig*', '*Config.in*', 'external.in*', 'standard-modules.in'] mimetypes = ['text/x-kconfig'] url = 'https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html'
# No re.MULTILINE, indentation-aware help text needs line-by-line handling flags = 0
def call_indent(level): # If indentation >= {level} is detected, enter state 'indent{level}' return (_rx_indent(level), String.Doc, f'indent{level}')
def do_indent(level): # Print paragraphs of indentation level >= {level} as String.Doc, # ignoring blank lines. Then return to 'root' state. return [ (_rx_indent(level), String.Doc), (r'\s*\n', Text), default('#pop:2') ]
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*?\n', Comment.Single), (words(( 'mainmenu', 'config', 'menuconfig', 'choice', 'endchoice', 'comment', 'menu', 'endmenu', 'visible if', 'if', 'endif', 'source', 'prompt', 'select', 'depends on', 'default', 'range', 'option'), suffix=r'\b'), Keyword), (r'(---help---|help)[\t ]*\n', Keyword, 'help'), (r'(bool|tristate|string|hex|int|defconfig_list|modules|env)\b', Name.Builtin), (r'[!=&|]', Operator), (r'[()]', Punctuation), (r'[0-9]+', Number.Integer), (r"'(''|[^'])*'", String.Single), (r'"(""|[^"])*"', String.Double), (r'\S+', Text), ], # Help text is indented, multi-line and ends when a lower indentation # level is detected. 'help': [ # Skip blank lines after help token, if any (r'\s*\n', Text), # Determine the first help line's indentation level heuristically(!). # Attention: this is not perfect, but works for 99% of "normal" # indentation schemes up to a max. indentation level of 7. call_indent(7), call_indent(6), call_indent(5), call_indent(4), call_indent(3), call_indent(2), call_indent(1), default('#pop'), # for incomplete help sections without text ], # Handle text for indentation levels 7 to 1 'indent7': do_indent(7), 'indent6': do_indent(6), 'indent5': do_indent(5), 'indent4': do_indent(4), 'indent3': do_indent(3), 'indent2': do_indent(2), 'indent1': do_indent(1), }
class Cfengine3Lexer(RegexLexer): """ Lexer for CFEngine3 policy files. """
name = 'CFEngine3' url = 'http://cfengine.org' aliases = ['cfengine3', 'cf3'] filenames = ['*.cf'] mimetypes = [] version_added = '1.5'
tokens = { 'root': [ (r'#.*?\n', Comment), (r'(body)(\s+)(\S+)(\s+)(control)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)), (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)(\()', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function, Punctuation), 'arglist'), (r'(body|bundle)(\s+)(\S+)(\s+)(\w+)', bygroups(Keyword, Whitespace, Keyword, Whitespace, Name.Function)), (r'(")([^"]+)(")(\s+)(string|slist|int|real)(\s*)(=>)(\s*)', bygroups(Punctuation, Name.Variable, Punctuation, Whitespace, Keyword.Type, Whitespace, Operator, Whitespace)), (r'(\S+)(\s*)(=>)(\s*)', bygroups(Keyword.Reserved, Whitespace, Operator, Text)), (r'"', String, 'string'), (r'(\w+)(\()', bygroups(Name.Function, Punctuation)), (r'([\w.!&|()]+)(::)', bygroups(Name.Class, Punctuation)), (r'(\w+)(:)', bygroups(Keyword.Declaration, Punctuation)), (r'@[{(][^)}]+[})]', Name.Variable), (r'[(){},;]', Punctuation), (r'=>', Operator), (r'->', Operator), (r'\d+\.\d+', Number.Float), (r'\d+', Number.Integer), (r'\w+', Name.Function), (r'\s+', Whitespace), ], 'string': [ (r'\$[{(]', String.Interpol, 'interpol'), (r'\\.', String.Escape), (r'"', String, '#pop'), (r'\n', String), (r'.', String), ], 'interpol': [ (r'\$[{(]', String.Interpol, '#push'), (r'[})]', String.Interpol, '#pop'), (r'[^${()}]+', String.Interpol), ], 'arglist': [ (r'\)', Punctuation, '#pop'), (r',', Punctuation), (r'\w+', Name.Variable), (r'\s+', Whitespace), ], }
class ApacheConfLexer(RegexLexer): """ Lexer for configuration files following the Apache config file format. """
name = 'ApacheConf' aliases = ['apacheconf', 'aconf', 'apache'] filenames = ['.htaccess', 'apache.conf', 'apache2.conf'] mimetypes = ['text/x-apacheconf'] url = 'https://httpd.apache.org/docs/current/configuring.html' version_added = '0.6' flags = re.MULTILINE | re.IGNORECASE
tokens = { 'root': [ (r'\s+', Whitespace), (r'#(.*\\\n)+.*$|(#.*?)$', Comment), (r'(<[^\s>/][^\s>]*)(?:(\s+)(.*))?(>)', bygroups(Name.Tag, Whitespace, String, Name.Tag)), (r'(</[^\s>]+)(>)', bygroups(Name.Tag, Name.Tag)), (r'[a-z]\w*', Name.Builtin, 'value'), (r'\.+', Text), ], 'value': [ (r'\\\n', Text), (r'\n+', Whitespace, '#pop'), (r'\\', Text), (r'[^\S\n]+', Whitespace), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'\d+', Number), (r'/([*a-z0-9][*\w./-]+)', String.Other), (r'(on|off|none|any|all|double|email|dns|min|minimal|' r'os|productonly|full|emerg|alert|crit|error|warn|' r'notice|info|debug|registry|script|inetd|standalone|' r'user|group)\b', Keyword), (r'"([^"\\]*(?:\\(.|\n)[^"\\]*)*)"', String.Double), (r'[^\s"\\]+', Text) ], }
class SquidConfLexer(RegexLexer): """ Lexer for squid configuration files. """
name = 'SquidConf' url = 'http://www.squid-cache.org/' aliases = ['squidconf', 'squid.conf', 'squid'] filenames = ['squid.conf'] mimetypes = ['text/x-squidconf'] version_added = '0.9' flags = re.IGNORECASE
keywords = ( "access_log", "acl", "always_direct", "announce_host", "announce_period", "announce_port", "announce_to", "anonymize_headers", "append_domain", "as_whois_server", "auth_param_basic", "authenticate_children", "authenticate_program", "authenticate_ttl", "broken_posts", "buffered_logs", "cache_access_log", "cache_announce", "cache_dir", "cache_dns_program", "cache_effective_group", "cache_effective_user", "cache_host", "cache_host_acl", "cache_host_domain", "cache_log", "cache_mem", "cache_mem_high", "cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer", "cache_peer_access", "cache_replacement_policy", "cache_stoplist", "cache_stoplist_pattern", "cache_store_log", "cache_swap", "cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db", "client_lifetime", "client_netmask", "connect_timeout", "coredump_dir", "dead_peer_timeout", "debug_options", "delay_access", "delay_class", "delay_initial_bucket_level", "delay_parameters", "delay_pools", "deny_info", "dns_children", "dns_defnames", "dns_nameservers", "dns_testnames", "emulate_httpd_log", "err_html_text", "fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port", "fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width", "ftp_passive", "ftp_user", "half_closed_clients", "header_access", "header_replace", "hierarchy_stoplist", "high_response_time_warning", "high_page_fault_warning", "hosts_file", "htcp_port", "http_access", "http_anonymizer", "httpd_accel", "httpd_accel_host", "httpd_accel_port", "httpd_accel_uses_host_header", "httpd_accel_with_proxy", "http_port", "http_reply_access", "icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout", "ident_lookup", "ident_lookup_access", "ident_timeout", "incoming_http_average", "incoming_icp_average", "inside_firewall", "ipcache_high", "ipcache_low", "ipcache_size", "local_domain", "local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries", "log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries", "mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr", "mcast_miss_encode_key", "mcast_miss_port", "memory_pools", "memory_pools_limit", "memory_replacement_policy", "mime_table", "min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops", "minimum_object_size", "minimum_retry_timeout", "miss_access", "negative_dns_ttl", "negative_ttl", "neighbor_timeout", "neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period", "netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy", "pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl", "prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp", "quick_abort", "quick_abort_max", "quick_abort_min", "quick_abort_pct", "range_offset_limit", "read_timeout", "redirect_children", "redirect_program", "redirect_rewrites_host_header", "reference_age", "refresh_pattern", "reload_into_ims", "request_body_max_size", "request_size", "request_timeout", "shutdown_lifetime", "single_parent_bypass", "siteselect_timeout", "snmp_access", "snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy", "store_avg_object_size", "store_objects_per_bucket", "strip_query_terms", "swap_level1_dirs", "swap_level2_dirs", "tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize", "test_reachability", "udp_hit_obj", "udp_hit_obj_size", "udp_incoming_address", "udp_outgoing_address", "unique_hostname", "unlinkd_program", "uri_whitespace", "useragent_log", "visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port", )
opts = ( "proxy-only", "weight", "ttl", "no-query", "default", "round-robin", "multicast-responder", "on", "off", "all", "deny", "allow", "via", "parent", "no-digest", "heap", "lru", "realm", "children", "q1", "q2", "credentialsttl", "none", "disable", "offline_toggle", "diskd", )
actions = ( "shutdown", "info", "parameter", "server_list", "client_list", r'squid.conf', )
actions_stats = ( "objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns", "redirector", "io", "reply_headers", "filedescriptors", "netdb", )
actions_log = ("status", "enable", "disable", "clear")
acls = ( "url_regex", "urlpath_regex", "referer_regex", "port", "proto", "req_mime_type", "rep_mime_type", "method", "browser", "user", "src", "dst", "time", "dstdomain", "ident", "snmp_community", )
ipv4_group = r'(\d+|0x[0-9a-f]+)' ipv4 = rf'({ipv4_group}(\.{ipv4_group}){{3}})' ipv6_group = r'([0-9a-f]{0,4})' ipv6 = rf'({ipv6_group}(:{ipv6_group}){{1,7}})' bare_ip = rf'({ipv4}|{ipv6})' # XXX: /integer is a subnet mark, but what is /IP ? # There is no test where it is used. ip = rf'{bare_ip}(/({bare_ip}|\d+))?'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#', Comment, 'comment'), (words(keywords, prefix=r'\b', suffix=r'\b'), Keyword), (words(opts, prefix=r'\b', suffix=r'\b'), Name.Constant), # Actions (words(actions, prefix=r'\b', suffix=r'\b'), String), (words(actions_stats, prefix=r'stats/', suffix=r'\b'), String), (words(actions_log, prefix=r'log/', suffix=r'='), String), (words(acls, prefix=r'\b', suffix=r'\b'), Keyword), (ip, Number.Float), (r'(?:\b\d+\b(?:-\b\d+|%)?)', Number), (r'\S+', Text), ], 'comment': [ (r'\s*TAG:.*', String.Escape, '#pop'), (r'.+', Comment, '#pop'), default('#pop'), ], }
class NginxConfLexer(RegexLexer): """ Lexer for Nginx configuration files. """ name = 'Nginx configuration file' url = 'http://nginx.net/' aliases = ['nginx'] filenames = ['nginx.conf'] mimetypes = ['text/x-nginx-conf'] version_added = '0.11'
tokens = { 'root': [ (r'(include)(\s+)([^\s;]+)', bygroups(Keyword, Whitespace, Name)), (r'[^\s;#]+', Keyword, 'stmt'), include('base'), ], 'block': [ (r'\}', Punctuation, '#pop:2'), (r'[^\s;#]+', Keyword.Namespace, 'stmt'), include('base'), ], 'stmt': [ (r'\{', Punctuation, 'block'), (r';', Punctuation, '#pop'), include('base'), ], 'base': [ (r'#.*\n', Comment.Single), (r'on|off', Name.Constant), (r'\$[^\s;#()]+', Name.Variable), (r'([a-z0-9.-]+)(:)([0-9]+)', bygroups(Name, Punctuation, Number.Integer)), (r'[a-z-]+/[a-z-+]+', String), # mimetype # (r'[a-zA-Z._-]+', Keyword), (r'[0-9]+[km]?\b', Number.Integer), (r'(~)(\s*)([^\s{]+)', bygroups(Punctuation, Whitespace, String.Regex)), (r'[:=~]', Punctuation), (r'[^\s;#{}$]+', String), # catch all (r'/[^\s;#]*', Name), # pathname (r'\s+', Whitespace), (r'[$;]', Text), # leftover characters ], }
class LighttpdConfLexer(RegexLexer): """ Lexer for Lighttpd configuration files. """ name = 'Lighttpd configuration file' url = 'http://lighttpd.net/' aliases = ['lighttpd', 'lighty'] filenames = ['lighttpd.conf'] mimetypes = ['text/x-lighttpd-conf'] version_added = '0.11'
tokens = { 'root': [ (r'#.*\n', Comment.Single), (r'/\S*', Name), # pathname (r'[a-zA-Z._-]+', Keyword), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'[0-9]+', Number), (r'=>|=~|\+=|==|=|\+', Operator), (r'\$[A-Z]+', Name.Builtin), (r'[(){}\[\],]', Punctuation), (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), (r'\s+', Whitespace), ],
}
class DockerLexer(RegexLexer): """ Lexer for Docker configuration files. """ name = 'Docker' url = 'http://docker.io' aliases = ['docker', 'dockerfile'] filenames = ['Dockerfile', '*.docker'] mimetypes = ['text/x-dockerfile-config'] version_added = '2.0'
_keywords = (r'(?:MAINTAINER|EXPOSE|WORKDIR|USER|STOPSIGNAL)') _bash_keywords = (r'(?:RUN|CMD|ENTRYPOINT|ENV|ARG|LABEL|ADD|COPY)') _lb = r'(?:\s*\\?\s*)' # dockerfile line break regex flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'#.*', Comment), (r'(FROM)([ \t]*)(\S*)([ \t]*)(?:(AS)([ \t]*)(\S*))?', bygroups(Keyword, Whitespace, String, Whitespace, Keyword, Whitespace, String)), (rf'(ONBUILD)(\s+)({_lb})', bygroups(Keyword, Whitespace, using(BashLexer))), (rf'(HEALTHCHECK)(\s+)(({_lb}--\w+=\w+{_lb})*)', bygroups(Keyword, Whitespace, using(BashLexer))), (rf'(VOLUME|ENTRYPOINT|CMD|SHELL)(\s+)({_lb})(\[.*?\])', bygroups(Keyword, Whitespace, using(BashLexer), using(JsonLexer))), (rf'(LABEL|ENV|ARG)(\s+)(({_lb}\w+=\w+{_lb})*)', bygroups(Keyword, Whitespace, using(BashLexer))), (rf'({_keywords}|VOLUME)\b(\s+)(.*)', bygroups(Keyword, Whitespace, String)), (rf'({_bash_keywords})(\s+)', bygroups(Keyword, Whitespace)), (r'(.*\\\n)*.+', using(BashLexer)), ] }
class TerraformLexer(ExtendedRegexLexer): """ Lexer for terraformi ``.tf`` files. """
name = 'Terraform' url = 'https://www.terraform.io/' aliases = ['terraform', 'tf', 'hcl'] filenames = ['*.tf', '*.hcl'] mimetypes = ['application/x-tf', 'application/x-terraform'] version_added = '2.1'
classes = ('backend', 'data', 'module', 'output', 'provider', 'provisioner', 'resource', 'variable') classes_re = "({})".format(('|').join(classes))
types = ('string', 'number', 'bool', 'list', 'tuple', 'map', 'set', 'object', 'null')
numeric_functions = ('abs', 'ceil', 'floor', 'log', 'max', 'mix', 'parseint', 'pow', 'signum')
string_functions = ('chomp', 'format', 'formatlist', 'indent', 'join', 'lower', 'regex', 'regexall', 'replace', 'split', 'strrev', 'substr', 'title', 'trim', 'trimprefix', 'trimsuffix', 'trimspace', 'upper' )
collection_functions = ('alltrue', 'anytrue', 'chunklist', 'coalesce', 'coalescelist', 'compact', 'concat', 'contains', 'distinct', 'element', 'flatten', 'index', 'keys', 'length', 'list', 'lookup', 'map', 'matchkeys', 'merge', 'range', 'reverse', 'setintersection', 'setproduct', 'setsubtract', 'setunion', 'slice', 'sort', 'sum', 'transpose', 'values', 'zipmap' )
encoding_functions = ('base64decode', 'base64encode', 'base64gzip', 'csvdecode', 'jsondecode', 'jsonencode', 'textdecodebase64', 'textencodebase64', 'urlencode', 'yamldecode', 'yamlencode')
filesystem_functions = ('abspath', 'dirname', 'pathexpand', 'basename', 'file', 'fileexists', 'fileset', 'filebase64', 'templatefile')
date_time_functions = ('formatdate', 'timeadd', 'timestamp')
hash_crypto_functions = ('base64sha256', 'base64sha512', 'bcrypt', 'filebase64sha256', 'filebase64sha512', 'filemd5', 'filesha1', 'filesha256', 'filesha512', 'md5', 'rsadecrypt', 'sha1', 'sha256', 'sha512', 'uuid', 'uuidv5')
ip_network_functions = ('cidrhost', 'cidrnetmask', 'cidrsubnet', 'cidrsubnets')
type_conversion_functions = ('can', 'defaults', 'tobool', 'tolist', 'tomap', 'tonumber', 'toset', 'tostring', 'try')
builtins = numeric_functions + string_functions + collection_functions + encoding_functions +\ filesystem_functions + date_time_functions + hash_crypto_functions + ip_network_functions +\ type_conversion_functions builtins_re = "({})".format(('|').join(builtins))
def heredoc_callback(self, match, ctx): # Parse a terraform heredoc # match: 1 = <<[-]?, 2 = name 3 = rest of line
start = match.start(1) yield start, Operator, match.group(1) # <<[-]? yield match.start(2), String.Delimiter, match.group(2) # heredoc name
ctx.pos = match.start(3) ctx.end = match.end(3) yield ctx.pos, String.Heredoc, match.group(3) ctx.pos = match.end()
hdname = match.group(2) tolerant = True # leading whitespace is always accepted
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)
tokens = { 'root': [ include('basic'), include('whitespace'),
# Strings (r'(".*")', bygroups(String.Double)),
# Constants (words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Name.Constant),
# Types (words(types, prefix=r'\b', suffix=r'\b'), Keyword.Type),
include('identifier'), include('punctuation'), (r'[0-9]+', Number), ], 'basic': [ (r'\s*/\*', Comment.Multiline, 'comment'), (r'\s*(#|//).*\n', Comment.Single), include('whitespace'),
# e.g. terraform { # e.g. egress { (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=?)(\s*)(\{)', bygroups(Whitespace, Name.Builtin, Whitespace, Operator, Whitespace, Punctuation)),
# Assignment with attributes, e.g. something = ... (r'(\s*)([0-9a-zA-Z-_]+)(\s*)(=)(\s*)', bygroups(Whitespace, Name.Attribute, Whitespace, Operator, Whitespace)),
# Assignment with environment variables and similar, e.g. "something" = ... # or key value assignment, e.g. "SlotName" : ... (r'(\s*)("\S+")(\s*)([=:])(\s*)', bygroups(Whitespace, Literal.String.Double, Whitespace, Operator, Whitespace)),
# Functions, e.g. jsonencode(element("value")) (builtins_re + r'(\()', bygroups(Name.Function, Punctuation)),
# List of attributes, e.g. ignore_changes = [last_modified, filename] (r'(\[)([a-z_,\s]+)(\])', bygroups(Punctuation, Name.Builtin, Punctuation)),
# e.g. resource "aws_security_group" "allow_tls" { # e.g. backend "consul" { (classes_re + r'(\s+)("[0-9a-zA-Z-_]+")?(\s*)("[0-9a-zA-Z-_]+")(\s+)(\{)', bygroups(Keyword.Reserved, Whitespace, Name.Class, Whitespace, Name.Variable, Whitespace, Punctuation)),
# here-doc style delimited strings (r'(<<-?)\s*([a-zA-Z_]\w*)(.*?\n)', heredoc_callback), ], 'identifier': [ (r'\b(var\.[0-9a-zA-Z-_\.\[\]]+)\b', bygroups(Name.Variable)), (r'\b([0-9a-zA-Z-_\[\]]+\.[0-9a-zA-Z-_\.\[\]]+)\b', bygroups(Name.Variable)), ], 'punctuation': [ (r'[\[\]()\{\},.?:!=]', Punctuation), ], 'comment': [ (r'[^*/]', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), ], }
class TermcapLexer(RegexLexer): """ Lexer for termcap database source.
This is very simple and minimal. """ name = 'Termcap' aliases = ['termcap'] filenames = ['termcap', 'termcap.src'] mimetypes = [] url = 'https://en.wikipedia.org/wiki/Termcap' version_added = '2.1'
# NOTE: # * multiline with trailing backslash # * separator is ':' # * to embed colon as data, we must use \072 # * space after separator is not allowed (mayve) tokens = { 'root': [ (r'^#.*', Comment), (r'^[^\s#:|]+', Name.Tag, 'names'), (r'\s+', Whitespace), ], 'names': [ (r'\n', Whitespace, '#pop'), (r':', Punctuation, 'defs'), (r'\|', Punctuation), (r'[^:|]+', Name.Attribute), ], 'defs': [ (r'(\\)(\n[ \t]*)', bygroups(Text, Whitespace)), (r'\n[ \t]*', Whitespace, '#pop:2'), (r'(#)([0-9]+)', bygroups(Operator, Number)), (r'=', Operator, 'data'), (r':', Punctuation), (r'[^\s:=#]+', Name.Class), ], 'data': [ (r'\\072', Literal), (r':', Punctuation, '#pop'), (r'[^:\\]+', Literal), # for performance (r'.', Literal), ], }
class TerminfoLexer(RegexLexer): """ Lexer for terminfo database source.
This is very simple and minimal. """ name = 'Terminfo' aliases = ['terminfo'] filenames = ['terminfo', 'terminfo.src'] mimetypes = [] url = 'https://en.wikipedia.org/wiki/Terminfo' version_added = '2.1'
# NOTE: # * multiline with leading whitespace # * separator is ',' # * to embed comma as data, we can use \, # * space after separator is allowed tokens = { 'root': [ (r'^#.*$', Comment), (r'^[^\s#,|]+', Name.Tag, 'names'), (r'\s+', Whitespace), ], 'names': [ (r'\n', Whitespace, '#pop'), (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), 'defs'), (r'\|', Punctuation), (r'[^,|]+', Name.Attribute), ], 'defs': [ (r'\n[ \t]+', Whitespace), (r'\n', Whitespace, '#pop:2'), (r'(#)([0-9]+)', bygroups(Operator, Number)), (r'=', Operator, 'data'), (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace)), (r'[^\s,=#]+', Name.Class), ], 'data': [ (r'\\[,\\]', Literal), (r'(,)([ \t]*)', bygroups(Punctuation, Whitespace), '#pop'), (r'[^\\,]+', Literal), # for performance (r'.', Literal), ], }
class PkgConfigLexer(RegexLexer): """ Lexer for pkg-config (see also `manual page <http://linux.die.net/man/1/pkg-config>`_). """
name = 'PkgConfig' url = 'http://www.freedesktop.org/wiki/Software/pkg-config/' aliases = ['pkgconfig'] filenames = ['*.pc'] mimetypes = [] version_added = '2.1'
tokens = { 'root': [ (r'#.*$', Comment.Single),
# variable definitions (r'^(\w+)(=)', bygroups(Name.Attribute, Operator)),
# keyword lines (r'^([\w.]+)(:)', bygroups(Name.Tag, Punctuation), 'spvalue'),
# variable references include('interp'),
# fallback (r'\s+', Whitespace), (r'[^${}#=:\n.]+', Text), (r'.', Text), ], 'interp': [ # you can escape literal "$" as "$$" (r'\$\$', Text),
# variable references (r'\$\{', String.Interpol, 'curly'), ], 'curly': [ (r'\}', String.Interpol, '#pop'), (r'\w+', Name.Attribute), ], 'spvalue': [ include('interp'),
(r'#.*$', Comment.Single, '#pop'), (r'\n', Whitespace, '#pop'),
# fallback (r'\s+', Whitespace), (r'[^${}#\n\s]+', Text), (r'.', Text), ], }
class PacmanConfLexer(RegexLexer): """ Lexer for pacman.conf.
Actually, IniLexer works almost fine for this format, but it yield error token. It is because pacman.conf has a form without assignment like:
UseSyslog Color TotalDownload CheckSpace VerbosePkgLists
These are flags to switch on. """
name = 'PacmanConf' url = 'https://www.archlinux.org/pacman/pacman.conf.5.html' aliases = ['pacmanconf'] filenames = ['pacman.conf'] mimetypes = [] version_added = '2.1'
tokens = { 'root': [ # comment (r'#.*$', Comment.Single),
# section header (r'^(\s*)(\[.*?\])(\s*)$', bygroups(Whitespace, Keyword, Whitespace)),
# variable definitions # (Leading space is allowed...) (r'(\w+)(\s*)(=)', bygroups(Name.Attribute, Whitespace, Operator)),
# flags to on (r'^(\s*)(\w+)(\s*)$', bygroups(Whitespace, Name.Attribute, Whitespace)),
# built-in special values (words(( '$repo', # repository '$arch', # architecture '%o', # outfile '%u', # url ), suffix=r'\b'), Name.Variable),
# fallback (r'\s+', Whitespace), (r'.', Text), ], }
class AugeasLexer(RegexLexer): """ Lexer for Augeas. """ name = 'Augeas' url = 'http://augeas.net' aliases = ['augeas'] filenames = ['*.aug'] version_added = '2.4'
tokens = { 'root': [ (r'(module)(\s*)([^\s=]+)', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), (r'(let)(\s*)([^\s=]+)', bygroups(Keyword.Declaration, Whitespace, Name.Variable)), (r'(del|store|value|counter|seq|key|label|autoload|incl|excl|transform|test|get|put)(\s+)', bygroups(Name.Builtin, Whitespace)), (r'(\()([^:]+)(\:)(unit|string|regexp|lens|tree|filter)(\))', bygroups(Punctuation, Name.Variable, Punctuation, Keyword.Type, Punctuation)), (r'\(\*', Comment.Multiline, 'comment'), (r'[*+\-.;=?|]', Operator), (r'[()\[\]{}]', Operator), (r'"', String.Double, 'string'), (r'\/', String.Regex, 'regex'), (r'([A-Z]\w*)(\.)(\w+)', bygroups(Name.Namespace, Punctuation, Name.Variable)), (r'.', Name.Variable), (r'\s+', Whitespace), ], 'string': [ (r'\\.', String.Escape), (r'[^"]', String.Double), (r'"', String.Double, '#pop'), ], 'regex': [ (r'\\.', String.Escape), (r'[^/]', String.Regex), (r'\/', String.Regex, '#pop'), ], 'comment': [ (r'[^*)]', Comment.Multiline), (r'\(\*', Comment.Multiline, '#push'), (r'\*\)', Comment.Multiline, '#pop'), (r'[)*]', Comment.Multiline) ], }
class TOMLLexer(RegexLexer): """ Lexer for TOML, a simple language for config files. """
name = 'TOML' aliases = ['toml'] filenames = ['*.toml', 'Pipfile', 'poetry.lock'] mimetypes = ['application/toml'] url = 'https://toml.io' version_added = '2.4'
# Based on the TOML spec: https://toml.io/en/v1.0.0
# The following is adapted from CPython's tomllib: _time = r"\d\d:\d\d(:\d\d(\.\d+)?)?" _datetime = rf"""(?x) \d\d\d\d-\d\d-\d\d # date, e.g., 1988-10-27 ( [Tt ] {_time} # optional time ( [Zz]|[+-]\d\d:\d\d # optional time offset )? )? """
tokens = { 'root': [ # Note that we make an effort in order to distinguish # moments at which we're parsing a key and moments at # which we're parsing a value. In the TOML code # # 1234 = 1234 # # the first "1234" should be Name, the second Integer.
# Whitespace (r'\s+', Whitespace),
# Comment (r'#.*', Comment.Single),
# Assignment keys include('key'),
# After "=", find a value (r'(=)(\s*)', bygroups(Operator, Whitespace), 'value'),
# Table header (r'\[\[?', Keyword, 'table-key'), ], 'key': [ # Start of bare key (only ASCII is allowed here). (r'[A-Za-z0-9_-]+', Name), # Quoted key (r'"', String.Double, 'basic-string'), (r"'", String.Single, 'literal-string'), # Dots act as separators in keys (r'\.', Punctuation), ], 'table-key': [ # This is like 'key', but highlights the name components # and separating dots as Keyword because it looks better # when the whole table header is Keyword. We do highlight # strings as strings though. # Start of bare key (only ASCII is allowed here). (r'[A-Za-z0-9_-]+', Keyword), (r'"', String.Double, 'basic-string'), (r"'", String.Single, 'literal-string'), (r'\.', Keyword), (r'\]\]?', Keyword, '#pop'),
# Inline whitespace allowed (r'[ \t]+', Whitespace), ], 'value': [ # Datetime, baretime (_datetime, Literal.Date, '#pop'), (_time, Literal.Date, '#pop'),
# Recognize as float if there is a fractional part # and/or an exponent. (r'[+-]?\d[0-9_]*[eE][+-]?\d[0-9_]*', Number.Float, '#pop'), (r'[+-]?\d[0-9_]*\.\d[0-9_]*([eE][+-]?\d[0-9_]*)?', Number.Float, '#pop'),
# Infinities and NaN (r'[+-]?(inf|nan)', Number.Float, '#pop'),
# Integers (r'-?0b[01_]+', Number.Bin, '#pop'), (r'-?0o[0-7_]+', Number.Oct, '#pop'), (r'-?0x[0-9a-fA-F_]+', Number.Hex, '#pop'), (r'[+-]?[0-9_]+', Number.Integer, '#pop'),
# Strings (r'"""', String.Double, ('#pop', 'multiline-basic-string')), (r'"', String.Double, ('#pop', 'basic-string')), (r"'''", String.Single, ('#pop', 'multiline-literal-string')), (r"'", String.Single, ('#pop', 'literal-string')),
# Booleans (r'true|false', Keyword.Constant, '#pop'),
# Start of array (r'\[', Punctuation, ('#pop', 'array')),
# Start of inline table (r'\{', Punctuation, ('#pop', 'inline-table')), ], 'array': [ # Whitespace, including newlines, is ignored inside arrays, # and comments are allowed. (r'\s+', Whitespace), (r'#.*', Comment.Single),
# Delimiters (r',', Punctuation),
# End of array (r'\]', Punctuation, '#pop'),
# Parse a value and come back default('value'), ], 'inline-table': [ # Whitespace (since TOML 1.1.0, same as in array) (r'\s+', Whitespace), (r'#.*', Comment.Single),
# Keys include('key'),
# Values (r'(=)(\s*)', bygroups(Punctuation, Whitespace), 'value'),
# Delimiters (r',', Punctuation),
# End of inline table (r'\}', Punctuation, '#pop'), ], 'basic-string': [ (r'"', String.Double, '#pop'), include('escapes'), (r'[^"\\]+', String.Double), ], 'literal-string': [ (r".*?'", String.Single, '#pop'), ], 'multiline-basic-string': [ (r'"""', String.Double, '#pop'), (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), include('escapes'), (r'[^"\\]+', String.Double), (r'"', String.Double), ], 'multiline-literal-string': [ (r"'''", String.Single, '#pop'), (r"[^']+", String.Single), (r"'", String.Single), ], 'escapes': [ (r'\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}', String.Escape), (r'\\.', String.Escape), ], }
class NestedTextLexer(RegexLexer): """ Lexer for *NextedText*, a human-friendly data format.
.. versionchanged:: 2.16 Added support for *NextedText* v3.0. """
name = 'NestedText' url = 'https://nestedtext.org' aliases = ['nestedtext', 'nt'] filenames = ['*.nt'] version_added = '2.9'
tokens = { 'root': [ # Comment: # ... (r'^([ ]*)(#.*)$', bygroups(Whitespace, Comment)),
# Inline dictionary: {...} (r'^([ ]*)(\{)', bygroups(Whitespace, Punctuation), 'inline_dict'),
# Inline list: [...] (r'^([ ]*)(\[)', bygroups(Whitespace, Punctuation), 'inline_list'),
# empty multiline string item: > (r'^([ ]*)(>)$', bygroups(Whitespace, Punctuation)),
# multiline string item: > ... (r'^([ ]*)(>)( )(.*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Text, Whitespace)),
# empty list item: - (r'^([ ]*)(-)$', bygroups(Whitespace, Punctuation)),
# list item: - ... (r'^([ ]*)(-)( )(.*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Text, Whitespace)),
# empty multiline key item: : (r'^([ ]*)(:)$', bygroups(Whitespace, Punctuation)),
# multiline key item: : ... (r'^([ ]*)(:)( )([^\n]*?)([ \t]*)$', bygroups(Whitespace, Punctuation, Whitespace, Name.Tag, Whitespace)),
# empty dict key item: ...: (r'^([ ]*)([^\{\[\s].*?)(:)$', bygroups(Whitespace, Name.Tag, Punctuation)),
# dict key item: ...: ... (r'^([ ]*)([^\{\[\s].*?)(:)( )(.*?)([ \t]*)$', bygroups(Whitespace, Name.Tag, Punctuation, Whitespace, Text, Whitespace)), ], 'inline_list': [ include('whitespace'), (r'[^\{\}\[\],\s]+', Text), include('inline_value'), (r',', Punctuation), (r'\]', Punctuation, '#pop'), (r'\n', Error, '#pop'), ], 'inline_dict': [ include('whitespace'), (r'[^\{\}\[\],:\s]+', Name.Tag), (r':', Punctuation, 'inline_dict_value'), (r'\}', Punctuation, '#pop'), (r'\n', Error, '#pop'), ], 'inline_dict_value': [ include('whitespace'), (r'[^\{\}\[\],:\s]+', Text), include('inline_value'), (r',', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), ], 'inline_value': [ include('whitespace'), (r'\{', Punctuation, 'inline_dict'), (r'\[', Punctuation, 'inline_list'), ], 'whitespace': [ (r'[ \t]+', Whitespace), ], }
class SingularityLexer(RegexLexer): """ Lexer for Singularity definition files. """
name = 'Singularity' url = 'https://www.sylabs.io/guides/3.0/user-guide/definition_files.html' aliases = ['singularity'] filenames = ['*.def', 'Singularity'] version_added = '2.6' flags = re.IGNORECASE | re.MULTILINE | re.DOTALL
_headers = r'^(\s*)(bootstrap|from|osversion|mirrorurl|include|registry|namespace|includecmd)(:)' _section = r'^(%(?:pre|post|setup|environment|help|labels|test|runscript|files|startscript))(\s*)' _appsect = r'^(%app(?:install|help|run|labels|env|test|files))(\s*)'
tokens = { 'root': [ (_section, bygroups(Generic.Heading, Whitespace), 'script'), (_appsect, bygroups(Generic.Heading, Whitespace), 'script'), (_headers, bygroups(Whitespace, Keyword, Text)), (r'\s*#.*?\n', Comment), (r'\b(([0-9]+\.?[0-9]*)|(\.[0-9]+))\b', Number), (r'[ \t]+', Whitespace), (r'(?!^\s*%).', Text), ], 'script': [ (r'(.+?(?=^\s*%))|(.*)', using(BashLexer), '#pop'), ], }
def analyse_text(text): """This is a quite simple script file, but there are a few keywords which seem unique to this language.""" result = 0 if re.search(r'\b(?:osversion|includecmd|mirrorurl)\b', text, re.IGNORECASE): result += 0.5
if re.search(SingularityLexer._section[1:], text): result += 0.49
return result
class UnixConfigLexer(RegexLexer): """ Lexer for Unix/Linux config files using colon-separated values, e.g.
* ``/etc/group`` * ``/etc/passwd`` * ``/etc/shadow`` """
name = 'Unix/Linux config files' aliases = ['unixconfig', 'linuxconfig'] filenames = [] url = 'https://en.wikipedia.org/wiki/Configuration_file#Unix_and_Unix-like_operating_systems' version_added = '2.12'
tokens = { 'root': [ (r'^#.*', Comment), (r'\n', Whitespace), (r':', Punctuation), (r'[0-9]+', Number), (r'((?!\n)[a-zA-Z0-9\_\-\s\(\),]){2,}', Text), (r'[^:\n]+', String), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114""" pygments.lexers.console ~~~~~~~~~~~~~~~~~~~~~~~
Lexers for misc console output.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Generic, Comment, String, Text, Keyword, Name, \ Punctuation, Number, Whitespace
__all__ = ['VCTreeStatusLexer', 'PyPyLogLexer']
class VCTreeStatusLexer(RegexLexer): """ For colorizing output of version control status commands, like "hg status" or "svn status". """ name = 'VCTreeStatus' aliases = ['vctreestatus'] filenames = [] mimetypes = [] url = "" version_added = '2.0'
tokens = { 'root': [ (r'^A \+ C\s+', Generic.Error), (r'^A\s+\+?\s+', String), (r'^M\s+', Generic.Inserted), (r'^C\s+', Generic.Error), (r'^D\s+', Generic.Deleted), (r'^[?!]\s+', Comment.Preproc), (r' >\s+.*\n', Comment.Preproc), (r'\S+', Text), (r'\s+', Whitespace), ] }
class PyPyLogLexer(RegexLexer): """ Lexer for PyPy log files. """ name = "PyPy Log" aliases = ["pypylog", "pypy"] filenames = ["*.pypylog"] mimetypes = ['application/x-pypylog'] url = 'pypy.org' version_added = '1.5'
tokens = { "root": [ (r"\[\w+\] \{jit-log-.*?$", Keyword, "jit-log"), (r"\[\w+\] \{jit-backend-counts$", Keyword, "jit-backend-counts"), include("extra-stuff"), ], "jit-log": [ (r"\[\w+\] jit-log-.*?}$", Keyword, "#pop"), (r"^\+\d+: ", Comment), (r"--end of the loop--", Comment), (r"[ifp]\d+", Name), (r"ptr\d+", Name), (r"(\()(\w+(?:\.\w+)?)(\))", bygroups(Punctuation, Name.Builtin, Punctuation)), (r"[\[\]=,()]", Punctuation), (r"(\d+\.\d+|inf|-inf)", Number.Float), (r"-?\d+", Number.Integer), (r"'.*'", String), (r"(None|descr|ConstClass|ConstPtr|TargetToken)", Name), (r"<.*?>+", Name.Builtin), (r"(label|debug_merge_point|jump|finish)", Name.Class), (r"(int_add_ovf|int_add|int_sub_ovf|int_sub|int_mul_ovf|int_mul|" r"int_floordiv|int_mod|int_lshift|int_rshift|int_and|int_or|" r"int_xor|int_eq|int_ne|int_ge|int_gt|int_le|int_lt|int_is_zero|" r"int_is_true|" r"uint_floordiv|uint_ge|uint_lt|" r"float_add|float_sub|float_mul|float_truediv|float_neg|" r"float_eq|float_ne|float_ge|float_gt|float_le|float_lt|float_abs|" r"ptr_eq|ptr_ne|instance_ptr_eq|instance_ptr_ne|" r"cast_int_to_float|cast_float_to_int|" r"force_token|quasiimmut_field|same_as|virtual_ref_finish|" r"virtual_ref|mark_opaque_ptr|" r"call_may_force|call_assembler|call_loopinvariant|" r"call_release_gil|call_pure|call|" r"new_with_vtable|new_array|newstr|newunicode|new|" r"arraylen_gc|" r"getarrayitem_gc_pure|getarrayitem_gc|setarrayitem_gc|" r"getarrayitem_raw|setarrayitem_raw|getfield_gc_pure|" r"getfield_gc|getinteriorfield_gc|setinteriorfield_gc|" r"getfield_raw|setfield_gc|setfield_raw|" r"strgetitem|strsetitem|strlen|copystrcontent|" r"unicodegetitem|unicodesetitem|unicodelen|" r"guard_true|guard_false|guard_value|guard_isnull|" r"guard_nonnull_class|guard_nonnull|guard_class|guard_no_overflow|" r"guard_not_forced|guard_no_exception|guard_not_invalidated)", Name.Builtin), include("extra-stuff"), ], "jit-backend-counts": [ (r"\[\w+\] jit-backend-counts}$", Keyword, "#pop"), (r":", Punctuation), (r"\d+", Number), include("extra-stuff"), ], "extra-stuff": [ (r"\s+", Whitespace), (r"#.*?$", Comment), ], }12345678910111213141516171819202122232425262728293031323334353637383940414243""" pygments.lexers.cplint ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the cplint language
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import bygroups, inherit, wordsfrom pygments.lexers import PrologLexerfrom pygments.token import Operator, Keyword, Name, String, Punctuation
__all__ = ['CplintLexer']
class CplintLexer(PrologLexer): """ Lexer for cplint files, including CP-logic, Logic Programs with Annotated Disjunctions, Distributional Clauses syntax, ProbLog, DTProbLog. """ name = 'cplint' url = 'https://cplint.eu' aliases = ['cplint'] filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl', '*.P', '*.lpad', '*.cpl'] mimetypes = ['text/x-cplint'] version_added = '2.12'
tokens = { 'root': [ (r'map_query', Keyword), (words(('gaussian', 'uniform_dens', 'dirichlet', 'gamma', 'beta', 'poisson', 'binomial', 'geometric', 'exponential', 'pascal', 'multinomial', 'user', 'val', 'uniform', 'discrete', 'finite')), Name.Builtin), # annotations of atoms (r'([a-z]+)(:)', bygroups(String.Atom, Punctuation)), (r':(-|=)|::?|~=?|=>', Operator), (r'\?', Name.Builtin), inherit, ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364""" pygments.lexers.crystal ~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Crystal.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, include, bygroups, default, \ words, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Error, Whitespace
__all__ = ['CrystalLexer']
CRYSTAL_OPERATORS = [ '!=', '!~', '!', '%', '&&', '&', '**', '*', '+', '-', '/', '<=>', '<<', '<=', '<', '===', '==', '=~', '=', '>=', '>>', '>', '[]=', '[]?', '[]', '^', '||', '|', '~']
class CrystalLexer(ExtendedRegexLexer): """ For Crystal source code. """
name = 'Crystal' url = 'https://crystal-lang.org' aliases = ['cr', 'crystal'] filenames = ['*.cr'] mimetypes = ['text/x-crystal'] version_added = '2.2'
flags = re.DOTALL | re.MULTILINE
def heredoc_callback(self, match, ctx): # okay, this is the hardest part of parsing Crystal... # 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) == '<<-', 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_crystalstrings_rules(): states = {} states['strings'] = [ (r'\:\w+[!?]?', String.Symbol), (words(CRYSTAL_OPERATORS, prefix=r'\:'), String.Symbol), (r":'(\\\\|\\[^\\]|[^'\\])*'", String.Symbol), # This allows arbitrary text after '\ for simplicity (r"'(\\\\|\\'|[^']|\\[^'\\]+)'", String.Char), (r':"', String.Symbol, 'simple-sym'), # Crystal doesn't have "symbol:"s but this simplifies function args (r'([a-zA-Z_]\w*)(:)(?!:)', bygroups(String.Symbol, Punctuation)), (r'"', String.Double, 'simple-string'), (r'(?<!\.)`', String.Backtick, 'simple-backtick'), ]
# double-quoted string and symbol for name, ttype, end in ('string', String.Double, '"'), \ ('sym', String.Symbol, '"'), \ ('backtick', String.Backtick, '`'): states['simple-'+name] = [ include('string-escaped' if name == 'sym' else 'string-intp-escaped'), (rf'[^\\{end}#]+', ttype), (r'[\\#]', ttype), (end, ttype, '#pop'), ]
# https://crystal-lang.org/docs/syntax_and_semantics/literals/string.html#percent-string-literals for lbrace, rbrace, bracecc, name in \ ('\\{', '\\}', '{}', 'cb'), \ ('\\[', '\\]', '\\[\\]', 'sb'), \ ('\\(', '\\)', '()', 'pa'), \ ('<', '>', '<>', 'ab'), \ ('\\|', '\\|', '\\|', 'pi'): states[name+'-intp-string'] = [ (r'\\' + lbrace, String.Other), ] + (lbrace != rbrace) * [ (lbrace, String.Other, '#push'), ] + [ (rbrace, String.Other, '#pop'), include('string-intp-escaped'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] states['strings'].append((r'%Q?' + lbrace, String.Other, name+'-intp-string')) states[name+'-string'] = [ (r'\\[\\' + bracecc + ']', String.Other), ] + (lbrace != rbrace) * [ (lbrace, String.Other, '#push'), ] + [ (rbrace, String.Other, '#pop'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] # https://crystal-lang.org/docs/syntax_and_semantics/literals/array.html#percent-array-literals states['strings'].append((r'%[qwi]' + lbrace, String.Other, name+'-string')) states[name+'-regex'] = [ (r'\\[\\' + bracecc + ']', String.Regex), ] + (lbrace != rbrace) * [ (lbrace, String.Regex, '#push'), ] + [ (rbrace + '[imsx]*', String.Regex, '#pop'), include('string-intp'), (r'[\\#' + bracecc + ']', String.Regex), (r'[^\\#' + bracecc + ']+', String.Regex), ] states['strings'].append((r'%r' + lbrace, String.Regex, name+'-regex'))
return states
tokens = { 'root': [ (r'#.*?$', Comment.Single), # keywords (words(''' abstract asm begin break case do else elsif end ensure extend if in include next of private protected require rescue return select self super then unless until when while with yield '''.split(), suffix=r'\b'), Keyword), (words(''' previous_def forall out uninitialized __DIR__ __FILE__ __LINE__ __END_LINE__ '''.split(), prefix=r'(?<!\.)', suffix=r'\b'), Keyword.Pseudo), # https://crystal-lang.org/docs/syntax_and_semantics/is_a.html (r'\.(is_a\?|nil\?|responds_to\?|as\?|as\b)', Keyword.Pseudo), (words(['true', 'false', 'nil'], suffix=r'\b'), Keyword.Constant), # start of function, class and module names (r'(module|lib)(\s+)([a-zA-Z_]\w*(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'(def|fun|macro)(\s+)((?:[a-zA-Z_]\w*::)*)', bygroups(Keyword, Whitespace, Name.Namespace), 'funcname'), (r'def(?=[*%&^`~+-/\[<>=])', Keyword, 'funcname'), (r'(annotation|class|struct|union|type|alias|enum)(\s+)((?:[a-zA-Z_]\w*::)*)', bygroups(Keyword, Whitespace, Name.Namespace), 'classname'), # https://crystal-lang.org/api/toplevel.html (words(''' instance_sizeof offsetof pointerof sizeof typeof '''.split(), prefix=r'(?<!\.)', suffix=r'\b'), Keyword.Pseudo), # macros (r'(?<!\.)(debugger\b|p!|pp!|record\b|spawn\b)', Name.Builtin.Pseudo), # builtins (words(''' abort at_exit caller exit gets loop main p pp print printf puts raise rand read_line sleep spawn sprintf system '''.split(), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), # https://crystal-lang.org/api/Object.html#macro-summary (r'(?<!\.)(((class_)?((getter|property)\b[!?]?|setter\b))|' r'(def_(clone|equals|equals_and_hash|hash)|delegate|forward_missing_to)\b)', Name.Builtin.Pseudo), # normal heredocs (r'(?<!\w)(<<-?)(["`\']?)([a-zA-Z_]\w*)(\2)(.*?\n)', heredoc_callback), # empty string heredocs (r'(<<-?)("|\')()(\2)(.*?\n)', heredoc_callback), (r'__END__', Comment.Preproc, 'end-part'), # multiline regex (after keywords or assignments) (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(Whitespace, 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'(0o[0-7]+(?:_[0-7]+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Oct, Whitespace, Operator)), (r'(0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Hex, Whitespace, Operator)), (r'(0b[01]+(?:_[01]+)*(?:_?[iu][0-9]+)?)\b(\s*)([/?])?', bygroups(Number.Bin, Whitespace, Operator)), # 3 separate expressions for floats because any of the 3 optional # parts makes it a float (r'((?:0(?![0-9])|[1-9][\d_]*)(?:\.\d[\d_]*)(?:e[+-]?[0-9]+)?' r'(?:_?f[0-9]+)?)(\s*)([/?])?', bygroups(Number.Float, Whitespace, Operator)), (r'((?:0(?![0-9])|[1-9][\d_]*)(?:\.\d[\d_]*)?(?:e[+-]?[0-9]+)' r'(?:_?f[0-9]+)?)(\s*)([/?])?', bygroups(Number.Float, Whitespace, Operator)), (r'((?:0(?![0-9])|[1-9][\d_]*)(?:\.\d[\d_]*)?(?:e[+-]?[0-9]+)?' r'(?:_?f[0-9]+))(\s*)([/?])?', bygroups(Number.Float, Whitespace, Operator)), (r'(0\b|[1-9][\d]*(?:_\d+)*(?:_?[iu][0-9]+)?)\b(\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'), # https://crystal-lang.org/reference/syntax_and_semantics/literals/char.html (r'\?(\\[MC]-)*' # modifiers r'(\\([\\abefnrtv#"\']|[0-7]{1,3}|x[a-fA-F0-9]{2}|u[a-fA-F0-9]{4}|u\{[a-fA-F0-9 ]+\})|\S)' r'(?!\w)', String.Char), (r'[A-Z][A-Z_]+\b(?!::|\.)', Name.Constant), # macro expansion (r'\{%', String.Interpol, 'in-macro-control'), (r'\{\{', String.Interpol, 'in-macro-expr'), # annotations (r'(@\[)(\s*)([A-Z]\w*(::[A-Z]\w*)*)', bygroups(Operator, Whitespace, Name.Decorator), 'in-annot'), # this is needed because Crystal attributes can look # like keywords (class) or like this: ` ?!? (words(CRYSTAL_OPERATORS, prefix=r'(\.|::)'), bygroups(Operator, Name.Operator)), (r'(\.|::)([a-zA-Z_]\w*[!?]?|[*%&^`~+\-/\[<>=])', bygroups(Operator, Name)), # Names can end with [!?] unless it's "!=" (r'[a-zA-Z_]\w*(?:[!?](?!=))?', Name), (r'(\[|\]\??|\*\*|<=>?|>=|<<?|>>?|=~|===|' r'!~|&&?|\|\||\.{1,3})', Operator), (r'[-+/*%=<>&!^|~]=?', Operator), (r'[(){};,/?:\\]', Punctuation), (r'\s+', Whitespace) ], 'funcname': [ (r'(?:([a-zA-Z_]\w*)(\.))?' r'([a-zA-Z_]\w*[!?]?|\*\*?|[-+]@?|' r'[/%&|^`~]|\[\]=?|<<|>>|<=?>|>=?|===?)', bygroups(Name.Class, Operator, Name.Function), '#pop'), default('#pop') ], 'classname': [ (r'[A-Z_]\w*', Name.Class), (r'(\()(\s*)([A-Z_]\w*)(\s*)(\))', bygroups(Punctuation, Whitespace, Name.Class, Whitespace, Punctuation)), default('#pop') ], 'in-intp': [ (r'\{', String.Interpol, '#push'), (r'\}', String.Interpol, '#pop'), include('root'), ], 'string-intp': [ (r'#\{', String.Interpol, 'in-intp'), ], 'string-escaped': [ # https://crystal-lang.org/reference/syntax_and_semantics/literals/string.html (r'\\([\\abefnrtv#"\']|[0-7]{1,3}|x[a-fA-F0-9]{2}|u[a-fA-F0-9]{4}|u\{[a-fA-F0-9 ]+\})', String.Escape) ], 'string-intp-escaped': [ include('string-intp'), include('string-escaped'), ], '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'/[imsx]*', String.Regex, '#pop'), ], 'end-part': [ (r'.+', Comment.Preproc, '#pop') ], 'in-macro-control': [ (r'\{%', String.Interpol, '#push'), (r'%\}', String.Interpol, '#pop'), (r'(for|verbatim)\b', Keyword), include('root'), ], 'in-macro-expr': [ (r'\{\{', String.Interpol, '#push'), (r'\}\}', String.Interpol, '#pop'), include('root'), ], 'in-annot': [ (r'\[', Operator, '#push'), (r'\]', Operator, '#pop'), include('root'), ], } tokens.update(gen_crystalstrings_rules())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466""" pygments.lexers.csound ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Csound 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, default, include, using, wordsfrom pygments.token import Comment, Error, Keyword, Name, Number, Operator, Punctuation, \ String, Text, Whitespacefrom pygments.lexers._csound_builtins import OPCODES, DEPRECATED_OPCODES, REMOVED_OPCODESfrom pygments.lexers.html import HtmlLexerfrom pygments.lexers.python import PythonLexerfrom pygments.lexers.scripting import LuaLexer
__all__ = ['CsoundScoreLexer', 'CsoundOrchestraLexer', 'CsoundDocumentLexer']
newline = (r'((?:(?:;|//).*)*)(\n)', bygroups(Comment.Single, Text))
class CsoundLexer(RegexLexer): url = 'https://csound.com/'
tokens = { 'whitespace': [ (r'[ \t]+', Whitespace), (r'/[*](?:.|\n)*?[*]/', Comment.Multiline), (r'(?:;|//).*$', Comment.Single), (r'(\\)(\n)', bygroups(Text, Whitespace)) ],
'preprocessor directives': [ (r'#(?:e(?:nd(?:if)?|lse)\b|##)|@@?[ \t]*\d+', Comment.Preproc), (r'#includestr', Comment.Preproc, 'includestr directive'), (r'#include', Comment.Preproc, 'include directive'), (r'#[ \t]*define', Comment.Preproc, 'define directive'), (r'#(?:ifn?def|undef)\b', Comment.Preproc, 'macro directive') ],
'include directive': [ include('whitespace'), (r'([^ \t]).*?\1', String, '#pop') ], 'includestr directive': [ include('whitespace'), (r'"', String, ('#pop', 'quoted string')) ],
'define directive': [ (r'\n', Whitespace), include('whitespace'), (r'([A-Z_a-z]\w*)(\()', bygroups(Comment.Preproc, Punctuation), ('#pop', 'macro parameter name list')), (r'[A-Z_a-z]\w*', Comment.Preproc, ('#pop', 'before macro body')) ], 'macro parameter name list': [ include('whitespace'), (r'[A-Z_a-z]\w*', Comment.Preproc), (r"['#]", Punctuation), (r'\)', Punctuation, ('#pop', 'before macro body')) ], 'before macro body': [ (r'\n', Whitespace), include('whitespace'), (r'#', Punctuation, ('#pop', 'macro body')) ], 'macro body': [ (r'(?:\\(?!#)|[^#\\]|\n)+', Comment.Preproc), (r'\\#', Comment.Preproc), (r'(?<!\\)#', Punctuation, '#pop') ],
'macro directive': [ include('whitespace'), (r'[A-Z_a-z]\w*', Comment.Preproc, '#pop') ],
'macro uses': [ (r'(\$[A-Z_a-z]\w*\.?)(\()', bygroups(Comment.Preproc, Punctuation), 'macro parameter value list'), (r'\$[A-Z_a-z]\w*(?:\.|\b)', Comment.Preproc) ], 'macro parameter value list': [ (r'(?:[^\'#"{()]|\{(?!\{))+', Comment.Preproc), (r"['#]", Punctuation), (r'"', String, 'macro parameter value quoted string'), (r'\{\{', String, 'macro parameter value braced string'), (r'\(', Comment.Preproc, 'macro parameter value parenthetical'), (r'\)', Punctuation, '#pop') ], 'macro parameter value quoted string': [ (r"\\[#'()]", Comment.Preproc), (r"[#'()]", Error), include('quoted string') ], 'macro parameter value braced string': [ (r"\\[#'()]", Comment.Preproc), (r"[#'()]", Error), include('braced string') ], 'macro parameter value parenthetical': [ (r'(?:[^\\()]|\\\))+', Comment.Preproc), (r'\(', Comment.Preproc, '#push'), (r'\)', Comment.Preproc, '#pop') ],
'whitespace and macro uses': [ include('whitespace'), include('macro uses') ],
'numbers': [ (r'\d+[Ee][+-]?\d+|(\d+\.\d*|\d*\.\d+)([Ee][+-]?\d+)?', Number.Float), (r'(0[Xx])([0-9A-Fa-f]+)', bygroups(Keyword.Type, Number.Hex)), (r'\d+', Number.Integer) ],
'quoted string': [ (r'"', String, '#pop'), (r'[^"$]+', String), include('macro uses'), (r'[$]', String) ],
'braced string': [ # Do nothing. This must be defined in subclasses. ] }
class CsoundScoreLexer(CsoundLexer): """ For `Csound <https://csound.com>`_ scores. """
name = 'Csound Score' aliases = ['csound-score', 'csound-sco'] filenames = ['*.sco'] version_added = '2.1'
tokens = { 'root': [ (r'\n', Whitespace), include('whitespace and macro uses'), include('preprocessor directives'),
(r'[aBbCdefiqstvxy]', Keyword), # There is also a w statement that is generated internally and should not be # used; see https://github.com/csound/csound/issues/750.
(r'z', Keyword.Constant), # z is a constant equal to 800,000,000,000. 800 billion seconds is about # 25,367.8 years. See also # https://csound.com/docs/manual/ScoreTop.html and # https://github.com/csound/csound/search?q=stof+path%3AEngine+filename%3Asread.c.
(r'([nNpP][pP])(\d+)', bygroups(Keyword, Number.Integer)),
(r'[mn]', Keyword, 'mark statement'),
include('numbers'), (r'[!+\-*/^%&|<>#~.]', Operator), (r'[()\[\]]', Punctuation), (r'"', String, 'quoted string'), (r'\{', Comment.Preproc, 'loop after left brace'), ],
'mark statement': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', Name.Label), (r'\n', Whitespace, '#pop') ],
'loop after left brace': [ include('whitespace and macro uses'), (r'\d+', Number.Integer, ('#pop', 'loop after repeat count')), ], 'loop after repeat count': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', Comment.Preproc, ('#pop', 'loop')) ], 'loop': [ (r'\}', Comment.Preproc, '#pop'), include('root') ],
# Braced strings are not allowed in Csound scores, but this is needed because the # superclass includes it. 'braced string': [ (r'\}\}', String, '#pop'), (r'[^}]|\}(?!\})', String) ] }
class CsoundOrchestraLexer(CsoundLexer): """ For `Csound <https://csound.com>`_ orchestras. """
name = 'Csound Orchestra' aliases = ['csound', 'csound-orc'] filenames = ['*.orc', '*.udo'] version_added = '2.1'
user_defined_opcodes = set()
def opcode_name_callback(lexer, match): opcode = match.group(0) lexer.user_defined_opcodes.add(opcode) yield match.start(), Name.Function, opcode
def name_callback(lexer, match): type_annotation_token = Keyword.Type
name = match.group(1) if name in OPCODES or name in DEPRECATED_OPCODES or name in REMOVED_OPCODES: yield match.start(), Name.Builtin, name elif name in lexer.user_defined_opcodes: yield match.start(), Name.Function, name else: type_annotation_token = Name name_match = re.search(r'^(g?[afikSw])(\w+)', name) if name_match: yield name_match.start(1), Keyword.Type, name_match.group(1) yield name_match.start(2), Name, name_match.group(2) else: yield match.start(), Name, name
if match.group(2): yield match.start(2), Punctuation, match.group(2) yield match.start(3), type_annotation_token, match.group(3)
tokens = { 'root': [ (r'\n', Whitespace),
(r'^([ \t]*)(\w+)(:)([ \t]+|$)', bygroups(Whitespace, Name.Label, Punctuation, Whitespace)),
include('whitespace and macro uses'), include('preprocessor directives'),
(r'\binstr\b', Keyword.Declaration, 'instrument numbers and identifiers'), (r'\bopcode\b', Keyword.Declaration, 'after opcode keyword'), (r'\b(?:end(?:in|op))\b', Keyword.Declaration),
include('partial statements') ],
'partial statements': [ (r'\b(?:0dbfs|A4|k(?:r|smps)|nchnls(?:_i)?|sr)\b', Name.Variable.Global),
include('numbers'),
(r'\+=|-=|\*=|/=|<<|>>|<=|>=|==|!=|&&|\|\||[~ยฌ]|[=!+\-*/^%&|<>#?:]', Operator), (r'[(),\[\]]', Punctuation),
(r'"', String, 'quoted string'), (r'\{\{', String, 'braced string'),
(words(( 'do', 'else', 'elseif', 'endif', 'enduntil', 'fi', 'if', 'ithen', 'kthen', 'od', 'then', 'until', 'while', ), prefix=r'\b', suffix=r'\b'), Keyword), (words(('return', 'rireturn'), prefix=r'\b', suffix=r'\b'), Keyword.Pseudo),
(r'\b[ik]?goto\b', Keyword, 'goto label'), (r'\b(r(?:einit|igoto)|tigoto)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), 'goto label'), (r'\b(c(?:g|in?|k|nk?)goto)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument')), (r'\b(timout)(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument', 'goto argument')), (r'\b(loop_[gl][et])(\(|\b)', bygroups(Keyword.Pseudo, Punctuation), ('goto label', 'goto argument', 'goto argument', 'goto argument')),
(r'\bprintk?s\b', Name.Builtin, 'prints opcode'), (r'\b(?:readscore|scoreline(?:_i)?)\b', Name.Builtin, 'Csound score opcode'), (r'\bpyl?run[it]?\b', Name.Builtin, 'Python opcode'), (r'\blua_(?:exec|opdef)\b', Name.Builtin, 'Lua opcode'), (r'\bp\d+\b', Name.Variable.Instance), (r'\b([A-Z_a-z]\w*)(?:(:)([A-Za-z]))?\b', name_callback) ],
'instrument numbers and identifiers': [ include('whitespace and macro uses'), (r'\d+|[A-Z_a-z]\w*', Name.Function), (r'[+,]', Punctuation), (r'\n', Whitespace, '#pop') ],
'after opcode keyword': [ include('whitespace and macro uses'), (r'[A-Z_a-z]\w*', opcode_name_callback, ('#pop', 'opcode type signatures')), (r'\n', Whitespace, '#pop') ], 'opcode type signatures': [ include('whitespace and macro uses'),
# https://github.com/csound/csound/search?q=XIDENT+path%3AEngine+filename%3Acsound_orc.lex (r'0|[afijkKoOpPStV\[\]]+', Keyword.Type),
(r',', Punctuation), (r'\n', Whitespace, '#pop') ],
'quoted string': [ (r'"', String, '#pop'), (r'[^\\"$%)]+', String), include('macro uses'), include('escape sequences'), include('format specifiers'), (r'[\\$%)]', String) ], 'braced string': [ (r'\}\}', String, '#pop'), (r'(?:[^\\%)}]|\}(?!\}))+', String), include('escape sequences'), include('format specifiers'), (r'[\\%)]', String) ], 'escape sequences': [ # https://github.com/csound/csound/search?q=unquote_string+path%3AEngine+filename%3Acsound_orc_compile.c (r'\\(?:[\\abnrt"]|[0-7]{1,3})', String.Escape) ], # Format specifiers are highlighted in all strings, even though only # fprintks https://csound.com/docs/manual/fprintks.html # fprints https://csound.com/docs/manual/fprints.html # printf/printf_i https://csound.com/docs/manual/printf.html # printks https://csound.com/docs/manual/printks.html # prints https://csound.com/docs/manual/prints.html # sprintf https://csound.com/docs/manual/sprintf.html # sprintfk https://csound.com/docs/manual/sprintfk.html # work with strings that contain format specifiers. In addition, these opcodesโ # handling of format specifiers is inconsistent: # - fprintks and fprints accept %a and %A specifiers, and accept %s specifiers # starting in Csound 6.15.0. # - printks and prints accept %a and %A specifiers, but donโt accept %s # specifiers. # - printf, printf_i, sprintf, and sprintfk donโt accept %a and %A specifiers, # but accept %s specifiers. # See https://github.com/csound/csound/issues/747 for more information. 'format specifiers': [ (r'%[#0\- +]*\d*(?:\.\d+)?[AE-GXac-giosux]', String.Interpol), (r'%%', String.Escape) ],
'goto argument': [ include('whitespace and macro uses'), (r',', Punctuation, '#pop'), include('partial statements') ], 'goto label': [ include('whitespace and macro uses'), (r'\w+', Name.Label, '#pop'), default('#pop') ],
'prints opcode': [ include('whitespace and macro uses'), (r'"', String, 'prints quoted string'), default('#pop') ], 'prints quoted string': [ (r'\\\\[aAbBnNrRtT]', String.Escape), (r'%[!nNrRtT]|[~^]{1,2}', String.Escape), include('quoted string') ],
'Csound score opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Csound score'), (r'\n', Whitespace, '#pop') ], 'Csound score': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(CsoundScoreLexer)) ],
'Python opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Python'), (r'\n', Whitespace, '#pop') ], 'Python': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(PythonLexer)) ],
'Lua opcode': [ include('whitespace and macro uses'), (r'"', String, 'quoted string'), (r'\{\{', String, 'Lua'), (r'\n', Whitespace, '#pop') ], 'Lua': [ (r'\}\}', String, '#pop'), (r'([^}]+)|\}(?!\})', using(LuaLexer)) ] }
class CsoundDocumentLexer(RegexLexer): """ For Csound documents. """
name = 'Csound Document' aliases = ['csound-document', 'csound-csd'] filenames = ['*.csd'] url = 'https://csound.com' version_added = '2.1'
# These tokens are based on those in XmlLexer in pygments/lexers/html.py. Making # CsoundDocumentLexer a subclass of XmlLexer rather than RegexLexer may seem like a # better idea, since Csound Document files look like XML files. However, Csound # Documents can contain Csound comments (preceded by //, for example) before and # after the root element, unescaped bitwise AND & and less than < operators, etc. In # other words, while Csound Document files look like XML files, they may not actually # be XML files. tokens = { 'root': [ (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'(?:;|//).*$', Comment.Single), (r'[^/;<]+|/(?!/)', Text),
(r'<\s*CsInstruments', Name.Tag, ('orchestra', 'tag')), (r'<\s*CsScore', Name.Tag, ('score', 'tag')), (r'<\s*[Hh][Tt][Mm][Ll]', Name.Tag, ('HTML', 'tag')),
(r'<\s*[\w:.-]+', Name.Tag, 'tag'), (r'<\s*/\s*[\w:.-]+\s*>', Name.Tag) ],
'orchestra': [ (r'<\s*/\s*CsInstruments\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*CsInstruments\s*>)', using(CsoundOrchestraLexer)) ], 'score': [ (r'<\s*/\s*CsScore\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*CsScore\s*>)', using(CsoundScoreLexer)) ], 'HTML': [ (r'<\s*/\s*[Hh][Tt][Mm][Ll]\s*>', Name.Tag, '#pop'), (r'(.|\n)+?(?=<\s*/\s*[Hh][Tt][Mm][Ll]\s*>)', using(HtmlLexer)) ],
'tag': [ (r'\s+', Whitespace), (r'[\w.:-]+\s*=', Name.Attribute, 'attr'), (r'/?\s*>', Name.Tag, '#pop') ], 'attr': [ (r'\s+', Whitespace), (r'".*?"', String, '#pop'), (r"'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop') ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632""" pygments.lexers.css ~~~~~~~~~~~~~~~~~~~
Lexers for CSS and related stylesheet formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import reimport copy
from pygments.lexer import ExtendedRegexLexer, RegexLexer, include, bygroups, \ default, words, inheritfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespacefrom pygments.lexers._css_builtins import _css_properties
__all__ = ['CssLexer', 'SassLexer', 'ScssLexer', 'LessCssLexer']
# List of vendor prefixes obtained from:# https://www.w3.org/TR/CSS21/syndata.html#vendor-keyword-history_vendor_prefixes = ( '-ms-', 'mso-', '-moz-', '-o-', '-xv-', '-atsc-', '-wap-', '-khtml-', '-webkit-', 'prince-', '-ah-', '-hp-', '-ro-', '-rim-', '-tc-',)
# List of extended color keywords obtained from:# https://drafts.csswg.org/css-color/#named-colors_color_keywords = ( 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen',) + ('transparent',)
# List of keyword values obtained from:# http://cssvalues.com/_keyword_values = ( 'absolute', 'alias', 'all', 'all-petite-caps', 'all-scroll', 'all-small-caps', 'allow-end', 'alpha', 'alternate', 'alternate-reverse', 'always', 'armenian', 'auto', 'avoid', 'avoid-column', 'avoid-page', 'backwards', 'balance', 'baseline', 'below', 'blink', 'block', 'bold', 'bolder', 'border-box', 'both', 'bottom', 'box-decoration', 'break-word', 'capitalize', 'cell', 'center', 'circle', 'clip', 'clone', 'close-quote', 'col-resize', 'collapse', 'color', 'color-burn', 'color-dodge', 'column', 'column-reverse', 'compact', 'condensed', 'contain', 'container', 'content-box', 'context-menu', 'copy', 'cover', 'crisp-edges', 'crosshair', 'currentColor', 'cursive', 'darken', 'dashed', 'decimal', 'decimal-leading-zero', 'default', 'descendants', 'difference', 'digits', 'disc', 'distribute', 'dot', 'dotted', 'double', 'double-circle', 'e-resize', 'each-line', 'ease', 'ease-in', 'ease-in-out', 'ease-out', 'edges', 'ellipsis', 'end', 'ew-resize', 'exclusion', 'expanded', 'extra-condensed', 'extra-expanded', 'fantasy', 'fill', 'fill-box', 'filled', 'first', 'fixed', 'flat', 'flex', 'flex-end', 'flex-start', 'flip', 'force-end', 'forwards', 'from-image', 'full-width', 'geometricPrecision', 'georgian', 'groove', 'hanging', 'hard-light', 'help', 'hidden', 'hide', 'horizontal', 'hue', 'icon', 'infinite', 'inherit', 'initial', 'ink', 'inline', 'inline-block', 'inline-flex', 'inline-table', 'inset', 'inside', 'inter-word', 'invert', 'isolate', 'italic', 'justify', 'large', 'larger', 'last', 'left', 'lighten', 'lighter', 'line-through', 'linear', 'list-item', 'local', 'loose', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'lowercase', 'ltr', 'luminance', 'luminosity', 'mandatory', 'manipulation', 'manual', 'margin-box', 'match-parent', 'medium', 'mixed', 'monospace', 'move', 'multiply', 'n-resize', 'ne-resize', 'nesw-resize', 'no-close-quote', 'no-drop', 'no-open-quote', 'no-repeat', 'none', 'normal', 'not-allowed', 'nowrap', 'ns-resize', 'nw-resize', 'nwse-resize', 'objects', 'oblique', 'off', 'on', 'open', 'open-quote', 'optimizeLegibility', 'optimizeSpeed', 'outset', 'outside', 'over', 'overlay', 'overline', 'padding-box', 'page', 'pan-down', 'pan-left', 'pan-right', 'pan-up', 'pan-x', 'pan-y', 'paused', 'petite-caps', 'pixelated', 'pointer', 'preserve-3d', 'progress', 'proximity', 'relative', 'repeat', 'repeat no-repeat', 'repeat-x', 'repeat-y', 'reverse', 'revert', 'ridge', 'right', 'round', 'row', 'row-resize', 'row-reverse', 'rtl', 'ruby', 'ruby-base', 'ruby-base-container', 'ruby-text', 'ruby-text-container', 'run-in', 'running', 's-resize', 'sans-serif', 'saturation', 'scale-down', 'screen', 'scroll', 'se-resize', 'semi-condensed', 'semi-expanded', 'separate', 'serif', 'sesame', 'show', 'sideways', 'sideways-left', 'sideways-right', 'slice', 'small', 'small-caps', 'smaller', 'smooth', 'snap', 'soft-light', 'solid', 'space', 'space-around', 'space-between', 'spaces', 'square', 'start', 'static', 'step-end', 'step-start', 'sticky', 'stretch', 'strict', 'stroke-box', 'style', 'sw-resize', 'table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group', 'text', 'thick', 'thin', 'titling-caps', 'to', 'top', 'triangle', 'ultra-condensed', 'ultra-expanded', 'under', 'underline', 'unicase', 'unset', 'upper-alpha', 'upper-latin', 'upper-roman', 'uppercase', 'upright', 'use-glyph-orientation', 'vertical', 'vertical-text', 'view-box', 'visible', 'w-resize', 'wait', 'wavy', 'weight', 'weight style', 'wrap', 'wrap-reverse', 'x-large', 'x-small', 'xx-large', 'xx-small', 'zoom-in', 'zoom-out',)
# List of other keyword values from other sources:_other_keyword_values = ( 'above', 'aural', 'behind', 'bidi-override', 'center-left', 'center-right', 'cjk-ideographic', 'continuous', 'crop', 'cross', 'embed', 'far-left', 'far-right', 'fast', 'faster', 'hebrew', 'high', 'higher', 'hiragana', 'hiragana-iroha', 'katakana', 'katakana-iroha', 'landscape', 'left-side', 'leftwards', 'level', 'loud', 'low', 'lower', 'message-box', 'middle', 'mix', 'narrower', 'once', 'portrait', 'right-side', 'rightwards', 'silent', 'slow', 'slower', 'small-caption', 'soft', 'spell-out', 'status-bar', 'super', 'text-bottom', 'text-top', 'wider', 'x-fast', 'x-high', 'x-loud', 'x-low', 'x-soft', 'yes', 'pre', 'pre-wrap', 'pre-line',)
# List of functional notation and function keyword values:_functional_notation_keyword_values = ( 'attr', 'blackness', 'blend', 'blenda', 'blur', 'brightness', 'calc', 'circle', 'color-mod', 'contrast', 'counter', 'cubic-bezier', 'device-cmyk', 'drop-shadow', 'ellipse', 'gray', 'grayscale', 'hsl', 'hsla', 'hue', 'hue-rotate', 'hwb', 'image', 'inset', 'invert', 'lightness', 'linear-gradient', 'matrix', 'matrix3d', 'opacity', 'perspective', 'polygon', 'radial-gradient', 'rect', 'repeating-linear-gradient', 'repeating-radial-gradient', 'rgb', 'rgba', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'saturate', 'saturation', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'sepia', 'shade', 'skewX', 'skewY', 'steps', 'tint', 'toggle', 'translate', 'translate3d', 'translateX', 'translateY', 'translateZ', 'whiteness',)# Note! Handle url(...) separately.
# List of units obtained from:# https://www.w3.org/TR/css3-values/_angle_units = ( 'deg', 'grad', 'rad', 'turn',)_frequency_units = ( 'Hz', 'kHz',)_length_units = ( 'em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax', 'px', 'mm', 'cm', 'in', 'pt', 'pc', 'q',)_resolution_units = ( 'dpi', 'dpcm', 'dppx',)_time_units = ( 's', 'ms',)_all_units = _angle_units + _frequency_units + _length_units + \ _resolution_units + _time_units
class CssLexer(RegexLexer): """ For CSS (Cascading Style Sheets). """
name = 'CSS' url = 'https://www.w3.org/TR/CSS/#css' aliases = ['css'] filenames = ['*.css'] mimetypes = ['text/css'] version_added = ''
tokens = { 'root': [ include('basics'), ], 'basics': [ (r'\s+', Whitespace), (r'/\*(?:.|\n)*?\*/', Comment), (r'\{', Punctuation, 'content'), (r'(\:{1,2})([\w-]+)', bygroups(Punctuation, Name.Decorator)), (r'(\.)([\w-]+)', bygroups(Punctuation, Name.Class)), (r'(\#)([\w-]+)', bygroups(Punctuation, Name.Namespace)), (r'(@)([\w-]+)', bygroups(Punctuation, Keyword), 'atrule'), (r'[\w-]+', Name.Tag), (r'[~^*!%&$\[\]()<>|+=@:;,./?-]', Operator), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), ], 'atrule': [ (r'\{', Punctuation, 'atcontent'), (r';', Punctuation, '#pop'), include('basics'), ], 'atcontent': [ include('basics'), (r'\}', Punctuation, '#pop:2'), ], 'content': [ (r'\s+', Whitespace), (r'\}', Punctuation, '#pop'), (r';', Punctuation), (r'^@.*?$', Comment.Preproc),
(words(_vendor_prefixes,), Keyword.Pseudo), (r'('+r'|'.join(_css_properties)+r')(\s*)(\:)', bygroups(Keyword, Whitespace, Punctuation), 'value-start'), (r'([-]+[a-zA-Z_][\w-]*)(\s*)(\:)', bygroups(Name.Variable, Whitespace, Punctuation), 'value-start'), (r'([a-zA-Z_][\w-]*)(\s*)(\:)', bygroups(Name, Whitespace, Punctuation), 'value-start'),
(r'/\*(?:.|\n)*?\*/', Comment), ], 'value-start': [ (r'\s+', Whitespace), (words(_vendor_prefixes,), Name.Builtin.Pseudo), include('urls'), (r'('+r'|'.join(_functional_notation_keyword_values)+r')(\()', bygroups(Name.Builtin, Punctuation), 'function-start'), (r'([a-zA-Z_][\w-]+)(\()', bygroups(Name.Function, Punctuation), 'function-start'), (words(_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_other_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_color_keywords, suffix=r'\b'), Keyword.Constant), # for transition-property etc. (words(_css_properties, suffix=r'\b'), Keyword), (r'\!important', Comment.Preproc), (r'/\*(?:.|\n)*?\*/', Comment),
include('numeric-values'),
(r'[~^*!%&<>|+=@:./?-]+', Operator), (r'[\[\](),]+', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_][\w-]*', Name), (r';', Punctuation, '#pop'), (r'\}', Punctuation, '#pop:2'), ], 'function-start': [ (r'\s+', Whitespace), (r'[-]+([A-Za-z][\w+]*[-]*)+', Name.Variable), include('urls'), (words(_vendor_prefixes,), Keyword.Pseudo), (words(_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_other_keyword_values, suffix=r'\b'), Keyword.Constant), (words(_color_keywords, suffix=r'\b'), Keyword.Constant),
# function-start may be entered recursively (r'(' + r'|'.join(_functional_notation_keyword_values) + r')(\()', bygroups(Name.Builtin, Punctuation), 'function-start'), (r'([a-zA-Z_][\w-]+)(\()', bygroups(Name.Function, Punctuation), 'function-start'),
(r'/\*(?:.|\n)*?\*/', Comment), include('numeric-values'), (r'[*+/-]', Operator), (r',', Punctuation), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_-]\w*', Name), (r'\)', Punctuation, '#pop'), ], 'urls': [ (r'(url)(\()(".*?")(\))', bygroups(Name.Builtin, Punctuation, String.Double, Punctuation)), (r"(url)(\()('.*?')(\))", bygroups(Name.Builtin, Punctuation, String.Single, Punctuation)), (r'(url)(\()(.*?)(\))', bygroups(Name.Builtin, Punctuation, String.Other, Punctuation)), ], 'numeric-values': [ (r'\#[a-zA-Z0-9]{1,6}', Number.Hex), (r'[+\-]?[0-9]*[.][0-9]+', Number.Float, 'numeric-end'), (r'[+\-]?[0-9]+', Number.Integer, 'numeric-end'), ], 'numeric-end': [ (words(_all_units, suffix=r'\b'), Keyword.Type), (r'%', Keyword.Type), default('#pop'), ], }
common_sass_tokens = { 'value': [ (r'[ \t]+', Whitespace), (r'[!$][\w-]+', Name.Variable), (r'url\(', String.Other, 'string-url'), (r'[a-z_-][\w-]*(?=\()', Name.Function), (words(_css_properties + ( 'above', 'absolute', 'always', 'armenian', 'aural', 'auto', 'avoid', 'baseline', 'behind', 'below', 'bidi-override', 'blink', 'block', 'bold', 'bolder', 'both', 'capitalize', 'center-left', 'center-right', 'center', 'circle', 'cjk-ideographic', 'close-quote', 'collapse', 'condensed', 'continuous', 'crosshair', 'cross', 'cursive', 'dashed', 'decimal-leading-zero', 'decimal', 'default', 'digits', 'disc', 'dotted', 'double', 'e-resize', 'embed', 'extra-condensed', 'extra-expanded', 'expanded', 'fantasy', 'far-left', 'far-right', 'faster', 'fast', 'fixed', 'georgian', 'groove', 'hebrew', 'help', 'hidden', 'hide', 'higher', 'high', 'hiragana-iroha', 'hiragana', 'icon', 'inherit', 'inline-table', 'inline', 'inset', 'inside', 'invert', 'italic', 'justify', 'katakana-iroha', 'katakana', 'landscape', 'larger', 'large', 'left-side', 'leftwards', 'level', 'lighter', 'line-through', 'list-item', 'loud', 'lower-alpha', 'lower-greek', 'lower-roman', 'lowercase', 'ltr', 'lower', 'low', 'medium', 'message-box', 'middle', 'mix', 'monospace', 'n-resize', 'narrower', 'ne-resize', 'no-close-quote', 'no-open-quote', 'no-repeat', 'none', 'normal', 'nowrap', 'nw-resize', 'oblique', 'once', 'open-quote', 'outset', 'outside', 'overline', 'pointer', 'portrait', 'px', 'relative', 'repeat-x', 'repeat-y', 'repeat', 'rgb', 'ridge', 'right-side', 'rightwards', 's-resize', 'sans-serif', 'scroll', 'se-resize', 'semi-condensed', 'semi-expanded', 'separate', 'serif', 'show', 'silent', 'slow', 'slower', 'small-caps', 'small-caption', 'smaller', 'soft', 'solid', 'spell-out', 'square', 'static', 'status-bar', 'super', 'sw-resize', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group', 'text', 'text-bottom', 'text-top', 'thick', 'thin', 'transparent', 'ultra-condensed', 'ultra-expanded', 'underline', 'upper-alpha', 'upper-latin', 'upper-roman', 'uppercase', 'url', 'visible', 'w-resize', 'wait', 'wider', 'x-fast', 'x-high', 'x-large', 'x-loud', 'x-low', 'x-small', 'x-soft', 'xx-large', 'xx-small', 'yes'), suffix=r'\b'), Name.Constant), (words(_color_keywords, suffix=r'\b'), Name.Entity), (words(( 'black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua'), suffix=r'\b'), Name.Builtin), (r'\!(important|default)', Name.Exception), (r'(true|false)', Name.Pseudo), (r'(and|or|not)', Operator.Word), (r'/\*', Comment.Multiline, 'inline-comment'), (r'//[^\n]*', Comment.Single), (r'\#[a-z0-9]{1,6}', Number.Hex), (r'(-?\d+)(\%|[a-z]+)?', bygroups(Number.Integer, Keyword.Type)), (r'(-?\d*\.\d+)(\%|[a-z]+)?', bygroups(Number.Float, Keyword.Type)), (r'#\{', String.Interpol, 'interpolation'), (r'[~^*!&%<>|+=@:,./?-]+', Operator), (r'[\[\]()]+', Punctuation), (r'"', String.Double, 'string-double'), (r"'", String.Single, 'string-single'), (r'[a-z_-][\w-]*', Name), ],
'interpolation': [ (r'\}', String.Interpol, '#pop'), include('value'), ],
'selector': [ (r'[ \t]+', Whitespace), (r'\:', Name.Decorator, 'pseudo-class'), (r'\.', Name.Class, 'class'), (r'\#', Name.Namespace, 'id'), (r'[\w-]+', Name.Tag), (r'#\{', String.Interpol, 'interpolation'), (r'&', Keyword), (r'[~^*!&\[\]()<>|+=@:;,./?-]', Operator), (r'"', String.Double, 'string-double'), (r"'", String.Single, 'string-single'), ],
'string-double': [ (r'(\\.|#(?=[^\n{])|[^\n"#])+', String.Double), (r'#\{', String.Interpol, 'interpolation'), (r'"', String.Double, '#pop'), ],
'string-single': [ (r"(\\.|#(?=[^\n{])|[^\n'#])+", String.Single), (r'#\{', String.Interpol, 'interpolation'), (r"'", String.Single, '#pop'), ],
'string-url': [ (r'(\\#|#(?=[^\n{])|[^\n#)])+', String.Other), (r'#\{', String.Interpol, 'interpolation'), (r'\)', String.Other, '#pop'), ],
'pseudo-class': [ (r'[\w-]+', Name.Decorator), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'class': [ (r'[\w-]+', Name.Class), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'id': [ (r'[\w-]+', Name.Namespace), (r'#\{', String.Interpol, 'interpolation'), default('#pop'), ],
'for': [ (r'(from|to|through)', Operator.Word), include('value'), ],}
def _indentation(lexer, match, ctx): indentation = match.group(0) yield match.start(), Whitespace, indentation ctx.last_indentation = indentation ctx.pos = match.end()
if hasattr(ctx, 'block_state') and ctx.block_state and \ indentation.startswith(ctx.block_indentation) and \ indentation != ctx.block_indentation: ctx.stack.append(ctx.block_state) else: ctx.block_state = None ctx.block_indentation = None ctx.stack.append('content')
def _starts_block(token, state): def callback(lexer, match, ctx): yield match.start(), token, match.group(0)
if hasattr(ctx, 'last_indentation'): ctx.block_indentation = ctx.last_indentation else: ctx.block_indentation = ''
ctx.block_state = state ctx.pos = match.end()
return callback
class SassLexer(ExtendedRegexLexer): """ For Sass stylesheets. """
name = 'Sass' url = 'https://sass-lang.com/' aliases = ['sass'] filenames = ['*.sass'] mimetypes = ['text/x-sass'] version_added = '1.3'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ (r'[ \t]*\n', Whitespace), (r'[ \t]*', _indentation), ],
'content': [ (r'//[^\n]*', _starts_block(Comment.Single, 'single-comment'), 'root'), (r'/\*[^\n]*', _starts_block(Comment.Multiline, 'multi-comment'), 'root'), (r'@import', Keyword, 'import'), (r'@for', Keyword, 'for'), (r'@(debug|warn|if|while)', Keyword, 'value'), (r'(@mixin)( )([\w-]+)', bygroups(Keyword, Whitespace, Name.Function), 'value'), (r'(@include)( )([\w-]+)', bygroups(Keyword, Whitespace, Name.Decorator), 'value'), (r'@extend', Keyword, 'selector'), (r'@[\w-]+', Keyword, 'selector'), (r'=[\w-]+', Name.Function, 'value'), (r'\+[\w-]+', Name.Decorator, 'value'), (r'([!$][\w-]\w*)([ \t]*(?:(?:\|\|)?=|:))', bygroups(Name.Variable, Operator), 'value'), (r':', Name.Attribute, 'old-style-attr'), (r'(?=.+?[=:]([^a-z]|$))', Name.Attribute, 'new-style-attr'), default('selector'), ],
'single-comment': [ (r'.+', Comment.Single), (r'\n', Whitespace, 'root'), ],
'multi-comment': [ (r'.+', Comment.Multiline), (r'\n', Whitespace, 'root'), ],
'import': [ (r'[ \t]+', Whitespace), (r'\S+', String), (r'\n', Whitespace, 'root'), ],
'old-style-attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'([ \t]*)(=)', bygroups(Whitespace, Operator), 'value'), default('value'), ],
'new-style-attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'([ \t]*)([=:])', bygroups(Whitespace, Operator), 'value'), ],
'inline-comment': [ (r"(\\#|#(?=[^\n{])|\*(?=[^\n/])|[^\n#*])+", Comment.Multiline), (r'#\{', String.Interpol, 'interpolation'), (r"\*/", Comment, '#pop'), ], } for group, common in common_sass_tokens.items(): tokens[group] = copy.copy(common) tokens['value'].append((r'\n', Whitespace, 'root')) tokens['selector'].append((r'\n', Whitespace, 'root'))
class ScssLexer(RegexLexer): """ For SCSS stylesheets. """
name = 'SCSS' url = 'https://sass-lang.com/' aliases = ['scss'] filenames = ['*.scss'] mimetypes = ['text/x-scss'] version_added = ''
flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'\s+', Whitespace), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@import', Keyword, 'value'), (r'@for', Keyword, 'for'), (r'@(debug|warn|if|while)', Keyword, 'value'), (r'(@mixin)( [\w-]+)', bygroups(Keyword, Name.Function), 'value'), (r'(@include)( [\w-]+)', bygroups(Keyword, Name.Decorator), 'value'), (r'@extend', Keyword, 'selector'), (r'(@media)(\s+)', bygroups(Keyword, Whitespace), 'value'), (r'@[\w-]+', Keyword, 'selector'), (r'(\$[\w-]*\w)([ \t]*:)', bygroups(Name.Variable, Operator), 'value'), # TODO: broken, and prone to infinite loops. # (r'(?=[^;{}][;}])', Name.Attribute, 'attr'), # (r'(?=[^;{}:]+:[^a-z])', Name.Attribute, 'attr'), default('selector'), ],
'attr': [ (r'[^\s:="\[]+', Name.Attribute), (r'#\{', String.Interpol, 'interpolation'), (r'[ \t]*:', Operator, 'value'), default('#pop'), ],
'inline-comment': [ (r"(\\#|#(?=[^{])|\*(?=[^/])|[^#*])+", Comment.Multiline), (r'#\{', String.Interpol, 'interpolation'), (r"\*/", Comment, '#pop'), ], } for group, common in common_sass_tokens.items(): tokens[group] = copy.copy(common) tokens['value'].extend([(r'\n', Whitespace), (r'[;{}]', Punctuation, '#pop')]) tokens['selector'].extend([(r'\n', Whitespace), (r'[;{}]', Punctuation, '#pop')])
class LessCssLexer(CssLexer): """ For LESS styleshets. """
name = 'LessCss' url = 'http://lesscss.org/' aliases = ['less'] filenames = ['*.less'] mimetypes = ['text/x-less-css'] version_added = '2.1'
tokens = { # FIXME: It's not currently possible to simply do the following, # as `include('basics')` doesn't take overrides into account: # 'basics': [ # (r'//.*\n', Comment.Single), # (r'/\*(?:.|\n)*?\*/', Comment.Multiline), # inherit, # ], 'root': [ (r'@\w+', Name.Variable), (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'atcontent': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'atrule': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'content': [ (r'\{', Punctuation, '#push'), (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'value-start': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], 'function-start': [ (r'//.*\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), inherit, ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259""" pygments.lexers.d ~~~~~~~~~~~~~~~~~
Lexers for D languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Keyword, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['DLexer', 'CrocLexer', 'MiniDLexer']
class DLexer(RegexLexer): """ For D source. """ name = 'D' url = 'https://dlang.org/' filenames = ['*.d', '*.di'] aliases = ['d'] mimetypes = ['text/x-dsrc'] version_added = '1.2'
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), # (r'\\\n', Text), # line continuations # Comments (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), (r'/\+', Comment.Multiline, 'nested_comment'), # Keywords (words(( 'abstract', 'alias', 'align', 'asm', 'assert', 'auto', 'body', 'break', 'case', 'cast', 'catch', 'class', 'const', 'continue', 'debug', 'default', 'delegate', 'delete', 'deprecated', 'do', 'else', 'enum', 'export', 'extern', 'finally', 'final', 'foreach_reverse', 'foreach', 'for', 'function', 'goto', 'if', 'immutable', 'import', 'interface', 'invariant', 'inout', 'in', 'is', 'lazy', 'mixin', 'module', 'new', 'nothrow', 'out', 'override', 'package', 'pragma', 'private', 'protected', 'public', 'pure', 'ref', 'return', 'scope', 'shared', 'static', 'struct', 'super', 'switch', 'synchronized', 'template', 'this', 'throw', 'try', 'typeid', 'typeof', 'union', 'unittest', 'version', 'volatile', 'while', 'with', '__gshared', '__traits', '__vector', '__parameters'), suffix=r'\b'), Keyword), (words(( # Removed in 2.072 'typedef', ), suffix=r'\b'), Keyword.Removed), (words(( 'bool', 'byte', 'cdouble', 'cent', 'cfloat', 'char', 'creal', 'dchar', 'double', 'float', 'idouble', 'ifloat', 'int', 'ireal', 'long', 'real', 'short', 'ubyte', 'ucent', 'uint', 'ulong', 'ushort', 'void', 'wchar'), suffix=r'\b'), Keyword.Type), (r'(false|true|null)\b', Keyword.Constant), (words(( '__FILE__', '__FILE_FULL_PATH__', '__MODULE__', '__LINE__', '__FUNCTION__', '__PRETTY_FUNCTION__', '__DATE__', '__EOF__', '__TIME__', '__TIMESTAMP__', '__VENDOR__', '__VERSION__'), suffix=r'\b'), Keyword.Pseudo), (r'macro\b', Keyword.Reserved), (r'(string|wstring|dstring|size_t|ptrdiff_t)\b', Name.Builtin), # FloatLiteral # -- HexFloat (r'0[xX]([0-9a-fA-F_]*\.[0-9a-fA-F_]+|[0-9a-fA-F_]+)' r'[pP][+\-]?[0-9_]+[fFL]?[i]?', Number.Float), # -- DecimalFloat (r'[0-9_]+(\.[0-9_]+[eE][+\-]?[0-9_]+|' r'\.[0-9_]*|[eE][+\-]?[0-9_]+)[fFL]?[i]?', Number.Float), (r'\.(0|[1-9][0-9_]*)([eE][+\-]?[0-9_]+)?[fFL]?[i]?', Number.Float), # IntegerLiteral # -- Binary (r'0[Bb][01_]+', Number.Bin), # -- Octal (r'0[0-7_]+', Number.Oct), # -- Hexadecimal (r'0[xX][0-9a-fA-F_]+', Number.Hex), # -- Decimal (r'(0|[1-9][0-9_]*)([LUu]|Lu|LU|uL|UL)?', Number.Integer), # CharacterLiteral (r"""'(\\['"?\\abfnrtv]|\\x[0-9a-fA-F]{2}|\\[0-7]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\&\w+;|.)'""", String.Char), # StringLiteral # -- WysiwygString (r'r"[^"]*"[cwd]?', String), # -- AlternateWysiwygString (r'`[^`]*`[cwd]?', String), # -- DoubleQuotedString (r'"(\\\\|\\[^\\]|[^"\\])*"[cwd]?', String), # -- EscapeSequence (r"\\(['\"?\\abfnrtv]|x[0-9a-fA-F]{2}|[0-7]{1,3}" r"|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|&\w+;)", String), # -- HexString (r'x"[0-9a-fA-F_\s]*"[cwd]?', String), # -- DelimitedString (r'q"\[', String, 'delimited_bracket'), (r'q"\(', String, 'delimited_parenthesis'), (r'q"<', String, 'delimited_angle'), (r'q"\{', String, 'delimited_curly'), (r'q"([a-zA-Z_]\w*)\n.*?\n\1"', String), (r'q"(.).*?\1"', String), # -- TokenString (r'q\{', String, 'token_string'), # Attributes (r'@([a-zA-Z_]\w*)?', Name.Decorator), # Tokens (r'(~=|\^=|%=|\*=|==|!>=|!<=|!<>=|!<>|!<|!>|!=|>>>=|>>>|>>=|>>|>=' r'|<>=|<>|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.\.|\.\.|/=)' r'|[/.&|\-+<>!()\[\]{}?,;:$=*%^~]', Punctuation), # Identifier (r'[a-zA-Z_]\w*', Name), # Line (r'(#line)(\s)(.*)(\n)', bygroups(Comment.Special, Whitespace, Comment.Special, Whitespace)), ], 'nested_comment': [ (r'[^+/]+', Comment.Multiline), (r'/\+', Comment.Multiline, '#push'), (r'\+/', Comment.Multiline, '#pop'), (r'[+/]', Comment.Multiline), ], 'token_string': [ (r'\{', Punctuation, 'token_string_nest'), (r'\}', String, '#pop'), include('root'), ], 'token_string_nest': [ (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), include('root'), ], 'delimited_bracket': [ (r'[^\[\]]+', String), (r'\[', String, 'delimited_inside_bracket'), (r'\]"', String, '#pop'), ], 'delimited_inside_bracket': [ (r'[^\[\]]+', String), (r'\[', String, '#push'), (r'\]', String, '#pop'), ], 'delimited_parenthesis': [ (r'[^()]+', String), (r'\(', String, 'delimited_inside_parenthesis'), (r'\)"', String, '#pop'), ], 'delimited_inside_parenthesis': [ (r'[^()]+', String), (r'\(', String, '#push'), (r'\)', String, '#pop'), ], 'delimited_angle': [ (r'[^<>]+', String), (r'<', String, 'delimited_inside_angle'), (r'>"', String, '#pop'), ], 'delimited_inside_angle': [ (r'[^<>]+', String), (r'<', String, '#push'), (r'>', String, '#pop'), ], 'delimited_curly': [ (r'[^{}]+', String), (r'\{', String, 'delimited_inside_curly'), (r'\}"', String, '#pop'), ], 'delimited_inside_curly': [ (r'[^{}]+', String), (r'\{', String, '#push'), (r'\}', String, '#pop'), ], }
class CrocLexer(RegexLexer): """ For Croc source. """ name = 'Croc' url = 'http://jfbillingsley.com/croc' filenames = ['*.croc'] aliases = ['croc'] mimetypes = ['text/x-crocsrc'] version_added = ''
tokens = { 'root': [ (r'\n', Whitespace), (r'\s+', Whitespace), # Comments (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'/\*', Comment.Multiline, 'nestedcomment'), # Keywords (words(( 'as', 'assert', 'break', 'case', 'catch', 'class', 'continue', 'default', 'do', 'else', 'finally', 'for', 'foreach', 'function', 'global', 'namespace', 'if', 'import', 'in', 'is', 'local', 'module', 'return', 'scope', 'super', 'switch', 'this', 'throw', 'try', 'vararg', 'while', 'with', 'yield'), suffix=r'\b'), Keyword), (r'(false|true|null)\b', Keyword.Constant), # FloatLiteral (r'([0-9][0-9_]*)(?=[.eE])(\.[0-9][0-9_]*)?([eE][+\-]?[0-9_]+)?', Number.Float), # IntegerLiteral # -- Binary (r'0[bB][01][01_]*', Number.Bin), # -- Hexadecimal (r'0[xX][0-9a-fA-F][0-9a-fA-F_]*', Number.Hex), # -- Decimal (r'([0-9][0-9_]*)(?![.eE])', Number.Integer), # CharacterLiteral (r"""'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\[0-9]{1,3}""" r"""|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|.)'""", String.Char), # StringLiteral # -- WysiwygString (r'@"(""|[^"])*"', String), (r'@`(``|[^`])*`', String), (r"@'(''|[^'])*'", String), # -- DoubleQuotedString (r'"(\\\\|\\[^\\]|[^"\\])*"', String), # Tokens (r'(~=|\^=|%=|\*=|==|!=|>>>=|>>>|>>=|>>|>=|<=>|\?=|-\>' r'|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.|/=)' r'|[-/.&$@|\+<>!()\[\]{}?,;:=*%^~#\\]', Punctuation), # Identifier (r'[a-zA-Z_]\w*', Name), ], 'nestedcomment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], }
class MiniDLexer(CrocLexer): """ For MiniD source. MiniD is now known as Croc. """ name = 'MiniD' filenames = [] # don't lex .md as MiniD, reserve for Markdown aliases = ['minid'] mimetypes = ['text/x-minidsrc'] version_added = ''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126""" pygments.lexers.dalvik ~~~~~~~~~~~~~~~~~~~~~~
Pygments lexers for Dalvik VM-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, include, bygroupsfrom pygments.token import Keyword, Text, Comment, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['SmaliLexer']
class SmaliLexer(RegexLexer): """ For Smali (Android/Dalvik) assembly code. """ name = 'Smali' url = 'http://code.google.com/p/smali/' aliases = ['smali'] filenames = ['*.smali'] mimetypes = ['text/smali'] version_added = '1.6'
tokens = { 'root': [ include('comment'), include('label'), include('field'), include('method'), include('class'), include('directive'), include('access-modifier'), include('instruction'), include('literal'), include('punctuation'), include('type'), include('whitespace') ], 'directive': [ (r'^([ \t]*)(\.(?:class|super|implements|field|subannotation|annotation|' r'enum|method|registers|locals|array-data|packed-switch|' r'sparse-switch|catchall|catch|line|parameter|local|prologue|' r'epilogue|source))', bygroups(Whitespace, Keyword)), (r'^([ \t]*)(\.end)( )(field|subannotation|annotation|method|array-data|' 'packed-switch|sparse-switch|parameter|local)', bygroups(Whitespace, Keyword, Whitespace, Keyword)), (r'^([ \t]*)(\.restart)( )(local)', bygroups(Whitespace, Keyword, Whitespace, Keyword)), ], 'access-modifier': [ (r'(public|private|protected|static|final|synchronized|bridge|' r'varargs|native|abstract|strictfp|synthetic|constructor|' r'declared-synchronized|interface|enum|annotation|volatile|' r'transient)', Keyword), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'instruction': [ (r'\b[vp]\d+\b', Name.Builtin), # registers (r'(\b[a-z][A-Za-z0-9/-]+)(\s+)', bygroups(Text, Whitespace)), # instructions ], 'literal': [ (r'".*"', String), (r'0x[0-9A-Fa-f]+t?', Number.Hex), (r'[0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'[0-9]+L?', Number.Integer), ], 'field': [ (r'(\$?\b)([\w$]*)(:)', bygroups(Punctuation, Name.Variable, Punctuation)), ], 'method': [ (r'<(?:cl)?init>', Name.Function), # constructor (r'(\$?\b)([\w$]*)(\()', bygroups(Punctuation, Name.Function, Punctuation)), ], 'label': [ (r':\w+', Name.Label), ], 'class': [ # class names in the form Lcom/namespace/ClassName; # I only want to color the ClassName part, so the namespace part is # treated as 'Text' (r'(L)((?:[\w$]+/)*)([\w$]+)(;)', bygroups(Keyword.Type, Text, Name.Class, Text)), ], 'punctuation': [ (r'->', Punctuation), (r'[{},():=.-]', Punctuation), ], 'type': [ (r'[ZBSCIJFDV\[]+', Keyword.Type), ], 'comment': [ (r'#.*?\n', Comment), ], }
def analyse_text(text): score = 0 if re.search(r'^\s*\.class\s', text, re.MULTILINE): score += 0.5 if re.search(r'\b((check-cast|instance-of|throw-verification-error' r')\b|(-to|add|[ais]get|[ais]put|and|cmpl|const|div|' r'if|invoke|move|mul|neg|not|or|rem|return|rsub|shl|' r'shr|sub|ushr)[-/])|{|}', text, re.MULTILINE): score += 0.3 if re.search(r'(\.(catchall|epilogue|restart local|prologue)|' r'\b(array-data|class-change-error|declared-synchronized|' r'(field|inline|vtable)@0x[0-9a-fA-F]|generic-error|' r'illegal-class-access|illegal-field-access|' r'illegal-method-access|instantiation-error|no-error|' r'no-such-class|no-such-field|no-such-method|' r'packed-switch|sparse-switch))\b', text, re.MULTILINE): score += 0.6 return score123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763""" pygments.lexers.data ~~~~~~~~~~~~~~~~~~~~
Lexers for data file format.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import Lexer, ExtendedRegexLexer, LexerContext, \ include, bygroupsfrom pygments.token import Comment, Error, Keyword, Literal, Name, Number, \ Punctuation, String, Whitespace
__all__ = ['YamlLexer', 'JsonLexer', 'JsonBareObjectLexer', 'JsonLdLexer']
class YamlLexerContext(LexerContext): """Indentation context for the YAML lexer."""
def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.indent_stack = [] self.indent = -1 self.next_indent = 0 self.block_scalar_indent = None
class YamlLexer(ExtendedRegexLexer): """ Lexer for YAML, a human-friendly data serialization language. """
name = 'YAML' url = 'http://yaml.org/' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] version_added = '0.11'
def something(token_class): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), token_class, text context.pos = match.end() return callback
def reset_indent(token_class): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), token_class, text context.pos = match.end() return callback
def save_indent(token_class, start=False): """Save a possible indentation level.""" def callback(lexer, match, context): text = match.group() extra = '' if start: context.next_indent = len(text) if context.next_indent < context.indent: while context.next_indent < context.indent: context.indent = context.indent_stack.pop() if context.next_indent > context.indent: extra = text[context.indent:] text = text[:context.indent] else: context.next_indent += len(text) if text: yield match.start(), token_class, text if extra: yield match.start()+len(text), token_class.Error, extra context.pos = match.end() return callback
def set_indent(token_class, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_indent += len(text) yield match.start(), token_class, text context.pos = match.end() return callback
def set_block_scalar_indent(token_class): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), token_class, text context.pos = match.end() return callback
def parse_block_scalar_empty_line(indent_token_class, content_token_class): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if text: yield match.start(), indent_token_class, text else: indentation = text[:context.block_scalar_indent] content = text[context.block_scalar_indent:] yield match.start(), indent_token_class, indentation yield (match.start()+context.block_scalar_indent, content_token_class, content) context.pos = match.end() return callback
def parse_block_scalar_indent(token_class): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return context.block_scalar_indent = len(text) else: if len(text) < context.block_scalar_indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback
def parse_plain_scalar_indent(token_class): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback
tokens = { # the root rules 'root': [ # ignored whitespaces (r'[ ]+(?=#|$)', Whitespace), # line breaks (r'\n+', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # the '%YAML' directive (r'^%YAML(?=[ ]|$)', reset_indent(Name.Tag), 'yaml-directive'), # the %TAG directive (r'^%TAG(?=[ ]|$)', reset_indent(Name.Tag), 'tag-directive'), # document start and document end indicators (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Name.Namespace), 'block-line'), # indentation spaces (r'[ ]*(?!\s|$)', save_indent(Whitespace, start=True), ('block-line', 'indentation')), ],
# trailing whitespaces after directives or a block scalar indicator 'ignored-line': [ # ignored whitespaces (r'[ ]+(?=#|$)', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # line break (r'\n', Whitespace, '#pop:2'), ],
# the %YAML directive 'yaml-directive': [ # the version number (r'([ ]+)([0-9]+\.[0-9]+)', bygroups(Whitespace, Number), 'ignored-line'), ],
# the %TAG directive 'tag-directive': [ # a tag handle and the corresponding prefix (r'([ ]+)(!|![\w-]*!)' r'([ ]+)(!|!?[\w;/?:@&=+$,.!~*\'()\[\]%-]+)', bygroups(Whitespace, Keyword.Type, Whitespace, Keyword.Type), 'ignored-line'), ],
# block scalar indicators and indentation spaces 'indentation': [ # trailing whitespaces are ignored (r'[ ]*$', something(Whitespace), '#pop:2'), # whitespaces preceding block collection indicators (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Whitespace)), # block collection indicators (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)), # the beginning a block line (r'[ ]*', save_indent(Whitespace), '#pop'), ],
# an indented line in the block context 'block-line': [ # the line end (r'[ ]*(?=#|$)', something(Whitespace), '#pop'), # whitespaces separating tokens (r'[ ]+', Whitespace), # key with colon (r'''([^#,?\[\]{}"'\n]+)(:)(?=[ ]|$)''', bygroups(Name.Tag, set_indent(Punctuation, implicit=True))), # tags, anchors and aliases, include('descriptors'), # block collections and scalars include('block-nodes'), # flow collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`-]|[?:-]\S)', something(Name.Variable), 'plain-scalar-in-block-context'), ],
# tags, anchors, aliases 'descriptors': [ # a full-form tag (r'!<[\w#;/?:@&=+$,.!~*\'()\[\]%-]+>', Keyword.Type), # a tag in the form '!', '!suffix' or '!handle!suffix' (r'!(?:[\w-]+!)?' r'[\w#;/?:@&=+$,.!~*\'()\[\]%-]*', Keyword.Type), # an anchor (r'&[\w-]+', Name.Label), # an alias (r'\*[\w-]+', Name.Variable), ],
# block collections and scalars 'block-nodes': [ # implicit key (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)), # literal and folded scalars (r'[|>]', Punctuation.Indicator, ('block-scalar-content', 'block-scalar-header')), ],
# flow collections and quoted scalars 'flow-nodes': [ # a flow sequence (r'\[', Punctuation.Indicator, 'flow-sequence'), # a flow mapping (r'\{', Punctuation.Indicator, 'flow-mapping'), # a single-quoted scalar (r'\'', String, 'single-quoted-scalar'), # a double-quoted scalar (r'\"', String, 'double-quoted-scalar'), ],
# the content of a flow collection 'flow-collection': [ # whitespaces (r'[ ]+', Whitespace), # line breaks (r'\n+', Whitespace), # a comment (r'#[^\n]*', Comment.Single), # simple indicators (r'[?:,]', Punctuation.Indicator), # tags, anchors and aliases include('descriptors'), # nested collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`])', something(Name.Variable), 'plain-scalar-in-flow-context'), ],
# a flow sequence indicated by '[' and ']' 'flow-sequence': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\]', Punctuation.Indicator, '#pop'), ],
# a flow mapping indicated by '{' and '}' 'flow-mapping': [ # key with colon (r'''([^,:?\[\]{}"'\n]+)(:)(?=[ ]|$)''', bygroups(Name.Tag, Punctuation)), # include flow collection rules include('flow-collection'), # the closing indicator (r'\}', Punctuation.Indicator, '#pop'), ],
# block scalar lines 'block-scalar-content': [ # line break (r'\n', Whitespace), # empty line (r'^[ ]+$', parse_block_scalar_empty_line(Whitespace, Name.Constant)), # indentation spaces (we may leave the state here) (r'^[ ]*', parse_block_scalar_indent(Whitespace)), # line content (r'[\S\t ]+', Name.Constant), ],
# the content of a literal or folded scalar 'block-scalar-header': [ # indentation indicator followed by chomping flag (r'([1-9])?[+-]?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), # chomping flag followed by indentation indicator (r'[+-]?([1-9])?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), ],
# ignored and regular whitespaces in quoted scalars 'quoted-scalar-whitespaces': [ # leading and trailing whitespaces are ignored (r'^[ ]+', Whitespace), (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), ],
# single-quoted scalars 'single-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of the quote character (r'\'\'', String.Escape), # regular non-whitespace characters (r'[^\s\']+', String), # the closing quote (r'\'', String, '#pop'), ],
# double-quoted scalars 'double-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of special characters (r'\\[0abt\tn\nvfre "\\N_LP]', String), # escape codes (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})', String.Escape), # regular non-whitespace characters (r'[^\s"\\]+', String), # the closing quote (r'"', String, '#pop'), ],
# the beginning of a new line while scanning a plain scalar 'plain-scalar-in-block-context-new-line': [ # empty lines (r'^[ ]+$', Whitespace), # line breaks (r'\n+', Whitespace), # document start and document end indicators (r'^(?=---|\.\.\.)', something(Name.Namespace), '#pop:3'), # indentation spaces (we may leave the block line state here) (r'^[ ]*', parse_plain_scalar_indent(Whitespace), '#pop'), ],
# a plain scalar in the block context 'plain-scalar-in-block-context': [ # the scalar ends with the ':' indicator (r'[ ]*(?=:[ ]|:$)', something(Whitespace), '#pop'), # the scalar ends with whitespaces followed by a comment (r'[ ]+(?=#)', Whitespace, '#pop'), # trailing whitespaces are ignored (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace, 'plain-scalar-in-block-context-new-line'), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'(?::(?!\s)|[^\s:])+', Literal.Scalar.Plain), ],
# a plain scalar is the flow context 'plain-scalar-in-flow-context': [ # the scalar ends with an indicator character (r'[ ]*(?=[,:?\[\]{}])', something(Whitespace), '#pop'), # the scalar ends with a comment (r'[ ]+(?=#)', Whitespace, '#pop'), # leading and trailing whitespaces are ignored (r'^[ ]+', Whitespace), (r'[ ]+$', Whitespace), # line breaks are ignored (r'\n+', Whitespace), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), # regular non-whitespace characters (r'[^\s,:?\[\]{}]+', Name.Variable), ],
}
def get_tokens_unprocessed(self, text=None, context=None): if context is None: context = YamlLexerContext(text, 0) return super().get_tokens_unprocessed(text, context)
class JsonLexer(Lexer): """ For JSON data structures.
Javascript-style comments are supported (like ``/* */`` and ``//``), though comments are not part of the JSON specification. This allows users to highlight JSON as it is used in the wild.
No validation is performed on the input JSON document. """
name = 'JSON' url = 'https://www.json.org' aliases = ['json', 'json-object'] filenames = ['*.json', '*.jsonl', '*.ndjson', 'Pipfile.lock', '*.module', '*.xc'] mimetypes = ['application/json', 'application/json-object', 'application/x-ndjson', 'application/jsonl', 'application/json-seq'] version_added = '1.5'
# No validation of integers, floats, or constants is done. # As long as the characters are members of the following # sets, the token will be considered valid. For example, # # "--1--" is parsed as an integer # "1...eee" is parsed as a float # "trustful" is parsed as a constant # integers = set('-0123456789') floats = set('.eE+') constants = set('truefalsenull') # true|false|null hexadecimals = set('0123456789abcdefABCDEF') punctuations = set('{}[],') whitespaces = {'\u0020', '\u000a', '\u000d', '\u0009'}
def get_tokens_unprocessed(self, text): """Parse JSON data."""
in_string = False in_escape = False in_unicode_escape = 0 in_whitespace = False in_constant = False in_number = False in_float = False in_punctuation = False in_comment_single = False in_comment_multiline = False expecting_second_comment_opener = False # // or /* expecting_second_comment_closer = False # */
start = 0
# The queue is used to store data that may need to be tokenized # differently based on what follows. In particular, JSON object # keys are tokenized differently than string values, but cannot # be distinguished until punctuation is encountered outside the # string. # # A ":" character after the string indicates that the string is # an object key; any other character indicates the string is a # regular string value. # # The queue holds tuples that contain the following data: # # (start_index, token_type, text) # # By default the token type of text in double quotes is # String.Double. The token type will be replaced if a colon # is encountered after the string closes. # queue = []
for stop, character in enumerate(text): if in_string: if in_unicode_escape: if character in self.hexadecimals: in_unicode_escape -= 1 if not in_unicode_escape: in_escape = False else: in_unicode_escape = 0 in_escape = False
elif in_escape: if character == 'u': in_unicode_escape = 4 else: in_escape = False
elif character == '\\': in_escape = True
elif character == '"': queue.append((start, String.Double, text[start:stop + 1])) in_string = False in_escape = False in_unicode_escape = 0
continue
elif in_whitespace: if character in self.whitespaces: continue
if queue: queue.append((start, Whitespace, text[start:stop])) else: yield start, Whitespace, text[start:stop] in_whitespace = False # Fall through so the new character can be evaluated.
elif in_constant: if character in self.constants: continue
yield start, Keyword.Constant, text[start:stop] in_constant = False # Fall through so the new character can be evaluated.
elif in_number: if character in self.integers: continue elif character in self.floats: in_float = True continue
if in_float: yield start, Number.Float, text[start:stop] else: yield start, Number.Integer, text[start:stop] in_number = False in_float = False # Fall through so the new character can be evaluated.
elif in_punctuation: if character in self.punctuations: continue
yield start, Punctuation, text[start:stop] in_punctuation = False # Fall through so the new character can be evaluated.
elif in_comment_single: if character != '\n': continue
if queue: queue.append((start, Comment.Single, text[start:stop])) else: yield start, Comment.Single, text[start:stop]
in_comment_single = False # Fall through so the new character can be evaluated.
elif in_comment_multiline: if character == '*': expecting_second_comment_closer = True elif expecting_second_comment_closer: expecting_second_comment_closer = False if character == '/': if queue: queue.append((start, Comment.Multiline, text[start:stop + 1])) else: yield start, Comment.Multiline, text[start:stop + 1]
in_comment_multiline = False
continue
elif expecting_second_comment_opener: expecting_second_comment_opener = False if character == '/': in_comment_single = True continue elif character == '*': in_comment_multiline = True continue
# Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
yield start, Error, text[start:stop] # Fall through so the new character can be evaluated.
start = stop
if character == '"': in_string = True
elif character in self.whitespaces: in_whitespace = True
elif character in {'f', 'n', 't'}: # The first letters of true|false|null # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_constant = True
elif character in self.integers: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_number = True
elif character == ':': # Yield from the queue. Replace string token types. for _start, _token, _text in queue: # There can be only three types of tokens before a ':': # Whitespace, Comment, or a quoted string. # # If it's a quoted string we emit Name.Tag. # Otherwise, we yield the original token. # # In all other cases this would be invalid JSON, # but this is not a validating JSON lexer, so it's OK. if _token is String.Double: yield _start, Name.Tag, _text else: yield _start, _token, _text queue.clear()
in_punctuation = True
elif character in self.punctuations: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
in_punctuation = True
elif character == '/': # This is the beginning of a comment. expecting_second_comment_opener = True
else: # Exhaust the queue. Accept the existing token types. yield from queue queue.clear()
yield start, Error, character
# Yield any remaining text. yield from queue if in_string: yield start, Error, text[start:] elif in_float: yield start, Number.Float, text[start:] elif in_number: yield start, Number.Integer, text[start:] elif in_constant: yield start, Keyword.Constant, text[start:] elif in_whitespace: yield start, Whitespace, text[start:] elif in_punctuation: yield start, Punctuation, text[start:] elif in_comment_single: yield start, Comment.Single, text[start:] elif in_comment_multiline: yield start, Error, text[start:] elif expecting_second_comment_opener: yield start, Error, text[start:]
class JsonBareObjectLexer(JsonLexer): """ For JSON data structures (with missing object curly braces).
.. deprecated:: 2.8.0
Behaves the same as `JsonLexer` now. """
name = 'JSONBareObject' aliases = [] filenames = [] mimetypes = [] version_added = '2.2'
class JsonLdLexer(JsonLexer): """ For JSON-LD linked data. """
name = 'JSON-LD' url = 'https://json-ld.org/' aliases = ['jsonld', 'json-ld'] filenames = ['*.jsonld'] mimetypes = ['application/ld+json'] version_added = '2.0'
json_ld_keywords = { f'"@{keyword}"' for keyword in ( 'base', 'container', 'context', 'direction', 'graph', 'id', 'import', 'included', 'index', 'json', 'language', 'list', 'nest', 'none', 'prefix', 'propagate', 'protected', 'reverse', 'set', 'type', 'value', 'version', 'vocab', ) }
def get_tokens_unprocessed(self, text): for start, token, value in super().get_tokens_unprocessed(text): if token is Name.Tag and value in self.json_ld_keywords: yield start, Name.Decorator, value else: yield start, token, value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135""" pygments.lexers.dax ~~~~~~~~~~~~~~~~~~~
Lexer for LilyPond.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, wordsfrom pygments.token import Comment, Punctuation, Whitespace,\ Name, Operator, String, Number, Text
__all__ = ['DaxLexer']
class DaxLexer(RegexLexer): """ Lexer for Power BI DAX Referenced from: https://github.com/sql-bi/SyntaxHighlighterBrushDax """ name = 'Dax' aliases = ['dax'] filenames = ['*.dax'] url = 'https://learn.microsoft.com/en-us/dax/dax-function-reference' mimetypes = [] version_added = '2.15'
tokens = { 'root': [ (r'\s+', Whitespace), (r"--.*\n?", Comment.Single), # Comment: Double dash comment (r"//.*\n?", Comment.Single), # Comment: Double backslash comment (r'/\*', Comment.Multiline, 'multiline-comments'), (words(('abs', 'accrint', 'accrintm', 'acos', 'acosh', 'acot', 'acoth', 'addcolumns', 'addmissingitems', 'all', 'allcrossfiltered', 'allexcept', 'allnoblankrow', 'allselected', 'amordegrc', 'amorlinc', 'and','approximatedistinctcount', 'asin', 'asinh', 'atan', 'atanh', 'average', 'averagea', 'averagex', 'beta.dist', 'beta.inv', 'bitand', 'bitlshift', 'bitor', 'bitrshift', 'bitxor', 'blank', 'calculate', 'calculatetable', 'calendar', 'calendarauto', 'ceiling', 'chisq.dist', 'chisq.dist.rt', 'chisq.inv', 'chisq.inv.rt', 'closingbalancemonth', 'closingbalancequarter', 'closingbalanceyear', 'coalesce', 'columnstatistics', 'combin', 'combina', 'combinevalues', 'concatenate', 'concatenatex', 'confidence.norm', 'confidence.t', 'contains', 'containsrow', 'containsstring', 'containsstringexact', 'convert', 'cos', 'cosh', 'cot', 'coth', 'count', 'counta', 'countax', 'countblank', 'countrows', 'countx', 'coupdaybs', 'coupdays', 'coupdaysnc', 'coupncd', 'coupnum', 'couppcd', 'crossfilter', 'crossjoin', 'cumipmt', 'cumprinc', 'currency', 'currentgroup', 'customdata', 'datatable', 'date', 'dateadd', 'datediff', 'datesbetween', 'datesinperiod', 'datesmtd', 'datesqtd', 'datesytd', 'datevalue', 'day', 'db', 'ddb', 'degrees', 'detailrows', 'disc', 'distinct', 'distinctcount', 'distinctcountnoblank', 'divide', 'dollarde', 'dollarfr', 'duration', 'earlier', 'earliest', 'edate', 'effect', 'endofmonth', 'endofquarter', 'endofyear', 'eomonth', 'error', 'evaluateandlog', 'even', 'exact', 'except', 'exp', 'expon.dist', 'fact', 'false', 'filter', 'filters', 'find', 'firstdate', 'firstnonblank', 'firstnonblankvalue', 'fixed', 'floor', 'format', 'fv', 'gcd', 'generate', 'generateall', 'generateseries', 'geomean', 'geomeanx', 'groupby', 'hash', 'hasonefilter', 'hasonevalue', 'hour', 'if', 'if.eager', 'iferror', 'ignore', 'index', 'int', 'intersect', 'intrate', 'ipmt', 'isafter', 'isblank', 'iscrossfiltered', 'isempty', 'iserror', 'iseven', 'isfiltered', 'isinscope', 'islogical', 'isnontext', 'isnumber', 'iso.ceiling', 'isodd', 'isonorafter', 'ispmt', 'isselectedmeasure', 'issubtotal', 'istext', 'keepfilters', 'keywordmatch', 'lastdate', 'lastnonblank', 'lastnonblankvalue', 'lcm', 'left', 'len', 'linest', 'linestx', 'ln', 'log', 'log10', 'lookupvalue', 'lower', 'max', 'maxa', 'maxx', 'mduration', 'median', 'medianx', 'mid', 'min', 'mina', 'minute', 'minx', 'mod', 'month', 'mround', 'nameof', 'naturalinnerjoin', 'naturalleftouterjoin', 'networkdays', 'nextday', 'nextmonth', 'nextquarter', 'nextyear', 'nominal', 'nonvisual', 'norm.dist', 'norm.inv', 'norm.s.dist', 'norm.s.inv', 'not', 'now', 'nper', 'odd', 'oddfprice', 'oddfyield', 'oddlprice', 'oddlyield', 'offset', 'openingbalancemonth', 'openingbalancequarter', 'openingbalanceyear', 'or', 'orderby', 'parallelperiod', 'partitionby', 'path', 'pathcontains', 'pathitem', 'pathitemreverse', 'pathlength', 'pduration', 'percentile.exc', 'percentile.inc', 'percentilex.exc', 'percentilex.inc', 'permut', 'pi', 'pmt', 'poisson.dist', 'power', 'ppmt', 'previousday', 'previousmonth', 'previousquarter', 'previousyear', 'price', 'pricedisc', 'pricemat', 'product', 'productx', 'pv', 'quarter', 'quotient', 'radians', 'rand', 'randbetween', 'rank.eq', 'rankx', 'rate', 'received', 'related', 'relatedtable', 'removefilters', 'replace', 'rept', 'right', 'rollup', 'rollupaddissubtotal', 'rollupgroup', 'rollupissubtotal', 'round', 'rounddown', 'roundup', 'row', 'rri', 'sameperiodlastyear', 'sample', 'sampleaxiswithlocalminmax', 'search', 'second', 'selectcolumns', 'selectedmeasure', 'selectedmeasureformatstring', 'selectedmeasurename', 'selectedvalue', 'sign', 'sin', 'sinh', 'sln', 'sqrt', 'sqrtpi', 'startofmonth', 'startofquarter', 'startofyear', 'stdev.p', 'stdev.s', 'stdevx.p', 'stdevx.s', 'substitute', 'substitutewithindex', 'sum', 'summarize', 'summarizecolumns', 'sumx', 'switch', 'syd', 't.dist', 't.dist.2t', 't.dist.rt', 't.inv', 't.inv.2t', 'tan', 'tanh', 'tbilleq', 'tbillprice', 'tbillyield', 'time', 'timevalue', 'tocsv', 'today', 'tojson', 'topn', 'topnperlevel', 'topnskip', 'totalmtd', 'totalqtd', 'totalytd', 'treatas', 'trim', 'true', 'trunc', 'unichar', 'unicode', 'union', 'upper', 'userculture', 'userelationship', 'username', 'userobjectid', 'userprincipalname', 'utcnow', 'utctoday', 'value', 'values', 'var.p', 'var.s', 'varx.p', 'varx.s', 'vdb', 'weekday', 'weeknum', 'window', 'xirr', 'xnpv', 'year', 'yearfrac', 'yield', 'yielddisc', 'yieldmat'), prefix=r'(?i)', suffix=r'\b'), Name.Function), #Functions
(words(('at','asc','boolean','both','by','create','currency', 'datetime','day','define','desc','double', 'evaluate','false','integer','measure', 'month','none','order','return','single','start','string', 'table','true','var','year'), prefix=r'(?i)', suffix=r'\b'), Name.Builtin), # Keyword
(r':=|[-+*\/=^]', Operator), (r'\b(IN|NOT)\b', Operator.Word), (r'"', String, 'string'), #StringLiteral (r"'(?:[^']|'')*'(?!')(?:\[[ \w]+\])?|\w+\[[ \w]+\]", Name.Attribute), # Column reference (r"\[[ \w]+\]", Name.Attribute), #Measure reference (r'(?<!\w)(\d+\.?\d*|\.\d+\b)', Number),# Number (r'[\[\](){}`,.]', Punctuation), #Parenthesis (r'.*\n', Text),
], 'multiline-comments': [ (r'/\*', Comment.Multiline, 'multiline-comments'), (r'\*/', Comment.Multiline, '#pop'), (r'[^/*]+', Comment.Multiline), (r'[/*]', Comment.Multiline) ], 'string': [ (r'""', String.Escape), (r'"', String, '#pop'), (r'[^"]+', String), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120""" pygments.lexers.devicetree ~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Devicetree language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, default, wordsfrom pygments.token import Comment, Keyword, Name, Number, Operator, \ Punctuation, String, Text, Whitespace
__all__ = ['DevicetreeLexer']
class DevicetreeLexer(RegexLexer): """ Lexer for Devicetree files. """
name = 'Devicetree' url = 'https://www.devicetree.org/' aliases = ['devicetree', 'dts'] filenames = ['*.dts', '*.dtsi'] mimetypes = ['text/x-c'] version_added = '2.7'
#: optional Whitespace or /*...*/ style comment _ws = r'\s*(?:/[*][^*/]*?[*]/\s*)*'
tokens = { 'macro': [ # Include preprocessor directives (C style): (r'(#include)(' + _ws + r')([^\n]+)', bygroups(Comment.Preproc, Comment.Multiline, Comment.PreprocFile)), # Define preprocessor directives (C style): (r'(#define)(' + _ws + r')([^\n]+)', bygroups(Comment.Preproc, Comment.Multiline, Comment.Preproc)), # devicetree style with file: (r'(/[^*/{]+/)(' + _ws + r')("[^\n{]+")', bygroups(Comment.Preproc, Comment.Multiline, Comment.PreprocFile)), # devicetree style with property: (r'(/[^*/{]+/)(' + _ws + r')([^\n;{]*)([;]?)', bygroups(Comment.Preproc, Comment.Multiline, Comment.Preproc, Punctuation)), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'\\\n', Text), # line continuation (r'//(\n|[\w\W]*?[^\\]\n)', Comment.Single), (r'/(\\\n)?[*][\w\W]*?[*](\\\n)?/', Comment.Multiline), # Open until EOF, so no ending delimiter (r'/(\\\n)?[*][\w\W]*', Comment.Multiline), ], 'statements': [ (r'(L?)(")', bygroups(String.Affix, String), 'string'), (r'0x[0-9a-fA-F]+', Number.Hex), (r'\d+', Number.Integer), (r'([^\s{}/*]*)(\s*)(:)', bygroups(Name.Label, Text, Punctuation), '#pop'), (words(('compatible', 'model', 'phandle', 'status', '#address-cells', '#size-cells', 'reg', 'virtual-reg', 'ranges', 'dma-ranges', 'device_type', 'name'), suffix=r'\b'), Keyword.Reserved), (r'([~!%^&*+=|?:<>/#-])', Operator), (r'[(){},.\]]', Punctuation), (r'\[', Punctuation, 'bytestring'), (r'[a-zA-Z_][\w-]*(?=(?:\s*,' + _ws + r'[a-zA-Z_][\w-]*)*' + _ws + r'[=;])', Name), (r'[a-zA-Z_]\w*', Name.Attribute), ], 'root': [ include('whitespace'), include('macro'), # Overlay/fragment: &label { ... } or &{/path/to/node} { ... } (r'(&)(?:([A-Za-z_]\w*)|(\{)([^}]+)(\}))(' + _ws + r')(\{)', bygroups(Operator, Name.Function, Punctuation, Name.Namespace, Punctuation, Comment.Multiline, Punctuation), 'node'), # Nodes (r'([^/*@\s&]+|/)(@?)((?:0x)?[0-9a-fA-F,]*)(' + _ws + r')(\{)', bygroups(Name.Function, Operator, Number.Integer, Comment.Multiline, Punctuation), 'node'),
default('statement'), ], 'statement': [ include('whitespace'), include('statements'), (';', Punctuation, '#pop'), ], 'node': [ include('whitespace'), include('macro'), # Overlay/fragment: &label { ... } or &{/path/to/node} { ... } (r'(&)(?:([A-Za-z_]\w*)|(\{)([^}]+)(\}))(' + _ws + r')(\{)', bygroups(Operator, Name.Function, Punctuation, Name.Namespace, Punctuation, Comment.Multiline, Punctuation), '#push'), (r'([^/*@\s&]+|/)(@?)((?:0x)?[0-9a-fA-F,]*)(' + _ws + r')(\{)', bygroups(Name.Function, Operator, Number.Integer, Comment.Multiline, Punctuation), '#push'),
include('statements'),
(r'\};', Punctuation, '#pop'), (';', Punctuation), ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|' r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash ], 'bytestring': [ (r'\]', Punctuation, '#pop'), (r'[0-9a-fA-F]{2}', Number.Hex), (r'\s+', Whitespace), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169""" pygments.lexers.diff ~~~~~~~~~~~~~~~~~~~~
Lexers for diff/patch formats.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import RegexLexer, include, bygroupsfrom pygments.token import Text, Comment, Operator, Keyword, Name, Generic, \ Literal, Whitespace
__all__ = ['DiffLexer', 'DarcsPatchLexer', 'WDiffLexer']
class DiffLexer(RegexLexer): """ Lexer for unified or context-style diffs or patches. """
name = 'Diff' aliases = ['diff', 'udiff'] filenames = ['*.diff', '*.patch'] mimetypes = ['text/x-diff', 'text/x-patch'] url = 'https://en.wikipedia.org/wiki/Diff' version_added = ''
tokens = { 'root': [ (r'( )(.*)(\n)', bygroups(Whitespace, Text, Whitespace)), (r'(!.*|---)(\n)', bygroups(Generic.Strong, Whitespace)), (r'((?:< |-).*)(\n)', bygroups(Generic.Deleted, Whitespace)), (r'((?:> |\+).*)(\n)', bygroups(Generic.Inserted, Whitespace)), ( r'(@.*|\d(?:,\d+)?(?:a|c|d)\d+(?:,\d+)?)(\n)', bygroups(Generic.Subheading, Whitespace), ), (r'((?:[Ii]ndex|diff).*)(\n)', bygroups(Generic.Heading, Whitespace)), (r'(=.*)(\n)', bygroups(Generic.Heading, Whitespace)), (r'(.*)(\n)', bygroups(Text, Whitespace)), ] }
def analyse_text(text): if text[:7] == 'Index: ': return True if text[:5] == 'diff ': return True if text[:4] == '--- ': return 0.9
class DarcsPatchLexer(RegexLexer): """ DarcsPatchLexer is a lexer for the various versions of the darcs patch format. Examples of this format are derived by commands such as ``darcs annotate --patch`` and ``darcs send``. """
name = 'Darcs Patch' aliases = ['dpatch'] filenames = ['*.dpatch', '*.darcspatch'] url = 'https://darcs.net' version_added = '0.10'
DPATCH_KEYWORDS = ('hunk', 'addfile', 'adddir', 'rmfile', 'rmdir', 'move', 'replace')
tokens = { 'root': [ (r'<', Operator), (r'>', Operator), (r'\{', Operator), (r'\}', Operator), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)(\])', bygroups(Operator, Keyword, Name, Whitespace, Name, Operator, Literal.Date, Whitespace, Operator)), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)', bygroups(Operator, Keyword, Name, Whitespace, Name, Operator, Literal.Date, Whitespace), 'comment'), (r'New patches:', Generic.Heading), (r'Context:', Generic.Heading), (r'Patch bundle hash:', Generic.Heading), (r'(\s*)({})(.*)(\n)'.format('|'.join(DPATCH_KEYWORDS)), bygroups(Whitespace, Keyword, Text, Whitespace)), (r'\+', Generic.Inserted, "insert"), (r'-', Generic.Deleted, "delete"), (r'(.*)(\n)', bygroups(Text, Whitespace)), ], 'comment': [ (r'[^\]].*\n', Comment), (r'\]', Operator, "#pop"), ], 'specialText': [ # darcs add [_CODE_] special operators for clarity (r'\n', Whitespace, "#pop"), # line-based (r'\[_[^_]*_]', Operator), ], 'insert': [ include('specialText'), (r'\[', Generic.Inserted), (r'[^\n\[]+', Generic.Inserted), ], 'delete': [ include('specialText'), (r'\[', Generic.Deleted), (r'[^\n\[]+', Generic.Deleted), ], }
class WDiffLexer(RegexLexer): """ A wdiff lexer.
Note that:
* It only works with normal output (without options like ``-l``). * If the target files contain "[-", "-]", "{+", or "+}", especially they are unbalanced, the lexer will get confused. """
name = 'WDiff' url = 'https://www.gnu.org/software/wdiff/' aliases = ['wdiff'] filenames = ['*.wdiff'] mimetypes = [] version_added = '2.2'
flags = re.MULTILINE | re.DOTALL
# We can only assume "[-" after "[-" before "-]" is `nested`, # for instance wdiff to wdiff outputs. We have no way to # distinct these marker is of wdiff output from original text.
ins_op = r"\{\+" ins_cl = r"\+\}" del_op = r"\[\-" del_cl = r"\-\]" normal = r'[^{}[\]+-]+' # for performance tokens = { 'root': [ (ins_op, Generic.Inserted, 'inserted'), (del_op, Generic.Deleted, 'deleted'), (normal, Text), (r'.', Text), ], 'inserted': [ (ins_op, Generic.Inserted, '#push'), (del_op, Generic.Inserted, '#push'), (del_cl, Generic.Inserted, '#pop'),
(ins_cl, Generic.Inserted, '#pop'), (normal, Generic.Inserted), (r'.', Generic.Inserted), ], 'deleted': [ (del_op, Generic.Deleted, '#push'), (ins_op, Generic.Deleted, '#push'), (ins_cl, Generic.Deleted, '#pop'),
(del_cl, Generic.Deleted, '#pop'), (normal, Generic.Deleted), (r'.', Generic.Deleted), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109""" pygments.lexers.dns ~~~~~~~~~~~~~~~~~~~
Pygments lexers for DNS
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace, Literalfrom pygments.lexer import RegexLexer, bygroups, include
__all__ = ['DnsZoneLexer']
CLASSES = [ "IN", "CS", "CH", "HS",]
CLASSES_RE = "(" + "|".join(CLASSES) + ')'
class DnsZoneLexer(RegexLexer):
""" Lexer for DNS zone file """
flags = re.MULTILINE
name = 'Zone' aliases = ['zone'] filenames = [ "*.zone" ] url = "https://datatracker.ietf.org/doc/html/rfc1035" mimetypes = ['text/dns'] version_added = '2.16'
tokens = { 'root': [ # Empty/comment line: (r'([ \t]*)(;.*)(\n)', bygroups(Whitespace, Comment.Single, Whitespace)), # Special directives: (r'^\$ORIGIN\b', Keyword, 'values'), (r'^\$TTL\b', Keyword, 'values'), (r'^\$INCLUDE\b', Comment.Preproc, 'include'), # TODO, $GENERATE https://bind9.readthedocs.io/en/v9.18.14/chapter3.html#soa-rr (r'^\$[A-Z]+\b', Keyword, 'values'), # Records: # <domain-name> [<TTL>] [<class>] <type> <RDATA> [<comment>] (r'^(@)([ \t]+)(?:([0-9]+[smhdw]?)([ \t]+))?(?:' + CLASSES_RE + "([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Operator, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), (r'^([^ \t\n]*)([ \t]+)(?:([0-9]+[smhdw]?)([ \t]+))?(?:' + CLASSES_RE + "([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), # <domain-name> [<class>] [<TTL>] <type> <RDATA> [<comment>] (r'^(Operator)([ \t]+)(?:' + CLASSES_RE + "([ \t]+))?(?:([0-9]+[smhdw]?)([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), (r'^([^ \t\n]*)([ \t]+)(?:' + CLASSES_RE + "([ \t]+))?(?:([0-9]+[smhdw]?)([ \t]+))?([A-Z]+)([ \t]+)", bygroups(Name, Whitespace, Number.Integer, Whitespace, Name.Class, Whitespace, Keyword.Type, Whitespace), "values"), ], # Parsing values: 'values': [ (r'\n', Whitespace, "#pop"), (r'\(', Punctuation, 'nested'), include('simple-value'), ], # Parsing nested values (...): 'nested': [ (r'\)', Punctuation, "#pop"), include('multiple-simple-values'), ], # Parsing values: 'simple-value': [ (r'(;.*)', bygroups(Comment.Single)), (r'[ \t]+', Whitespace), (r"@\b", Operator), ('"', String, 'string'), (r'[0-9]+[smhdw]?$', Number.Integer), (r'([0-9]+[smhdw]?)([ \t]+)', bygroups(Number.Integer, Whitespace)), (r'\S+', Literal), ], 'multiple-simple-values': [ include('simple-value'), (r'[\n]+', Whitespace), ], 'include': [ (r'([ \t]+)([^ \t\n]+)([ \t]+)([-\._a-zA-Z]+)([ \t]+)(;.*)?$', bygroups(Whitespace, Comment.PreprocFile, Whitespace, Name, Whitespace, Comment.Single), '#pop'), (r'([ \t]+)([^ \t\n]+)([ \t\n]+)$', bygroups(Whitespace, Comment.PreprocFile, Whitespace), '#pop'), ], "string": [ (r'\\"', String), (r'"', String, "#pop"), (r'[^"]+', String), ] }
def analyse_text(text): return text.startswith("$ORIGIN")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873""" pygments.lexers.dotnet ~~~~~~~~~~~~~~~~~~~~~~
Lexers for .net languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""import re
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \ using, this, default, wordsfrom pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String, Number, Literal, Other, Whitespacefrom pygments.util import get_choice_optfrom pygments import unistring as uni
from pygments.lexers.html import XmlLexer
__all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer', 'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer', 'XppLexer']
class CSharpLexer(RegexLexer): """ For C# source code.
Additional options accepted:
`unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``.
.. versionadded:: 0.8 """
name = 'C#' url = 'https://docs.microsoft.com/en-us/dotnet/csharp/' aliases = ['csharp', 'c#', 'cs'] filenames = ['*.cs'] mimetypes = ['text/x-csharp'] # inferred version_added = ''
flags = re.MULTILINE | re.DOTALL
# for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = { 'none': r'@?[_a-zA-Z]\w*', 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), }
tokens = {} token_variants = True
for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ include('numbers'), # method names (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, Punctuation)), (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Whitespace), (words(( '>>>=', '>>=', '<<=', '<=', '>=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '??=', '=>', '??', '?.', '!=', '==', '&&', '||', '>>>', '>>', '<<', '++', '--', '+', '-', '*', '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', )), Operator), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'[()\[\];:,.]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b(.*?)(\n)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Comment.Preproc, Whitespace)), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), (words(( 'abstract', 'as', 'async', 'await', 'base', 'break', 'by', 'case', 'catch', 'checked', 'const', 'continue', 'default', 'delegate', 'do', 'else', 'enum', 'event', 'explicit', 'extern', 'false', 'finally', 'fixed', 'for', 'foreach', 'goto', 'if', 'implicit', 'in', 'interface', 'internal', 'is', 'let', 'lock', 'new', 'null', 'on', 'operator', 'out', 'override', 'params', 'private', 'protected', 'public', 'readonly', 'ref', 'return', 'sealed', 'sizeof', 'stackalloc', 'static', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'unchecked', 'unsafe', 'virtual', 'void', 'while', 'get', 'set', 'new', 'partial', 'yield', 'add', 'remove', 'value', 'alias', 'ascending', 'descending', 'from', 'group', 'into', 'orderby', 'select', 'thenby', 'where', 'join', 'equals', 'record', 'allows', 'and', 'init', 'managed', 'nameof', 'nint', 'not', 'notnull', 'nuint', 'or', 'scoped', 'unmanaged', 'when', 'with' ), suffix=r'\b'), Keyword), # version 1: assumes that 'file' is the only contextual keyword # that is a class modifier (r'(file)(\s+)(record|class|abstract|enum|new|sealed|static)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|' r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type), (r'(class|struct)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (cs_ident, Name), ], 'numbers_int': [ (r"0[xX][0-9a-fA-F]+(([uU][lL]?)|[lL][uU]?)?", Number.Hex), (r"0[bB][01]+(([uU][lL]?)|[lL][uU]?)?", Number.Bin), (r"[0-9]+(([uU][lL]?)|[lL][uU]?)?", Number.Integer), ], 'numbers_float': [ (r"([0-9]+\.[0-9]+([eE][+-]?[0-9]+)?[fFdDmM]?)|" r"(\.[0-9]+([eE][+-]?[0-9]+)?[fFdDmM]?)|" r"([0-9]+([eE][+-]?[0-9]+)[fFdDmM]?)|" r"([0-9]+[fFdDmM])", Number.Float), ], 'numbers': [ include('numbers_float'), include('numbers_int'), ], 'class': [ (cs_ident, Name.Class, '#pop'), default('#pop'), ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop'), ] }
def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
class NemerleLexer(RegexLexer): """ For Nemerle source code.
Additional options accepted:
`unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``. """
name = 'Nemerle' url = 'http://nemerle.org' aliases = ['nemerle'] filenames = ['*.n'] mimetypes = ['text/x-nemerle'] # inferred version_added = '1.5'
flags = re.MULTILINE | re.DOTALL
# for the range of allowed unicode characters in identifiers, see # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = { 'none': r'@?[_a-zA-Z]\w*', 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' + '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), }
tokens = {} token_variants = True
for levelname, cs_ident in levels.items(): tokens[levelname] = { 'root': [ # method names (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, \ Punctuation)), (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//.*?\n', Comment.Single), (r'/[*].*?[*]/', Comment.Multiline), (r'\n', Whitespace), (r'(\$)(\s*)(")', bygroups(String, Whitespace, String), 'splice-string'), (r'(\$)(\s*)(<#)', bygroups(String, Whitespace, String), 'splice-string2'), (r'<#', String, 'recursive-string'),
(r'(<\[)(\s*)(' + cs_ident + ':)?', bygroups(Keyword, Whitespace, Keyword)), (r'\]\>', Keyword),
# quasiquotation only (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'),
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number), (r'(#)([ \t]*)(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b', bygroups(Comment.Preproc, Whitespace, Comment.Preproc), 'preproc'), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)), (r'(abstract|and|as|base|catch|def|delegate|' r'enum|event|extern|false|finally|' r'fun|implements|interface|internal|' r'is|macro|match|matches|module|mutable|new|' r'null|out|override|params|partial|private|' r'protected|public|ref|sealed|static|' r'syntax|this|throw|true|try|type|typeof|' r'virtual|volatile|when|where|with|' r'assert|assert2|async|break|checked|continue|do|else|' r'ensures|for|foreach|if|late|lock|new|nolate|' r'otherwise|regexp|repeat|requires|return|surroundwith|' r'unchecked|unless|using|while|yield)\b', Keyword), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|' r'short|string|uint|ulong|ushort|void|array|list)\b\??', Keyword.Type), (r'(:>?)(\s*)(' + cs_ident + r'\??)', bygroups(Punctuation, Whitespace, Keyword.Type)), (r'(class|struct|variant|module)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (cs_ident, Name), ], 'class': [ (cs_ident, Name.Class, '#pop') ], 'preproc': [ (r'\w+', Comment.Preproc), (r'[ \t]+', Whitespace), (r'\n', Whitespace, '#pop') ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') ], 'splice-string': [ (r'[^"$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'\\"', String), (r'"', String, '#pop') ], 'splice-string2': [ (r'[^#<>$]', String), (r'\$' + cs_ident, Name), (r'(\$)(\()', bygroups(Name, Punctuation), 'splice-string-content'), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'recursive-string': [ (r'[^#<>]', String), (r'<#', String, '#push'), (r'#>', String, '#pop') ], 'splice-string-content': [ (r'if|match', Keyword), (r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation), (cs_ident, Name), (r'\d+', Number), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop') ] }
def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
def analyse_text(text): """Nemerle is quite similar to Python, but @if is relatively uncommon elsewhere.""" result = 0
if '@if' in text: result += 0.1
return result
class BooLexer(RegexLexer): """ For Boo source code. """
name = 'Boo' url = 'https://github.com/boo-lang/boo' aliases = ['boo'] filenames = ['*.boo'] mimetypes = ['text/x-boo'] version_added = ''
tokens = { 'root': [ (r'\s+', Whitespace), (r'(#|//).*$', Comment.Single), (r'/[*]', Comment.Multiline, 'comment'), (r'[]{}:(),.;[]', Punctuation), (r'(\\)(\n)', bygroups(Text, Whitespace)), (r'\\', Text), (r'(in|is|and|or|not)\b', Operator.Word), (r'/(\\\\|\\[^\\]|[^/\\\s])/', String.Regex), (r'@/(\\\\|\\[^\\]|[^/\\])*/', String.Regex), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'(as|abstract|callable|constructor|destructor|do|import|' r'enum|event|final|get|interface|internal|of|override|' r'partial|private|protected|public|return|set|static|' r'struct|transient|virtual|yield|super|and|break|cast|' r'continue|elif|else|ensure|except|for|given|goto|if|in|' r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|' r'while|from|as)\b', Keyword), (r'def(?=\s+\(.*?\))', Keyword), (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(namespace)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|' r'assert|checked|enumerate|filter|getter|len|lock|map|' r'matrix|max|min|normalArrayIndexing|print|property|range|' r'rawArrayIndexing|required|typeof|unchecked|using|' r'yieldAll|zip)\b', Name.Builtin), (r'"""(\\\\|\\"|.*?)"""', String.Double), (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double), (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single), (r'[a-zA-Z_]\w*', Name), (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float), (r'[0-9][0-9.]*(ms?|d|h|s)', Number), (r'0\d+', Number.Oct), (r'0x[a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+', Number.Integer), ], 'comment': [ ('/[*]', Comment.Multiline, '#push'), ('[*]/', Comment.Multiline, '#pop'), ('[^/*]', Comment.Multiline), ('[*/]', Comment.Multiline) ], 'funcname': [ (r'[a-zA-Z_]\w*', Name.Function, '#pop') ], 'classname': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop') ], 'namespace': [ (r'[a-zA-Z_][\w.]*', Name.Namespace, '#pop') ] }
class VbNetLexer(RegexLexer): """ For Visual Basic.NET source code. Also LibreOffice Basic, OpenOffice Basic, and StarOffice Basic. """
name = 'VB.net' url = 'https://docs.microsoft.com/en-us/dotnet/visual-basic/' aliases = ['vb.net', 'vbnet', 'lobas', 'oobas', 'sobas', 'visual-basic', 'visualbasic'] filenames = ['*.vb', '*.bas'] mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?) version_added = ''
uni_name = '[_' + uni.combine('Ll', 'Lt', 'Lm', 'Nl') + ']' + \ '[' + uni.combine('Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'
flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'^\s*<.*?>', Name.Attribute), (r'\s+', Whitespace), (r'\n', Whitespace), (r'(rem\b.*?)(\n)', bygroups(Comment, Whitespace)), (r"('.*?)(\n)", bygroups(Comment, Whitespace)), (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|' r'#ExternalSource.*?\n|#End\s+ExternalSource|' r'#Region.*?\n|#End\s+Region|#ExternalChecksum', Comment.Preproc), (r'[(){}!#,.:]', Punctuation), (r'(Option)(\s+)(Strict|Explicit|Compare)(\s+)' r'(On|Off|Binary|Text)', bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration, Whitespace, Keyword.Declaration)), (words(( 'AddHandler', 'Alias', 'ByRef', 'ByVal', 'Call', 'Case', 'Catch', 'CBool', 'CByte', 'CChar', 'CDate', 'CDec', 'CDbl', 'CInt', 'CLng', 'CObj', 'Continue', 'CSByte', 'CShort', 'CSng', 'CStr', 'CType', 'CUInt', 'CULng', 'CUShort', 'Declare', 'Default', 'Delegate', 'DirectCast', 'Do', 'Each', 'Else', 'ElseIf', 'EndIf', 'Erase', 'Error', 'Event', 'Exit', 'False', 'Finally', 'For', 'Friend', 'Get', 'Global', 'GoSub', 'GoTo', 'Handles', 'If', 'Implements', 'Inherits', 'Interface', 'Let', 'Lib', 'Loop', 'Me', 'MustInherit', 'MustOverride', 'MyBase', 'MyClass', 'Narrowing', 'New', 'Next', 'Not', 'Nothing', 'NotInheritable', 'NotOverridable', 'Of', 'On', 'Operator', 'Option', 'Optional', 'Overloads', 'Overridable', 'Overrides', 'ParamArray', 'Partial', 'Private', 'Protected', 'Public', 'RaiseEvent', 'ReadOnly', 'ReDim', 'RemoveHandler', 'Resume', 'Return', 'Select', 'Set', 'Shadows', 'Shared', 'Single', 'Static', 'Step', 'Stop', 'SyncLock', 'Then', 'Throw', 'To', 'True', 'Try', 'TryCast', 'Wend', 'Using', 'When', 'While', 'Widening', 'With', 'WithEvents', 'WriteOnly'), prefix=r'(?<!\.)', suffix=r'\b'), Keyword), (r'(?<!\.)End\b', Keyword, 'end'), (r'(?<!\.)(Dim|Const)\b', Keyword, 'dim'), (r'(?<!\.)(Function|Sub|Property)(\s+)', bygroups(Keyword, Whitespace), 'funcname'), (r'(?<!\.)(Class|Structure|Enum)(\s+)', bygroups(Keyword, Whitespace), 'classname'), (r'(?<!\.)(Module|Namespace|Imports)(\s+)', bygroups(Keyword, Whitespace), 'namespace'), (r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|' r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|' r'UShort)\b', Keyword.Type), (r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|' r'Or|OrElse|TypeOf|Xor)\b', Operator.Word), (r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|' r'<=|>=|<>|[-&*/\\^+=<>\[\]]', Operator), ('"', String, 'string'), (r'(_)(\n)', bygroups(Text, Whitespace)), # Line continuation (must be before Name) (uni_name + '[%&@!#$]?', Name), ('#.*?#', Literal.Date), (r'(\d+\.\d*|\d*\.\d+)(F[+-]?[0-9]+)?', Number.Float), (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer), (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer), ], 'string': [ (r'""', String), (r'"C?', String, '#pop'), (r'[^"]+', String), ], 'dim': [ (uni_name, Name.Variable, '#pop'), default('#pop'), # any other syntax ], 'funcname': [ (uni_name, Name.Function, '#pop'), ], 'classname': [ (uni_name, Name.Class, '#pop'), ], 'namespace': [ (uni_name, Name.Namespace), (r'\.', Name.Namespace), default('#pop'), ], 'end': [ (r'\s+', Whitespace), (r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b', Keyword, '#pop'), default('#pop'), ] }
def analyse_text(text): if re.search(r'^\s*(#If|Module|Namespace)', text, re.MULTILINE): return 0.5
class GenericAspxLexer(RegexLexer): """ Lexer for ASP.NET pages. """
name = 'aspx-gen' filenames = [] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet'
flags = re.DOTALL
tokens = { 'root': [ (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)), (r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer), Other, using(XmlLexer))), (r'(.+?)(?=<)', using(XmlLexer)), (r'.+', using(XmlLexer)), ], }
# TODO support multiple languages within the same source fileclass CSharpAspxLexer(DelegatingLexer): """ Lexer for highlighting C# within ASP.NET pages. """
name = 'aspx-cs' aliases = ['aspx-cs'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet' version_added = ''
def __init__(self, **options): super().__init__(CSharpLexer, GenericAspxLexer, **options)
def analyse_text(text): if re.search(r'Page\s*Language="C#"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None: return 0.15
class VbNetAspxLexer(DelegatingLexer): """ Lexer for highlighting Visual Basic.net within ASP.NET pages. """
name = 'aspx-vb' aliases = ['aspx-vb'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] url = 'https://dotnet.microsoft.com/en-us/apps/aspnet' version_added = ''
def __init__(self, **options): super().__init__(VbNetLexer, GenericAspxLexer, **options)
def analyse_text(text): if re.search(r'Page\s*Language="Vb"', text, re.I) is not None: return 0.2 elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None: return 0.15
# Very close to functional.OcamlLexerclass FSharpLexer(RegexLexer): """ For the F# language (version 3.0). """
name = 'F#' url = 'https://fsharp.org/' aliases = ['fsharp', 'f#'] filenames = ['*.fs', '*.fsi', '*.fsx'] mimetypes = ['text/x-fsharp'] version_added = '1.5'
keywords = [ 'abstract', 'as', 'assert', 'base', 'begin', 'class', 'default', 'delegate', 'do!', 'do', 'done', 'downcast', 'downto', 'elif', 'else', 'end', 'exception', 'extern', 'false', 'finally', 'for', 'function', 'fun', 'global', 'if', 'inherit', 'inline', 'interface', 'internal', 'in', 'lazy', 'let!', 'let', 'match', 'member', 'module', 'mutable', 'namespace', 'new', 'null', 'of', 'open', 'override', 'private', 'public', 'rec', 'return!', 'return', 'select', 'static', 'struct', 'then', 'to', 'true', 'try', 'type', 'upcast', 'use!', 'use', 'val', 'void', 'when', 'while', 'with', 'yield!', 'yield', ] # Reserved words; cannot hurt to color them as keywords too. keywords += [ 'atomic', 'break', 'checked', 'component', 'const', 'constraint', 'constructor', 'continue', 'eager', 'event', 'external', 'fixed', 'functor', 'include', 'method', 'mixin', 'object', 'parallel', 'process', 'protected', 'pure', 'sealed', 'tailcall', 'trait', 'virtual', 'volatile', ] keyopts = [ '!=', '#', '&&', '&', r'\(', r'\)', r'\*', r'\+', ',', r'-\.', '->', '-', r'\.\.', r'\.', '::', ':=', ':>', ':', ';;', ';', '<-', r'<\]', '<', r'>\]', '>', r'\?\?', r'\?', r'\[<', r'\[\|', r'\[', r'\]', '_', '`', r'\{', r'\|\]', r'\|', r'\}', '~', '<@@', '<@', '=', '@>', '@@>', ]
operators = r'[!$%&*+\./:<=>?@^|~-]' word_operators = ['and', 'or', 'not'] prefix_syms = r'[!?~]' infix_syms = r'[=<>@^|&+\*/$%-]' primitives = [ 'sbyte', 'byte', 'char', 'nativeint', 'unativeint', 'float32', 'single', 'float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'decimal', 'unit', 'bool', 'string', 'list', 'exn', 'obj', 'enum', ]
# See http://msdn.microsoft.com/en-us/library/dd233181.aspx and/or # http://fsharp.org/about/files/spec.pdf for reference. Good luck.
tokens = { 'escape-sequence': [ (r'\\[\\"\'ntbrafv]', String.Escape), (r'\\[0-9]{3}', String.Escape), (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\U[0-9a-fA-F]{8}', String.Escape), ], 'root': [ (r'\s+', Whitespace), (r'\(\)|\[\]', Name.Builtin.Pseudo), (r'\b(?<!\.)([A-Z][\w\']*)(?=\s*\.)', Name.Namespace, 'dotted'), (r'\b([A-Z][\w\']*)', Name), (r'(///.*?)(\n)', bygroups(String.Doc, Whitespace)), (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)), (r'\(\*(?!\))', Comment, 'comment'),
(r'@"', String, 'lstring'), (r'"""', String, 'tqs'), (r'"', String, 'string'),
(r'\b(open|module)(\s+)([\w.]+)', bygroups(Keyword, Whitespace, Name.Namespace)), (r'\b(let!?)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Variable)), (r'\b(type)(\s+)(\w+)', bygroups(Keyword, Whitespace, Name.Class)), (r'\b(member|override)(\s+)(\w+)(\.)(\w+)', bygroups(Keyword, Whitespace, Name, Punctuation, Name.Function)), (r'\b({})\b'.format('|'.join(keywords)), Keyword), (r'``([^`\n\r\t]|`[^`\n\r\t])+``', Name), (r'({})'.format('|'.join(keyopts)), Operator), (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'(#)([ \t]*)(if|endif|else|line|nowarn|light|\d+)\b(.*?)(\n)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc, Comment.Preproc, Whitespace)),
(r"[^\W\d][\w']*", Name),
(r'\d[\d_]*[uU]?[yslLnQRZINGmM]?', Number.Integer), (r'0[xX][\da-fA-F][\da-fA-F_]*[uU]?[yslLn]?[fF]?', Number.Hex), (r'0[oO][0-7][0-7_]*[uU]?[yslLn]?', Number.Oct), (r'0[bB][01][01_]*[uU]?[yslLn]?', Number.Bin), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)[fFmM]?', Number.Float),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'B?", String.Char), (r"'.'", String.Char), (r"'", Keyword), # a stray quote is another syntax element
(r'@?"', String.Double, 'string'),
(r'[~?][a-z][\w\']*:', Name.Variable), ], 'dotted': [ (r'\s+', Whitespace), (r'\.', Punctuation), (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace), (r'[A-Z][\w\']*', Name, '#pop'), (r'[a-z_][\w\']*', Name, '#pop'), # e.g. dictionary index access default('#pop'), ], 'comment': [ (r'[^(*)@"]+', Comment), (r'\(\*', Comment, '#push'), (r'\*\)', Comment, '#pop'), # comments cannot be closed within strings in comments (r'@"', String, 'lstring'), (r'"""', String, 'tqs'), (r'"', String, 'string'), (r'[(*)@]', Comment), ], 'string': [ (r'[^\\"]+', String), include('escape-sequence'), (r'\\\n', String), (r'\n', String), # newlines are allowed in any string (r'"B?', String, '#pop'), ], 'lstring': [ (r'[^"]+', String), (r'\n', String), (r'""', String), (r'"B?', String, '#pop'), ], 'tqs': [ (r'[^"]+', String), (r'\n', String), (r'"""B?', String, '#pop'), (r'"', String), ], }
def analyse_text(text): """F# doesn't have that many unique features -- |> and <| are weak indicators.""" result = 0 if '|>' in text: result += 0.05 if '<|' in text: result += 0.05
return result
class XppLexer(RegexLexer):
""" For X++ source code. This is based loosely on the CSharpLexer """
name = 'X++' url = 'https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/dev-ref/xpp-language-reference' aliases = ['xpp', 'x++'] filenames = ['*.xpp'] version_added = '2.15'
flags = re.MULTILINE
XPP_CHARS = ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*') # Temporary, see # https://github.com/thatch/regexlint/pull/49 XPP_CHARS = XPP_CHARS.replace('\x00', '\x01')
OPERATORS = ( '<=', '>=', '+=', '-=', '*=', '/=', '!=', '==', '&&', '||', '>>', '<<', '++', '--', '+', '-', '*', '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=', ) KEYWORDS = ('abstract','anytype','as','async','asc','at','avg','break','breakpoint','by','byref','case','catch', 'changecompany','client','container','continue','count','crosscompany','default','delegate', 'delete_from','desc','display','div','do','edit','else','element','eventhandler','exists','false','final', 'firstfast','firstonly','firstonly10','firstonly100','firstonly1000','flush','for','forceliterals', 'forcenestedloop','forceplaceholders','forceselectorder','forupdate','from','group','if','insert_recordset', 'interface','is','join','like','maxof','minof','mod','new','next','nofetch','notexists','null','optimisticlock','order', 'outer','pause','pessimisticlock','print','private','protected','public','repeatableread','retry','return', 'reverse','select','server','setting','static','sum','super','switch','tablelock','this','throw','true','try','ttsabort','ttsbegin', 'ttscommit','update_recordset','validtimestate','void','where','while','window') RUNTIME_FUNCTIONS = ('_duration','abs','acos','any2Date','any2Enum','any2Guid','any2Int','any2Int64','any2Real','any2Str','anytodate', 'anytoenum','anytoguid','anytoint','anytoint64','anytoreal','anytostr','asin','atan','beep','cTerm','char2Num','classIdGet', 'corrFlagGet','corrFlagSet','cos','cosh','curExt','curUserId','date2Num','date2Str','datetime2Str','dayName','dayOfMth', 'dayOfWk','dayOfYr','ddb','decRound','dg','dimOf','endMth','enum2str','exp','exp10','fV','fieldId2Name','fieldId2PName', 'fieldName2Id','frac','funcName','getCurrentPartition','getCurrentPartitionRecId','getPrefix','guid2Str','idg','indexId2Name', 'indexName2Id','int2Str','int642Str','intvMax','intvName','intvNo','intvNorm','log10','logN','match','max','min','mkDate','mthName', 'mthOfYr','newGuid','nextMth','nextQtr','nextYr','num2Char','num2Date','num2Str','pmt','power','prevMth','prevQtr','prevYr', 'prmIsDefault','pt','pv','rate','refPrintAll','round','runAs','sessionId','setPrefix','sin','sinh','sleep','sln','str2Date', 'str2Datetime','str2Enum','str2Guid','str2Int','str2Int64','str2Num','str2Time','strAlpha','strCmp','strColSeq','strDel', 'strFind','strFmt','strIns','strKeep','strLTrim','strLen','strLine','strLwr','strNFind','strPoke','strPrompt','strRTrim', 'strRem','strRep','strScan','strUpr','subStr','syd','systemDateGet','systemDateSet','tableId2Name', 'tableId2PName','tableName2Id','tan','tanh','term','time2Str','timeNow','today','trunc','typeOf','uint2Str','wkOfYr','year') COMPILE_FUNCTIONS = ('attributeStr','classNum','classStr','configurationKeyNum','configurationKeyStr','dataEntityDataSourceStr','delegateStr', 'dimensionHierarchyLevelStr','dimensionHierarchyStr','dimensionReferenceStr','dutyStr','enumCnt','enumLiteralStr','enumNum','enumStr', 'extendedTypeNum','extendedTypeStr','fieldNum','fieldPName','fieldStr','formControlStr','formDataFieldStr','formDataSourceStr', 'formMethodStr','formStr','identifierStr','indexNum','indexStr','licenseCodeNum','licenseCodeStr','literalStr','maxDate','maxInt', 'measureStr','measurementStr','menuItemActionStr','menuItemDisplayStr','menuItemOutputStr','menuStr','methodStr','minInt','privilegeStr', 'queryDatasourceStr','queryMethodStr','queryStr','reportStr','resourceStr','roleStr','ssrsReportStr','staticDelegateStr','staticMethodStr', 'tableCollectionStr','tableFieldGroupStr','tableMethodStr','tableNum','tablePName','tableStaticMethodStr','tableStr','tileStr','varStr', 'webActionItemStr','webDisplayContentItemStr','webFormStr','webMenuStr','webOutputContentItemStr','webReportStr','webSiteTempStr', 'webStaticFileStr','webUrlItemStr','webWebPartStr','webletItemStr','webpageDefStr','websiteDefStr','workflowApprovalStr', 'workflowCategoryStr','workflowTaskStr','workflowTypeStr')
tokens = {}
tokens = { 'root': [ # method names (r'(\s*)\b(else|if)\b([^\n])', bygroups(Whitespace, Keyword, using(this))), # ensure that if is not treated like a function (r'^([ \t]*)((?:' + XPP_CHARS + r'(?:\[\])?\s+)+?)' # return type r'(' + XPP_CHARS + ')' # method name r'(\s*)(\()', # signature start bygroups(Whitespace, using(this), Name.Function, Whitespace, Punctuation)), (r'^(\s*)(\[)([^\n]*?)(\])', bygroups(Whitespace, Name.Attribute, Name.Variable.Class, Name.Attribute)), (r'[^\S\n]+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation (r'//[^\n]*?\n', Comment.Single), (r'/[*][^\n]*?[*]/', Comment.Multiline), (r'\n', Whitespace), (words(OPERATORS), Operator), (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator), (r'[()\[\];:,.#@]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (words(KEYWORDS, suffix=r'\b'), Keyword), (r'(boolean|int|int64|str|real|guid|date)\b\??', Keyword.Type), (r'(class|struct|extends|implements)(\s+)', bygroups(Keyword, Whitespace), 'class'), (r'('+XPP_CHARS+')(::)', bygroups(Name.Variable.Class, Punctuation)), (r'(\s*)(\w+)(\s+\w+(,|=)?[^\n]*;)', bygroups(Whitespace, Name.Variable.Class, using(this))), # declaration # x++ specific function to get field should highlight the classname (r'(fieldNum\()('+XPP_CHARS+r')(\s*,\s*)('+XPP_CHARS+r')(\s*\))', bygroups(using(this), Name.Variable.Class, using(this), Name.Property, using(this))), # x++ specific function to get table should highlight the classname (r'(tableNum\()('+XPP_CHARS+r')(\s*\))', bygroups(using(this), Name.Variable.Class, using(this))), (words(RUNTIME_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), (words(COMPILE_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic), (XPP_CHARS, Name), ], 'class': [ (XPP_CHARS, Name.Class, '#pop'), default('#pop'), ], 'namespace': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + XPP_CHARS + r'|\.)+', Name.Namespace, '#pop'), ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970""" pygments.lexers.dsls ~~~~~~~~~~~~~~~~~~~~
Lexers for various domain-specific languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
import re
from pygments.lexer import ExtendedRegexLexer, RegexLexer, bygroups, words, \ include, default, this, using, combinedfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ProtoBufLexer', 'ZeekLexer', 'PuppetLexer', 'RslLexer', 'MscgenLexer', 'VGLLexer', 'AlloyLexer', 'PanLexer', 'CrmshLexer', 'ThriftLexer', 'FlatlineLexer', 'SnowballLexer']
class ProtoBufLexer(RegexLexer): """ Lexer for Protocol Buffer definition files. """
name = 'Protocol Buffer' url = 'https://developers.google.com/protocol-buffers/' aliases = ['protobuf', 'proto'] filenames = ['*.proto'] version_added = '1.4'
tokens = { 'root': [ (r'[ \t]+', Whitespace), (r'[,;{}\[\]()<>]', Punctuation), (r'/(\\\n)?/(\n|(.|\n)*?[^\\]\n)', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), (words(( 'import', 'option', 'optional', 'required', 'repeated', 'reserved', 'default', 'packed', 'ctype', 'extensions', 'to', 'max', 'rpc', 'returns', 'oneof', 'syntax'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'fixed32', 'fixed64', 'sfixed32', 'sfixed64', 'float', 'double', 'bool', 'string', 'bytes'), suffix=r'\b'), Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'(package)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'package'), (r'(message|extend)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'message'), (r'(enum|group|service)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'type'), (r'\".*?\"', String), (r'\'.*?\'', String), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+[LlUu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+[fF])[fF]?', Number.Float), (r'(\-?(inf|nan))\b', 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'([a-zA-Z_][\w.]*)([ \t]*)(=)', bygroups(Name.Attribute, Whitespace, Operator)), (r'[a-zA-Z_][\w.]*', Name), ], 'package': [ (r'[a-zA-Z_][\w\.]*', Name.Namespace, '#pop'), default('#pop'), ], 'message': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'type': [ (r'[a-zA-Z_]\w*', Name, '#pop'), default('#pop'), ], }
class ThriftLexer(RegexLexer): """ For Thrift interface definitions. """ name = 'Thrift' url = 'https://thrift.apache.org/' aliases = ['thrift'] filenames = ['*.thrift'] mimetypes = ['application/x-thrift'] version_added = '2.1'
tokens = { 'root': [ include('whitespace'), include('comments'), (r'"', String.Double, combined('stringescape', 'dqs')), (r'\'', String.Single, combined('stringescape', 'sqs')), (r'(namespace)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'namespace'), (r'(enum|union|struct|service|exception)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'class'), (r'((?:(?:[^\W\d]|\$)[\w.\[\]$<>]*\s+)+?)' # return arguments r'((?:[^\W\d]|\$)[\w$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Whitespace, Operator)), include('keywords'), include('numbers'), (r'[&=]', Operator), (r'[:;,{}()<>\[\]]', Punctuation), (r'[a-zA-Z_](\.\w|\w)*', Name), ], 'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), ], 'comments': [ (r'#.*$', Comment), (r'//.*?\n', Comment), (r'/\*[\w\W]*?\*/', Comment.Multiline), ], 'stringescape': [ (r'\\([\\nrt"\'])', String.Escape), ], 'dqs': [ (r'"', String.Double, '#pop'), (r'[^\\"\n]+', String.Double), ], 'sqs': [ (r"'", String.Single, '#pop'), (r'[^\\\'\n]+', String.Single), ], 'namespace': [ (r'[a-z*](\.\w|\w)*', Name.Namespace, '#pop'), default('#pop'), ], 'class': [ (r'[a-zA-Z_]\w*', Name.Class, '#pop'), default('#pop'), ], 'keywords': [ (r'(async|oneway|extends|throws|required|optional)\b', Keyword), (r'(true|false)\b', Keyword.Constant), (r'(const|typedef)\b', Keyword.Declaration), (words(( 'cpp_namespace', 'cpp_include', 'cpp_type', 'java_package', 'cocoa_prefix', 'csharp_namespace', 'delphi_namespace', 'php_namespace', 'py_module', 'perl_package', 'ruby_namespace', 'smalltalk_category', 'smalltalk_prefix', 'xsd_all', 'xsd_optional', 'xsd_nillable', 'xsd_namespace', 'xsd_attrs', 'include'), suffix=r'\b'), Keyword.Namespace), (words(( 'void', 'bool', 'byte', 'i16', 'i32', 'i64', 'double', 'string', 'binary', 'map', 'list', 'set', 'slist', 'senum'), suffix=r'\b'), Keyword.Type), (words(( 'BEGIN', 'END', '__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', 'abstract', 'alias', 'and', 'args', 'as', 'assert', 'begin', 'break', 'case', 'catch', 'class', 'clone', 'continue', 'declare', 'def', 'default', 'del', 'delete', 'do', 'dynamic', 'elif', 'else', 'elseif', 'elsif', 'end', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'ensure', 'except', 'exec', 'finally', 'float', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'import', 'in', 'inline', 'instanceof', 'interface', 'is', 'lambda', 'module', 'native', 'new', 'next', 'nil', 'not', 'or', 'pass', 'public', 'print', 'private', 'protected', 'raise', 'redo', 'rescue', 'retry', 'register', 'return', 'self', 'sizeof', 'static', 'super', 'switch', 'synchronized', 'then', 'this', 'throw', 'transient', 'try', 'undef', 'unless', 'unsigned', 'until', 'use', 'var', 'virtual', 'volatile', 'when', 'while', 'with', 'xor', 'yield'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), ], 'numbers': [ (r'[+-]?(\d+\.\d+([eE][+-]?\d+)?|\.?\d+[eE][+-]?\d+)', Number.Float), (r'[+-]?0x[0-9A-Fa-f]+', Number.Hex), (r'[+-]?[0-9]+', Number.Integer), ], }
class ZeekLexer(RegexLexer): """ For Zeek scripts. """ name = 'Zeek' url = 'https://www.zeek.org/' aliases = ['zeek', 'bro'] filenames = ['*.zeek', '*.bro'] version_added = '2.5'
_hex = r'[0-9a-fA-F]' _float = r'((\d*\.?\d+)|(\d+\.?\d*))([eE][-+]?\d+)?' _h = r'[A-Za-z0-9][-A-Za-z0-9]*'
tokens = { 'root': [ include('whitespace'), include('comments'), include('directives'), include('attributes'), include('types'), include('keywords'), include('literals'), include('operators'), include('punctuation'), (r'((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(?=\s*\()', Name.Function), include('identifiers'), ],
'whitespace': [ (r'\n', Whitespace), (r'\s+', Whitespace), (r'(\\)(\n)', bygroups(Text, Whitespace)), ],
'comments': [ (r'#.*$', Comment), ],
'directives': [ (r'@(load-plugin|load-sigs|load|unload)\b.*$', Comment.Preproc), (r'@(DEBUG|DIR|FILENAME|deprecated|if|ifdef|ifndef|else|endif)\b', Comment.Preproc), (r'(@prefixes)(\s*)((\+?=).*)$', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)), ],
'attributes': [ (words(('redef', 'priority', 'log', 'optional', 'default', 'add_func', 'delete_func', 'expire_func', 'read_expire', 'write_expire', 'create_expire', 'synchronized', 'persistent', 'rotate_interval', 'rotate_size', 'encrypt', 'raw_output', 'mergeable', 'error_handler', 'type_column', 'deprecated'), prefix=r'&', suffix=r'\b'), Keyword.Pseudo), ],
'types': [ (words(('any', 'enum', 'record', 'set', 'table', 'vector', 'function', 'hook', 'event', 'addr', 'bool', 'count', 'double', 'file', 'int', 'interval', 'pattern', 'port', 'string', 'subnet', 'time'), suffix=r'\b'), Keyword.Type),
(r'(opaque)(\s+)(of)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b', bygroups(Keyword.Type, Whitespace, Operator.Word, Whitespace, Keyword.Type)),
(r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)(\s*)\b(record|enum)\b', bygroups(Keyword, Whitespace, Name.Class, Whitespace, Operator, Whitespace, Keyword.Type)),
(r'(type)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)(\s*)(:)', bygroups(Keyword, Whitespace, Name, Whitespace, Operator)),
(r'(redef)(\s+)(record|enum)(\s+)((?:[A-Za-z_]\w*)(?:::(?:[A-Za-z_]\w*))*)\b', bygroups(Keyword, Whitespace, Keyword.Type, Whitespace, Name.Class)), ],
'keywords': [ (words(('redef', 'export', 'if', 'else', 'for', 'while', 'return', 'break', 'next', 'continue', 'fallthrough', 'switch', 'default', 'case', 'add', 'delete', 'when', 'timeout', 'schedule'), suffix=r'\b'), Keyword), (r'(print)\b', Keyword), (r'(global|local|const|option)\b', Keyword.Declaration), (r'(module)(\s+)(([A-Za-z_]\w*)(?:::([A-Za-z_]\w*))*)\b', bygroups(Keyword.Namespace, Whitespace, Name.Namespace)), ],
'literals': [ (r'"', String, 'string'),
# Not the greatest match for patterns, but generally helps # disambiguate between start of a pattern and just a division # operator. (r'/(?=.*/)', String.Regex, 'regex'),
(r'(T|F)\b', Keyword.Constant),
# Port (r'\d{1,5}/(udp|tcp|icmp|unknown)\b', Number),
# IPv4 Address (r'(\d{1,3}.){3}(\d{1,3})\b', Number),
# IPv6 Address (r'\[([0-9a-fA-F]{0,4}:){2,7}([0-9a-fA-F]{0,4})?((\d{1,3}.){3}(\d{1,3}))?\]', Number),
# Numeric (r'0[xX]' + _hex + r'+\b', Number.Hex), (_float + r'\s*(day|hr|min|sec|msec|usec)s?\b', Number.Float), (_float + r'\b', Number.Float), (r'(\d+)\b', Number.Integer),
# Hostnames (_h + r'(\.' + _h + r')+', String), ],
'operators': [ (r'[!%*/+<=>~|&^-]', Operator), (r'([-+=&|]{2}|[+=!><-]=)', Operator), (r'(in|as|is|of)\b', Operator.Word), (r'\??\$', Operator), ],
'punctuation': [ (r'[{}()\[\],;.]', Punctuation), # The "ternary if", which uses '?' and ':', could instead be # treated as an Operator, but colons are more frequently used to # separate field/identifier names from their types, so the (often) # less-prominent Punctuation is used even with '?' for consistency. (r'[?:]', Punctuation), ],
'identifiers': [ (r'([a-zA-Z_]\w*)(::)', bygroups(Name, Punctuation)), (r'[a-zA-Z_]\w*', Name) ],
'string': [ (r'\\.', String.Escape), (r'%-?[0-9]*(\.[0-9]+)?[DTd-gsx]', String.Escape), (r'"', String, '#pop'), (r'.', String), ],
'regex': [ (r'\\.', String.Escape), (r'/', String.Regex, '#pop'), (r'.', String.Regex), ], }
BroLexer = ZeekLexer
class PuppetLexer(RegexLexer): """ For Puppet configuration DSL. """ name = 'Puppet' url = 'https://puppet.com/' aliases = ['puppet'] filenames = ['*.pp'] version_added = '1.6'
tokens = { 'root': [ include('comments'), include('keywords'), include('names'), include('numbers'), include('operators'), include('strings'),
(r'[]{}:(),;[]', Punctuation), (r'\s+', Whitespace), ],
'comments': [ (r'(\s*)(#.*)$', bygroups(Whitespace, Comment)), (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline), ],
'operators': [ (r'(=>|\?|<|>|=|\+|-|/|\*|~|!|\|)', Operator), (r'(in|and|or|not)\b', Operator.Word), ],
'names': [ (r'[a-zA-Z_]\w*', Name.Attribute), (r'(\$\S+)(\[)(\S+)(\])', bygroups(Name.Variable, Punctuation, String, Punctuation)), (r'\$\S+', Name.Variable), ],
'numbers': [ # Copypasta from the Python lexer (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float), (r'\d+[eE][+-]?[0-9]+j?', Number.Float), (r'0[0-7]+j?', Number.Oct), (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'\d+L', Number.Integer.Long), (r'\d+j?', Number.Integer) ],
'keywords': [ # Left out 'group' and 'require' # Since they're often used as attributes (words(( 'absent', 'alert', 'alias', 'audit', 'augeas', 'before', 'case', 'check', 'class', 'computer', 'configured', 'contained', 'create_resources', 'crit', 'cron', 'debug', 'default', 'define', 'defined', 'directory', 'else', 'elsif', 'emerg', 'err', 'exec', 'extlookup', 'fail', 'false', 'file', 'filebucket', 'fqdn_rand', 'generate', 'host', 'if', 'import', 'include', 'info', 'inherits', 'inline_template', 'installed', 'interface', 'k5login', 'latest', 'link', 'loglevel', 'macauthorization', 'mailalias', 'maillist', 'mcx', 'md5', 'mount', 'mounted', 'nagios_command', 'nagios_contact', 'nagios_contactgroup', 'nagios_host', 'nagios_hostdependency', 'nagios_hostescalation', 'nagios_hostextinfo', 'nagios_hostgroup', 'nagios_service', 'nagios_servicedependency', 'nagios_serviceescalation', 'nagios_serviceextinfo', 'nagios_servicegroup', 'nagios_timeperiod', 'node', 'noop', 'notice', 'notify', 'package', 'present', 'purged', 'realize', 'regsubst', 'resources', 'role', 'router', 'running', 'schedule', 'scheduled_task', 'search', 'selboolean', 'selmodule', 'service', 'sha1', 'shellquote', 'split', 'sprintf', 'ssh_authorized_key', 'sshkey', 'stage', 'stopped', 'subscribe', 'tag', 'tagged', 'template', 'tidy', 'true', 'undef', 'unmounted', 'user', 'versioncmp', 'vlan', 'warning', 'yumrepo', 'zfs', 'zone', 'zpool'), prefix='(?i)', suffix=r'\b'), Keyword), ],
'strings': [ (r'"([^"])*"', String), (r"'(\\'|[^'])*'", String), ],
}
class RslLexer(RegexLexer): """ RSL is the formal specification language used in RAISE (Rigorous Approach to Industrial Software Engineering) method. """ name = 'RSL' url = 'http://en.wikipedia.org/wiki/RAISE' aliases = ['rsl'] filenames = ['*.rsl'] mimetypes = ['text/rsl'] version_added = '2.0'
flags = re.MULTILINE | re.DOTALL
tokens = { 'root': [ (words(( 'Bool', 'Char', 'Int', 'Nat', 'Real', 'Text', 'Unit', 'abs', 'all', 'always', 'any', 'as', 'axiom', 'card', 'case', 'channel', 'chaos', 'class', 'devt_relation', 'dom', 'elems', 'else', 'elif', 'end', 'exists', 'extend', 'false', 'for', 'hd', 'hide', 'if', 'in', 'is', 'inds', 'initialise', 'int', 'inter', 'isin', 'len', 'let', 'local', 'ltl_assertion', 'object', 'of', 'out', 'post', 'pre', 'read', 'real', 'rng', 'scheme', 'skip', 'stop', 'swap', 'then', 'theory', 'test_case', 'tl', 'transition_system', 'true', 'type', 'union', 'until', 'use', 'value', 'variable', 'while', 'with', 'write', '~isin', '-inflist', '-infset', '-list', '-set'), prefix=r'\b', suffix=r'\b'), Keyword), (r'(variable|value)\b', Keyword.Declaration), (r'--.*?\n', Comment), (r'<:.*?:>', Comment), (r'\{!.*?!\}', Comment), (r'/\*.*?\*/', Comment), (r'^([ \t]*)([\w]+)([ \t]*)(:[^:])', bygroups(Whitespace, Name.Function, Whitespace, Name.Function)), (r'(^[ \t]*)([\w]+)([ \t]*)(\([\w\s,]*\))([ \t]*)(is|as)', bygroups(Whitespace, Name.Function, Whitespace, Text, Whitespace, Keyword)), (r'\b[A-Z]\w*\b', Keyword.Type), (r'(true|false)\b', Keyword.Constant), (r'".*"', String), (r'\'.\'', String.Char), (r'(><|->|-m->|/\\|<=|<<=|<\.|\|\||\|\^\||-~->|-~m->|\\/|>=|>>|' r'\.>|\+\+|-\\|<->|=>|:-|~=|\*\*|<<|>>=|\+>|!!|\|=\||#)', Operator), (r'[0-9]+\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-f]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'\s+', Whitespace), (r'.', Text), ], }
def analyse_text(text): """ Check for the most common text in the beginning of a RSL file. """ if re.search(r'scheme\s*.*?=\s*class\s*type', text, re.I) is not None: return 1.0
class MscgenLexer(RegexLexer): """ For Mscgen files. """ name = 'Mscgen' url = 'http://www.mcternan.me.uk/mscgen/' aliases = ['mscgen', 'msc'] filenames = ['*.msc'] version_added = '1.6'
_var = r'(\w+|"(?:\\"|[^"])*")'
tokens = { 'root': [ (r'msc\b', Keyword.Type), # Options (r'(hscale|HSCALE|width|WIDTH|wordwraparcs|WORDWRAPARCS' r'|arcgradient|ARCGRADIENT)\b', Name.Property), # Operators (r'(abox|ABOX|rbox|RBOX|box|BOX|note|NOTE)\b', Operator.Word), (r'(\.|-|\|){3}', Keyword), (r'(?:-|=|\.|:){2}' r'|<<=>>|<->|<=>|<<>>|<:>' r'|->|=>>|>>|=>|:>|-x|-X' r'|<-|<<=|<<|<=|<:|x-|X-|=', Operator), # Names (r'\*', Name.Builtin), (_var, Name.Variable), # Other (r'\[', Punctuation, 'attrs'), (r'\{|\}|,|;', Punctuation), include('comments') ], 'attrs': [ (r'\]', Punctuation, '#pop'), (_var + r'(\s*)(=)(\s*)' + _var, bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String)), (r',', Punctuation), include('comments') ], 'comments': [ (r'(?://|#).*?\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), (r'[ \t\r\n]+', Whitespace) ] }
class VGLLexer(RegexLexer): """ For SampleManager VGL source code. """ name = 'VGL' url = 'http://www.thermoscientific.com/samplemanager' aliases = ['vgl'] filenames = ['*.rpf'] version_added = '1.6'
flags = re.MULTILINE | re.DOTALL | re.IGNORECASE
tokens = { 'root': [ (r'\{[^}]*\}', Comment.Multiline), (r'declare', Keyword.Constant), (r'(if|then|else|endif|while|do|endwhile|and|or|prompt|object' r'|create|on|line|with|global|routine|value|endroutine|constant' r'|global|set|join|library|compile_option|file|exists|create|copy' r'|delete|enable|windows|name|notprotected)(?! *[=<>.,()])', Keyword), (r'(true|false|null|empty|error|locked)', Keyword.Constant), (r'[~^*#!%&\[\]()<>|+=:;,./?-]', Operator), (r'"[^"]*"', String), (r'(\.)([a-z_$][\w$]*)', bygroups(Operator, Name.Attribute)), (r'[0-9][0-9]*(\.[0-9]+(e[+\-]?[0-9]+)?)?', Number), (r'[a-z_$][\w$]*', Name), (r'[\r\n]+', Whitespace), (r'\s+', Whitespace) ] }
class AlloyLexer(RegexLexer): """ For Alloy source code. """
name = 'Alloy' url = 'http://alloy.mit.edu' aliases = ['alloy'] filenames = ['*.als'] mimetypes = ['text/x-alloy'] version_added = '2.0'
flags = re.MULTILINE | re.DOTALL
iden_rex = r'[a-zA-Z_][\w]*"*' string_rex = r'"\b(\\\\|\\[^\\]|[^"\\])*"' text_tuple = (r'[^\S\n]+', Whitespace)
tokens = { 'sig': [ (r'(extends)\b', Keyword, '#pop'), (iden_rex, Name), text_tuple, (r',', Punctuation), (r'\{', Operator, '#pop'), ], 'module': [ text_tuple, (iden_rex, Name, '#pop'), ], 'fun': [ text_tuple, (r'\{', Operator, '#pop'), (iden_rex, Name, '#pop'), ], 'fact': [ include('fun'), (string_rex, String, '#pop'), ], 'root': [ (r'--.*?$', Comment.Single), (r'//.*?$', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), text_tuple, (r'(module|open)(\s+)', bygroups(Keyword.Namespace, Whitespace), 'module'), (r'(sig|enum)(\s+)', bygroups(Keyword.Declaration, Whitespace), 'sig'), (r'(iden|univ|none)\b', Keyword.Constant), (r'(int|Int)\b', Keyword.Type), (r'(var|this|abstract|extends|set|seq|one|lone|let)\b', Keyword), (r'(all|some|no|sum|disj|when|else)\b', Keyword), (r'(run|check|for|but|exactly|expect|as|steps)\b', Keyword), (r'(always|after|eventually|until|release)\b', Keyword), # future time operators (r'(historically|before|once|since|triggered)\b', Keyword), # past time operators (r'(and|or|implies|iff|in)\b', Operator.Word), (r'(fun|pred|assert)(\s+)', bygroups(Keyword, Whitespace), 'fun'), (r'(fact)(\s+)', bygroups(Keyword, Whitespace), 'fact'), (r'!|#|&&|\+\+|<<|>>|>=|<=>|<=|\.\.|\.|->', Operator), (r'[-+/*%=<>&!^|~{}\[\]().\';]', Operator), (iden_rex, Name), (r'[:,]', Punctuation), (r'[0-9]+', Number.Integer), (string_rex, String), (r'\n', Whitespace), ] }
class PanLexer(RegexLexer): """ Lexer for pan source files.
Based on tcsh lexer. """
name = 'Pan' url = 'https://github.com/quattor/pan/' aliases = ['pan'] filenames = ['*.pan'] version_added = '2.0'
tokens = { 'root': [ include('basic'), (r'\(', Keyword, 'paren'), (r'\{', Keyword, 'curly'), include('data'), ], 'basic': [ (words(( 'if', 'for', 'with', 'else', 'type', 'bind', 'while', 'valid', 'final', 'prefix', 'unique', 'object', 'foreach', 'include', 'template', 'function', 'variable', 'structure', 'extensible', 'declaration'), prefix=r'\b', suffix=r'\b'), Keyword), (words(( 'file_contents', 'format', 'index', 'length', 'match', 'matches', 'replace', 'splice', 'split', 'substr', 'to_lowercase', 'to_uppercase', 'debug', 'error', 'traceback', 'deprecated', 'base64_decode', 'base64_encode', 'digest', 'escape', 'unescape', 'append', 'create', 'first', 'nlist', 'key', 'list', 'merge', 'next', 'prepend', 'is_boolean', 'is_defined', 'is_double', 'is_list', 'is_long', 'is_nlist', 'is_null', 'is_number', 'is_property', 'is_resource', 'is_string', 'to_boolean', 'to_double', 'to_long', 'to_string', 'clone', 'delete', 'exists', 'path_exists', 'if_exists', 'return', 'value'), prefix=r'\b', suffix=r'\b'), Name.Builtin), (r'#.*', Comment), (r'\\[\w\W]', String.Escape), (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Whitespace, 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+', Whitespace), (r'[^=\s\[\]{}()$"\'`\\;#]+', Text), (r'\d+(?= |\Z)', Number), ], 'curly': [ (r'\}', Keyword, '#pop'), (r':-', Keyword), (r'\w+', Name.Variable), (r'[^}:"\'`$]+', Punctuation), (r':', Punctuation), include('root'), ], 'paren': [ (r'\)', Keyword, '#pop'), include('root'), ], }
class CrmshLexer(RegexLexer): """ Lexer for crmsh configuration files for Pacemaker clusters. """ name = 'Crmsh' url = 'http://crmsh.github.io/' aliases = ['crmsh', 'pcmk'] filenames = ['*.crmsh', '*.pcmk'] mimetypes = [] version_added = '2.1'
elem = words(( 'node', 'primitive', 'group', 'clone', 'ms', 'location', 'colocation', 'order', 'fencing_topology', 'rsc_ticket', 'rsc_template', 'property', 'rsc_defaults', 'op_defaults', 'acl_target', 'acl_group', 'user', 'role', 'tag'), suffix=r'(?![\w#$-])') sub = words(( 'params', 'meta', 'operations', 'op', 'rule', 'attributes', 'utilization'), suffix=r'(?![\w#$-])') acl = words(('read', 'write', 'deny'), suffix=r'(?![\w#$-])') bin_rel = words(('and', 'or'), suffix=r'(?![\w#$-])') un_ops = words(('defined', 'not_defined'), suffix=r'(?![\w#$-])') date_exp = words(('in_range', 'date', 'spec', 'in'), suffix=r'(?![\w#$-])') acl_mod = (r'(?:tag|ref|reference|attribute|type|xpath)') bin_ops = (r'(?:lt|gt|lte|gte|eq|ne)') val_qual = (r'(?:string|version|number)') rsc_role_action = (r'(?:Master|Started|Slave|Stopped|' r'start|promote|demote|stop)')
tokens = { 'root': [ (r'^(#.*)(\n)?', bygroups(Comment, Whitespace)), # attr=value (nvpair) (r'([\w#$-]+)(=)("(?:""|[^"])*"|\S+)', bygroups(Name.Attribute, Punctuation, String)), # need this construct, otherwise numeric node ids # are matched as scores # elem id: (r'(node)(\s+)([\w#$-]+)(:)', bygroups(Keyword, Whitespace, Name, Punctuation)), # scores (r'([+-]?([0-9]+|inf)):', Number), # keywords (elements and other) (elem, Keyword), (sub, Keyword), (acl, Keyword), # binary operators (rf'(?:{val_qual}:)?({bin_ops})(?![\w#$-])', Operator.Word), # other operators (bin_rel, Operator.Word), (un_ops, Operator.Word), (date_exp, Operator.Word), # builtin attributes (e.g. #uname) (r'#[a-z]+(?![\w#$-])', Name.Builtin), # acl_mod:blah (rf'({acl_mod})(:)("(?:""|[^"])*"|\S+)', bygroups(Keyword, Punctuation, Name)), # rsc_id[:(role|action)] # NB: this matches all other identifiers (rf'([\w#$-]+)(?:(:)({rsc_role_action}))?(?![\w#$-])', bygroups(Name, Punctuation, Operator.Word)), # punctuation (r'(\\(?=\n)|[\[\](){}/:@])', Punctuation), (r'\s+|\n', Whitespace), ], }
class FlatlineLexer(RegexLexer): """ Lexer for Flatline expressions. """ name = 'Flatline' url = 'https://github.com/bigmlcom/flatline' aliases = ['flatline'] filenames = [] mimetypes = ['text/x-flatline'] version_added = '2.2'
special_forms = ('let',)
builtins = ( "!=", "*", "+", "-", "<", "<=", "=", ">", ">=", "abs", "acos", "all", "all-but", "all-with-defaults", "all-with-numeric-default", "and", "asin", "atan", "avg", "avg-window", "bin-center", "bin-count", "call", "category-count", "ceil", "cond", "cond-window", "cons", "cos", "cosh", "count", "diff-window", "div", "ensure-value", "ensure-weighted-value", "epoch", "epoch-day", "epoch-fields", "epoch-hour", "epoch-millisecond", "epoch-minute", "epoch-month", "epoch-second", "epoch-weekday", "epoch-year", "exp", "f", "field", "field-prop", "fields", "filter", "first", "floor", "head", "if", "in", "integer", "language", "length", "levenshtein", "linear-regression", "list", "ln", "log", "log10", "map", "matches", "matches?", "max", "maximum", "md5", "mean", "median", "min", "minimum", "missing", "missing-count", "missing?", "missing_count", "mod", "mode", "normalize", "not", "nth", "occurrences", "or", "percentile", "percentile-label", "population", "population-fraction", "pow", "preferred", "preferred?", "quantile-label", "rand", "rand-int", "random-value", "re-quote", "real", "replace", "replace-first", "rest", "round", "row-number", "segment-label", "sha1", "sha256", "sin", "sinh", "sqrt", "square", "standard-deviation", "standard_deviation", "str", "subs", "sum", "sum-squares", "sum-window", "sum_squares", "summary", "summary-no", "summary-str", "tail", "tan", "tanh", "to-degrees", "to-radians", "variance", "vectorize", "weighted-random-value", "window", "winnow", "within-percentiles?", "z-score", )
valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+'
tokens = { 'root': [ # whitespaces - usually not relevant (r'[,]+', Text), (r'\s+', Whitespace),
# numbers (r'-?\d+\.\d+', Number.Float), (r'-?\d+', Number.Integer), (r'0x-?[a-f\d]+', Number.Hex),
# strings, symbols and characters (r'"(\\\\|\\[^\\]|[^"\\])*"', String), (r"\\(.|[a-z]+)", String.Char),
# expression template placeholder (r'_', String.Symbol),
# highlight the special forms (words(special_forms, suffix=' '), Keyword),
# highlight the builtins (words(builtins, suffix=' '), Name.Builtin),
# the remaining functions (r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables (valid_name, Name.Variable),
# parentheses (r'(\(|\))', Punctuation), ], }
class SnowballLexer(ExtendedRegexLexer): """ Lexer for Snowball source code. """
name = 'Snowball' url = 'https://snowballstem.org/' aliases = ['snowball'] filenames = ['*.sbl'] version_added = '2.2'
_ws = r'\n\r\t '
def __init__(self, **options): self._reset_stringescapes() ExtendedRegexLexer.__init__(self, **options)
def _reset_stringescapes(self): self._start = "'" self._end = "'"
def _string(do_string_first): def callback(lexer, match, ctx): s = match.start() text = match.group() string = re.compile(rf'([^{re.escape(lexer._start)}]*)(.)').match escape = re.compile(rf'([^{re.escape(lexer._end)}]*)(.)').match pos = 0 do_string = do_string_first while pos < len(text): if do_string: match = string(text, pos) yield s + match.start(1), String.Single, match.group(1) if match.group(2) == "'": yield s + match.start(2), String.Single, match.group(2) ctx.stack.pop() break yield s + match.start(2), String.Escape, match.group(2) pos = match.end() match = escape(text, pos) yield s + match.start(), String.Escape, match.group() if match.group(2) != lexer._end: ctx.stack[-1] = 'escape' break pos = match.end() do_string = True ctx.pos = s + match.end() return callback
def _stringescapes(lexer, match, ctx): lexer._start = match.group(3) lexer._end = match.group(5) return bygroups(Keyword.Reserved, Whitespace, String.Escape, Whitespace, String.Escape)(lexer, match, ctx)
tokens = { 'root': [ (r'len\b', Name.Builtin), (r'lenof\b', Operator.Word), include('root1'), ], 'root1': [ (rf'[{_ws}]+', Whitespace), (r'\d+', Number.Integer), (r"'", String.Single, 'string'), (r'[()]', Punctuation), (r'/\*[\w\W]*?\*/', Comment.Multiline), (r'//.*', Comment.Single), (r'[!*+\-/<=>]=|[-=]>|<[+-]|[$*+\-/<=>?\[\]]', Operator), (words(('as', 'get', 'hex', 'among', 'define', 'decimal', 'backwardmode'), suffix=r'\b'), Keyword.Reserved), (words(('strings', 'booleans', 'integers', 'routines', 'externals', 'groupings'), suffix=r'\b'), Keyword.Reserved, 'declaration'), (words(('do', 'or', 'and', 'for', 'hop', 'non', 'not', 'set', 'try', 'fail', 'goto', 'loop', 'next', 'test', 'true', 'false', 'unset', 'atmark', 'attach', 'delete', 'gopast', 'insert', 'repeat', 'sizeof', 'tomark', 'atleast', 'atlimit', 'reverse', 'setmark', 'tolimit', 'setlimit', 'backwards', 'substring'), suffix=r'\b'), Operator.Word), (words(('size', 'limit', 'cursor', 'maxint', 'minint'), suffix=r'\b'), Name.Builtin), (rf'(stringdef\b)([{_ws}]*)([^{_ws}]+)', bygroups(Keyword.Reserved, Whitespace, String.Escape)), (rf'(stringescapes\b)([{_ws}]*)(.)([{_ws}]*)(.)', _stringescapes), (r'[A-Za-z]\w*', Name), ], 'declaration': [ (r'\)', Punctuation, '#pop'), (words(('len', 'lenof'), suffix=r'\b'), Name, ('root1', 'declaration')), include('root1'), ], 'string': [ (r"[^']*'", _string(True)), ], 'escape': [ (r"[^']*'", _string(False)), ], }
def get_tokens_unprocessed(self, text=None, context=None): self._reset_stringescapes() return ExtendedRegexLexer.get_tokens_unprocessed(self, text, context)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279""" pygments.lexers.dylan ~~~~~~~~~~~~~~~~~~~~~
Lexers for the Dylan language.
: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, do_insertions, \ default, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Literal, Whitespace
__all__ = ['DylanLexer', 'DylanConsoleLexer', 'DylanLidLexer']
class DylanLexer(RegexLexer): """ For the Dylan language. """
name = 'Dylan' url = 'http://www.opendylan.org/' aliases = ['dylan'] filenames = ['*.dylan', '*.dyl', '*.intr'] mimetypes = ['text/x-dylan'] version_added = '0.7'
flags = re.IGNORECASE
builtins = { 'subclass', 'abstract', 'block', 'concrete', 'constant', 'class', 'compiler-open', 'compiler-sideways', 'domain', 'dynamic', 'each-subclass', 'exception', 'exclude', 'function', 'generic', 'handler', 'inherited', 'inline', 'inline-only', 'instance', 'interface', 'import', 'keyword', 'library', 'macro', 'method', 'module', 'open', 'primary', 'required', 'sealed', 'sideways', 'singleton', 'slot', 'thread', 'variable', 'virtual'}
keywords = { 'above', 'afterwards', 'begin', 'below', 'by', 'case', 'cleanup', 'create', 'define', 'else', 'elseif', 'end', 'export', 'finally', 'for', 'from', 'if', 'in', 'let', 'local', 'otherwise', 'rename', 'select', 'signal', 'then', 'to', 'unless', 'until', 'use', 'when', 'while'}
operators = { '~', '+', '-', '*', '|', '^', '=', '==', '~=', '~==', '<', '<=', '>', '>=', '&', '|'}
functions = { 'abort', 'abs', 'add', 'add!', 'add-method', 'add-new', 'add-new!', 'all-superclasses', 'always', 'any?', 'applicable-method?', 'apply', 'aref', 'aref-setter', 'as', 'as-lowercase', 'as-lowercase!', 'as-uppercase', 'as-uppercase!', 'ash', 'backward-iteration-protocol', 'break', 'ceiling', 'ceiling/', 'cerror', 'check-type', 'choose', 'choose-by', 'complement', 'compose', 'concatenate', 'concatenate-as', 'condition-format-arguments', 'condition-format-string', 'conjoin', 'copy-sequence', 'curry', 'default-handler', 'dimension', 'dimensions', 'direct-subclasses', 'direct-superclasses', 'disjoin', 'do', 'do-handlers', 'element', 'element-setter', 'empty?', 'error', 'even?', 'every?', 'false-or', 'fill!', 'find-key', 'find-method', 'first', 'first-setter', 'floor', 'floor/', 'forward-iteration-protocol', 'function-arguments', 'function-return-values', 'function-specializers', 'gcd', 'generic-function-mandatory-keywords', 'generic-function-methods', 'head', 'head-setter', 'identity', 'initialize', 'instance?', 'integral?', 'intersection', 'key-sequence', 'key-test', 'last', 'last-setter', 'lcm', 'limited', 'list', 'logand', 'logbit?', 'logior', 'lognot', 'logxor', 'make', 'map', 'map-as', 'map-into', 'max', 'member?', 'merge-hash-codes', 'min', 'modulo', 'negative', 'negative?', 'next-method', 'object-class', 'object-hash', 'odd?', 'one-of', 'pair', 'pop', 'pop-last', 'positive?', 'push', 'push-last', 'range', 'rank', 'rcurry', 'reduce', 'reduce1', 'remainder', 'remove', 'remove!', 'remove-duplicates', 'remove-duplicates!', 'remove-key!', 'remove-method', 'replace-elements!', 'replace-subsequence!', 'restart-query', 'return-allowed?', 'return-description', 'return-query', 'reverse', 'reverse!', 'round', 'round/', 'row-major-index', 'second', 'second-setter', 'shallow-copy', 'signal', 'singleton', 'size', 'size-setter', 'slot-initialized?', 'sort', 'sort!', 'sorted-applicable-methods', 'subsequence-position', 'subtype?', 'table-protocol', 'tail', 'tail-setter', 'third', 'third-setter', 'truncate', 'truncate/', 'type-error-expected-type', 'type-error-value', 'type-for-copy', 'type-union', 'union', 'values', 'vector', 'zero?'}
valid_name = '\\\\?[\\w!&*<>|^$%@\\-+~?/=]+'
def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): if token is Name: lowercase_value = value.lower() if lowercase_value in self.builtins: yield index, Name.Builtin, value continue if lowercase_value in self.keywords: yield index, Keyword, value continue if lowercase_value in self.functions: yield index, Name.Builtin, value continue if lowercase_value in self.operators: yield index, Operator, value continue yield index, token, value
tokens = { 'root': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'//.*?\n', Comment.Single),
# lid header (r'([a-z0-9-]+)(:)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Operator, Whitespace, String)),
default('code') # no header match, switch to code ], 'code': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# multi-line comment (r'/\*', Comment.Multiline, 'comment'),
# strings and characters (r'"', String, 'string'), (r"'(\\.|\\[0-7]{1,3}|\\x[a-f0-9]{1,2}|[^\\\'\n])'", String.Char),
# binary integer (r'#b[01]+', Number.Bin),
# octal integer (r'#o[0-7]+', Number.Oct),
# floating point (r'[-+]?(\d*\.\d+(e[-+]?\d+)?|\d+(\.\d*)?e[-+]?\d+)', Number.Float),
# decimal integer (r'[-+]?\d+', Number.Integer),
# hex integer (r'#x[0-9a-f]+', Number.Hex),
# Macro parameters (r'(\?' + valid_name + ')(:)' r'(token|name|variable|expression|body|case-body|\*)', bygroups(Name.Tag, Operator, Name.Builtin)), (r'(\?)(:)(token|name|variable|expression|body|case-body|\*)', bygroups(Name.Tag, Operator, Name.Builtin)), (r'\?' + valid_name, Name.Tag),
# Punctuation (r'(=>|::|#\(|#\[|##|\?\?|\?=|\?|[(){}\[\],.;])', Punctuation),
# Most operators are picked up as names and then re-flagged. # This one isn't valid in a name though, so we pick it up now. (r':=', Operator),
# Pick up #t / #f before we match other stuff with #. (r'#[tf]', Literal),
# #"foo" style keywords (r'#"', String.Symbol, 'keyword'),
# #rest, #key, #all-keys, etc. (r'#[a-z0-9-]+', Keyword),
# required-init-keyword: style keywords. (valid_name + ':', Keyword),
# class names ('<' + valid_name + '>', Name.Class),
# define variable forms. (r'\*' + valid_name + r'\*', Name.Variable.Global),
# define constant forms. (r'\$' + valid_name, Name.Constant),
# everything else. We re-flag some of these in the method above. (valid_name, Name), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'keyword': [ (r'"', String.Symbol, '#pop'), (r'[^\\"]+', String.Symbol), # all other characters ], 'string': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-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 ] }
class DylanLidLexer(RegexLexer): """ For Dylan LID (Library Interchange Definition) files. """
name = 'DylanLID' aliases = ['dylan-lid', 'lid'] filenames = ['*.lid', '*.hdp'] mimetypes = ['text/x-dylan-lid'] url = 'http://www.opendylan.org/' version_added = '1.6' flags = re.IGNORECASE
tokens = { 'root': [ # Whitespace (r'\s+', Whitespace),
# single line comment (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
# lid header (r'(.*?)(:)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Operator, Whitespace, String)), ] }
class DylanConsoleLexer(Lexer): """ For Dylan interactive console output.
This is based on a copy of the ``RubyConsoleLexer``. """ name = 'Dylan session' aliases = ['dylan-console', 'dylan-repl'] filenames = ['*.dylan-console'] mimetypes = ['text/x-dylan-console'] url = 'http://www.opendylan.org/' version_added = '1.6' _example = 'dylan-console/console.dylan-console'
_prompt_re = re.compile(r'\?| ')
def get_tokens_unprocessed(self, text): dylexer = DylanLexer(**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, dylexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, dylexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144""" pygments.lexers.ecl ~~~~~~~~~~~~~~~~~~~
Lexers for the ECL 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, wordsfrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Whitespace
__all__ = ['ECLLexer']
class ECLLexer(RegexLexer): """ Lexer for the declarative big-data ECL language. """
name = 'ECL' url = 'https://hpccsystems.com/training/documentation/ecl-language-reference/html' aliases = ['ecl'] filenames = ['*.ecl'] mimetypes = ['application/x-ecl'] version_added = '1.5'
flags = re.IGNORECASE | re.MULTILINE
tokens = { 'root': [ include('whitespace'), include('statements'), ], 'whitespace': [ (r'\s+', Whitespace), (r'\/\/.*', Comment.Single), (r'/(\\\n)?\*(.|\n)*?\*(\\\n)?/', Comment.Multiline), ], 'statements': [ include('types'), include('keywords'), include('functions'), include('hash'), (r'"', String, 'string'), (r'\'', String, 'string'), (r'(\d+\.\d*|\.\d+|\d+)e[+-]?\d+[lu]*', Number.Float), (r'(\d+\.\d*|\.\d+|\d+f)f?', Number.Float), (r'0x[0-9a-f]+[lu]*', Number.Hex), (r'0[0-7]+[lu]*', Number.Oct), (r'\d+[lu]*', Number.Integer), (r'[~!%^&*+=|?:<>/-]+', Operator), (r'[{}()\[\],.;]', Punctuation), (r'[a-z_]\w*', Name), ], 'hash': [ (r'^#.*$', Comment.Preproc), ], 'types': [ (r'(RECORD|END)\D', Keyword.Declaration), (r'((?:ASCII|BIG_ENDIAN|BOOLEAN|DATA|DECIMAL|EBCDIC|INTEGER|PATTERN|' r'QSTRING|REAL|RECORD|RULE|SET OF|STRING|TOKEN|UDECIMAL|UNICODE|' r'UNSIGNED|VARSTRING|VARUNICODE)\d*)(\s+)', bygroups(Keyword.Type, Whitespace)), ], 'keywords': [ (words(( 'APPLY', 'ASSERT', 'BUILD', 'BUILDINDEX', 'EVALUATE', 'FAIL', 'KEYDIFF', 'KEYPATCH', 'LOADXML', 'NOTHOR', 'NOTIFY', 'OUTPUT', 'PARALLEL', 'SEQUENTIAL', 'SOAPCALL', 'CHECKPOINT', 'DEPRECATED', 'FAILCODE', 'FAILMESSAGE', 'FAILURE', 'GLOBAL', 'INDEPENDENT', 'ONWARNING', 'PERSIST', 'PRIORITY', 'RECOVERY', 'STORED', 'SUCCESS', 'WAIT', 'WHEN'), suffix=r'\b'), Keyword.Reserved), # These are classed differently, check later (words(( 'ALL', 'AND', 'ANY', 'AS', 'ATMOST', 'BEFORE', 'BEGINC++', 'BEST', 'BETWEEN', 'CASE', 'CONST', 'COUNTER', 'CSV', 'DESCEND', 'ENCRYPT', 'ENDC++', 'ENDMACRO', 'EXCEPT', 'EXCLUSIVE', 'EXPIRE', 'EXPORT', 'EXTEND', 'FALSE', 'FEW', 'FIRST', 'FLAT', 'FULL', 'FUNCTION', 'GROUP', 'HEADER', 'HEADING', 'HOLE', 'IFBLOCK', 'IMPORT', 'IN', 'JOINED', 'KEEP', 'KEYED', 'LAST', 'LEFT', 'LIMIT', 'LOAD', 'LOCAL', 'LOCALE', 'LOOKUP', 'MACRO', 'MANY', 'MAXCOUNT', 'MAXLENGTH', 'MIN SKEW', 'MODULE', 'INTERFACE', 'NAMED', 'NOCASE', 'NOROOT', 'NOSCAN', 'NOSORT', 'NOT', 'OF', 'ONLY', 'OPT', 'OR', 'OUTER', 'OVERWRITE', 'PACKED', 'PARTITION', 'PENALTY', 'PHYSICALLENGTH', 'PIPE', 'QUOTE', 'RELATIONSHIP', 'REPEAT', 'RETURN', 'RIGHT', 'SCAN', 'SELF', 'SEPARATOR', 'SERVICE', 'SHARED', 'SKEW', 'SKIP', 'SQL', 'STORE', 'TERMINATOR', 'THOR', 'THRESHOLD', 'TOKEN', 'TRANSFORM', 'TRIM', 'TRUE', 'TYPE', 'UNICODEORDER', 'UNSORTED', 'VALIDATE', 'VIRTUAL', 'WHOLE', 'WILD', 'WITHIN', 'XML', 'XPATH', '__COMPRESSED__'), suffix=r'\b'), Keyword.Reserved), ], 'functions': [ (words(( 'ABS', 'ACOS', 'ALLNODES', 'ASCII', 'ASIN', 'ASSTRING', 'ATAN', 'ATAN2', 'AVE', 'CASE', 'CHOOSE', 'CHOOSEN', 'CHOOSESETS', 'CLUSTERSIZE', 'COMBINE', 'CORRELATION', 'COS', 'COSH', 'COUNT', 'COVARIANCE', 'CRON', 'DATASET', 'DEDUP', 'DEFINE', 'DENORMALIZE', 'DISTRIBUTE', 'DISTRIBUTED', 'DISTRIBUTION', 'EBCDIC', 'ENTH', 'ERROR', 'EVALUATE', 'EVENT', 'EVENTEXTRA', 'EVENTNAME', 'EXISTS', 'EXP', 'FAILCODE', 'FAILMESSAGE', 'FETCH', 'FROMUNICODE', 'GETISVALID', 'GLOBAL', 'GRAPH', 'GROUP', 'HASH', 'HASH32', 'HASH64', 'HASHCRC', 'HASHMD5', 'HAVING', 'IF', 'INDEX', 'INTFORMAT', 'ISVALID', 'ITERATE', 'JOIN', 'KEYUNICODE', 'LENGTH', 'LIBRARY', 'LIMIT', 'LN', 'LOCAL', 'LOG', 'LOOP', 'MAP', 'MATCHED', 'MATCHLENGTH', 'MATCHPOSITION', 'MATCHTEXT', 'MATCHUNICODE', 'MAX', 'MERGE', 'MERGEJOIN', 'MIN', 'NOLOCAL', 'NONEMPTY', 'NORMALIZE', 'PARSE', 'PIPE', 'POWER', 'PRELOAD', 'PROCESS', 'PROJECT', 'PULL', 'RANDOM', 'RANGE', 'RANK', 'RANKED', 'REALFORMAT', 'RECORDOF', 'REGEXFIND', 'REGEXREPLACE', 'REGROUP', 'REJECTED', 'ROLLUP', 'ROUND', 'ROUNDUP', 'ROW', 'ROWDIFF', 'SAMPLE', 'SET', 'SIN', 'SINH', 'SIZEOF', 'SOAPCALL', 'SORT', 'SORTED', 'SQRT', 'STEPPED', 'STORED', 'SUM', 'TABLE', 'TAN', 'TANH', 'THISNODE', 'TOPN', 'TOUNICODE', 'TRANSFER', 'TRIM', 'TRUNCATE', 'TYPEOF', 'UNGROUP', 'UNICODEORDER', 'VARIANCE', 'WHICH', 'WORKUNIT', 'XMLDECODE', 'XMLENCODE', 'XMLTEXT', 'XMLUNICODE'), suffix=r'\b'), Name.Function), ], 'string': [ (r'"', String, '#pop'), (r'\'', String, '#pop'), (r'[^"\']+', String), ], }
def analyse_text(text): """This is very difficult to guess relative to other business languages. -> in conjunction with BEGIN/END seems relatively rare though.""" result = 0
if '->' in text: result += 0.01 if 'BEGIN' in text: result += 0.01 if 'END' in text: result += 0.01
return result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768""" pygments.lexers.eiffel ~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Eiffel language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Whitespace
__all__ = ['EiffelLexer']
class EiffelLexer(RegexLexer): """ For Eiffel source code. """ name = 'Eiffel' url = 'https://www.eiffel.com' aliases = ['eiffel'] filenames = ['*.e'] mimetypes = ['text/x-eiffel'] version_added = '2.0'
tokens = { 'root': [ (r'[^\S\n]+', Whitespace), (r'--.*?$', Comment.Single), (r'[^\S\n]+', Whitespace), # Please note that keyword and operator are case insensitive. (r'(?i)(true|false|void|current|result|precursor)\b', Keyword.Constant), (r'(?i)(not|xor|implies|or)\b', Operator.Word), (r'(?i)(and)(?:(\s+)(then))?\b', bygroups(Operator.Word, Whitespace, Operator.Word)), (r'(?i)(or)(?:(\s+)(else))?\b', bygroups(Operator.Word, Whitespace, Operator.Word)), (words(( 'across', 'agent', 'alias', 'all', 'as', 'assign', 'attached', 'attribute', 'check', 'class', 'convert', 'create', 'debug', 'deferred', 'detachable', 'do', 'else', 'elseif', 'end', 'ensure', 'expanded', 'export', 'external', 'feature', 'from', 'frozen', 'if', 'inherit', 'inspect', 'invariant', 'like', 'local', 'loop', 'none', 'note', 'obsolete', 'old', 'once', 'only', 'redefine', 'rename', 'require', 'rescue', 'retry', 'select', 'separate', 'then', 'undefine', 'until', 'variant', 'when'), prefix=r'(?i)\b', suffix=r'\b'), Keyword.Reserved), (r'"\[([^\]%]|%(.|\n)|\][^"])*?\]"', String), (r'"([^"%\n]|%.)*?"', String), include('numbers'), (r"'([^'%]|%'|%%)'", String.Char), (r"(//|\\\\|>=|<=|:=|/=|~|/~|[\\?!#%&@|+/\-=>*$<^\[\]])", Operator), (r"([{}():;,.])", Punctuation), (r'([a-z]\w*)|([A-Z][A-Z0-9_]*[a-z]\w*)', Name), (r'([A-Z][A-Z0-9_]*)', Name.Class), (r'\n+', Whitespace), ], 'numbers': [ (r'0[xX][a-fA-F0-9]+', Number.Hex), (r'0[bB][01]+', Number.Bin), (r'0[cC][0-7]+', Number.Oct), (r'([0-9]+\.[0-9]*)|([0-9]*\.[0-9]+)', Number.Float), (r'[0-9]+', Number.Integer), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123""" pygments.lexers.elm ~~~~~~~~~~~~~~~~~~~
Lexer for the Elm 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, bygroupsfrom pygments.token import Comment, Keyword, Name, Number, Punctuation, \ String, Whitespace
__all__ = ['ElmLexer']
class ElmLexer(RegexLexer): """ For Elm source code. """
name = 'Elm' url = 'https://elm-lang.org/' aliases = ['elm'] filenames = ['*.elm'] mimetypes = ['text/x-elm'] version_added = '2.1'
validName = r'[a-z_][a-zA-Z0-9_\']*'
specialName = r'^main '
builtinOps = ( '~', '||', '|>', '|', '`', '^', '\\', '\'', '>>', '>=', '>', '==', '=', '<~', '<|', '<=', '<<', '<-', '<', '::', ':', '/=', '//', '/', '..', '.', '->', '-', '++', '+', '*', '&&', '%', )
reservedWords = words(( 'alias', 'as', 'case', 'else', 'if', 'import', 'in', 'let', 'module', 'of', 'port', 'then', 'type', 'where', ), suffix=r'\b')
tokens = { 'root': [
# Comments (r'\{-', Comment.Multiline, 'comment'), (r'--.*', Comment.Single),
# Whitespace (r'\s+', Whitespace),
# Strings (r'"', String, 'doublequote'),
# Modules (r'^(\s*)(module)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
# Imports (r'^(\s*)(import)(\s*)', bygroups(Whitespace, Keyword.Namespace, Whitespace), 'imports'),
# Shaders (r'\[glsl\|.*', Name.Entity, 'shader'),
# Keywords (reservedWords, Keyword.Reserved),
# Types (r'[A-Z][a-zA-Z0-9_]*', Keyword.Type),
# Main (specialName, Keyword.Reserved),
# Prefix Operators (words((builtinOps), prefix=r'\(', suffix=r'\)'), Name.Function),
# Infix Operators (words(builtinOps), Name.Function),
# Numbers include('numbers'),
# Variable Names (validName, Name.Variable),
# Parens (r'[,()\[\]{}]', Punctuation),
],
'comment': [ (r'-(?!\})', Comment.Multiline), (r'\{-', Comment.Multiline, 'comment'), (r'[^-}]', Comment.Multiline), (r'-\}', Comment.Multiline, '#pop'), ],
'doublequote': [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\[nrfvb\\"]', String.Escape), (r'[^"]', String), (r'"', String, '#pop'), ],
'imports': [ (r'\w+(\.\w+)*', Name.Class, '#pop'), ],
'numbers': [ (r'_?\d+\.(?=\d+)', Number.Float), (r'_?\d+', Number.Integer), ],
'shader': [ (r'\|(?!\])', Name.Entity), (r'\|\]', Name.Entity, '#pop'), (r'(.*)(\n)', bygroups(Name.Entity, Whitespace)), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201""" pygments.lexers.elpi ~~~~~~~~~~~~~~~~~~~~
Lexer for the `Elpi <http://github.com/LPCIC/elpi>`_ programming language.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, bygroups, include, usingfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation
__all__ = ['ElpiLexer']
from pygments.lexers.theorem import RocqLexer
class ElpiLexer(RegexLexer): """ Lexer for the Elpi programming language. """
name = 'Elpi' url = 'http://github.com/LPCIC/elpi' aliases = ['elpi'] filenames = ['*.elpi'] mimetypes = ['text/x-elpi'] version_added = '2.11'
lcase_re = r"[a-z]" ucase_re = r"[A-Z]" digit_re = r"[0-9]" schar2_re = r"([+*^?/<>`'@#~=&!])" schar_re = rf"({schar2_re}|-|\$|_)" idchar_re = rf"({lcase_re}|{ucase_re}|{digit_re}|{schar_re})" idcharstarns_re = rf"({idchar_re}*(\.({lcase_re}|{ucase_re}){idchar_re}*)*)" symbchar_re = rf"({lcase_re}|{ucase_re}|{digit_re}|{schar_re}|:)" constant_re = rf"({ucase_re}{idchar_re}*|{lcase_re}{idcharstarns_re}|{schar2_re}{symbchar_re}*|_{idchar_re}+)" symbol_re = r"(,|<=>|->|:-|;|\?-|->|&|=>|\bas\b|\buvar\b|<|=<|=|==|>=|>|\bi<|\bi=<|\bi>=|\bi>|\bis\b|\br<|\br=<|\br>=|\br>|\bs<|\bs=<|\bs>=|\bs>|@|::|\[\]|`->|`:|`:=|\^|-|\+|\bi-|\bi\+|r-|r\+|/|\*|\bdiv\b|\bi\*|\bmod\b|\br\*|~|\bi~|\br~)" escape_re = rf"\(({constant_re}|{symbol_re})\)" const_sym_re = rf"({constant_re}|{symbol_re}|{escape_re})"
tokens = { 'root': [ include('elpi') ],
'elpi': [ include('_elpi-comment'),
(r"(:before|:after|:if|:name)(\s*)(\")", bygroups(Keyword.Mode, Text.Whitespace, String.Double), 'elpi-string'), (r"(:index)(\s*)(\()", bygroups(Keyword.Mode, Text.Whitespace, Punctuation), 'elpi-indexing-expr'), (rf"\b(external pred|pred)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-pred-item'), (rf"\b(func)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-func-item'), (rf"\b(external type|type)(\s+)(({const_sym_re}(,\s*)?)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (rf"\b(kind)(\s+)(({const_sym_re}|,)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (rf"\b(typeabbrev)(\s+)({const_sym_re})", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (r"\b(typeabbrev)(\s+)(\([^)]+\))", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-type'), (r"\b(accumulate)(\s+)(\")", bygroups(Keyword.Declaration, Text.Whitespace, String.Double), 'elpi-string'), (rf"\b(accumulate|namespace|local)(\s+)({constant_re})", bygroups(Keyword.Declaration, Text.Whitespace, Text)), (rf"\b(shorten)(\s+)({constant_re}\.)", bygroups(Keyword.Declaration, Text.Whitespace, Text)), (r"\b(pi|sigma)(\s+)([a-zA-Z][A-Za-z0-9_ ]*)(\\)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Variable, Text)), (rf"\b(constraint)(\s+)(({const_sym_re}(\s+)?)+)", bygroups(Keyword.Declaration, Text.Whitespace, Name.Function), 'elpi-chr-rule-start'),
(rf"(?=[A-Z_]){constant_re}", Name.Variable), (rf"(?=[a-z_])({constant_re}|_)\\", Name.Variable), (r"_", Name.Variable), (rf"({symbol_re}|!|=>|;)", Keyword.Declaration), (constant_re, Text), (r"\[|\]|\||=>", Keyword.Declaration), (r'"', String.Double, 'elpi-string'), (r'`', String.Double, 'elpi-btick'), (r'\'', String.Double, 'elpi-tick'), (r'\{\{', Punctuation, 'elpi-quote'), (r'\{[^\{]', Text, 'elpi-spill'), (r"\(", Punctuation, 'elpi-in-parens'), (r'\d[\d_]*', Number.Integer), (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)', Number.Float), (r"[\+\*\-/\^\.]", Operator), ], '_elpi-comment': [ (r'%[^\n]*\n', Comment), (r'/(?:\\\n)?[*](?:[^*]|[*](?!(?:\\\n)?/))*[*](?:\\\n)?/', Comment), (r"\s+", Text.Whitespace), ], 'elpi-indexing-expr':[ (r'[0-9 _]+', Number.Integer), (r'\)', Punctuation, '#pop'), ], 'elpi-type': [ (r"(ctype\s+)(\")", bygroups(Keyword.Type, String.Double), 'elpi-string'), (r'->', Keyword.Type), (r'prop', Keyword.Mode), (constant_re, Keyword.Type), (r"\(|\)", Keyword.Type), (r"\.", Text, '#pop'), include('_elpi-comment'), ], 'elpi-chr-rule-start': [ (r"\{", Punctuation, 'elpi-chr-rule'), include('_elpi-comment'), ], 'elpi-chr-rule': [ (r"\brule\b", Keyword.Declaration), (r"\\", Keyword.Declaration), (r"\}", Punctuation, '#pop:2'), include('elpi'), ], 'elpi-pred-item': [ (r"[io]:", Keyword.Mode), (r"\.", Text, '#pop'), (r",", Keyword.Mode), include('_elpi-inner-pred-fun'), (r"\)", Keyword.Mode, '#pop'), (r"\(", Keyword.Type, '_elpi-type-item'), include('_elpi-comment'), include('_elpi-type-item'), ], 'elpi-func-item': [ (constant_re, Keyword.Type), (r"\.", Text, '#pop'), (r",", Keyword.Mode), (r'->', Keyword.Mode), include('_elpi-inner-pred-fun'), (r"\)", Keyword.Mode, '#pop'), (r"\(", Keyword.Type, '_elpi-type-item'), include('_elpi-comment'), include('_elpi-type-item'), ], '_elpi-inner-pred-fun': [ (r"(\()(\s*)(pred)", bygroups(Keyword.Mode,Text.Whitespace,Keyword.Declaration), 'elpi-pred-item'), (r"(\()(\s*)(func)", bygroups(Keyword.Mode,Text.Whitespace,Keyword.Declaration), 'elpi-func-item'), ], '_elpi-type-item': [ (r'->', Keyword.Type), (constant_re, Keyword.Type), include('_elpi-inner-pred-fun'), (r"\(", Keyword.Type, '#push'), (r"\)", Keyword.Type, '#pop'), include('_elpi-comment'), ],
''
'elpi-btick': [ (r'[^` ]+', String.Double), (r'`', String.Double, '#pop'), ], 'elpi-tick': [ (r'[^\' ]+', String.Double), (r'\'', String.Double, '#pop'), ], 'elpi-string': [ (r'[^\"]+', String.Double), (r'"', String.Double, '#pop'), ], 'elpi-quote': [ (r'\}\}', Punctuation, '#pop'), (r"\s+", Text.Whitespace), (r"(lp:)(\{\{)", bygroups(Number, Punctuation), 'elpi-quote-exit'), (rf"(lp:)((?=[A-Z_]){constant_re})", bygroups(Number, Name.Variable)), (r"((?!lp:|\}\}).)+", using(RocqLexer)), ], 'elpi-quote-exit': [ include('elpi'), (r'\}\}', Punctuation, '#pop'), ], 'elpi-spill': [ (r'\{[^\{]', Text, '#push'), (r'\}[^\}]', Text, '#pop'), include('elpi'), ], 'elpi-in-parens': [ (r"\(", Punctuation, '#push'), include('elpi'), (r"\)", Punctuation, '#pop'), ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132""" pygments.lexers.email ~~~~~~~~~~~~~~~~~~~~~
Lexer for the raw E-mail.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, DelegatingLexer, bygroupsfrom pygments.lexers.mime import MIMELexerfrom pygments.token import Text, Keyword, Name, String, Number, Commentfrom pygments.util import get_bool_opt
__all__ = ["EmailLexer"]
class EmailHeaderLexer(RegexLexer): """ Sub-lexer for raw E-mail. This lexer only process header part of e-mail.
.. versionadded:: 2.5 """
def __init__(self, **options): super().__init__(**options) self.highlight_x = get_bool_opt(options, "highlight-X-header", False)
def get_x_header_tokens(self, match): if self.highlight_x: # field yield match.start(1), Name.Tag, match.group(1)
# content default_actions = self.get_tokens_unprocessed( match.group(2), stack=("root", "header")) yield from default_actions else: # lowlight yield match.start(1), Comment.Special, match.group(1) yield match.start(2), Comment.Multiline, match.group(2)
tokens = { "root": [ (r"^(?:[A-WYZ]|X400)[\w\-]*:", Name.Tag, "header"), (r"^(X-(?:\w[\w\-]*:))([\s\S]*?\n)(?![ \t])", get_x_header_tokens), ], "header": [ # folding (r"\n[ \t]", Text.Whitespace), (r"\n(?![ \t])", Text.Whitespace, "#pop"),
# keywords (r"\bE?SMTPS?\b", Keyword), (r"\b(?:HE|EH)LO\b", Keyword),
# mailbox (r"[\w\.\-\+=]+@[\w\.\-]+", Name.Label), (r"<[\w\.\-\+=]+@[\w\.\-]+>", Name.Label),
# domain (r"\b(\w[\w\.-]*\.[\w\.-]*\w[a-zA-Z]+)\b", Name.Function),
# IPv4 (r"(?<=\b)(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0" r"-5]|2[0-4][0-9]|1?[0-9][0-9]?)(?=\b)", Number.Integer),
# IPv6 (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,7}:(?!\b)", Number.Hex), (r"(?<=\b):((:[0-9a-fA-F]{1,4}){1,7}|:)(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}(?=\b)", Number.Hex), (r"(?<=\b)[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})(?=\b)", Number.Hex), (r"(?<=\b)fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}(?=\b)", Number.Hex), (r"(?<=\b)::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}" r"[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}" r"[0-9])(?=\b)", Number.Hex), (r"(?<=\b)([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9])" r"{0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])(?=\b)", Number.Hex),
# Date time (r"(?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s+)?(0[1-9]|[1-2]?[0-9]|3[" r"01])\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(" r"19[0-9]{2}|[2-9][0-9]{3})\s+(2[0-3]|[0-1][0-9]):([0-5][0-9])" r"(?::(60|[0-5][0-9]))?(?:\.\d{1,5})?\s+([-\+][0-9]{2}[0-5][0-" r"9]|\(?(?:UTC?|GMT|(?:E|C|M|P)(?:ST|ET|DT)|[A-IK-Z])\)?)", Name.Decorator),
# RFC-2047 encoded string (r"(=\?)([\w-]+)(\?)([BbQq])(\?)([\[\w!\"#$%&\'()*+,-./:;<=>@[\\" r"\]^_`{|}~]+)(\?=)", bygroups(String.Affix, Name.Constant, String.Affix, Keyword.Constant, String.Affix, Number.Hex, String.Affix)),
# others (r'[\s]+', Text.Whitespace), (r'[\S]', Text), ], }
class EmailLexer(DelegatingLexer): """ Lexer for raw E-mail.
Additional options accepted:
`highlight-X-header` Highlight the fields of ``X-`` user-defined email header. (default: ``False``). """
name = "E-mail" aliases = ["email", "eml"] filenames = ["*.eml"] mimetypes = ["message/rfc822"] url = "https://en.wikipedia.org/wiki/Email#Message_format" version_added = '2.5'
def __init__(self, **options): super().__init__(EmailHeaderLexer, MIMELexer, Comment, **options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526""" pygments.lexers.erlang ~~~~~~~~~~~~~~~~~~~~~~
Lexers for Erlang.
: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, words, do_insertions, \ include, default, line_refrom pygments.token import Comment, Operator, Keyword, Name, String, \ Number, Punctuation, Generic, Whitespace
__all__ = ['ErlangLexer', 'ErlangShellLexer', 'ElixirConsoleLexer', 'ElixirLexer']
class ErlangLexer(RegexLexer): """ For the Erlang functional programming language. """
name = 'Erlang' url = 'https://www.erlang.org/' aliases = ['erlang'] filenames = ['*.erl', '*.hrl', '*.es', '*.escript'] mimetypes = ['text/x-erlang'] version_added = '0.9'
keywords = ( 'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if', 'let', 'of', 'query', 'receive', 'try', 'when', )
builtins = ( # See erlang(3) man page 'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list', 'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions', 'byte_size', 'cancel_timer', 'check_process_code', 'delete_module', 'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit', 'float', 'float_to_list', 'fun_info', 'fun_to_list', 'function_exported', 'garbage_collect', 'get', 'get_keys', 'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary', 'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean', 'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list', 'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record', 'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom', 'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom', 'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple', 'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5', 'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor', 'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2', 'pid_to_list', 'port_close', 'port_command', 'port_connect', 'port_control', 'port_call', 'port_info', 'port_to_list', 'process_display', 'process_flag', 'process_info', 'purge_module', 'put', 'read_timer', 'ref_to_list', 'register', 'resume_process', 'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie', 'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor', 'spawn_opt', 'split_binary', 'start_timer', 'statistics', 'suspend_process', 'system_flag', 'system_info', 'system_monitor', 'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered', 'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list', 'universaltime_to_localtime', 'unlink', 'unregister', 'whereis' )
operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)' word_operators = ( 'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor', 'div', 'not', 'or', 'orelse', 'rem', 'xor' )
atom_re = r"(?:[a-z]\w*|'[^\n']*[^\\]')"
variable_re = r'(?:[A-Z_]\w*)'
esc_char_re = r'[bdefnrstv\'"\\]' esc_octal_re = r'[0-7][0-7]?[0-7]?' esc_hex_re = r'(?:x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]+\})' esc_ctrl_re = r'\^[a-zA-Z]' escape_re = r'(?:\\(?:'+esc_char_re+r'|'+esc_octal_re+r'|'+esc_hex_re+r'|'+esc_ctrl_re+r'))'
macro_re = r'(?:'+variable_re+r'|'+atom_re+r')'
base_re = r'(?:[2-9]|[12][0-9]|3[0-6])'
tokens = { 'root': [ (r'\s+', Whitespace), (r'(%.*)(\n)', bygroups(Comment, Whitespace)), (words(keywords, suffix=r'\b'), Keyword), (words(builtins, suffix=r'\b'), Name.Builtin), (words(word_operators, suffix=r'\b'), Operator.Word), (r'^-', Punctuation, 'directive'), (operators, Operator), (r'"', String, 'string'), (r'<<', Name.Label), (r'>>', Name.Label), ('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)), ('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()', bygroups(Name.Function, Whitespace, Punctuation)), (r'[+-]?' + base_re + r'#[0-9a-zA-Z]+', Number.Integer), (r'[+-]?\d+', Number.Integer), (r'[+-]?\d+.\d+', Number.Float), (r'[]\[:_@\".{}()|;,]', Punctuation), (variable_re, Name.Variable), (atom_re, Name), (r'\?'+macro_re, Name.Constant), (r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char), (r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label),
# Erlang script shebang (r'\A#!.+\n', Comment.Hashbang),
# EEP 43: Maps # http://www.erlang.org/eeps/eep-0043.html (r'#\{', Punctuation, 'map_key'), ], 'string': [ (escape_re, String.Escape), (r'"', String, '#pop'), (r'~[0-9.*]*[~#+BPWXb-ginpswx]', String.Interpol), (r'[^"\\~]+', String), (r'~', String), ], 'directive': [ (r'(define)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Whitespace, Punctuation, Name.Constant), '#pop'), (r'(record)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Whitespace, Punctuation, Name.Label), '#pop'), (atom_re, Name.Entity, '#pop'), ], 'map_key': [ include('root'), (r'=>', Punctuation, 'map_val'), (r':=', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], }
class ErlangShellLexer(Lexer): """ Shell sessions in erl (for Erlang code). """ name = 'Erlang erl session' aliases = ['erl'] filenames = ['*.erl-sh'] mimetypes = ['text/x-erl-shellsession'] url = 'https://www.erlang.org/' version_added = '1.1'
_prompt_re = re.compile(r'(?:\([\w@_.]+\))?\d+>(?=\s|\Z)')
def get_tokens_unprocessed(self, text): erlexer = ErlangLexer(**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, erlexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] if line.startswith('*'): yield match.start(), Generic.Traceback, line else: yield match.start(), Generic.Output, line if curcode: yield from do_insertions(insertions, erlexer.get_tokens_unprocessed(curcode))
def gen_elixir_string_rules(name, symbol, token): states = {} states['string_' + name] = [ (rf'[^#{symbol}\\]+', token), include('escapes'), (r'\\.', token), (rf'({symbol})', bygroups(token), "#pop"), include('interpol') ] return states
def gen_elixir_sigstr_rules(term, term_class, token, interpol=True): if interpol: return [ (rf'[^#{term_class}\\]+', token), include('escapes'), (r'\\.', token), (rf'{term}[a-zA-Z]*', token, '#pop'), include('interpol') ] else: return [ (rf'[^{term_class}\\]+', token), (r'\\.', token), (rf'{term}[a-zA-Z]*', token, '#pop'), ]
class ElixirLexer(RegexLexer): """ For the Elixir language. """
name = 'Elixir' url = 'https://elixir-lang.org' aliases = ['elixir', 'ex', 'exs'] filenames = ['*.ex', '*.eex', '*.exs', '*.leex'] mimetypes = ['text/x-elixir'] version_added = '1.5'
KEYWORD = ('fn', 'do', 'end', 'after', 'else', 'rescue', 'catch') KEYWORD_OPERATOR = ('not', 'and', 'or', 'when', 'in') BUILTIN = ( 'case', 'cond', 'for', 'if', 'unless', 'try', 'receive', 'raise', 'quote', 'unquote', 'unquote_splicing', 'throw', 'super', ) BUILTIN_DECLARATION = ( 'def', 'defp', 'defmodule', 'defprotocol', 'defmacro', 'defmacrop', 'defdelegate', 'defexception', 'defstruct', 'defimpl', 'defcallback', )
BUILTIN_NAMESPACE = ('import', 'require', 'use', 'alias') CONSTANT = ('nil', 'true', 'false')
PSEUDO_VAR = ('_', '__MODULE__', '__DIR__', '__ENV__', '__CALLER__')
OPERATORS3 = ( '<<<', '>>>', '|||', '&&&', '^^^', '~~~', '===', '!==', '~>>', '<~>', '|~>', '<|>', ) OPERATORS2 = ( '==', '!=', '<=', '>=', '&&', '||', '<>', '++', '--', '|>', '=~', '->', '<-', '|', '.', '=', '~>', '<~', ) OPERATORS1 = ('<', '>', '+', '-', '*', '/', '!', '^', '&')
PUNCTUATION = ( '\\\\', '<<', '>>', '=>', '(', ')', ':', ';', ',', '[', ']', )
def get_tokens_unprocessed(self, text): for index, token, value in RegexLexer.get_tokens_unprocessed(self, text): if token is Name: if value in self.KEYWORD: yield index, Keyword, value elif value in self.KEYWORD_OPERATOR: yield index, Operator.Word, value elif value in self.BUILTIN: yield index, Keyword, value elif value in self.BUILTIN_DECLARATION: yield index, Keyword.Declaration, value elif value in self.BUILTIN_NAMESPACE: yield index, Keyword.Namespace, value elif value in self.CONSTANT: yield index, Name.Constant, value elif value in self.PSEUDO_VAR: yield index, Name.Builtin.Pseudo, value else: yield index, token, value else: yield index, token, value
def gen_elixir_sigil_rules(): # all valid sigil terminators (excluding heredocs) terminators = [ (r'\{', r'\}', '}', 'cb'), (r'\[', r'\]', r'\]', 'sb'), (r'\(', r'\)', ')', 'pa'), ('<', '>', '>', 'ab'), ('/', '/', '/', 'slas'), (r'\|', r'\|', '|', 'pipe'), ('"', '"', '"', 'quot'), ("'", "'", "'", 'apos'), ]
# heredocs have slightly different rules triquotes = [(r'"""', 'triquot'), (r"'''", 'triapos')]
token = String.Other states = {'sigils': []}
for term, name in triquotes: states['sigils'] += [ (rf'(~[a-z])({term})', bygroups(token, String.Heredoc), (name + '-end', name + '-intp')), (rf'(~[A-Z])({term})', bygroups(token, String.Heredoc), (name + '-end', name + '-no-intp')), ]
states[name + '-end'] = [ (r'[a-zA-Z]+', token, '#pop'), default('#pop'), ] states[name + '-intp'] = [ (r'^(\s*)(' + term + ')', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_interpol'), ] states[name + '-no-intp'] = [ (r'^(\s*)(' + term +')', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_no_interpol'), ]
for lterm, rterm, rterm_class, name in terminators: states['sigils'] += [ (r'~[a-z]' + lterm, token, name + '-intp'), (r'~[A-Z]' + lterm, token, name + '-no-intp'), ] states[name + '-intp'] = \ gen_elixir_sigstr_rules(rterm, rterm_class, token) states[name + '-no-intp'] = \ gen_elixir_sigstr_rules(rterm, rterm_class, token, interpol=False)
return states
op3_re = "|".join(re.escape(s) for s in OPERATORS3) op2_re = "|".join(re.escape(s) for s in OPERATORS2) op1_re = "|".join(re.escape(s) for s in OPERATORS1) ops_re = rf'(?:{op3_re}|{op2_re}|{op1_re})' punctuation_re = "|".join(re.escape(s) for s in PUNCTUATION) alnum = r'\w' name_re = rf'(?:\.\.\.|[a-z_]{alnum}*[!?]?)' modname_re = rf'[A-Z]{alnum}*(?:\.[A-Z]{alnum}*)*' complex_name_re = rf'(?:{name_re}|{modname_re}|{ops_re})' special_atom_re = r'(?:\.\.\.|<<>>|%\{\}|%|\{\})'
long_hex_char_re = r'(\\x\{)([\da-fA-F]+)(\})' hex_char_re = r'(\\x[\da-fA-F]{1,2})' escape_char_re = r'(\\[abdefnrstv])'
tokens = { 'root': [ (r'\s+', Whitespace), (r'#.*$', Comment.Single),
# Various kinds of characters (r'(\?)' + long_hex_char_re, bygroups(String.Char, String.Escape, Number.Hex, String.Escape)), (r'(\?)' + hex_char_re, bygroups(String.Char, String.Escape)), (r'(\?)' + escape_char_re, bygroups(String.Char, String.Escape)), (r'\?\\?.', String.Char),
# '::' has to go before atoms (r':::', String.Symbol), (r'::', Operator),
# atoms (r':' + special_atom_re, String.Symbol), (r':' + complex_name_re, String.Symbol), (r':"', String.Symbol, 'string_double_atom'), (r":'", String.Symbol, 'string_single_atom'),
# [keywords: ...] (rf'({special_atom_re}|{complex_name_re})(:)(?=\s|\n)', bygroups(String.Symbol, Punctuation)),
# @attributes (r'@' + name_re, Name.Attribute),
# identifiers (name_re, Name), (rf'(%?)({modname_re})', bygroups(Punctuation, Name.Class)),
# operators and punctuation (op3_re, Operator), (op2_re, Operator), (punctuation_re, Punctuation), (r'&\d', Name.Entity), # anon func arguments (op1_re, Operator),
# numbers (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[\da-fA-F]+', Number.Hex), (r'\d(_?\d)*\.\d(_?\d)*([eE][-+]?\d(_?\d)*)?', Number.Float), (r'\d(_?\d)*', Number.Integer),
# strings and heredocs (r'(""")(\s*)', bygroups(String.Heredoc, Whitespace), 'heredoc_double'), (r"(''')(\s*)$", bygroups(String.Heredoc, Whitespace), 'heredoc_single'), (r'"', String.Double, 'string_double'), (r"'", String.Single, 'string_single'),
include('sigils'),
(r'%\{', Punctuation, 'map_key'), (r'\{', Punctuation, 'tuple'), ], 'heredoc_double': [ (r'^(\s*)(""")', bygroups(Whitespace, String.Heredoc), '#pop'), include('heredoc_interpol'), ], 'heredoc_single': [ (r"^\s*'''", String.Heredoc, '#pop'), include('heredoc_interpol'), ], 'heredoc_interpol': [ (r'[^#\\\n]+', String.Heredoc), include('escapes'), (r'\\.', String.Heredoc), (r'\n+', String.Heredoc), include('interpol'), ], 'heredoc_no_interpol': [ (r'[^\\\n]+', String.Heredoc), (r'\\.', String.Heredoc), (r'\n+', Whitespace), ], 'escapes': [ (long_hex_char_re, bygroups(String.Escape, Number.Hex, String.Escape)), (hex_char_re, String.Escape), (escape_char_re, String.Escape), ], 'interpol': [ (r'#\{', String.Interpol, 'interpol_string'), ], 'interpol_string': [ (r'\}', String.Interpol, "#pop"), include('root') ], 'map_key': [ include('root'), (r':', Punctuation, 'map_val'), (r'=>', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], 'tuple': [ include('root'), (r'\}', Punctuation, '#pop'), ], } tokens.update(gen_elixir_string_rules('double', '"', String.Double)) tokens.update(gen_elixir_string_rules('single', "'", String.Single)) tokens.update(gen_elixir_string_rules('double_atom', '"', String.Symbol)) tokens.update(gen_elixir_string_rules('single_atom', "'", String.Symbol)) tokens.update(gen_elixir_sigil_rules())
class ElixirConsoleLexer(Lexer): """ For Elixir interactive console (iex) output like:
.. sourcecode:: iex
iex> [head | tail] = [1,2,3] [1,2,3] iex> head 1 iex> tail [2,3] iex> [head | tail] [1,2,3] iex> length [head | tail] 3 """
name = 'Elixir iex session' aliases = ['iex'] mimetypes = ['text/x-elixir-shellsession'] url = 'https://elixir-lang.org' version_added = '1.5'
_prompt_re = re.compile(r'(iex|\.{3})((?:\([\w@_.]+\))?\d+|\(\d+\))?> ')
def get_tokens_unprocessed(self, text): exlexer = ElixirLexer(**self.options)
curcode = '' in_error = False insertions = [] for match in line_re.finditer(text): line = match.group() if line.startswith('** '): in_error = True insertions.append((len(curcode), [(0, Generic.Error, line[:-1])])) curcode += line[-1:] else: m = self._prompt_re.match(line) if m is not None: in_error = False end = m.end() insertions.append((len(curcode), [(0, Generic.Prompt, line[:end])])) curcode += line[end:] else: if curcode: yield from do_insertions( insertions, exlexer.get_tokens_unprocessed(curcode)) curcode = '' insertions = [] token = Generic.Error if in_error else Generic.Output yield match.start(), token, line if curcode: yield from do_insertions( insertions, exlexer.get_tokens_unprocessed(curcode))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300""" pygments.lexers.esoteric ~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for esoteric languages.
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.lexer import RegexLexer, include, words, bygroupsfrom pygments.token import Comment, Operator, Keyword, Name, String, Number, \ Punctuation, Error, Whitespace
__all__ = ['BrainfuckLexer', 'BefungeLexer', 'RedcodeLexer', 'CAmkESLexer', 'CapDLLexer', 'AheuiLexer']
class BrainfuckLexer(RegexLexer): """ Lexer for the esoteric BrainFuck language. """
name = 'Brainfuck' url = 'http://www.muppetlabs.com/~breadbox/bf/' aliases = ['brainfuck', 'bf'] filenames = ['*.bf', '*.b'] mimetypes = ['application/x-brainfuck'] version_added = ''
tokens = { 'common': [ # use different colors for different instruction types (r'[.,]+', Name.Tag), (r'[+-]+', Name.Builtin), (r'[<>]+', Name.Variable), (r'[^.,+\-<>\[\]]+', Comment), ], 'root': [ (r'\[', Keyword, 'loop'), (r'\]', Error), include('common'), ], 'loop': [ (r'\[', Keyword, '#push'), (r'\]', Keyword, '#pop'), include('common'), ] }
def analyse_text(text): """It's safe to assume that a program which mostly consists of + - and < > is brainfuck.""" plus_minus_count = 0 greater_less_count = 0
range_to_check = max(256, len(text))
for c in text[:range_to_check]: if c == '+' or c == '-': plus_minus_count += 1 if c == '<' or c == '>': greater_less_count += 1
if plus_minus_count > (0.25 * range_to_check): return 1.0 if greater_less_count > (0.25 * range_to_check): return 1.0
result = 0 if '[-]' in text: result += 0.5
return result
class BefungeLexer(RegexLexer): """ Lexer for the esoteric Befunge language. """ name = 'Befunge' url = 'http://en.wikipedia.org/wiki/Befunge' aliases = ['befunge'] filenames = ['*.befunge'] mimetypes = ['application/x-befunge'] version_added = '0.7'
tokens = { 'root': [ (r'[0-9a-f]', Number), (r'[+*/%!`-]', Operator), # Traditional math (r'[<>^v?\[\]rxjk]', Name.Variable), # Move, imperatives (r'[:\\$.,n]', Name.Builtin), # Stack ops, imperatives (r'[|_mw]', Keyword), (r'[{}]', Name.Tag), # Befunge-98 stack ops (r'".*?"', String.Double), # Strings don't appear to allow escapes (r'\'.', String.Single), # Single character (r'[#;]', Comment), # Trampoline... depends on direction hit (r'[pg&~=@iotsy]', Keyword), # Misc (r'[()A-Z]', Comment), # Fingerprints (r'\s+', Whitespace), # Whitespace doesn't matter ], }
class CAmkESLexer(RegexLexer): """ Basic lexer for the input language for the CAmkES component platform. """ name = 'CAmkES' url = 'https://sel4.systems/CAmkES/' aliases = ['camkes', 'idl4'] filenames = ['*.camkes', '*.idl4'] version_added = '2.1'
tokens = { 'root': [ # C pre-processor directive (r'^(\s*)(#.*)(\n)', bygroups(Whitespace, Comment.Preproc, Whitespace)),
# Whitespace, comments (r'\s+', Whitespace), (r'/\*(.|\n)*?\*/', Comment), (r'//.*$', Comment),
(r'[\[(){},.;\]]', Punctuation), (r'[~!%^&*+=|?:<>/-]', Operator),
(words(('assembly', 'attribute', 'component', 'composition', 'configuration', 'connection', 'connector', 'consumes', 'control', 'dataport', 'Dataport', 'Dataports', 'emits', 'event', 'Event', 'Events', 'export', 'from', 'group', 'hardware', 'has', 'interface', 'Interface', 'maybe', 'procedure', 'Procedure', 'Procedures', 'provides', 'template', 'thread', 'threads', 'to', 'uses', 'with'), suffix=r'\b'), Keyword),
(words(('bool', 'boolean', 'Buf', 'char', 'character', 'double', 'float', 'in', 'inout', 'int', 'int16_6', 'int32_t', 'int64_t', 'int8_t', 'integer', 'mutex', 'out', 'real', 'refin', 'semaphore', 'signed', 'string', 'struct', 'uint16_t', 'uint32_t', 'uint64_t', 'uint8_t', 'uintptr_t', 'unsigned', 'void'), suffix=r'\b'), Keyword.Type),
# Recognised attributes (r'[a-zA-Z_]\w*_(priority|domain|buffer)', Keyword.Reserved), (words(('dma_pool', 'from_access', 'to_access'), suffix=r'\b'), Keyword.Reserved),
# CAmkES-level include (r'(import)(\s+)((?:<[^>]*>|"[^"]*");)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)),
# C-level include (r'(include)(\s+)((?:<[^>]*>|"[^"]*");)', bygroups(Comment.Preproc, Whitespace, Comment.Preproc)),
# Literals (r'0[xX][\da-fA-F]+', Number.Hex), (r'-?[\d]+', Number), (r'-?[\d]+\.[\d]+', Number.Float), (r'"[^"]*"', String), (r'[Tt]rue|[Ff]alse', Name.Builtin),
# Identifiers (r'[a-zA-Z_]\w*', Name), ], }
class CapDLLexer(RegexLexer): """ Basic lexer for CapDL.
The source of the primary tool that reads such specifications is available at https://github.com/seL4/capdl/tree/master/capDL-tool. Note that this lexer only supports a subset of the grammar. For example, identifiers can shadow type names, but these instances are currently incorrectly highlighted as types. Supporting this would need a stateful lexer that is considered unnecessarily complex for now. """ name = 'CapDL' url = 'https://ssrg.nicta.com.au/publications/nictaabstracts/Kuz_KLW_10.abstract.pml' aliases = ['capdl'] filenames = ['*.cdl'] version_added = '2.2'
tokens = { 'root': [ # C pre-processor directive (r'^(\s*)(#.*)(\n)', bygroups(Whitespace, Comment.Preproc, Whitespace)),
# Whitespace, comments (r'\s+', Whitespace), (r'/\*(.|\n)*?\*/', Comment), (r'(//|--).*$', Comment),
(r'[<>\[(){},:;=\]]', Punctuation), (r'\.\.', Punctuation),
(words(('arch', 'arm11', 'caps', 'child_of', 'ia32', 'irq', 'maps', 'objects'), suffix=r'\b'), Keyword),
(words(('aep', 'asid_pool', 'cnode', 'ep', 'frame', 'io_device', 'io_ports', 'io_pt', 'notification', 'pd', 'pt', 'tcb', 'ut', 'vcpu'), suffix=r'\b'), Keyword.Type),
# Properties (words(('asid', 'addr', 'badge', 'cached', 'dom', 'domainID', 'elf', 'fault_ep', 'G', 'guard', 'guard_size', 'init', 'ip', 'prio', 'sp', 'R', 'RG', 'RX', 'RW', 'RWG', 'RWX', 'W', 'WG', 'WX', 'level', 'masked', 'master_reply', 'paddr', 'ports', 'reply', 'uncached'), suffix=r'\b'), Keyword.Reserved),
# Literals (r'0[xX][\da-fA-F]+', Number.Hex), (r'\d+(\.\d+)?(k|M)?', Number), (words(('bits',), suffix=r'\b'), Number), (words(('cspace', 'vspace', 'reply_slot', 'caller_slot', 'ipc_buffer_slot'), suffix=r'\b'), Number),
# Identifiers (r'[a-zA-Z_][-@\.\w]*', Name), ], }
class RedcodeLexer(RegexLexer): """ A simple Redcode lexer based on ICWS'94. Contributed by Adam Blinkinsop <blinks@acm.org>. """ name = 'Redcode' aliases = ['redcode'] filenames = ['*.cw'] url = 'https://en.wikipedia.org/wiki/Core_War' version_added = '0.8'
opcodes = ('DAT', 'MOV', 'ADD', 'SUB', 'MUL', 'DIV', 'MOD', 'JMP', 'JMZ', 'JMN', 'DJN', 'CMP', 'SLT', 'SPL', 'ORG', 'EQU', 'END') modifiers = ('A', 'B', 'AB', 'BA', 'F', 'X', 'I')
tokens = { 'root': [ # Whitespace: (r'\s+', Whitespace), (r';.*$', Comment.Single), # Lexemes: # Identifiers (r'\b({})\b'.format('|'.join(opcodes)), Name.Function), (r'\b({})\b'.format('|'.join(modifiers)), Name.Decorator), (r'[A-Za-z_]\w+', Name), # Operators (r'[-+*/%]', Operator), (r'[#$@<>]', Operator), # mode (r'[.,]', Punctuation), # mode # Numbers (r'[-+]?\d+', Number.Integer), ], }
class AheuiLexer(RegexLexer): """ Aheui is esoteric language based on Korean alphabets. """
name = 'Aheui' url = 'http://aheui.github.io/' aliases = ['aheui'] filenames = ['*.aheui'] version_added = ''
tokens = { 'root': [ ('[' '๋-๋ณ๋-๋ซ๋-๋ฃ๋
-๋
๋
ธ-๋๋จ-๋๋ด-๋' '๋ค-๋ฟ๋-๋ท๋-๋ฏ๋-๋ง๋-๋๋ด-๋ซ๋-๋' '๋ฐ-๋๋จ-๋๋ -๋ป๋-๋ณ๋-๋ซ๋-๋ท๋-๋' '๋ผ-๋๋ด-๋๋ฌ-๋ ๋ ค-๋ ฟ๋ก-๋กท๋ฃ-๋ค๋ฅ-๋ฆซ' '๋ง-๋งฃ๋จ-๋จ๋จธ-๋ฉ๋ฉฐ-๋ช๋ชจ-๋ซ๋ฌ-๋ญ๋ฎค-๋ฏท' '๋ฐ-๋ฐฏ๋ฑ-๋ฑง๋ฒ-๋ฒ๋ฒผ-๋ณ๋ณด-๋ด๋ตค-๋ถ๋ทฐ-๋น' '๋น -๋นป๋บ-๋บณ๋ป-๋ปซ๋ผ-๋ผฃ๋ฝ-๋ฝ๋พฐ-๋ฟง์ผ-์' '์ฌ-์์ค-์ฟ์-์ท์
-์
ฏ์-์ง์ผ-์ณ์-์' '์ธ-์์ฐ-์์จ-์์ -์ป์-์ณ์-์ฟ์-์ง' '์-์ซ์-์ฃ์ -์ ์ ธ-์ก์กฐ-์ข์ฃ -์ค์ฅฌ-์ฆฟ' '์ฐจ-์ฑ์ฑ -์ฑป์ฒ-์ฒณ์ณ-์ณซ์ด-์ดฃ์ตธ-์ถฏ์ธ-์น' '์นด-์บ์บฌ-์ป์ปค-์ปฟ์ผ-์ผท์ฝ-์ฝฏ์ฟ-์ฟปํ-ํฃ' 'ํ-ํํธ-ํํฐ-ํ
ํ
จ-ํํ -ํปํ-ํํ-ํฏ' 'ํ-ํงํ-ํํผ-ํํด-ํํฌ-ํํ-ํํจ-ํป' 'ํ-ํณํ-ํซํ-ํฃํ-ํํธ-ํํจ-ํํด-ํ' ']', Operator), ('.', Comment), ], }.cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet-1.4.3.dist-info/METADATAAdded+87
.cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet-1.4.3.dist-info/RECORDAdded+7
.cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet-1.4.3.dist-info/WHEELAdded+5
.cache/uv/archive-v0/4aVooOhc2U8_C1AX4CShI/hf_xet/__init__.pyAdded+5
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/METADATAAdded+202
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/RECORDAdded+17
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/WHEELAdded+5
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/licenses/LICENSE.txtAdded+22
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11-0.16.0.dist-info/top_level.txtAdded+1
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/__init__.pyAdded+62
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_abnf.pyAdded+132
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_connection.pyAdded+659
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_events.pyAdded+369
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_headers.pyAdded+282
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_readers.pyAdded+250
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_receivebuffer.pyAdded+153
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_state.pyAdded+365
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_util.pyAdded+135
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_version.pyAdded+16
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/_writers.pyAdded+145
.cache/uv/archive-v0/DqpXJYvHeaCihYd8XxyrF/h11/py.typedAdded+1
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/cddl.pyAdded+172
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/chapel.pyAdded+139
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/clean.pyAdded+180
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/codeql.pyAdded+80
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/comal.pyAdded+81
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/compiled.pyAdded+35
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/configs.pyAdded+1433
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/console.pyAdded+114
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/cplint.pyAdded+43
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/crystal.pyAdded+364
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/csound.pyAdded+466
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/css.pyAdded+632
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/d.pyAdded+259
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dalvik.pyAdded+126
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/data.pyAdded+763
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dax.pyAdded+135
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/devicetree.pyAdded+120
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/diff.pyAdded+169
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dns.pyAdded+109
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dotnet.pyAdded+873
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dsls.pyAdded+970
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/dylan.pyAdded+279
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/ecl.pyAdded+144
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/eiffel.pyAdded+68
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/elm.pyAdded+123
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/elpi.pyAdded+201
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/email.pyAdded+132
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/erlang.pyAdded+526
.cache/uv/archive-v0/RMeM3AGJKqUJ7n75un4yi/pygments/lexers/esoteric.pyAdded+300