Skip to content

fix(wasm): map FastLED DWARF source paths - #2675

Merged
zackees merged 3 commits into
masterfrom
feat/wasm-dwarf-prefix-maps
Jun 1, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/wasm-dwarf-prefix-maps

Conversation

@zackees

@zackees zackees commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Summary

  • synthesize debug/fast_debug -ffile-prefix-map flags for FastLED library sources from the known repo src root to the configured fastledsource prefix
  • normalize Meson-discovered source paths to forward slashes and invalidate old source metadata caches that may contain native Windows separators
  • remove the old Unix-root sketch prefix-map guidance from build_flags.toml and document the generated known-root maps
  • add focused tests for wasm flag emission and source discovery path normalization

Refs FastLED/cli#130.

Tests

  • uv run pytest ci/tests/test_wasm_flags.py -q
  • uv run ruff check ci/wasm_flags.py ci/meson/rglob.py ci/meson/src_metadata_cache.py ci/tests/test_wasm_flags.py
  • uv run ruff format --check ci/wasm_flags.py ci/meson/rglob.py ci/meson/src_metadata_cache.py ci/tests/test_wasm_flags.py
  • uv run pyright ci/wasm_flags.py ci/meson/rglob.py ci/meson/src_metadata_cache.py
  • uv run python ci/wasm_flags.py --target lib_compile --mode debug | Select-String -Pattern ffile-prefix-map
  • uv run python ci/wasm_flags.py --target lib_compile --mode quick | Select-String -Pattern ffile-prefix-map

Summary by CodeRabbit

  • New Features

    • DWARF source-path mapping for WebAssembly debug/fast_debug builds.
    • Versioned build cache for safer, compatible caching.
  • Bug Fixes

    • Tooling output normalized to use forward slashes for consistent path formatting.
  • Tests

    • Added tests for compilation flags, DWARF mapping behavior, and path-handling in tooling.
  • Documentation

    • Updated DWARF configuration guidance to reflect dynamic prefix mapping.

@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6ef934df-cf21-464d-81a2-35799fe8b593

📥 Commits

Reviewing files that changed from the base of the PR and between 270e56e and 1e0fb71.

📒 Files selected for processing (1)
  • ci/meson/src_metadata_cache.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • ci/meson/src_metadata_cache.py

📝 Walkthrough

Walkthrough

This PR normalizes rglob output paths to forward slashes, adds versioned source-metadata cache data via CACHE_VERSION and CacheEntry with validation, and emits -ffile-prefix-map DWARF flags for debug/fast_debug modes with tests and TOML guidance.

Changes

Build System Infrastructure and DWARF Debug Support

Layer / File(s) Summary
Path normalization in rglob
ci/meson/rglob.py, ci/tests/test_wasm_flags.py
rglob.py now prints normalized forward-slash paths. Integration test asserts the script's stdout contains forward slashes and the nested demo path and contains no backslashes.
Cache versioning and validation
ci/meson/src_metadata_cache.py
Added CACHE_VERSION = 2 and CacheEntry dataclass. load_cache() returns `CacheEntry
DWARF prefix-mapping for debug modes
ci/wasm_flags.py, ci/tests/test_wasm_flags.py, src/platforms/wasm/compiler/build_flags.toml
Added DEBUG_PATH_MAP_MODES and helpers to build -ffile-prefix-map=<from>=<to> flags for debug and fast_debug modes; get_lib_compile_flags_dict() appends these flags. Unit tests cover debug/fast_debug/quick behaviors and TOML documents synthesized prefix mapping for known roots.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Paths now hop in tidy forward lines,

Cache keeps its stamp through versioned signs,
DWARF maps weave roots into a thread,
Flags flutter bright where debuggers tread.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(wasm): map FastLED DWARF source paths' directly summarizes the main change—adding DWARF source path mapping for FastLED in WebAssembly builds.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/wasm-dwarf-prefix-maps

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
ci/meson/src_metadata_cache.py (2)

78-91: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle KeyboardInterrupt before other exceptions.

The try-except block does not handle KeyboardInterrupt before catching other exceptions. As per coding guidelines, all Python try-catch blocks must handle KeyboardInterrupt before other exceptions to ensure proper cleanup and prevent masking user interruptions.

🛡️ Proposed fix to handle KeyboardInterrupt
     try:
         with open(cache_file, "r", encoding="utf-8") as f:
             cache = json.load(f)
 
         # Validate cache structure
         required_keys = ["version", "hash", "timestamp", "metadata"]
         if not all(key in cache for key in required_keys):
             return None
         if cache["version"] != CACHE_VERSION:
             return None
 
         return cache
+    except KeyboardInterrupt:
+        raise
     except (json.JSONDecodeError, OSError):
         return None

As per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/meson/src_metadata_cache.py` around lines 78 - 91, The try-except around
reading/parsing the cache (the block that opens cache_file and calls json.load
and checks CACHE_VERSION) must handle KeyboardInterrupt first; add an explicit
except KeyboardInterrupt: raise before the existing except
(json.JSONDecodeError, OSError): return None so that user interrupts aren’t
swallowed and normal JSON/OSError handling remains unchanged.

63-63: 🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Return a dataclass instead of dict for type safety.

The function returns dict[str, str | float] | None with multiple fields (version, hash, timestamp, metadata). As per coding guidelines, functions with multiple return values should return dataclass structs instead of tuples or dicts for better type safety and maintainability.

♻️ Proposed refactor to use dataclass

Add a dataclass definition near the top of the file:

from dataclasses import dataclass
from typeguard import typechecked

`@typechecked`
`@dataclass`
class CacheEntry:
    version: int
    hash: str
    timestamp: float
    metadata: str

Then update the function signature:

-def load_cache(build_dir: Path) -> dict[str, str | float] | None:
+def load_cache(build_dir: Path) -> CacheEntry | None:
     """
     Load cached source metadata from build directory.
 
     Args:
         build_dir: Meson build directory (e.g., .build/meson-quick/)
 
     Returns:
-        Cache dictionary with keys: hash, timestamp, metadata
+        CacheEntry with version, hash, timestamp, and metadata
         None if cache doesn't exist or is invalid
     """

Update the validation and return logic:

         # Validate cache structure
         required_keys = ["version", "hash", "timestamp", "metadata"]
         if not all(key in cache for key in required_keys):
             return None
         if cache["version"] != CACHE_VERSION:
             return None
 
-        return cache
+        return CacheEntry(
+            version=cache["version"],
+            hash=cache["hash"],
+            timestamp=cache["timestamp"],
+            metadata=cache["metadata"]
+        )

Update call sites in main() to use dataclass fields instead of dict keys.

As per coding guidelines: "Return dataclass structs instead of tuples or dicts for functions with multiple return values" and "Use @typechecked decorator with @dataclass for runtime type validation".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/meson/src_metadata_cache.py` at line 63, Replace the loose dict return
from load_cache with a typed dataclass: add a `@typechecked` `@dataclass` CacheEntry
(fields: version:int, hash:str, timestamp:float, metadata:str) near the top of
the module, change load_cache signature to return Optional[CacheEntry] instead
of dict[str, str|float] | None, map/validate the parsed values into a CacheEntry
instance before returning, and update all call sites (e.g., usages in main()) to
access entry.version/entry.hash/entry.timestamp/entry.metadata instead of dict
keys.
🧹 Nitpick comments (1)
ci/tests/test_wasm_flags.py (1)

30-30: 💤 Low value

Use an explicit loop instead of the generator expression.

♻️ Proposed change
-    assert not any(flag.startswith("-ffile-prefix-map=") for flag in flags)
+    for flag in flags:
+        assert not flag.startswith("-ffile-prefix-map=")

As per coding guidelines: "Use explicit loops instead of list comprehensions for code clarity and debuggability".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/tests/test_wasm_flags.py` at line 30, The assertion uses a generator
expression; replace it with an explicit loop over the flags iterable to improve
clarity and debuggability: iterate through flags, check each
flag.startswith("-ffile-prefix-map="), and if any matches call an explicit test
failure (e.g., pytest.fail or assert False with a message) referencing the
offending flag; update the line containing the assertion on the flags variable
to use this loop and provide a clear failure message.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ci/wasm_flags.py`:
- Around line 64-69: The list comprehension in _file_prefix_map_flags should be
rewritten as an explicit loop to follow the guideline; replace the comprehension
that builds the list of "-ffile-prefix-map" entries with creating an empty list,
iterating over the iterator returned by _path_prefix_variants(from_path),
appending each formatted f"-ffile-prefix-map={path_prefix}={normalized_prefix}"
string to the list, and then return that list — keep the existing normalization
of to_prefix and the use of _path_prefix_variants as the source of path_prefix
values.

---

Outside diff comments:
In `@ci/meson/src_metadata_cache.py`:
- Around line 78-91: The try-except around reading/parsing the cache (the block
that opens cache_file and calls json.load and checks CACHE_VERSION) must handle
KeyboardInterrupt first; add an explicit except KeyboardInterrupt: raise before
the existing except (json.JSONDecodeError, OSError): return None so that user
interrupts aren’t swallowed and normal JSON/OSError handling remains unchanged.
- Line 63: Replace the loose dict return from load_cache with a typed dataclass:
add a `@typechecked` `@dataclass` CacheEntry (fields: version:int, hash:str,
timestamp:float, metadata:str) near the top of the module, change load_cache
signature to return Optional[CacheEntry] instead of dict[str, str|float] | None,
map/validate the parsed values into a CacheEntry instance before returning, and
update all call sites (e.g., usages in main()) to access
entry.version/entry.hash/entry.timestamp/entry.metadata instead of dict keys.

---

Nitpick comments:
In `@ci/tests/test_wasm_flags.py`:
- Line 30: The assertion uses a generator expression; replace it with an
explicit loop over the flags iterable to improve clarity and debuggability:
iterate through flags, check each flag.startswith("-ffile-prefix-map="), and if
any matches call an explicit test failure (e.g., pytest.fail or assert False
with a message) referencing the offending flag; update the line containing the
assertion on the flags variable to use this loop and provide a clear failure
message.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 18e454f2-bc0d-42c1-97bd-17aa9d849f5e

📥 Commits

Reviewing files that changed from the base of the PR and between 8c9443e and c70e490.

📒 Files selected for processing (5)
  • ci/meson/rglob.py
  • ci/meson/src_metadata_cache.py
  • ci/tests/test_wasm_flags.py
  • ci/wasm_flags.py
  • src/platforms/wasm/compiler/build_flags.toml

Comment thread ci/wasm_flags.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
ci/meson/src_metadata_cache.py (2)

62-63: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Move import to top of file.

The from os import stat_result import is inside the function body. All system imports must be at the top of the file.

📦 Proposed fix to move import to top-level

Add the import at the top of the file with other standard library imports:

 import argparse
 import hashlib
 import json
+from os import stat_result
 import sys
 from dataclasses import dataclass
 from pathlib import Path

Then remove the inline import from the function:

     hash_input: list[str] = []
     for f in source_files:
         if f.is_file():
-            from os import stat_result
-
             stat: stat_result = f.stat()

As per coding guidelines: "All system imports must be at the top of the file in proper order: standard library, third-party, local".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/meson/src_metadata_cache.py` around lines 62 - 63, The inline import "from
os import stat_result" must be moved to the module top with the other
standard-library imports; remove the in-function import and add "from os import
stat_result" alongside existing imports at the top of the file so functions
(e.g., wherever stat_result was used) reference the top-level symbol instead of
importing at runtime.

