Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions .agents/skills/cpp-layout/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
name: cpp-layout
description: Maintain the DocLang C++ class layout in src/doclang and src/pybind when adding or changing classes and methods.
---

# DocLang C++ class layout

Keep a class declaration easy to scan. Order access sections as `public`, then `protected` when needed, then `private` methods, then a separate `private` data section. Omit empty sections. Group related methods within each section using short `/* reading */`, `/* writing */`, or similarly concrete comments.

Declare methods inside the class and place their definitions after the closing `};`. In these header-only components, mark non-template definitions `inline` to preserve the one-definition rule. Put nested-class definitions after their enclosing class declaration when possible. Keep constructors, overloads, access levels, default arguments, and behavior intact when reorganizing an existing class.

Example:

```cpp
class archive
{
public:
/* reading */
bool has(std::string_view path) const;

protected:
/* extension points */
void on_change();

private:
/* helpers */
void set_error(std::string message);

private:
/* state */
std::string last_error;
};

inline void archive::set_error(std::string message)
{
last_error = std::move(message);
}
```

Prefer a short exception only when an in-class body is required by the language (for example, a local class), and explain it in a comment. Run the relevant C++ build and tests after moving definitions.

Follow the repository's `.clang-format` settings for edited C++ files. The pre-commit hook uses clang-format 19.1.7 in check mode; compiling and passing tests do not establish formatting compliance. Format changed files, then run `uv run pre-commit run clang-format --all-files` before finishing.
12 changes: 12 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
BasedOnStyle: GNU
Standard: c++20
NamespaceIndentation: All
InsertBraces: true
SpaceBeforeParens: Never
ColumnLimit: 100
BreakAfterReturnType: None
AlwaysBreakAfterDefinitionReturnType: None
AllowShortFunctionsOnASingleLine: None
PointerAlignment: Left
SortIncludes: Never
EmptyLineAfterAccessModifier: Always
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,18 @@ jobs:
run: uv sync --frozen --no-default-groups --group ci
- name: Check style and run tests
run: pre-commit run --all-files

native-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install native build dependencies
run: sudo apt-get update && sudo apt-get install -y libxml2-dev ninja-build
- name: Configure native tests
run: cmake -S . -B build/native-tests -G Ninja -DDOCLANG_BUILD_PYTHON=OFF -DDOCLANG_BUILD_CPP_TESTS=ON -DDOCLANG_BUILD_VALIDATION_TESTS=ON
- name: Build native tests
run: cmake --build build/native-tests --parallel
- name: Run core native tests
run: ctest --test-dir build/native-tests -L core --output-on-failure
- name: Run native validation tests
run: ctest --test-dir build/native-tests -L validation --output-on-failure
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ repos:
name: "Ruff linter"
args: [--exit-non-zero-on-fix, --fix, --config=pyproject.toml]
files: '^(doclang|tests|utils).*\.py$'
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v19.1.7
hooks:
- id: clang-format
name: "C++ formatting"
entry: clang-format --dry-run --Werror
args: [--style=file]
files: '^(src|tests/cpp)/.*\.(h|cpp)$'
- repo: local
hooks:
- id: mypy
Expand Down
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# DocLang repository guidance

When editing C++ headers under `src/`, read [the C++ class layout skill](.agents/skills/cpp-layout/SKILL.md) and follow it for touched classes.
76 changes: 76 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
cmake_minimum_required(VERSION 3.21)
project(doclang LANGUAGES C CXX)

option(DOCLANG_BUILD_PYTHON "Build the Python extension" ON)
option(DOCLANG_BUILD_CPP_TESTS "Build native C++ tests" OFF)
option(DOCLANG_BUILD_VALIDATION_TESTS "Build native validation tests" OFF)

include(FetchContent)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(BUILD_SHARED_LIBS OFF)

find_package(pugixml CONFIG QUIET)
if(NOT TARGET pugixml::pugixml)
set(PUGIXML_INSTALL OFF CACHE BOOL "" FORCE)
FetchContent_Declare(
pugixml
GIT_REPOSITORY https://github.com/zeux/pugixml.git
GIT_TAG v1.15
GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(pugixml)
endif()

find_package(miniz CONFIG QUIET)
if(TARGET miniz::miniz)
set(DOCLANG_MINIZ_TARGET miniz::miniz)
elseif(TARGET miniz)
set(DOCLANG_MINIZ_TARGET miniz)
else()
set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(BUILD_FUZZERS OFF CACHE BOOL "" FORCE)
set(INSTALL_PROJECT OFF CACHE BOOL "" FORCE)
# miniz 3.0.2 declares CMake 3.0 and leaves CMP0077 unset.
set(CMAKE_POLICY_VERSION_MINIMUM 3.10)
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
FetchContent_Declare(
miniz
GIT_REPOSITORY https://github.com/richgel999/miniz.git
GIT_TAG 3.0.2
GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(miniz)
unset(CMAKE_POLICY_DEFAULT_CMP0077)
unset(CMAKE_POLICY_VERSION_MINIMUM)
set(DOCLANG_MINIZ_TARGET miniz)
endif()

find_package(LibXml2 REQUIRED)
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/doclang/doclang.xsd" DOCLANG_XSD_TEXT)
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/generated/doclang/validation")
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/src/doclang/validation/schema_data.h.in"
"${CMAKE_CURRENT_BINARY_DIR}/generated/doclang/validation/schema_data.h"
@ONLY)

add_library(doclang_native INTERFACE)
target_compile_features(doclang_native INTERFACE cxx_std_20)
target_include_directories(doclang_native INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR}/generated)
target_link_libraries(doclang_native INTERFACE
pugixml::pugixml ${DOCLANG_MINIZ_TARGET} LibXml2::LibXml2)

if(DOCLANG_BUILD_PYTHON)
set(PYBIND11_FINDPYTHON ON)
find_package(pybind11 CONFIG REQUIRED)
pybind11_add_module(_native src/pybind/doclang_module.cpp)
target_link_libraries(_native PRIVATE doclang_native)
install(TARGETS _native LIBRARY DESTINATION doclang RUNTIME DESTINATION doclang)
endif()

if(DOCLANG_BUILD_CPP_TESTS OR DOCLANG_BUILD_VALIDATION_TESTS)
include(CTest)
if(BUILD_TESTING)
add_subdirectory(tests/cpp)
endif()
endif()
134 changes: 134 additions & 0 deletions doclang/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,58 @@ except ValidationError as exc:
print(f"{exc.schematron_errors=}")
```

### Writing and editing documents

```python
from doclang import (
DoclangDocument,
DoclangPictureNode,
DoclangTableNode,
DoclangTextNode,
)

doc = DoclangDocument.empty()
first = doc.append_child("/doclang[1]", DoclangTextNode("Introduction"))
doc.insert_after(first, DoclangTextNode("Measurements"))

table = DoclangTableNode(rows=2, columns=2)
table.set_caption("Results")
table.append_to_cell(0, 0, DoclangTextNode("42"))
table.append_to_cell(0, 1, DoclangPictureNode("assets/plot.png"))
doc.append_child("/doclang[1]", table)

valid, error = doc.is_valid()
assert valid, error
xml = doc.xml()
```

`append_child` and `prepend_child` take a parent XPath. `insert_before` and
`insert_after` take an existing sibling XPath. `delete` removes an element at
its XPath. Each inserted node is copied into the document; editing the detached
node later does not change the document. Validation runs only when requested.
Named nodes also provide `is_valid()` for local checks and
`is_valid_in(document, InsertionSite.append_child(...))` for a proposed edit.

`DocLangXDocument` inherits these edits. After editing an archive with
annotations, `write()` reports that annotation XPath values may be stale.
Review them before calling `write(path, allow_stale_annotations=True)`.

Both `DoclangDocument` and `DoclangXDocument` expose the root specification
version as a comparable `DoclangVersion`:

```python
from doclang import DoclangVersion, ElementTag, OtslToken, xml_name

assert doc.version() >= DoclangVersion.parse("0.6")
assert xml_name(ElementTag.table) == "table"
assert xml_name(OtslToken.fc) == "fcel"
```

The version comes from the root `version` attribute, with the schema default
of `0.7` when it is absent. A document without a parsed root returns `None`.
Ordering compares the numeric major and minor components; it does not claim
schema compatibility between `0.x` versions.

### Custom Schematron backends

DocLang does not bundle a single Schematron runtime in the core package. Instead,
Expand Down Expand Up @@ -274,6 +326,9 @@ The bundled Saxon/C backend transpiles these rules to XSLT 3.0 at validation tim
Alternative backends may evaluate the same `.sch` file directly or use a precompiled
`.xsl` artifact if their runtime requires it.

Native document validation is explicit: callers can assemble or edit a document
before requesting a validation report.

## XSD Validation with VS Code

In VS Code you can use [Red Hat's XML extension](https://open-vsx.org/vscode/item?itemName=redhat.vscode-xml) and enable IDE-native XSD validation by adding the following to your `settings.json` (ℹ️ replacing the actual XSD path):
Expand Down Expand Up @@ -302,3 +357,82 @@ Note that this approach does not cover Schematron validation rules.
- [XSD 1.0 Specification](https://www.w3.org/TR/xmlschema-1/)
- [ISO Schematron](http://schematron.com/)
- [XPath 3.1 Specification](https://www.w3.org/TR/xpath-31/)
# Native DCLX editing and package access

The feature-branch native API exposes `DoclangDocument` for DocLang XML and
`DoclangXDocument` (also exported as `DocLangXDocument`) for DCLX packages.
`DoclangXDocument.read_bytes()` and `write_bytes()` operate on complete DCLX
archives in memory; `read()` and `write()` operate on files. Both read methods
accept optional `ArchiveLimits`. The default limits are 256 MiB compressed,
10,000 entries, 256 MiB per uncompressed entry, 1 GiB total uncompressed,
and a compression ratio of 200. ZIP entries are checked before extraction;
parts are decompressed when requested. The compressed archive is retained in
memory while the document is open.

```python
from doclang import ArchiveLimits, DocLangXDocumentRole, DoclangDocument, DoclangXDocument

doc = DoclangXDocument()
assert doc.read_xml('<doclang version="0.7"><text>Hello</text></doclang>')
summary = DoclangDocument('<doclang><text>Short summary</text></doclang>')
assert doc.set(DocLangXDocumentRole.SUMMARY, summary)
doc.set_part_text("context/source.json", '{"kind":"example"}', "application/json")
payload = doc.write_bytes()

copy = DoclangXDocument()
limits = ArchiveLimits()
assert copy.read_bytes(payload, limits)
assert copy.get_part_text("context/source.json") == '{"kind":"example"}'
assert copy.get(DocLangXDocumentRole.SUMMARY).at("/doclang[1]/text[1]") == "Short summary"
assert copy.validate_package()["ok"]
```

`DocLangXDocumentRole` also provides `TABLE_OF_CONTENTS`, `CONCEPTS`, and
`REFERENCES`. These are all DCLG documents, and `set(role, document)` validates
their XML against DocLang's bundled XSD and Schematron rules. Use
`get(role)` and `clear(role)` for the same roles. The main document stays on
`read_xml()` and the inherited `DoclangDocument` API because replacing it
affects the package's archive and annotations. Table of contents entries are
DocLang headings with percent-encoded source XPaths in `href` fragments.

Original source documents belong exclusively to `DocLangXDocument`:

```python
xml = '<doclang><text>Converted content</text></doclang>'
package = DoclangXDocument(xml, source=b"original bytes", source_mimetype="application/pdf")
assert package.get_source() == (b"original bytes", "application/pdf")
package.set_source(b"replacement bytes", mimetype="application/pdf")
assert package.has_source()
package.clear_source()
```

The constructor accepts an XML string or a `DoclangDocument`, with optional
keyword-only `source` and `source_mimetype` arguments supplied together.
Constructing from a `DoclangDocument` copies its current XML into an independent
package. Empty and source-only construction are also supported.
`get_source()` returns
`(bytes, mimetype)` or `None`; an empty byte string is a valid source.
Source data survives XML edits and `read_xml()`. Reading another file or
archive replaces the source along with the package. DCLX writes store
`source/document` and `source/mimetype` with explicit OPC content types;
`clear_source()` removes both parts and their declarations. Generic part
setters and removal cannot modify these two managed paths.

`get_part_bytes`, `get_part_text`, `set_part_bytes`, `set_part_text`, and
`remove_part` use archive-relative paths. Generic setters reject the main
document, OPC metadata, and DocLang-managed `annotations/` paths. Setters
require an explicit content type and update `[Content_Types].xml`; `write`
also supplies declarations for parts carried over from an existing archive.
Unknown parts survive read/write unless removed. `validate_package()` returns
`{"ok": bool, "errors": [{"code", "path", "message"}, ...]}` and checks
the document, TOC targets, staleness, OPC metadata, and part declarations.
Legacy DCLX files without OPC metadata can still be read; writing them adds
the missing declarations and document relationship.

The XML-side `iter_nodes(xpath=None, limit=1000)` returns bounded records with
`xpath`, `parent_xpath`, `name`, `text`, `page`, and `bbox`. XPaths address a
particular document revision: structural edits can shift them. A document edit
marks existing annotations and sidecars stale. Writes refuse stale data by
default; repair or clear it first. The explicit `allow_stale_annotations` and
`allow_stale_sidecars` flags permit a reviewed override, though unresolved TOC
targets always block a write.
Loading
Loading