Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix generic type deduce bug of ShaderLab compiler in verbose mode #2477

Merged
merged 5 commits into from
Jan 9, 2025

Conversation

Sway007
Copy link
Member

@Sway007 Sway007 commented Dec 25, 2024

Please check if the PR fulfills these requirements

  • The commit message follows our guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)

Fix generic type deduce bug in ShaderLab compiler of verbose mode.

vec3 baseF0;

// In the snippets below, the compiler incorrectly inferred the signature 
// of the `clamp` function as `float clamp(float, float, float)`, 
// the correct signature should be `vec3 clamp(vec3, float, float)`.
fresnelToIOR(clamp(baseF0, 0.0, 0.9999))

image

Summary by CodeRabbit

  • New Features

    • Enhanced shader function call handling and type processing.
    • Improved shader macro definition and validation support.
  • Bug Fixes

    • Updated shader function signatures for more accurate type representation.
    • Added error logging for shader parsing issues.
  • Chores

    • Added new dependency for shader lab testing.

Copy link

coderabbitai bot commented Dec 25, 2024

Walkthrough

This pull request introduces modifications to the shader parsing and built-in function handling in the Galacean shader system. The changes primarily focus on improving the semantic analysis of function calls, specifically in the FunctionCallGeneric class and BuiltinFunction class. The modifications streamline how built-in functions are processed, with updates to parameter passing, return type assignment, and function signature management. Additionally, the changes include updates to test infrastructure and error reporting for shader validation.

Changes

File Change Summary
packages/shader-lab/src/parser/AST.ts - Modified FunctionCallGeneric class method for built-in function retrieval
- Simplified parameter passing and return type assignment
packages/shader-lab/src/parser/builtin/functions.ts - Added _realReturnType property to BuiltinFunction class
- Introduced realReturnType getter
- Refactored getFn static method
- Updated texture2D function signatures
tests/package.json - Added @galacean/engine-shader-shaderlab dependency
tests/src/shader-lab/ShaderLab.test.ts - Added registerIncludes import
- Defined commonMacros constant
- Enhanced test suite with macro definitions
tests/src/shader-lab/ShaderValidate.ts - Added error logging for shaderLab parsing errors

Possibly related PRs

Suggested labels

high priority

Suggested reviewers

  • GuoLei1990
  • zhuxudong

Poem

🐰 In shader's realm, where code takes flight,

Functions dance with type-safe might!

Parsing magic, clear and bright,

Galacean's syntax shines so right!

A rabbit's leap through type's delight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Sway007 Sway007 self-assigned this Dec 25, 2024
@Sway007 Sway007 added bug Something isn't working Rendering Rendering related functions shader Shader related functions medium priority Medium priority issue labels Dec 25, 2024
Copy link

codecov bot commented Dec 25, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 68.28%. Comparing base (b9b2e1c) to head (1f2414a).
Report is 1 commits behind head on dev/1.4.

Additional details and impacted files
@@             Coverage Diff             @@
##           dev/1.4    #2477      +/-   ##
===========================================
- Coverage    68.44%   68.28%   -0.16%     
===========================================
  Files          925      925              
  Lines        96170    96105      -65     
  Branches      8155     8168      +13     
===========================================
- Hits         65821    65628     -193     
- Misses       30094    30221     +127     
- Partials       255      256       +1     
Flag Coverage Δ
unittests 68.28% <100.00%> (-0.16%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (3)
packages/shader-lab/src/parser/builtin/functions.ts (1)

35-36: Consider clarifying the purpose of signatures.

It’s not immediately clear that this array is being used to store both the return type and parameter types. A more descriptive name (e.g., resolvedTypes) or explanatory comment could improve readability.

tests/src/shader-lab/ShaderLab.test.ts (1)

21-42: Consider isolating or documenting common macros.

Defining the macros inline with the test is convenient, but future expansions might complicate the file. Consider extracting them into a separate constants file or adding doc comments.

tests/src/shader-lab/ShaderValidate.ts (1)

93-97: Consider adding specific test cases for generic type deduction.

Given that this PR fixes a bug with generic type deduction for the clamp function, it would be valuable to add specific test cases that verify:

  1. Correct type deduction for vec3 clamp(vec3, float, float)
  2. Error cases for incorrect type usage

Would you like me to help create test cases that specifically validate the generic type deduction fix for the clamp function?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90c3228 and 15eb742.

⛔ Files ignored due to path filters (2)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • tests/src/shader-lab/shaders/builtin-function.shader is excluded by !**/*.shader
📒 Files selected for processing (6)
  • packages/shader-lab/src/parser/AST.ts (1 hunks)
  • packages/shader-lab/src/parser/builtin/functions.ts (3 hunks)
  • tests/package.json (1 hunks)
  • tests/src/shader-lab/ShaderLab.test.ts (3 hunks)
  • tests/src/shader-lab/ShaderValidate.ts (1 hunks)
  • tests/vitest.config.ts (1 hunks)
🔇 Additional comments (9)
packages/shader-lab/src/parser/builtin/functions.ts (3)

67-67: Refine function signature for clarity.

The updated getFn method uses clearer parameter naming (parameterTypes). This improves maintainability by making the signature more explicit.


89-97: Validate type matching logic fully.

Proceeding with found = true if each compared type matches or is generic is correct. However, for more complex scenarios (e.g., multiple generics in a single built-in), you may need additional checks. If you anticipate more generics, consider systematically storing type mappings.


261-262: Confirm return type for texture2D.

Changing the return from SAMPLER2D to VEC4 aligns with GLSL usage (sampler2D typically returns vec4). Ensure that no other parts of the code still expect the deprecated return type.

tests/vitest.config.ts (1)

22-22: Ensure that running in non-headless mode meets CI requirements.

Removing the headless: true option can be beneficial for interactive debugging, but might break or slow automated CI pipelines. Verify that CI supports the new setting.

tests/src/shader-lab/ShaderLab.test.ts (2)

12-12: New import for registerIncludes.

This import is necessary for the new macros and include registration. Ensure that the underlying library is installed and well-documented in the test setup instructions.


150-156: Test coverage for built-in functions.

Introducing the "builtin-function" test is a good step. Confirm coverage includes scenarios where clamp with vector parameters is used, matching the PR’s objective about correct type deduction.

Would you like an additional test focusing specifically on clamp(vec3, float, float) usage?

packages/shader-lab/src/parser/AST.ts (2)

704-704: Retrieve built-in function carefully.

getFn(fnIdent, paramSig) may return undefined; ensure you handle that scenario before proceeding. Otherwise, an error might occur on the following lines.


706-706: Safely use builtinFn.realReturnType.

After verifying builtinFn is not null, using builtinFn.realReturnType is appropriate. Good job aligning this AST logic with the newly introduced property in BuiltinFunction.

tests/package.json (1)

26-27: Added @galacean/engine-shader-shaderlab dependency.

This is essential for the new shader-lab tests and macros. Verify that the version is pinned correctly to avoid mismatches during local or CI builds.

packages/shader-lab/src/parser/builtin/functions.ts Outdated Show resolved Hide resolved
tests/src/shader-lab/ShaderValidate.ts Show resolved Hide resolved
@Sway007 Sway007 changed the title Fix generic type deduce bug in ShaderLab compiler of verbose mode Fix generic type deduce bug of ShaderLab compiler in verbose mode Dec 25, 2024
tests/vitest.config.ts Outdated Show resolved Hide resolved
packages/shader-lab/src/parser/builtin/functions.ts Outdated Show resolved Hide resolved
packages/shader-lab/src/parser/builtin/functions.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
tests/src/shader-lab/ShaderLab.test.ts (2)

21-41: Add documentation for shader macros.

While the macro definitions are well-structured, adding documentation would improve maintainability by explaining:

  • The purpose of each macro
  • When each macro should be enabled/disabled
  • The impact of each macro on shader behavior

150-150: Add error handling for include registration.

Consider wrapping the registerIncludes() call in a try-catch block to handle potential registration failures gracefully.

- registerIncludes();
+ try {
+   registerIncludes();
+ } catch (error) {
+   console.error('Failed to register shader includes:', error);
+   throw error;
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15eb742 and 1171cf8.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • packages/shader-lab/src/parser/AST.ts (1 hunks)
  • packages/shader-lab/src/parser/builtin/functions.ts (3 hunks)
  • tests/package.json (1 hunks)
  • tests/src/shader-lab/ShaderLab.test.ts (3 hunks)
  • tests/src/shader-lab/ShaderValidate.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/package.json
  • tests/src/shader-lab/ShaderValidate.ts
  • packages/shader-lab/src/parser/AST.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: lint
  • GitHub Check: build (22.x, windows-latest)
  • GitHub Check: e2e (22.x)
  • GitHub Check: build (22.x, macos-latest)
  • GitHub Check: codecov
🔇 Additional comments (5)
packages/shader-lab/src/parser/builtin/functions.ts (4)

67-85: LGTM: Generic type deduction logic looks correct.

The implementation properly handles generic parameter type matching, which should fix the type deduction bug mentioned in the PR objectives.


261-262: LGTM: Correct texture2D return type.

The change to return VEC4 instead of SAMPLER2D aligns with the GLSL specification where texture2D returns a vec4.


35-39: ⚠️ Potential issue

Add safety check for empty signatures array.

The realReturnType getter could return undefined if signatures is empty, potentially causing runtime errors.

Apply this diff to add a safety check:

  get realReturnType(): NonGenericGalaceanType {
-   return this.signatures[0];
+   return this.signatures.length > 0 ? this.signatures[0] : TypeAny;
  }

Likely invalid or redundant comment.


89-96: 🛠️ Refactor suggestion

Consider immutable approach to prevent shared state issues.

Modifying the shared signatures array could cause issues with concurrent calls or re-entrancy.

Apply this diff to create a new instance instead:

  if (found) {
-   fn.signatures.length = 0;
-   fn.signatures.push(returnType);
-   for (let i = 0; i < argLength; i++) {
-     fn.signatures.push(parameterTypes[i]);
-   }
-   return fn;
+   const newFn = new BuiltinFunction(fn.ident, fn._returnType, fn.scope, ...fn.args);
+   newFn.signatures.push(returnType);
+   for (let i = 0; i < argLength; i++) {
+     newFn.signatures.push(parameterTypes[i]);
+   }
+   return newFn;
  }

Likely invalid or redundant comment.

tests/src/shader-lab/ShaderLab.test.ts (1)

12-12: LGTM!

The import statement follows the project's import style and is required for the new test functionality.

Comment on lines +153 to +156
it("builtin-function", async () => {
let shaderSource = await readFile("./shaders/builtin-function.shader");
shaderSource = shaderSource.replace("__$$insert_maros$$__", commonMacros);
glslValidate(shaderSource, shaderLabVerbose, {});
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Review comment is accurate - test needs improvement

The test case doesn't properly validate the generic type deduction bug fix. The shader file doesn't contain any specific tests for the clamp function with vector types, and the test only verifies basic shader compilation. The original review suggestions remain valid:

  1. Add explicit test cases using clamp with vec3 parameters
  2. Include assertions to verify correct type inference
  3. Add error cases with type mismatches
🔗 Analysis chain

Enhance test coverage for the generic type deduction bug.

The current test case doesn't fully validate the fix for the generic type deduction bug. Consider:

  1. Adding specific assertions to verify the correct type inference for the clamp function
  2. Including test cases for both correct and incorrect generic type deductions
  3. Adding error cases to ensure the compiler properly handles type mismatches

Run this script to check if the test shader contains the relevant clamp function usage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if the test shader contains the clamp function usage with vec3 type
# Expected: Find usage of clamp with vec3 parameter

rg -A 3 'clamp\s*\(\s*vec3' ./shaders/builtin-function.shader

Length of output: 137


Script:

#!/bin/bash
# Find all shader files in the repository
fd -e shader

# If no .shader files found, try looking for common shader extensions
fd -e glsl -e vert -e frag

Length of output: 7753


Script:

#!/bin/bash
# Check the content of builtin-function shader
cat tests/src/shader-lab/shaders/builtin-function.shader

# Also search for any clamp usage in other shader files for context
rg "clamp\s*\(" --type glsl -A 2

Length of output: 1046


Script:

#!/bin/bash
# Search for clamp usage in all files without type restriction
rg "clamp\s*\(" -A 2

# Check the content of ForwardPassPBR.glsl
cat packages/shader-shaderlab/src/shaders/shadingPBR/ForwardPassPBR.glsl

Length of output: 27020

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1171cf8 and 1f2414a.

📒 Files selected for processing (1)
  • packages/shader-lab/src/parser/builtin/functions.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (22.x, windows-latest)
  • GitHub Check: e2e (22.x)
  • GitHub Check: codecov
🔇 Additional comments (3)
packages/shader-lab/src/parser/builtin/functions.ts (3)

35-40: LGTM! Clean implementation of return type storage.

The addition of _realReturnType and its getter provides a clean way to store and access the concrete return type after generic type deduction.


258-259: LGTM! Correct texture2D return type.

The updated signatures now correctly specify VEC4 as the return type for texture2D functions, aligning with the GLSL specification.


68-94: Verify the generic type deduction with test cases.

The refactored implementation correctly handles generic type deduction, particularly fixing the clamp function issue. However, let's verify the changes with different function signatures.

Run the following script to find all generic function calls that could be affected:

✅ Verification successful

Generic type deduction implementation is correct and comprehensive.

The implementation correctly handles all generic function patterns found in the codebase, including:

  • Single generic parameter functions (e.g., sin, cos)
  • Multiple generic parameters (e.g., clamp, mix)
  • Mixed generic and non-generic parameters (e.g., step, texture)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all generic function calls in shader files
# Look for function calls with generic types (GenType, GenIntType, etc.)

ast-grep --pattern 'EGenType.$_'

Length of output: 24154

@GuoLei1990 GuoLei1990 merged commit ec6ca8c into galacean:dev/1.4 Jan 9, 2025
8 of 9 checks passed
@Sway007 Sway007 deleted the fix/builtin/type_deduce branch January 9, 2025 06:38
@coderabbitai coderabbitai bot mentioned this pull request Jan 23, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working medium priority Medium priority issue Rendering Rendering related functions shader Shader related functions
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants