Skip to content

fix: Dynamic code snippets now recognize bare Object and Random calls consistently#1657

Merged
hatayama merged 2 commits into
v3-betafrom
feat/port-stream-a-dynamic-code-aliases
Jul 9, 2026
Merged

fix: Dynamic code snippets now recognize bare Object and Random calls consistently#1657
hatayama merged 2 commits into
v3-betafrom
feat/port-stream-a-dynamic-code-aliases

Conversation

@hatayama

@hatayama hatayama commented Jul 9, 2026

Copy link
Copy Markdown
Owner

Summary

  • Dynamic code snippets that call Random.Range(...) without an explicit using now compile, matching the existing bare-Object support.
  • The bare-alias detection now understands comments and global using forms, so a snippet's own custom alias is respected even when written unusually (e.g. using @Object = ...;, or with comments between tokens).

User Impact

  • Before: only bare Object calls were auto-resolved; a bare Random.Range(...) in dynamic code failed to compile unless the user added using Random = UnityEngine.Random; manually. A global using alias with a comment in between tokens was also missed.
  • After: both Object and Random are auto-resolved when the snippet doesn't already alias them, and user-defined aliases (including verbatim/comment-containing forms) are correctly detected and respected.

Changes

  • SourceShaper now collects every using-alias name the snippet defines (AliasedNames), replacing the old ad-hoc string scan that only recognized "Object".
  • WrapperTemplate injects default aliases (Object, Random) from a small table, skipping any name already in AliasedNames.
  • Fixed a related gap where a comment between global and using caused the directive to be misclassified as a plain statement.
  • Restored unit test coverage for this behavior at the preparer/shaper level (the previous coverage was removed in chore: Remove Editor-freezing and obsolete tests from the Unity test suite #1310 because it was execution-based and risked freezing the Editor; these new tests do not compile-and-run).

Verification

  • dist/darwin-arm64/uloop compile — 0 errors, 0 warnings
  • dist/darwin-arm64/uloop run-tests (EditMode, full suite) — 1725 passed, 0 failed, 7 skipped (pre-existing skips)

Review in cubic

Ports main commit 045f525 (#1469) to v3-beta. The Object alias
already existed via WrapperTemplate's ad-hoc string scan (PR #1234),
but Random was missing and the detection approach did not generalize.

Replace the "Object"-only text scan with a generic mechanism:
SourceShaper now collects every user-defined using-alias name
(including global/verbatim/commented forms) into
SourceShapeResult.AliasedNames, and WrapperTemplate looks up a
small DefaultUsingAlias table (Object, Random) against that set
instead of re-parsing using-directive strings.

Also fixes a latent gap in global-using detection: the keyword scan
between "global" and "using" only skipped whitespace, so a comment
in between caused the whole global using directive to be
misclassified as a top-level statement.

Restores unit test coverage for this behavior (deleted in #1310
because the old tests were execution-based and froze the Editor);
these are pure preparer/shaper-level tests with no compile-and-run
step, so they carry no freeze risk.
@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

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: 64961534-888b-4797-8300-d601ee51c277

📥 Commits

Reviewing files that changed from the base of the PR and between b01f1e9 and acd95ad.

📒 Files selected for processing (3)
  • Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeSourcePreparerTests.cs
  • Assets/Tests/Editor/DynamicCodeToolTests/SourceShaperTests.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SourceShaper.cs
🚧 Files skipped from review as they are similar to previous changes (2)
  • Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeSourcePreparerTests.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SourceShaper.cs

📝 Walkthrough

Walkthrough

WrapperTemplate.Build now accepts aliasedNames and injects default aliases from a table of known mappings. SourceShaper collects alias names from using directives into AliasedNames and passes them through DynamicCodeSourcePreparer. Tests were updated for the new call signature and added coverage for alias parsing, injection, and substring counting.

Changes

Alias detection and injection

Layer / File(s) Summary
SourceShaper alias extraction
Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SourceShaper.cs
SourceShaper skips whitespace/comments while parsing using directives, extracts alias identifiers including verbatim @ forms, and exposes them via SourceShapeResult.AliasedNames.
WrapperTemplate default alias injection
Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs, Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/DynamicCodeSourcePreparer.cs
WrapperTemplate.Build adds an aliasedNames parameter, asserts inputs, and emits default Object/Random aliases from AppendDefaultUsingAliases; DynamicCodeSourcePreparer passes shape.AliasedNames into the wrapper build call.
Alias injection and analysis tests
Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeSourcePreparerTests.cs, Assets/Tests/Editor/DynamicCodeToolTests/SourceShaperTests.cs, Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeTestStringUtility.cs
New tests cover alias injection, alias preservation, verbatim alias handling, comment handling, default Random injection, and CountSubstring; a helper utility counts non-overlapping substrings.
Existing test call-site updates for Build signature change
Assets/Tests/Editor/DynamicCodeToolTests/AutoInjectedNamespacesTests.cs, Assets/Tests/Editor/DynamicCodeToolTests/PreUsingResolverTests.cs
Existing WrapperTemplate.Build invocations are updated to pass System.Array.Empty<string>() for the new aliasedNames argument.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • hatayama/unity-cli-loop#1234: Also touches the WrapperTemplate.Build alias-handling path around using Object = UnityEngine.Object;.
  • hatayama/unity-cli-loop#1469: Directly overlaps with the SourceShaperDynamicCodeSourcePreparerWrapperTemplate.Build alias wiring and default alias injection changes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% 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
Title check ✅ Passed The title clearly summarizes the main change: improved bare Object and Random handling in dynamic code snippets.
Description check ✅ Passed The description is directly related to the code changes and explains the alias-handling fix and test coverage.
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.
✨ 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/port-stream-a-dynamic-code-aliases

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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 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
`@Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs`:
- Around line 2-3: The precondition checks in WrapperTemplate currently resolve
to System.Diagnostics.Debug instead of Unity’s assertion API, so update the
assert calls to use UnityEngine.Debug explicitly or alias Debug to
UnityEngine.Debug. Keep the change scoped to the code that uses these asserts in
the dynamic compilation template so the intended Unity assertion behavior is
preserved.
🪄 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: d012552a-447d-437d-b996-ac0878a0a8a1

📥 Commits

Reviewing files that changed from the base of the PR and between 4890fe1 and b01f1e9.

⛔ Files ignored due to path filters (1)
  • Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeTestStringUtility.cs.meta is excluded by none and included by none
📒 Files selected for processing (8)
  • Assets/Tests/Editor/DynamicCodeToolTests/AutoInjectedNamespacesTests.cs
  • Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeSourcePreparerTests.cs
  • Assets/Tests/Editor/DynamicCodeToolTests/DynamicCodeTestStringUtility.cs
  • Assets/Tests/Editor/DynamicCodeToolTests/PreUsingResolverTests.cs
  • Assets/Tests/Editor/DynamicCodeToolTests/SourceShaperTests.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/DynamicCodeSourcePreparer.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SourceShaper.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs

Comment on lines +2 to +3
using System.Diagnostics;
using System.Linq;

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check using directives in WrapperTemplate.cs and SourceShaper.cs
echo "=== WrapperTemplate.cs (first 10 lines) ==="
head -10 Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs

echo ""
echo "=== SourceShaper.cs (first 10 lines) ==="
head -10 Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SourceShaper.cs

# Check if any file in this directory imports both UnityEngine and System.Diagnostics
echo ""
echo "=== Files importing both UnityEngine and System.Diagnostics ==="
rg -l 'using UnityEngine;' Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/ | xargs rg -l 'using System.Diagnostics;' 2>/dev/null || echo "None found"

Repository: hatayama/unity-cli-loop

Length of output: 1312


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== WrapperTemplate.cs (all lines with numbers) ==="
cat -n Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs

echo ""
echo "=== Search for any explicit Debug qualification in this directory ==="
rg -n '\b(UnityEngine\.)?Debug\.Assert|\busing\s+Debug\s*=' Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/

echo ""
echo "=== Search for UnityEngine imports in WrapperTemplate.cs vicinity ==="
rg -n 'using UnityEngine;|global using UnityEngine;|using Debug = ' Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs

Repository: hatayama/unity-cli-loop

Length of output: 13626


Use UnityEngine.Debug for these asserts
Debug.Assert here resolves to System.Diagnostics.Debug, so these precondition checks can be stripped in non-DEBUG builds instead of using Unity’s assertion path. Qualify them as UnityEngine.Debug.Assert or alias Debug to UnityEngine.Debug if that’s the intended API.

🤖 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
`@Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/WrapperTemplate.cs`
around lines 2 - 3, The precondition checks in WrapperTemplate currently resolve
to System.Diagnostics.Debug instead of Unity’s assertion API, so update the
assert calls to use UnityEngine.Debug explicitly or alias Debug to
UnityEngine.Debug. Keep the change scoped to the code that uses these asserts in
the dynamic compilation template so the intended Unity assertion behavior is
preserved.

Source: Learnings

…ments

The plain "using" path in TryAnalyzeTopLevelUsing still used
SkipWhitespace instead of SkipWhitespaceAndComments, so a comment
between "using" and "var"/"(" caused a using-statement to be
misclassified as a using-directive and dropped from the user code.
Fixed to match the already-corrected global-using path, and added a
regression test for the comment-before-var case.

Also added the required WHAT comment to each new test method per
this repo's test convention.
@hatayama
hatayama merged commit ce5c364 into v3-beta Jul 9, 2026
10 checks passed
@hatayama
hatayama deleted the feat/port-stream-a-dynamic-code-aliases branch July 9, 2026 07:46
@github-actions github-actions Bot mentioned this pull request Jul 11, 2026
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.

1 participant