137-137: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add argv parameter to main() for testing flexibility.

The main() function should accept an optional list[str] parameter to enable passing test arguments to parse_args().

🧪 Proposed fix to add argv parameter
-def main() -> None:
+def main(argv: list[str] | None = None) -> None:
     """Main entry point for source metadata cache operations."""
     parser = argparse.ArgumentParser(
         description="Manage source metadata cache for Meson build system"

Then update the parse_args call at line 180:

-    args = parser.parse_args()
+    args = parser.parse_args(argv)

As per coding guidelines: "parse_args functions MUST accept an optional list[str] parameter for testing flexibility".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/meson/src_metadata_cache.py` at line 137, Update the main function
signature to accept an optional argv parameter (e.g., def main(argv:
Optional[list[str]] = None) -> None) and pass that argv into the existing
parse_args call (replace parse_args() with parse_args(argv)) so tests can inject
arguments; reference the main() function and the parse_args() invocation for the
change and include the appropriate typing import if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ci/meson/src_metadata_cache.py`:
- Line 41: The function compute_src_files_hash currently declares pattern with a
default value; remove the default so the signature is def
compute_src_files_hash(src_dir: Path, pattern: str) -> str, and update every
call site to pass the desired pattern explicitly (e.g., "*.cpp" where previously
relied upon the default). Ensure any tests or internal usages that omitted the
pattern are updated to supply an explicit string and run the test suite to
verify nothing else depends on the default.
- Around line 31-38: The CacheEntry dataclass lacks the `@typechecked` decorator
for runtime type validation; import typechecked from typeguard and apply
`@typechecked` above the CacheEntry declaration so that the class CacheEntry (with
fields version, hash, timestamp, metadata) is validated at runtime. Ensure the
new import is added alongside other imports and the decorator is placed
immediately above the `@dataclass`(frozen=True) line referencing CacheEntry.

---

Outside diff comments:
In `@ci/meson/src_metadata_cache.py`:
- Around line 62-63: The inline import "from os import stat_result" must be
moved to the module top with the other standard-library imports; remove the
in-function import and add "from os import stat_result" alongside existing
imports at the top of the file so functions (e.g., wherever stat_result was
used) reference the top-level symbol instead of importing at runtime.
- Line 137: Update the main function signature to accept an optional argv
parameter (e.g., def main(argv: Optional[list[str]] = None) -> None) and pass
that argv into the existing parse_args call (replace parse_args() with
parse_args(argv)) so tests can inject arguments; reference the main() function
and the parse_args() invocation for the change and include the appropriate
typing import if needed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4e7ca668-1c7e-4d5c-a5fb-a511b1754d15

📥 Commits

Reviewing files that changed from the base of the PR and between c70e490 and 270e56e.

📒 Files selected for processing (3)
  • ci/meson/src_metadata_cache.py
  • ci/tests/test_wasm_flags.py
  • ci/wasm_flags.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • ci/tests/test_wasm_flags.py
  • ci/wasm_flags.py

Comment thread ci/meson/src_metadata_cache.py Resolved
Comment thread ci/meson/src_metadata_cache.py Resolved
@zackees
zackees merged commit 27a1682 into master Jun 1, 2026
7 of 8 checks passed
@zackees
zackees deleted the feat/wasm-dwarf-prefix-maps branch June 1, 2026 21:25
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant