Skip to content

Make wrapper generation more efficient - #126

Open
kwabenantim wants to merge 7 commits into
developfrom
perf-generation-speedups
Open

Make wrapper generation more efficient#126
kwabenantim wants to merge 7 commits into
developfrom
perf-generation-speedups

Conversation

@kwabenantim

Copy link
Copy Markdown
Member

Fixes #125

Profiling a from-scratch pychaste generation (758s) showed most of the
time was cppwg's own Python, not CastXML. Two hot spots dominated:

1. The `Path(a) in Path(b).parents` idiom, evaluated per declaration and
   per file across several phases (the source-declaration filter, unknown-
   class logging, auto-include resolution, file collection), allocated
   millions of Path objects and did O(depth) string-normalized compares.
   Replace it with utils.path_is_within(), a lexical normalized-string
   test with the same (strict, no-symlink) semantics as Path.parents.

2. ModuleInfo.sort_classes ran two C-by-C loops over the module's classes
   (~270 for pychaste) with utils.type_string_matches() inside, re-
   canonicalizing and re-compiling the same regex on every comparison
   (~11M re.sub calls). Precompute each class's canonical argument-type
   strings and a compiled whole-token regex for its name once, and cache
   the pairwise `requires` result. Factor the pattern build out of
   type_string_matches() into utils.compile_type_pattern() so both share it.

Also hoist the loop-invariant realpath() out of the per-declaration loop
in CppSourceParser.parse_instantiations().

These are equivalence-preserving refactors: the 274 pychaste wrappers are
byte-for-byte identical, the shapes example regenerates identically, and
the 480 unit tests pass. Measured on pychaste: 758.7s -> 275.2s (-64%),
with parse_headers -223s, resolve_auto_includes -77s, sort_classes -75s,
log_unknown_classes -57s.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@codecov

codecov Bot commented Aug 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.68%. Comparing base (ca85410) to head (46ada53).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop     #126      +/-   ##
===========================================
- Coverage    99.75%   99.68%   -0.08%     
===========================================
  Files           31       31              
  Lines         2478     2536      +58     
  Branches       534      545      +11     
===========================================
+ Hits          2472     2528      +56     
- Misses           5        7       +2     
  Partials         1        1              
Flag Coverage Δ
cells 71.74% <92.45%> (+0.66%) ⬆️
shapes 71.92% <89.62%> (+0.61%) ⬆️
unit 93.13% <93.39%> (-0.13%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cppwg/generators.py 99.43% <100.00%> (-0.01%) ⬇️
cppwg/info/base_info.py 100.00% <100.00%> (ø)
cppwg/info/module_info.py 100.00% <100.00%> (ø)
cppwg/info/package_info.py 99.43% <100.00%> (-0.01%) ⬇️
cppwg/parsers/source_parser.py 100.00% <100.00%> (ø)
cppwg/utils/utils.py 100.00% <100.00%> (ø)
cppwg/writers/class_writer.py 99.64% <100.00%> (+0.84%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

kwabenantim and others added 4 commits August 13, 2026 18:30
hierarchy_attribute and hierarchy_attribute_gather_flat walk the
class -> module -> package chain on every call. The shared exclusion
predicates (cppwg.info.exclusions) call gather_flat 2-3 times per method,
per constructor and per data member, and these run in dependency pruning,
auto-include resolution and again in the writers - so the same tree walk
was repeated thousands of times over identical, immutable config.

Memoize both accessors per info object, keyed by attribute name. The
gathered config is fixed by the time these are read (only the generation
phases call them, never the parser), so a value can be cached from first
read. The cache is created lazily via __dict__.setdefault so any BaseInfo
subclass works whether or not it ran BaseInfo.__init__ (some test doubles
do not). The cached flat list is returned directly; every caller only
reads or concatenates it, never mutates it.

Byte-for-byte identical wrappers (pychaste 274, shapes) and 480 unit
tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
# Conflicts:
#	cppwg/generators.py
exclude_inherited_overrides ran _overrides_wrapped_base_virtual for every
method: it walked the class's bases, re-queried each base's member functions
via pygccxml, re-canonicalized argument-type strings and re-ran the base's
method_is_excluded - repeating all of it for every sibling overload. Nothing
was memoized across methods, so it dominated wrapper writing.

Precompute once per package a map from each wrapped base class to the set of
virtual signatures (name, const-ness, argument types) it actually binds, and
reduce the per-method test to a set-membership lookup. Built in
write_class_wrappers and cached on the package info so every class writer
shares one build.

Byte-identical output (274 pychaste wrappers + shapes unchanged); write phase
~54.7s -> ~35.2s on a from-scratch pychaste generation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
… test

_overrides_wrapped_base_virtual still recomputed per method the cross-module
`imports` flag, the recursive_bases walk that filters to wrapped, pybind-linked
bases, and the candidate method's own signature - and _is_inherited_override
re-ran it for every sibling overload. The linked-base list is identical for all
methods of a class, so memoize it per class_decl (walking recursive_bases once
per class, not once per method); memoize each method's signature too.

Byte-identical output (274 pychaste wrappers + shapes unchanged); write phase a
further ~35.2s -> ~28.8s (~54.7s -> ~28.8s cumulative with the signature index).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@kwabenantim
kwabenantim marked this pull request as ready for review August 14, 2026 10:56
@kwabenantim
kwabenantim requested a balanced review from Copilot August 14, 2026 10:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Optimizes wrapper generation for issue #125 by reducing repeated path, regex, hierarchy, sorting, and virtual-method work.

Changes:

  • Adds reusable path and type-pattern helpers.
  • Precomputes class dependencies and virtual signatures.
  • Memoizes hierarchy and method-related lookups.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
cppwg/writers/module_writer.py Shares virtual-signature indexes.
cppwg/writers/class_writer.py Caches inherited-override lookups.
cppwg/utils/utils.py Adds optimized matching helpers.
cppwg/parsers/source_parser.py Reduces repeated path resolution.
cppwg/info/package_info.py Optimizes source-path filtering.
cppwg/info/module_info.py Precomputes class sorting dependencies.
cppwg/info/base_info.py Memoizes hierarchy lookups.
cppwg/generators.py Uses optimized source-path checks.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread cppwg/writers/module_writer.py Outdated
Comment thread cppwg/utils/utils.py Outdated
kwabenantim and others added 2 commits August 14, 2026 12:06
path_is_within appended os.sep to the normalized ancestor before the prefix
test, but a root ("/" or a Windows drive root) already ends in a separator, so
the test looked for a "//" prefix and rejected every real descendant - source
filtering against such a root would drop everything (or admit everything). Only
append a separator when the ancestor lacks one, treat an equal path as not
within (strict), and normcase so the comparison is case-insensitive on Windows
like the Path form it replaced. Adds direct unit tests including the root cases.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The index was built eagerly in write_class_wrappers, scanning every wrapped
class's member functions and running the exclusion checks even when no class
enables exclude_inherited_overrides (the package default) - work the previous
code never did in that common case, a generation-time regression. Only
_overrides_wrapped_base_virtual reads the index, and only when the option is on,
so build it lazily on first access via the class writer, sharing it across the
package by caching on the package info. A package that never uses the option now
builds it not at all.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Speed up wrapper generation

2 participants