parse-rtf 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- parse_rtf-0.1.0/LICENSE +21 -0
- parse_rtf-0.1.0/PKG-INFO +50 -0
- parse_rtf-0.1.0/README.md +35 -0
- parse_rtf-0.1.0/docs/releasing.md +37 -0
- parse_rtf-0.1.0/docs/security.md +18 -0
- parse_rtf-0.1.0/docs/supported-syntax.md +32 -0
- parse_rtf-0.1.0/pyproject.toml +46 -0
- parse_rtf-0.1.0/pyproject.toml.orig +34 -0
- parse_rtf-0.1.0/scripts/check_distribution.py +112 -0
- parse_rtf-0.1.0/src/parse_rtf/__init__.py +33 -0
- parse_rtf-0.1.0/src/parse_rtf/parser.py +669 -0
- parse_rtf-0.1.0/src/parse_rtf/py.typed +0 -0
- parse_rtf-0.1.0/tests/fixtures/basic.rtf +1 -0
- parse_rtf-0.1.0/tests/fixtures/codepage.rtf +1 -0
- parse_rtf-0.1.0/tests/test_parser.py +199 -0
parse_rtf-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wispsy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
parse_rtf-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parse-rtf
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Bounded, source-aware Rich Text Format parsing for Python
|
|
5
|
+
Author: wispsy
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.14
|
|
12
|
+
Project-URL: Repository, https://github.com/wispsy/parse-rtf
|
|
13
|
+
Project-URL: Issues, https://github.com/wispsy/parse-rtf/issues
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# parse-rtf
|
|
17
|
+
|
|
18
|
+
`parse-rtf` is a bounded, source-aware Rich Text Format (RTF 1) parser for
|
|
19
|
+
Python 3.14+. It has no runtime dependencies.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from parse_rtf import loads
|
|
23
|
+
|
|
24
|
+
document = loads(r"{\rtf1\ansi Hello, {\b world}!\par}")
|
|
25
|
+
print(document.text) # Hello, world!\n
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`Document.source` preserves the exact input. `Document.root` is an immutable
|
|
29
|
+
syntax tree of groups, literal text, control words and symbols, hexadecimal
|
|
30
|
+
bytes, and opaque binary data. Every node has a `SourceSpan` with source offsets
|
|
31
|
+
and one-based line/column positions. `Document.text` provides a safe plain-text
|
|
32
|
+
projection; non-text destinations and formatting controls remain available in
|
|
33
|
+
the syntax tree. Non-fatal limitations are reported in `Document.diagnostics`.
|
|
34
|
+
|
|
35
|
+
The parser enforces configurable input-size, nesting, and node limits. See
|
|
36
|
+
[supported syntax and API](docs/supported-syntax.md) and
|
|
37
|
+
[security boundaries](docs/security.md).
|
|
38
|
+
|
|
39
|
+
## Development
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
uv sync --locked
|
|
43
|
+
uv run --frozen python -W error::ResourceWarning -m pytest -q
|
|
44
|
+
uv run --frozen python scripts/check_distribution.py --output-dir dist
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The distribution is named `parse-rtf`; the Python import package is
|
|
48
|
+
`parse_rtf`.
|
|
49
|
+
|
|
50
|
+
See [release instructions](docs/releasing.md) for trusted PyPI publishing setup.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# parse-rtf
|
|
2
|
+
|
|
3
|
+
`parse-rtf` is a bounded, source-aware Rich Text Format (RTF 1) parser for
|
|
4
|
+
Python 3.14+. It has no runtime dependencies.
|
|
5
|
+
|
|
6
|
+
```python
|
|
7
|
+
from parse_rtf import loads
|
|
8
|
+
|
|
9
|
+
document = loads(r"{\rtf1\ansi Hello, {\b world}!\par}")
|
|
10
|
+
print(document.text) # Hello, world!\n
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`Document.source` preserves the exact input. `Document.root` is an immutable
|
|
14
|
+
syntax tree of groups, literal text, control words and symbols, hexadecimal
|
|
15
|
+
bytes, and opaque binary data. Every node has a `SourceSpan` with source offsets
|
|
16
|
+
and one-based line/column positions. `Document.text` provides a safe plain-text
|
|
17
|
+
projection; non-text destinations and formatting controls remain available in
|
|
18
|
+
the syntax tree. Non-fatal limitations are reported in `Document.diagnostics`.
|
|
19
|
+
|
|
20
|
+
The parser enforces configurable input-size, nesting, and node limits. See
|
|
21
|
+
[supported syntax and API](docs/supported-syntax.md) and
|
|
22
|
+
[security boundaries](docs/security.md).
|
|
23
|
+
|
|
24
|
+
## Development
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
uv sync --locked
|
|
28
|
+
uv run --frozen python -W error::ResourceWarning -m pytest -q
|
|
29
|
+
uv run --frozen python scripts/check_distribution.py --output-dir dist
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
The distribution is named `parse-rtf`; the Python import package is
|
|
33
|
+
`parse_rtf`.
|
|
34
|
+
|
|
35
|
+
See [release instructions](docs/releasing.md) for trusted PyPI publishing setup.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Releasing
|
|
2
|
+
|
|
3
|
+
Releases are published to PyPI from tags matching the package version (for
|
|
4
|
+
example, `v0.1.0`). The release workflow checks that the tag matches
|
|
5
|
+
`pyproject.toml` and that its commit is already an ancestor of `main`. It builds
|
|
6
|
+
and verifies the source distribution and wheel before publishing them with
|
|
7
|
+
PyPI Trusted Publishing; no long-lived PyPI token is used.
|
|
8
|
+
|
|
9
|
+
## One-time setup
|
|
10
|
+
|
|
11
|
+
1. In the GitHub repository settings, create an environment named `pypi`.
|
|
12
|
+
No environment secrets are required.
|
|
13
|
+
2. If the `parse-rtf` project does not exist on PyPI yet, sign in to the
|
|
14
|
+
`wispsy` PyPI account and add a pending publisher at
|
|
15
|
+
<https://pypi.org/manage/account/publishing/>. Set the owner to `wispsy`,
|
|
16
|
+
repository to `parse-rtf`, workflow filename to `release.yaml`, and
|
|
17
|
+
environment to `pypi`. If the project already exists, configure the same
|
|
18
|
+
trusted publisher in the project's publishing settings instead.
|
|
19
|
+
|
|
20
|
+
The pending publisher must be configured before the first release tag is
|
|
21
|
+
pushed. Otherwise, PyPI cannot authorize the workflow to create the initial
|
|
22
|
+
project.
|
|
23
|
+
|
|
24
|
+
## Publishing
|
|
25
|
+
|
|
26
|
+
After the release commit is merged to `main` and the trusted publisher is
|
|
27
|
+
configured, create and push the matching version tag:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
git tag v0.1.0
|
|
31
|
+
git push origin v0.1.0
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The tag-triggered workflow blocks publication unless release checks pass. The
|
|
35
|
+
checks reject a tag that differs from the package version or points to a commit
|
|
36
|
+
not contained in `main`; the publish job receives only the verified build
|
|
37
|
+
artifacts.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Security boundaries
|
|
2
|
+
|
|
3
|
+
RTF is a complex container format and may contain active or externally
|
|
4
|
+
referenced content. `parse-rtf` only tokenizes the input and projects ordinary
|
|
5
|
+
text. It does not instantiate embedded objects, execute macros or fields,
|
|
6
|
+
resolve links, read files, contact network resources, or render images.
|
|
7
|
+
|
|
8
|
+
Known non-text destinations such as `\object`, `\pict`, and `\fldinst` remain
|
|
9
|
+
inert in the syntax tree and are omitted from `Document.text`. Unknown starred
|
|
10
|
+
destinations are likewise omitted and surfaced as diagnostics. A field result
|
|
11
|
+
group (`\fldrslt`) can be included as ordinary text, but its instruction is
|
|
12
|
+
never executed.
|
|
13
|
+
|
|
14
|
+
The parser applies configurable maximum input, nesting, and node counts to
|
|
15
|
+
bound resource use. Applications should still treat parsed text and
|
|
16
|
+
diagnostics as untrusted input, apply their own output-encoding rules, and
|
|
17
|
+
choose limits suitable for their workload. This package is not a document
|
|
18
|
+
renderer or a malware scanner.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Supported syntax and API
|
|
2
|
+
|
|
3
|
+
`parse_rtf.loads(source, *, limits=None)` parses a Python `str` containing one
|
|
4
|
+
RTF 1 root group and returns an immutable `Document`. `parse` is an alias.
|
|
5
|
+
Malformed syntax, an unsupported RTF version, or a resource-limit breach raises
|
|
6
|
+
`ParseError`, which exposes a stable `code` and a source `span`.
|
|
7
|
+
|
|
8
|
+
The syntax tree retains nested groups, formatting/control words, control
|
|
9
|
+
symbols, literal source text, `\'hh` byte escapes, and opaque `\binN` payloads.
|
|
10
|
+
The plain-text projection handles escaped braces and backslashes, common
|
|
11
|
+
typographic symbols, `\par`, `\line`, `\tab`, `\uN` with scoped `\ucN`
|
|
12
|
+
fallback skipping, and `\ansicpgN`/`\cpgN` byte decoding. Windows-1252 is the
|
|
13
|
+
default code page. Unicode surrogate pairs are combined; unmatched surrogates
|
|
14
|
+
become U+FFFD.
|
|
15
|
+
|
|
16
|
+
Formatting values are preserved as syntax, not rendered. This package does not
|
|
17
|
+
interpret font tables, color tables, layout, images, or object payloads.
|
|
18
|
+
Known non-text destinations are retained in the tree and omitted from
|
|
19
|
+
`Document.text`; unknown starred destinations are also omitted and reported
|
|
20
|
+
with a diagnostic. Unknown controls are preserved and ignored by text
|
|
21
|
+
projection. If a Python codec is unavailable for a declared code page, the
|
|
22
|
+
projection uses Windows-1252 and reports a diagnostic. Invalid byte sequences
|
|
23
|
+
are replaced and reported.
|
|
24
|
+
|
|
25
|
+
`Limits` defaults to 10,000,000 input characters, 128 nested groups, and
|
|
26
|
+
1,000,000 syntax nodes. Supply a `Limits` instance to tighten or adjust these
|
|
27
|
+
bounds. Limits must be positive integers.
|
|
28
|
+
|
|
29
|
+
The string input representation means `\binN` counts Python string
|
|
30
|
+
characters, not original encoded file bytes. For byte-exact binary processing,
|
|
31
|
+
retain and separately manage the original encoded file; `parse-rtf` treats
|
|
32
|
+
binary payloads as opaque source characters.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "parse-rtf"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Bounded, source-aware Rich Text Format parsing for Python"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = []
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Programming Language :: Python :: 3.14",
|
|
13
|
+
"Typing :: Typed",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[[project.authors]]
|
|
17
|
+
name = "wispsy"
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Repository = "https://github.com/wispsy/parse-rtf"
|
|
21
|
+
Issues = "https://github.com/wispsy/parse-rtf/issues"
|
|
22
|
+
|
|
23
|
+
[dependency-groups]
|
|
24
|
+
dev = ["pytest>=8"]
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
28
|
+
build-backend = "uv_build"
|
|
29
|
+
|
|
30
|
+
[tool.uv.build-backend]
|
|
31
|
+
source-include = [
|
|
32
|
+
"tests/**",
|
|
33
|
+
"docs/**",
|
|
34
|
+
"scripts/**",
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"README.md",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
addopts = [
|
|
41
|
+
"-ra",
|
|
42
|
+
"--strict-config",
|
|
43
|
+
"--strict-markers",
|
|
44
|
+
]
|
|
45
|
+
testpaths = ["tests"]
|
|
46
|
+
filterwarnings = ["error"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "parse-rtf"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Bounded, source-aware Rich Text Format parsing for Python"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "wispsy" }]
|
|
10
|
+
dependencies = []
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Programming Language :: Python :: 3.14",
|
|
14
|
+
"Typing :: Typed",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Repository = "https://github.com/wispsy/parse-rtf"
|
|
19
|
+
Issues = "https://github.com/wispsy/parse-rtf/issues"
|
|
20
|
+
|
|
21
|
+
[dependency-groups]
|
|
22
|
+
dev = ["pytest>=8"]
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
26
|
+
build-backend = "uv_build"
|
|
27
|
+
|
|
28
|
+
[tool.uv.build-backend]
|
|
29
|
+
source-include = ["tests/**", "docs/**", "scripts/**", "LICENSE", "README.md"]
|
|
30
|
+
|
|
31
|
+
[tool.pytest.ini_options]
|
|
32
|
+
addopts = ["-ra", "--strict-config", "--strict-markers"]
|
|
33
|
+
testpaths = ["tests"]
|
|
34
|
+
filterwarnings = ["error"]
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Build and smoke-test the source and wheel distributions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import tarfile
|
|
9
|
+
import tempfile
|
|
10
|
+
import venv
|
|
11
|
+
import zipfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
NAME = "parse-rtf"
|
|
15
|
+
VERSION = "0.1.0"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _metadata_fields(text: str) -> dict[str, str]:
|
|
19
|
+
fields: dict[str, str] = {}
|
|
20
|
+
for line in text.splitlines():
|
|
21
|
+
if line.startswith(("Name:", "Version:", "Requires-Dist:")):
|
|
22
|
+
key, value = line.split(":", 1)
|
|
23
|
+
fields[key] = value.strip()
|
|
24
|
+
return fields
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _verify_metadata(metadata: str, artifact: Path) -> None:
|
|
28
|
+
fields = _metadata_fields(metadata)
|
|
29
|
+
if fields.get("Name") != NAME or fields.get("Version") != VERSION:
|
|
30
|
+
raise SystemExit(f"{artifact.name} has unexpected package metadata: {fields}")
|
|
31
|
+
if "Requires-Dist" in fields:
|
|
32
|
+
raise SystemExit(f"{artifact.name} declares runtime dependencies")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main() -> None:
|
|
36
|
+
argument_parser = argparse.ArgumentParser(description=__doc__)
|
|
37
|
+
argument_parser.add_argument("--tag", default="")
|
|
38
|
+
argument_parser.add_argument("--output-dir", required=True, type=Path)
|
|
39
|
+
args = argument_parser.parse_args()
|
|
40
|
+
if args.tag and args.tag != f"v{VERSION}":
|
|
41
|
+
raise SystemExit(
|
|
42
|
+
f"release tag {args.tag!r} does not match package version v{VERSION}"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
output_dir = args.output_dir.resolve()
|
|
46
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
subprocess.run(["uv", "build", "--out-dir", str(output_dir)], check=True)
|
|
48
|
+
wheels = sorted(output_dir.glob("parse_rtf-*.whl"))
|
|
49
|
+
sdists = sorted(output_dir.glob("parse_rtf-*.tar.gz"))
|
|
50
|
+
if len(wheels) != 1 or len(sdists) != 1:
|
|
51
|
+
raise SystemExit("expected exactly one parse-rtf wheel and source distribution")
|
|
52
|
+
|
|
53
|
+
wheel = wheels[0]
|
|
54
|
+
with zipfile.ZipFile(wheel) as archive:
|
|
55
|
+
members = archive.namelist()
|
|
56
|
+
package_metadata = next(
|
|
57
|
+
(member for member in members if member.endswith(".dist-info/METADATA")),
|
|
58
|
+
None,
|
|
59
|
+
)
|
|
60
|
+
if (
|
|
61
|
+
"parse_rtf/__init__.py" not in members
|
|
62
|
+
or "parse_rtf/py.typed" not in members
|
|
63
|
+
or package_metadata is None
|
|
64
|
+
):
|
|
65
|
+
raise SystemExit(f"{wheel.name} is missing the package or wheel metadata")
|
|
66
|
+
_verify_metadata(archive.read(package_metadata).decode("utf-8"), wheel)
|
|
67
|
+
|
|
68
|
+
sdist = sdists[0]
|
|
69
|
+
with tarfile.open(sdist, "r:gz") as archive:
|
|
70
|
+
members = archive.getnames()
|
|
71
|
+
package_source = next(
|
|
72
|
+
(
|
|
73
|
+
member
|
|
74
|
+
for member in members
|
|
75
|
+
if member.endswith("/src/parse_rtf/__init__.py")
|
|
76
|
+
),
|
|
77
|
+
None,
|
|
78
|
+
)
|
|
79
|
+
package_metadata = next(
|
|
80
|
+
(member for member in members if member.endswith("/PKG-INFO")),
|
|
81
|
+
None,
|
|
82
|
+
)
|
|
83
|
+
if package_source is None or package_metadata is None:
|
|
84
|
+
raise SystemExit(f"{sdist.name} is missing the package or source metadata")
|
|
85
|
+
metadata_file = archive.extractfile(package_metadata)
|
|
86
|
+
if metadata_file is None:
|
|
87
|
+
raise SystemExit(f"{sdist.name} has unreadable source metadata")
|
|
88
|
+
_verify_metadata(metadata_file.read().decode("utf-8"), sdist)
|
|
89
|
+
|
|
90
|
+
with tempfile.TemporaryDirectory(prefix="parse-rtf-install-") as directory:
|
|
91
|
+
environment = Path(directory) / "venv"
|
|
92
|
+
venv.EnvBuilder(with_pip=True).create(environment)
|
|
93
|
+
python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
|
94
|
+
subprocess.run(
|
|
95
|
+
[str(python), "-m", "pip", "install", "--no-index", "--no-deps", str(wheel)],
|
|
96
|
+
check=True,
|
|
97
|
+
)
|
|
98
|
+
subprocess.run(
|
|
99
|
+
[
|
|
100
|
+
str(python),
|
|
101
|
+
"-c",
|
|
102
|
+
"from parse_rtf import loads; "
|
|
103
|
+
"assert loads(r'{\\rtf1 Hello}').text == 'Hello'",
|
|
104
|
+
],
|
|
105
|
+
check=True,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
print(f"Verified {sdist.name} and {wheel.name}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
main()
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""A bounded, source-aware Rich Text Format parser."""
|
|
2
|
+
|
|
3
|
+
from .parser import (
|
|
4
|
+
BinaryData,
|
|
5
|
+
ControlSymbol,
|
|
6
|
+
ControlWord,
|
|
7
|
+
Diagnostic,
|
|
8
|
+
Document,
|
|
9
|
+
Group,
|
|
10
|
+
HexByte,
|
|
11
|
+
Limits,
|
|
12
|
+
ParseError,
|
|
13
|
+
SourceSpan,
|
|
14
|
+
Text,
|
|
15
|
+
loads,
|
|
16
|
+
parse,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"BinaryData",
|
|
21
|
+
"ControlSymbol",
|
|
22
|
+
"ControlWord",
|
|
23
|
+
"Diagnostic",
|
|
24
|
+
"Document",
|
|
25
|
+
"Group",
|
|
26
|
+
"HexByte",
|
|
27
|
+
"Limits",
|
|
28
|
+
"ParseError",
|
|
29
|
+
"SourceSpan",
|
|
30
|
+
"Text",
|
|
31
|
+
"loads",
|
|
32
|
+
"parse",
|
|
33
|
+
]
|
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
"""Parsing and safe text projection for Rich Text Format."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from array import array
|
|
6
|
+
from bisect import bisect_right
|
|
7
|
+
import codecs
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TypeAlias
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class SourceSpan:
|
|
14
|
+
"""A half-open source range with one-based line and column locations."""
|
|
15
|
+
|
|
16
|
+
start: int
|
|
17
|
+
end: int
|
|
18
|
+
start_line: int
|
|
19
|
+
start_column: int
|
|
20
|
+
end_line: int
|
|
21
|
+
end_column: int
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class Text:
|
|
26
|
+
"""Literal source text inside an RTF group."""
|
|
27
|
+
|
|
28
|
+
value: str
|
|
29
|
+
span: SourceSpan
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class ControlWord:
|
|
34
|
+
"""An RTF control word, with its optional signed decimal parameter."""
|
|
35
|
+
|
|
36
|
+
name: str
|
|
37
|
+
parameter: int | None
|
|
38
|
+
span: SourceSpan
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class ControlSymbol:
|
|
43
|
+
"""An RTF control symbol such as ``\\\\``, ``\\{`` or ``\\~``."""
|
|
44
|
+
|
|
45
|
+
symbol: str
|
|
46
|
+
span: SourceSpan
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class HexByte:
|
|
51
|
+
"""A byte encoded using an RTF ``\\'hh`` escape."""
|
|
52
|
+
|
|
53
|
+
value: int
|
|
54
|
+
span: SourceSpan
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class BinaryData:
|
|
59
|
+
"""Opaque data consumed by an RTF ``\\binN`` control word."""
|
|
60
|
+
|
|
61
|
+
value: str
|
|
62
|
+
span: SourceSpan
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
Node: TypeAlias = "Text | ControlWord | ControlSymbol | HexByte | BinaryData | Group"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class Group:
|
|
70
|
+
"""A brace-delimited RTF group whose children retain their source order."""
|
|
71
|
+
|
|
72
|
+
children: tuple[Node, ...]
|
|
73
|
+
span: SourceSpan
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True, slots=True)
|
|
77
|
+
class Diagnostic:
|
|
78
|
+
"""A non-fatal unsupported or malformed-content diagnostic."""
|
|
79
|
+
|
|
80
|
+
code: str
|
|
81
|
+
message: str
|
|
82
|
+
span: SourceSpan
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ParseError(ValueError):
|
|
86
|
+
"""An RTF syntax, version, or resource-limit error."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, code: str, message: str, span: SourceSpan) -> None:
|
|
89
|
+
self.code = code
|
|
90
|
+
self.message = message
|
|
91
|
+
self.span = span
|
|
92
|
+
super().__init__(
|
|
93
|
+
f"{message} at line {span.start_line}, column {span.start_column}"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True, slots=True)
|
|
98
|
+
class Limits:
|
|
99
|
+
"""Resource bounds applied while parsing an RTF source string."""
|
|
100
|
+
|
|
101
|
+
max_input_chars: int = 10_000_000
|
|
102
|
+
max_nesting: int = 128
|
|
103
|
+
max_nodes: int = 1_000_000
|
|
104
|
+
|
|
105
|
+
def __post_init__(self) -> None:
|
|
106
|
+
for name, value in (
|
|
107
|
+
("max_input_chars", self.max_input_chars),
|
|
108
|
+
("max_nesting", self.max_nesting),
|
|
109
|
+
("max_nodes", self.max_nodes),
|
|
110
|
+
):
|
|
111
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
112
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True, slots=True)
|
|
116
|
+
class Document:
|
|
117
|
+
"""A parsed RTF document with its original source, syntax tree, and text.
|
|
118
|
+
|
|
119
|
+
Formatting and control structure remain available in :attr:`root`.
|
|
120
|
+
:attr:`text` is a safe, best-effort plain-text projection. It does not
|
|
121
|
+
evaluate fields, load objects, or fetch external resources.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
source: str
|
|
125
|
+
root: Group
|
|
126
|
+
text: str
|
|
127
|
+
diagnostics: tuple[Diagnostic, ...]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class _Locations:
|
|
131
|
+
def __init__(self, source: str) -> None:
|
|
132
|
+
self.length = len(source)
|
|
133
|
+
self.line_starts = array("Q", [0])
|
|
134
|
+
self.line_starts.extend(
|
|
135
|
+
index + 1 for index, character in enumerate(source) if character == "\n"
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def span(self, start: int, end: int) -> SourceSpan:
|
|
139
|
+
start = min(max(start, 0), self.length)
|
|
140
|
+
end = min(max(end, start), self.length)
|
|
141
|
+
start_line_index = bisect_right(self.line_starts, start) - 1
|
|
142
|
+
end_line_index = bisect_right(self.line_starts, end) - 1
|
|
143
|
+
return SourceSpan(
|
|
144
|
+
start=start,
|
|
145
|
+
end=end,
|
|
146
|
+
start_line=start_line_index + 1,
|
|
147
|
+
start_column=start - self.line_starts[start_line_index] + 1,
|
|
148
|
+
end_line=end_line_index + 1,
|
|
149
|
+
end_column=end - self.line_starts[end_line_index] + 1,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(slots=True)
|
|
154
|
+
class _Frame:
|
|
155
|
+
start: int
|
|
156
|
+
children: list[Node]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
_KNOWN_DESTINATIONS = frozenset(
|
|
160
|
+
{
|
|
161
|
+
"annotation",
|
|
162
|
+
"atnauthor",
|
|
163
|
+
"author",
|
|
164
|
+
"colortbl",
|
|
165
|
+
"comment",
|
|
166
|
+
"doccomm",
|
|
167
|
+
"filetbl",
|
|
168
|
+
"fldinst",
|
|
169
|
+
"fonttbl",
|
|
170
|
+
"objalias",
|
|
171
|
+
"objclass",
|
|
172
|
+
"objdata",
|
|
173
|
+
"objname",
|
|
174
|
+
"footer",
|
|
175
|
+
"footerf",
|
|
176
|
+
"footerl",
|
|
177
|
+
"footerr",
|
|
178
|
+
"footnote",
|
|
179
|
+
"header",
|
|
180
|
+
"headerf",
|
|
181
|
+
"headerl",
|
|
182
|
+
"headerr",
|
|
183
|
+
"info",
|
|
184
|
+
"listoverridetable",
|
|
185
|
+
"listtable",
|
|
186
|
+
"object",
|
|
187
|
+
"pict",
|
|
188
|
+
"revtbl",
|
|
189
|
+
"stylesheet",
|
|
190
|
+
"themedata",
|
|
191
|
+
"xmlattrname",
|
|
192
|
+
"xmlattrvalue",
|
|
193
|
+
"xmlclose",
|
|
194
|
+
"xmlname",
|
|
195
|
+
"xmlopen",
|
|
196
|
+
"xmltext",
|
|
197
|
+
}
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
_TEXT_CONTROLS = {
|
|
201
|
+
"emdash": "\u2014",
|
|
202
|
+
"endash": "\u2013",
|
|
203
|
+
"bullet": "\u2022",
|
|
204
|
+
"lquote": "\u2018",
|
|
205
|
+
"rquote": "\u2019",
|
|
206
|
+
"ldblquote": "\u201c",
|
|
207
|
+
"rdblquote": "\u201d",
|
|
208
|
+
"tab": "\t",
|
|
209
|
+
"line": "\n",
|
|
210
|
+
"par": "\n",
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class _Parser:
|
|
215
|
+
def __init__(self, source: str, limits: Limits) -> None:
|
|
216
|
+
self.source = source
|
|
217
|
+
self.limits = limits
|
|
218
|
+
self.locations = _Locations(source)
|
|
219
|
+
self.node_count = 0
|
|
220
|
+
|
|
221
|
+
def error(
|
|
222
|
+
self, code: str, message: str, start: int, end: int | None = None
|
|
223
|
+
) -> ParseError:
|
|
224
|
+
return ParseError(
|
|
225
|
+
code,
|
|
226
|
+
message,
|
|
227
|
+
self.locations.span(
|
|
228
|
+
start, min(len(self.source), start + 1 if end is None else end)
|
|
229
|
+
),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def add(self, children: list[Node], node: Node) -> None:
|
|
233
|
+
self.node_count += 1
|
|
234
|
+
if self.node_count > self.limits.max_nodes:
|
|
235
|
+
raise self.error(
|
|
236
|
+
"node-limit-exceeded",
|
|
237
|
+
f"RTF exceeds the {self.limits.max_nodes}-node limit",
|
|
238
|
+
node.span.start,
|
|
239
|
+
node.span.end,
|
|
240
|
+
)
|
|
241
|
+
children.append(node)
|
|
242
|
+
|
|
243
|
+
def parse_tree(self) -> Group:
|
|
244
|
+
if len(self.source) > self.limits.max_input_chars:
|
|
245
|
+
raise self.error(
|
|
246
|
+
"input-limit-exceeded",
|
|
247
|
+
f"RTF exceeds the {self.limits.max_input_chars}-character limit",
|
|
248
|
+
0,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
frames: list[_Frame] = []
|
|
252
|
+
roots: list[Group] = []
|
|
253
|
+
index = 0
|
|
254
|
+
while index < len(self.source):
|
|
255
|
+
character = self.source[index]
|
|
256
|
+
if character == "{":
|
|
257
|
+
if len(frames) >= self.limits.max_nesting:
|
|
258
|
+
raise self.error(
|
|
259
|
+
"nesting-limit-exceeded",
|
|
260
|
+
f"RTF exceeds the {self.limits.max_nesting}-group nesting limit",
|
|
261
|
+
index,
|
|
262
|
+
)
|
|
263
|
+
self.node_count += 1
|
|
264
|
+
if self.node_count > self.limits.max_nodes:
|
|
265
|
+
raise self.error(
|
|
266
|
+
"node-limit-exceeded",
|
|
267
|
+
f"RTF exceeds the {self.limits.max_nodes}-node limit",
|
|
268
|
+
index,
|
|
269
|
+
)
|
|
270
|
+
frames.append(_Frame(index, []))
|
|
271
|
+
index += 1
|
|
272
|
+
continue
|
|
273
|
+
|
|
274
|
+
if character == "}":
|
|
275
|
+
if not frames:
|
|
276
|
+
raise self.error("unexpected-close", "Unexpected closing brace", index)
|
|
277
|
+
frame = frames.pop()
|
|
278
|
+
group = Group(
|
|
279
|
+
tuple(frame.children), self.locations.span(frame.start, index + 1)
|
|
280
|
+
)
|
|
281
|
+
if frames:
|
|
282
|
+
frames[-1].children.append(group)
|
|
283
|
+
else:
|
|
284
|
+
roots.append(group)
|
|
285
|
+
index += 1
|
|
286
|
+
continue
|
|
287
|
+
|
|
288
|
+
if not frames:
|
|
289
|
+
if character in " \t\r\n":
|
|
290
|
+
index += 1
|
|
291
|
+
continue
|
|
292
|
+
raise self.error(
|
|
293
|
+
"content-outside-group", "Content outside the RTF group", index
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
if character != "\\":
|
|
297
|
+
end = index + 1
|
|
298
|
+
while end < len(self.source) and self.source[end] not in "{}\\":
|
|
299
|
+
end += 1
|
|
300
|
+
self.add(
|
|
301
|
+
frames[-1].children,
|
|
302
|
+
Text(self.source[index:end], self.locations.span(index, end)),
|
|
303
|
+
)
|
|
304
|
+
index = end
|
|
305
|
+
continue
|
|
306
|
+
|
|
307
|
+
token_start = index
|
|
308
|
+
index += 1
|
|
309
|
+
if index >= len(self.source):
|
|
310
|
+
raise self.error("trailing-escape", "Trailing backslash in RTF", token_start)
|
|
311
|
+
|
|
312
|
+
if self.source[index] == "'":
|
|
313
|
+
if index + 2 >= len(self.source):
|
|
314
|
+
raise self.error(
|
|
315
|
+
"invalid-hex-escape", "Incomplete hexadecimal byte escape", token_start
|
|
316
|
+
)
|
|
317
|
+
digits = self.source[index + 1 : index + 3]
|
|
318
|
+
if any(character not in "0123456789abcdefABCDEF" for character in digits):
|
|
319
|
+
raise self.error(
|
|
320
|
+
"invalid-hex-escape",
|
|
321
|
+
f"Invalid hexadecimal byte escape {digits!r}",
|
|
322
|
+
token_start,
|
|
323
|
+
index + 3,
|
|
324
|
+
)
|
|
325
|
+
value = int(digits, 16)
|
|
326
|
+
end = index + 3
|
|
327
|
+
self.add(
|
|
328
|
+
frames[-1].children,
|
|
329
|
+
HexByte(value, self.locations.span(token_start, end)),
|
|
330
|
+
)
|
|
331
|
+
index = end
|
|
332
|
+
continue
|
|
333
|
+
|
|
334
|
+
if self.source[index].isascii() and self.source[index].isalpha():
|
|
335
|
+
name_start = index
|
|
336
|
+
while (
|
|
337
|
+
index < len(self.source)
|
|
338
|
+
and self.source[index].isascii()
|
|
339
|
+
and self.source[index].isalpha()
|
|
340
|
+
):
|
|
341
|
+
index += 1
|
|
342
|
+
name = self.source[name_start:index]
|
|
343
|
+
sign_start = index
|
|
344
|
+
if index < len(self.source) and self.source[index] == "-":
|
|
345
|
+
if (
|
|
346
|
+
index + 1 < len(self.source)
|
|
347
|
+
and self.source[index + 1].isascii()
|
|
348
|
+
and self.source[index + 1].isdigit()
|
|
349
|
+
):
|
|
350
|
+
index += 1
|
|
351
|
+
digit_start = index
|
|
352
|
+
while (
|
|
353
|
+
index < len(self.source)
|
|
354
|
+
and self.source[index].isascii()
|
|
355
|
+
and self.source[index].isdigit()
|
|
356
|
+
):
|
|
357
|
+
index += 1
|
|
358
|
+
digits = self.source[digit_start:index]
|
|
359
|
+
parameter: int | None = None
|
|
360
|
+
if digits:
|
|
361
|
+
if len(digits) > 10:
|
|
362
|
+
raise self.error(
|
|
363
|
+
"invalid-parameter",
|
|
364
|
+
"Control-word parameter exceeds the supported integer range",
|
|
365
|
+
token_start,
|
|
366
|
+
index,
|
|
367
|
+
)
|
|
368
|
+
try:
|
|
369
|
+
parameter = int(self.source[sign_start:index], 10)
|
|
370
|
+
except ValueError as error:
|
|
371
|
+
raise self.error(
|
|
372
|
+
"invalid-parameter",
|
|
373
|
+
"Invalid control-word parameter",
|
|
374
|
+
token_start,
|
|
375
|
+
index,
|
|
376
|
+
) from error
|
|
377
|
+
|
|
378
|
+
if index < len(self.source) and self.source[index] == " ":
|
|
379
|
+
index += 1
|
|
380
|
+
control = ControlWord(
|
|
381
|
+
name, parameter, self.locations.span(token_start, index)
|
|
382
|
+
)
|
|
383
|
+
self.add(frames[-1].children, control)
|
|
384
|
+
|
|
385
|
+
if name.lower() == "bin":
|
|
386
|
+
if parameter is None or parameter < 0:
|
|
387
|
+
raise self.error(
|
|
388
|
+
"invalid-binary-length",
|
|
389
|
+
"\\bin requires a non-negative length",
|
|
390
|
+
token_start,
|
|
391
|
+
index,
|
|
392
|
+
)
|
|
393
|
+
binary_end = index + parameter
|
|
394
|
+
if binary_end > len(self.source):
|
|
395
|
+
raise self.error(
|
|
396
|
+
"truncated-binary-data",
|
|
397
|
+
"\\bin length extends beyond the end of the source",
|
|
398
|
+
token_start,
|
|
399
|
+
len(self.source),
|
|
400
|
+
)
|
|
401
|
+
if parameter:
|
|
402
|
+
self.add(
|
|
403
|
+
frames[-1].children,
|
|
404
|
+
BinaryData(
|
|
405
|
+
self.source[index:binary_end],
|
|
406
|
+
self.locations.span(index, binary_end),
|
|
407
|
+
),
|
|
408
|
+
)
|
|
409
|
+
index = binary_end
|
|
410
|
+
continue
|
|
411
|
+
|
|
412
|
+
symbol = self.source[index]
|
|
413
|
+
index += 1
|
|
414
|
+
self.add(
|
|
415
|
+
frames[-1].children,
|
|
416
|
+
ControlSymbol(symbol, self.locations.span(token_start, index)),
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if frames:
|
|
420
|
+
frame = frames[-1]
|
|
421
|
+
raise self.error("unclosed-group", "Unclosed RTF group", frame.start)
|
|
422
|
+
if len(roots) != 1:
|
|
423
|
+
raise self.error("invalid-root", "RTF must contain exactly one root group", 0)
|
|
424
|
+
root = roots[0]
|
|
425
|
+
first = next(
|
|
426
|
+
(node for node in root.children if not isinstance(node, Text) or node.value.strip()),
|
|
427
|
+
None,
|
|
428
|
+
)
|
|
429
|
+
if not isinstance(first, ControlWord) or first.name.lower() != "rtf":
|
|
430
|
+
raise self.error(
|
|
431
|
+
"missing-rtf-header",
|
|
432
|
+
"Root group must begin with an RTF header",
|
|
433
|
+
root.span.start,
|
|
434
|
+
)
|
|
435
|
+
if first.parameter != 1:
|
|
436
|
+
raise self.error(
|
|
437
|
+
"unsupported-version",
|
|
438
|
+
f"Unsupported RTF version {first.parameter!r}; only RTF 1 is supported",
|
|
439
|
+
first.span.start,
|
|
440
|
+
first.span.end,
|
|
441
|
+
)
|
|
442
|
+
return root
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@dataclass(slots=True)
|
|
446
|
+
class _TextState:
|
|
447
|
+
codepage: int = 1252
|
|
448
|
+
unicode_fallback: int = 1
|
|
449
|
+
fallback_to_skip: int = 0
|
|
450
|
+
|
|
451
|
+
def copy(self) -> _TextState:
|
|
452
|
+
return _TextState(self.codepage, self.unicode_fallback, self.fallback_to_skip)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
class _TextProjector:
|
|
456
|
+
def __init__(self) -> None:
|
|
457
|
+
self.output: list[str] = []
|
|
458
|
+
self.diagnostics: list[Diagnostic] = []
|
|
459
|
+
self.reported_codepages: set[int] = set()
|
|
460
|
+
|
|
461
|
+
def diagnose(self, code: str, message: str, span: SourceSpan) -> None:
|
|
462
|
+
self.diagnostics.append(Diagnostic(code, message, span))
|
|
463
|
+
|
|
464
|
+
def emit(self, value: str, state: _TextState) -> None:
|
|
465
|
+
if not value:
|
|
466
|
+
return
|
|
467
|
+
if state.fallback_to_skip:
|
|
468
|
+
skipped = min(state.fallback_to_skip, len(value))
|
|
469
|
+
state.fallback_to_skip -= skipped
|
|
470
|
+
value = value[skipped:]
|
|
471
|
+
if value:
|
|
472
|
+
self.output.append(value)
|
|
473
|
+
|
|
474
|
+
def codec(self, codepage: int, span: SourceSpan) -> str:
|
|
475
|
+
codec = "utf-8" if codepage == 65001 else f"cp{codepage}"
|
|
476
|
+
try:
|
|
477
|
+
return codecs.lookup(codec).name
|
|
478
|
+
except LookupError:
|
|
479
|
+
if codepage not in self.reported_codepages:
|
|
480
|
+
self.reported_codepages.add(codepage)
|
|
481
|
+
self.diagnose(
|
|
482
|
+
"unsupported-codepage",
|
|
483
|
+
f"Python does not provide a codec for RTF code page {codepage}; "
|
|
484
|
+
"Windows-1252 is used for text projection",
|
|
485
|
+
span,
|
|
486
|
+
)
|
|
487
|
+
return "cp1252"
|
|
488
|
+
|
|
489
|
+
def decode_hex(self, nodes: list[HexByte], state: _TextState) -> None:
|
|
490
|
+
if not nodes:
|
|
491
|
+
return
|
|
492
|
+
codec = self.codec(state.codepage, nodes[0].span)
|
|
493
|
+
data = bytes(node.value for node in nodes)
|
|
494
|
+
try:
|
|
495
|
+
decoded = data.decode(codec)
|
|
496
|
+
except UnicodeDecodeError:
|
|
497
|
+
decoded = data.decode(codec, errors="replace")
|
|
498
|
+
self.diagnose(
|
|
499
|
+
"invalid-encoded-text",
|
|
500
|
+
f"Hexadecimal bytes are not valid {codec} text; "
|
|
501
|
+
"replacement characters were inserted",
|
|
502
|
+
self._cover(nodes[0].span, nodes[-1].span),
|
|
503
|
+
)
|
|
504
|
+
self.emit(decoded, state)
|
|
505
|
+
|
|
506
|
+
@staticmethod
|
|
507
|
+
def _cover(first: SourceSpan, last: SourceSpan) -> SourceSpan:
|
|
508
|
+
return SourceSpan(
|
|
509
|
+
first.start,
|
|
510
|
+
last.end,
|
|
511
|
+
first.start_line,
|
|
512
|
+
first.start_column,
|
|
513
|
+
last.end_line,
|
|
514
|
+
last.end_column,
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
@staticmethod
|
|
518
|
+
def _first_content(children: tuple[Node, ...]) -> tuple[int, Node] | None:
|
|
519
|
+
for index, node in enumerate(children):
|
|
520
|
+
if isinstance(node, Text) and not node.value.strip():
|
|
521
|
+
continue
|
|
522
|
+
return index, node
|
|
523
|
+
return None
|
|
524
|
+
|
|
525
|
+
def project_group(self, group: Group, inherited: _TextState) -> None:
|
|
526
|
+
state = inherited.copy()
|
|
527
|
+
first = self._first_content(group.children)
|
|
528
|
+
skip_through = -1
|
|
529
|
+
|
|
530
|
+
if first is not None:
|
|
531
|
+
index, node = first
|
|
532
|
+
destination: str | None = None
|
|
533
|
+
destination_node: Node = node
|
|
534
|
+
if isinstance(node, ControlWord) and node.name.lower() in _KNOWN_DESTINATIONS:
|
|
535
|
+
destination = node.name.lower()
|
|
536
|
+
elif isinstance(node, ControlSymbol) and node.symbol == "*":
|
|
537
|
+
next_content = self._first_content(group.children[index + 1 :])
|
|
538
|
+
if next_content is not None:
|
|
539
|
+
next_index, next_node = next_content
|
|
540
|
+
if isinstance(next_node, ControlWord):
|
|
541
|
+
destination = next_node.name.lower()
|
|
542
|
+
destination_node = next_node
|
|
543
|
+
skip_through = index + 1 + next_index
|
|
544
|
+
if destination is not None:
|
|
545
|
+
if destination in _KNOWN_DESTINATIONS:
|
|
546
|
+
self.diagnose(
|
|
547
|
+
"destination-skipped",
|
|
548
|
+
f"RTF {destination!r} destination is retained in the syntax tree "
|
|
549
|
+
"but omitted from plain text",
|
|
550
|
+
destination_node.span,
|
|
551
|
+
)
|
|
552
|
+
return
|
|
553
|
+
self.diagnose(
|
|
554
|
+
"unsupported-destination",
|
|
555
|
+
f"Unknown starred destination {destination!r} is omitted from plain text",
|
|
556
|
+
destination_node.span,
|
|
557
|
+
)
|
|
558
|
+
return
|
|
559
|
+
|
|
560
|
+
pending_hex: list[HexByte] = []
|
|
561
|
+
|
|
562
|
+
def flush_hex() -> None:
|
|
563
|
+
if pending_hex:
|
|
564
|
+
self.decode_hex(pending_hex, state)
|
|
565
|
+
pending_hex.clear()
|
|
566
|
+
|
|
567
|
+
for index, node in enumerate(group.children):
|
|
568
|
+
if index <= skip_through:
|
|
569
|
+
continue
|
|
570
|
+
if isinstance(node, Group):
|
|
571
|
+
flush_hex()
|
|
572
|
+
self.project_group(node, state)
|
|
573
|
+
continue
|
|
574
|
+
if isinstance(node, HexByte):
|
|
575
|
+
pending_hex.append(node)
|
|
576
|
+
continue
|
|
577
|
+
|
|
578
|
+
flush_hex()
|
|
579
|
+
if isinstance(node, Text):
|
|
580
|
+
self.emit(node.value.replace("\r", "").replace("\n", ""), state)
|
|
581
|
+
elif isinstance(node, BinaryData):
|
|
582
|
+
continue
|
|
583
|
+
elif isinstance(node, ControlSymbol):
|
|
584
|
+
value = {
|
|
585
|
+
"\\": "\\",
|
|
586
|
+
"{": "{",
|
|
587
|
+
"}": "}",
|
|
588
|
+
"~": "\u00a0",
|
|
589
|
+
"_": "\u2011",
|
|
590
|
+
"-": "\u00ad",
|
|
591
|
+
}.get(node.symbol, "")
|
|
592
|
+
self.emit(value, state)
|
|
593
|
+
elif isinstance(node, ControlWord):
|
|
594
|
+
name = node.name.lower()
|
|
595
|
+
if name == "uc":
|
|
596
|
+
if node.parameter is None or node.parameter < 0:
|
|
597
|
+
raise ParseError(
|
|
598
|
+
"invalid-unicode-fallback",
|
|
599
|
+
"\\uc requires a non-negative value",
|
|
600
|
+
node.span,
|
|
601
|
+
)
|
|
602
|
+
state.unicode_fallback = node.parameter
|
|
603
|
+
elif name == "u":
|
|
604
|
+
if node.parameter is None or not -32768 <= node.parameter <= 32767:
|
|
605
|
+
raise ParseError(
|
|
606
|
+
"invalid-unicode-escape",
|
|
607
|
+
"\\u requires a signed 16-bit value",
|
|
608
|
+
node.span,
|
|
609
|
+
)
|
|
610
|
+
self.emit(chr(node.parameter & 0xFFFF), state)
|
|
611
|
+
state.fallback_to_skip = state.unicode_fallback
|
|
612
|
+
elif name in {"ansicpg", "cpg"}:
|
|
613
|
+
if node.parameter is None or node.parameter < 1:
|
|
614
|
+
raise ParseError(
|
|
615
|
+
"invalid-codepage",
|
|
616
|
+
f"\\{name} requires a positive code page",
|
|
617
|
+
node.span,
|
|
618
|
+
)
|
|
619
|
+
state.codepage = node.parameter
|
|
620
|
+
self.codec(state.codepage, node.span)
|
|
621
|
+
elif name in {"par", "line", "tab", "emdash", "endash", "bullet",
|
|
622
|
+
"lquote", "rquote", "ldblquote", "rdblquote"}:
|
|
623
|
+
self.emit(_TEXT_CONTROLS[name], state)
|
|
624
|
+
|
|
625
|
+
flush_hex()
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def loads(source: str, *, limits: Limits | None = None) -> Document:
|
|
629
|
+
"""Parse an RTF 1 source string into a source-aware :class:`Document`.
|
|
630
|
+
|
|
631
|
+
The input is a Python string. Hexadecimal byte escapes are decoded using
|
|
632
|
+
the active ``\\ansicpgN`` value (Windows-1252 by default). Malformed
|
|
633
|
+
syntax and exceeded resource limits raise :class:`ParseError`.
|
|
634
|
+
"""
|
|
635
|
+
|
|
636
|
+
if not isinstance(source, str):
|
|
637
|
+
raise TypeError("RTF source must be a str")
|
|
638
|
+
parser = _Parser(source, limits or Limits())
|
|
639
|
+
root = parser.parse_tree()
|
|
640
|
+
projector = _TextProjector()
|
|
641
|
+
projector.project_group(root, _TextState())
|
|
642
|
+
return Document(
|
|
643
|
+
source,
|
|
644
|
+
root,
|
|
645
|
+
_join_surrogates("".join(projector.output)),
|
|
646
|
+
tuple(projector.diagnostics),
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def parse(source: str, *, limits: Limits | None = None) -> Document:
|
|
651
|
+
"""Alias for :func:`loads`."""
|
|
652
|
+
|
|
653
|
+
return loads(source, limits=limits)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _join_surrogates(value: str) -> str:
|
|
657
|
+
result: list[str] = []
|
|
658
|
+
index = 0
|
|
659
|
+
while index < len(value):
|
|
660
|
+
codepoint = ord(value[index])
|
|
661
|
+
if 0xD800 <= codepoint <= 0xDBFF and index + 1 < len(value):
|
|
662
|
+
low = ord(value[index + 1])
|
|
663
|
+
if 0xDC00 <= low <= 0xDFFF:
|
|
664
|
+
result.append(chr(0x10000 + ((codepoint - 0xD800) << 10) + low - 0xDC00))
|
|
665
|
+
index += 2
|
|
666
|
+
continue
|
|
667
|
+
result.append("\ufffd" if 0xD800 <= codepoint <= 0xDFFF else value[index])
|
|
668
|
+
index += 1
|
|
669
|
+
return "".join(result)
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{\rtf1\ansi Hello, {\b world}!\par Second line.}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{\rtf1\ansi\ansicpg1252 Caf\'e9}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from parse_rtf import (
|
|
8
|
+
BinaryData,
|
|
9
|
+
ControlWord,
|
|
10
|
+
Group,
|
|
11
|
+
HexByte,
|
|
12
|
+
Limits,
|
|
13
|
+
ParseError,
|
|
14
|
+
loads,
|
|
15
|
+
parse,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
FIXTURES = Path(__file__).parent / "fixtures"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_loads_preserves_source_structure_and_locations() -> None:
|
|
22
|
+
source = (FIXTURES / "basic.rtf").read_text(encoding="ascii")
|
|
23
|
+
|
|
24
|
+
document = loads(source)
|
|
25
|
+
|
|
26
|
+
assert document.source == source
|
|
27
|
+
assert document.root.span.start == 0
|
|
28
|
+
assert source[document.root.span.start : document.root.span.end].endswith("}")
|
|
29
|
+
assert document.root.span.end < len(source)
|
|
30
|
+
assert document.root.span.start_line == 1
|
|
31
|
+
assert any(
|
|
32
|
+
isinstance(child, ControlWord) and child.name == "b"
|
|
33
|
+
for node in document.root.children
|
|
34
|
+
if isinstance(node, Group)
|
|
35
|
+
for child in node.children
|
|
36
|
+
)
|
|
37
|
+
assert document.text == "Hello, world!\nSecond line."
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_parse_is_an_alias_for_loads() -> None:
|
|
41
|
+
assert parse(r"{\rtf1 text}").text == "text"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_escaped_characters_and_hex_bytes_use_declared_codepage() -> None:
|
|
45
|
+
document = loads(r"{\rtf1\ansi\ansicpg1252 Caf\'e9 \{safe\}\\}")
|
|
46
|
+
|
|
47
|
+
assert document.text == "Café {safe}\\"
|
|
48
|
+
assert any(isinstance(node, HexByte) for node in document.root.children)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_codepage_fixture() -> None:
|
|
52
|
+
source = (FIXTURES / "codepage.rtf").read_text(encoding="ascii")
|
|
53
|
+
|
|
54
|
+
assert loads(source).text == "Café"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_unicode_fallback_and_surrogate_pairs() -> None:
|
|
58
|
+
document = loads(r"{\rtf1\uc1 A \u233? \u-10179?\u-8704?}")
|
|
59
|
+
|
|
60
|
+
assert document.text == "A é 😀"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_unicode_fallback_setting_is_group_scoped() -> None:
|
|
64
|
+
document = loads(r"{\rtf1\uc1 A{\uc0\u233}?\u233?}")
|
|
65
|
+
|
|
66
|
+
assert document.text == "Aé?é"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_unicode_fallback_counts_multibyte_codepage_characters() -> None:
|
|
70
|
+
document = loads(r"{\rtf1\ansi\ansicpg932\uc1\u12354\'82\'a0Z}")
|
|
71
|
+
|
|
72
|
+
assert document.text == "あZ"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_control_words_create_common_text_structure() -> None:
|
|
76
|
+
assert loads(r"{\rtf1 first\par second\line third\tab end}").text == (
|
|
77
|
+
"first\nsecond\nthird\tend"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_unknown_controls_are_ignored_by_text_projection() -> None:
|
|
82
|
+
assert loads(r"{\rtf1 left\vendorword123 middle\? right}").text == (
|
|
83
|
+
"left middle right"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_non_text_destinations_and_fields_are_never_evaluated() -> None:
|
|
88
|
+
document = loads(
|
|
89
|
+
r"{\rtf1 before {\field{\*\fldinst INCLUDETEXT dangerous.txt}"
|
|
90
|
+
r"{\fldrslt visible}} {\pict\pngblip external bytes} after}"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
assert document.text == "before visible after"
|
|
94
|
+
assert {item.code for item in document.diagnostics} == {"destination-skipped"}
|
|
95
|
+
assert "dangerous.txt" not in document.text
|
|
96
|
+
assert "external bytes" not in document.text
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_unknown_starred_destination_is_skipped_with_diagnostic() -> None:
|
|
100
|
+
document = loads(r"{\rtf1 keep {\*\vendorcontrol do-not-show} visible}")
|
|
101
|
+
|
|
102
|
+
assert document.text == "keep visible"
|
|
103
|
+
assert [item.code for item in document.diagnostics] == ["unsupported-destination"]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_binary_data_is_opaque_and_braces_do_not_change_grouping() -> None:
|
|
107
|
+
document = loads(r"{\rtf1 A\bin3 {}}B}")
|
|
108
|
+
|
|
109
|
+
assert document.text == "AB"
|
|
110
|
+
assert any(
|
|
111
|
+
isinstance(node, BinaryData) and node.value == "{}}"
|
|
112
|
+
for node in document.root.children
|
|
113
|
+
)
|
|
114
|
+
assert not any(isinstance(node, Group) for node in document.root.children)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@pytest.mark.parametrize(
|
|
118
|
+
("source", "code"),
|
|
119
|
+
[
|
|
120
|
+
("{\\rtf1 text", "unclosed-group"),
|
|
121
|
+
("{\\rtf1 text}}", "unexpected-close"),
|
|
122
|
+
("{\\rtf2 text}", "unsupported-version"),
|
|
123
|
+
("{\\rtf1 \\'xz}", "invalid-hex-escape"),
|
|
124
|
+
("{\\rtf1 trailing\\", "trailing-escape"),
|
|
125
|
+
("{\\rtf1 \\bin-1 x}", "invalid-binary-length"),
|
|
126
|
+
("{\\rtf1 \\bin4 abc", "truncated-binary-data"),
|
|
127
|
+
("not RTF", "content-outside-group"),
|
|
128
|
+
],
|
|
129
|
+
)
|
|
130
|
+
def test_malformed_or_unsupported_input_has_explicit_errors(
|
|
131
|
+
source: str, code: str
|
|
132
|
+
) -> None:
|
|
133
|
+
with pytest.raises(ParseError) as error:
|
|
134
|
+
loads(source)
|
|
135
|
+
|
|
136
|
+
assert error.value.code == code
|
|
137
|
+
assert error.value.span.start_line >= 1
|
|
138
|
+
assert error.value.span.start_column >= 1
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_error_location_tracks_source_line_and_column() -> None:
|
|
142
|
+
with pytest.raises(ParseError) as error:
|
|
143
|
+
loads("{\\rtf1\r\n text\\'xz}")
|
|
144
|
+
|
|
145
|
+
assert error.value.span.start_line == 2
|
|
146
|
+
assert error.value.span.start_column == 6
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def test_unicode_controls_require_valid_parameters() -> None:
|
|
150
|
+
with pytest.raises(ParseError, match=r"\\u requires") as error:
|
|
151
|
+
loads(r"{\rtf1 \u text}")
|
|
152
|
+
assert error.value.code == "invalid-unicode-escape"
|
|
153
|
+
|
|
154
|
+
with pytest.raises(ParseError, match=r"\\u requires") as error:
|
|
155
|
+
loads(r"{\rtf1 \u65535?}")
|
|
156
|
+
assert error.value.code == "invalid-unicode-escape"
|
|
157
|
+
|
|
158
|
+
with pytest.raises(ParseError, match=r"\\uc requires") as error:
|
|
159
|
+
loads(r"{\rtf1 \uc-1 text}")
|
|
160
|
+
assert error.value.code == "invalid-unicode-fallback"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@pytest.mark.parametrize(
|
|
164
|
+
("limits", "source", "code"),
|
|
165
|
+
[
|
|
166
|
+
(Limits(max_input_chars=5), r"{\rtf1}", "input-limit-exceeded"),
|
|
167
|
+
(Limits(max_nesting=1), r"{\rtf1 {x}}", "nesting-limit-exceeded"),
|
|
168
|
+
(Limits(max_nodes=2), r"{\rtf1 x}", "node-limit-exceeded"),
|
|
169
|
+
],
|
|
170
|
+
)
|
|
171
|
+
def test_resource_limits_are_enforced(limits: Limits, source: str, code: str) -> None:
|
|
172
|
+
with pytest.raises(ParseError) as error:
|
|
173
|
+
loads(source, limits=limits)
|
|
174
|
+
assert error.value.code == code
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@pytest.mark.parametrize(
|
|
178
|
+
"kwargs",
|
|
179
|
+
[
|
|
180
|
+
{"max_input_chars": 0},
|
|
181
|
+
{"max_nesting": -1},
|
|
182
|
+
{"max_nodes": True},
|
|
183
|
+
],
|
|
184
|
+
)
|
|
185
|
+
def test_limits_must_be_positive_integers(kwargs: dict[str, int]) -> None:
|
|
186
|
+
with pytest.raises(ValueError):
|
|
187
|
+
Limits(**kwargs)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def test_unsupported_codepage_is_diagnostic_not_a_crash() -> None:
|
|
191
|
+
document = loads(r"{\rtf1\ansicpg999999 \'e9}")
|
|
192
|
+
|
|
193
|
+
assert document.text == "é"
|
|
194
|
+
assert [item.code for item in document.diagnostics] == ["unsupported-codepage"]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_non_string_source_is_rejected() -> None:
|
|
198
|
+
with pytest.raises(TypeError, match="source must be a str"):
|
|
199
|
+
loads(b"{\\rtf1 text}") # type: ignore[arg-type]
|