Skip to content

cb.IsTupleType#573

Merged
xushiwei merged 2 commits intogoplus:mainfrom
xushiwei:q
Jan 22, 2026
Merged

cb.IsTupleType#573
xushiwei merged 2 commits intogoplus:mainfrom
xushiwei:q

Conversation

@xushiwei
Copy link
Member

No description provided.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @xushiwei, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors and enhances the type checking mechanism for tuples within the CodeBuilder system. It introduces a new public API IsTupleType for clearer tuple identification and centralizes the underlying detection logic, making it more robust by explicitly checking for internal tuple naming conventions. These changes improve the clarity and reliability of tuple type handling.

Highlights

  • New Public API for Tuple Type Checking: Introduced a new public method CodeBuilder.IsTupleType which allows external code to determine if a given types.Type represents a tuple.
  • Refactored Tuple Detection Logic: The core logic for identifying tuple types has been extracted and refactored into a new private function checkTupleType. This function now includes a more robust check by verifying the naming convention of the first field in a types.Struct to confirm it's a tuple.
  • Updated Tuple Unpacking Mechanism: The tryUnpackTuple function has been updated to utilize the new checkTupleType function, ensuring consistency and leveraging the improved tuple identification logic.
  • New Unit Test for IsTupleType: A dedicated unit test TestIsTupleType has been added to validate the correct behavior of the newly introduced CodeBuilder.IsTupleType method, specifically ensuring it correctly identifies non-tuple structs.
  • Minor Code Refactoring: A small refactoring was performed in MethodToFunc to assign p.cb to a local variable cb for improved readability and conciseness.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@codecov
Copy link

codecov bot commented Jan 22, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.10%. Comparing base (4d87d11) to head (dca9f10).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #573      +/-   ##
==========================================
- Coverage   96.10%   96.10%   -0.01%     
==========================================
  Files          25       25              
  Lines        6838     6837       -1     
==========================================
- Hits         6572     6571       -1     
  Misses        198      198              
  Partials       68       68              

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

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

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the tuple type checking logic by introducing a new public method IsTupleType and a helper function checkTupleType. This improves the API for checking tuple types. The changes also include updates to tryUnpackTuple to use the new logic and a new test case for IsTupleType. My review includes a suggestion to simplify the implementation of checkTupleType for better readability and a small improvement to a test's failure message for better diagnostics.

Comment on lines +112 to 125
func checkTupleType(typ types.Type) (result *types.Struct) {
if t, ok := typ.(*types.Named); ok {
result, _ = t.Underlying().(*types.Struct)
} else {
result, _ = typ.(*types.Struct)
}
if result != nil {
n := result.NumFields()
if n > 0 && result.Field(0).Name() != tupleFieldName(0) {
result = nil
}
}
return nil, false
return
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The implementation of checkTupleType can be simplified. The Underlying() method on types.Type handles both named and non-named types, so you can avoid the explicit type check for *types.Named.

func checkTupleType(typ types.Type) (result *types.Struct) {
	result, _ = typ.Underlying().(*types.Struct)
	if result != nil {
		if result.NumFields() > 0 && result.Field(0).Name() != tupleFieldName(0) {
			result = nil
		}
	}
	return
}

Comment on lines +29 to +31
if cb.IsTupleType(types.NewStruct(flds, nil)) {
t.Fatal("TestIsTupleType: failed")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The test failure message could be more descriptive. A more specific message will help diagnose failures more quickly, improving maintainability.

Suggested change
if cb.IsTupleType(types.NewStruct(flds, nil)) {
t.Fatal("TestIsTupleType: failed")
}
if cb.IsTupleType(types.NewStruct(flds, nil)) {
t.Fatal("IsTupleType returned true for a struct with non-tuple field names")
}

}
return nil, false
return
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Critical Issue: Logic Change Breaks Tuple Type Detection

The refactored checkTupleType() has fundamentally different behavior from the original:

Old Logic: Checked if struct was registered in vfts map (explicit opt-in)
New Logic: Checks if first field name matches "X_0" (pattern matching)

Problems:

  1. False positives: Any struct with field named "X_0" will be treated as a tuple, even if not created via Package.NewTuple():
type MyStruct struct {
    X_0 int  // User-defined field
    Foo string
}
// This would incorrectly be identified as a tuple type
  1. Missing virtual fields: Returns *types.Struct instead of *tupleFields, losing access to virtual field information (original field names when withName=true)

  2. Inconsistency: LookupField() at line 164-178 still uses vfts map for virtual fields

Recommendation: Restore map-based lookup to maintain correct behavior and prevent false positives.

// IsTupleType reports whether typ is a tuple type.
func (p *CodeBuilder) IsTupleType(typ types.Type) bool {
return checkTupleType(typ) != nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Documentation Issue: Incomplete Godoc

The documentation doesn't explain what constitutes a "tuple type" in gogen. Users need to understand the field naming convention.

Suggested improvement:

// IsTupleType reports whether typ is a tuple type.
// A tuple type is a struct type where all fields are named with the ordinal
// pattern X_0, X_1, X_2, etc., as created by Package.NewTuple.
// This includes both underlying struct types and named types wrapping them.

if cb.IsTupleType(types.NewStruct(flds, nil)) {
t.Fatal("TestIsTupleType: failed")
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Test Coverage Issue: Missing Positive Cases

The test only validates the negative case. Missing test cases for:

  1. Positive case: Actual tuple types created via pkg.NewTuple() should return true
  2. Named tuple types: Testing with types.Named wrapper
  3. Empty struct edge case: Struct with zero fields
  4. Tuple with virtual names: When withName=true

Suggested addition:

func TestIsTupleType(t *testing.T) {
    pkg := newMainPackage()
    cb := pkg.CB()
    
    // Test 1: Non-tuple struct
    x := types.NewField(token.NoPos, nil, "x", types.Typ[types.Int], false)
    y := types.NewField(token.NoPos, nil, "y", types.Typ[types.Int], false)
    notTuple := types.NewStruct([]*types.Var{x, y}, nil)
    if cb.IsTupleType(notTuple) {
        t.Fatal("Non-tuple struct incorrectly identified as tuple")
    }
    
    // Test 2: Actual tuple type
    tupleType := pkg.NewTuple(false, x, y)
    if !cb.IsTupleType(tupleType) {
        t.Fatal("Tuple type not recognized")
    }
    
    // Test 3: Named tuple type
    namedTuple := types.NewNamed(
        types.NewTypeName(token.NoPos, pkg.Types, "Point", tupleType),
        tupleType, nil)
    if !cb.IsTupleType(namedTuple) {
        t.Fatal("Named tuple type not recognized")
    }
}

type_tuple.go Outdated
}
if result != nil {
n := result.NumFields()
if n > 0 && result.Field(0).Name() != tupleFieldName(0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Performance Concern: String Comparison on Every Call

OLD approach: O(1) hash map lookup in p.vfts[typ] - single operation

NEW approach:

  • Performs string comparison result.Field(0).Name() != tupleFieldName(0) on every invocation
  • String construction via tupleFieldName(0)"X_" + strconv.Itoa(0)

Impact: This function is called in hot paths during tuple unpacking, member access, and field reference operations. Every struct type now undergoes field inspection + string comparison instead of a cached map lookup.

Suggestion: Consider pre-computing the constant "X_0" or restoring the map-based caching approach for better performance.

@xgopilot
Copy link
Contributor

xgopilot bot commented Jan 22, 2026

Code Review Summary

This PR adds IsTupleType() and refactors tuple type checking. The refactoring improves code organization, but introduces a critical logic change that needs attention.

Critical Issue:
The refactored checkTupleType() changed from map-based lookup to field pattern matching. This creates false positives—any struct with an X_0 field will be treated as a tuple, even if not created via Package.NewTuple(). This also loses virtual field support for withName=true tuples.

Other Issues:

  • Insufficient test coverage (missing positive test cases)
  • Performance degradation (string comparison vs cached map lookup on hot paths)
  • Incomplete documentation for the new public API

Positive Aspects:

  • Improved code structure and nil safety
  • Good separation of concerns
  • Cleaner function signatures

Please see inline comments for detailed recommendations.

@xushiwei xushiwei merged commit b894bf8 into goplus:main Jan 22, 2026
23 checks passed
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