Skip to content

Add support for visual studio.#88

Merged
HavenDV merged 3 commits intotryAGI:mainfrom
paule96:try_to_fix_cycling_generics
May 9, 2025
Merged

Add support for visual studio.#88
HavenDV merged 3 commits intotryAGI:mainfrom
paule96:try_to_fix_cycling_generics

Conversation

@paule96
Copy link
Contributor

@paule96 paule96 commented May 9, 2025

Fixes: #87

This pull request introduces several changes to enhance type handling and serialization in the AutoSDK library. The most notable updates include the addition of a Box struct to encapsulate generic types, updates to various models to use Box for type safety, and improvements to error handling and documentation.

Enhancements to type handling:

  • Added a new Box struct and corresponding extension methods (Box and Unbox) in src/libs/AutoSDK/Helpers/Box.cs. This struct is used to encapsulate value or reference types, improving type safety and resolving issues with generic type cycling in structs.

  • Updated ModelData, TypeData, and PropertyData in src/libs/AutoSDK/Models to use Box for handling nested types (Parents and SubTypes). This ensures better encapsulation and simplifies type operations. [1] [2] [3]

Serialization and query parameter improvements:

  • Modified serialization logic in ParameterSerializer.cs to use Unbox when accessing boxed TypeData in query parameter handling. This ensures the correct type is used during serialization. [1] [2]

  • Updated SystemTextJsonSerializer.cs to handle boxed SubTypes during JSON serialization, ensuring compatibility with the new Box structure.

Code generation updates:

  • Updated methods in Sources.Methods.cs and Sources.Models.cs to use Unbox for accessing properties of boxed types, ensuring proper handling of nested types during code generation. [1] [2]

Documentation updates:

  • Added a "Known Errors" section to README.md to document a common generator error related to long file paths on Windows and provide a solution for enabling long path support.

Summary by CodeRabbit

  • New Features

    • Introduced a "Known Errors" section in the documentation, providing guidance on resolving specific generator errors related to long file paths on Windows.
  • Refactor

    • Updated internal data handling by introducing a new boxing mechanism for certain model properties, requiring explicit unboxing when accessing subtype or parent data. This change does not affect the external API or user-facing functionality.
  • Documentation

    • Enhanced README with troubleshooting information and links to official Microsoft documentation for resolving path length issues on Windows.

@coderabbitai
Copy link

coderabbitai bot commented May 9, 2025

Error: Could not generate a valid Mermaid diagram after multiple attempts.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@CLAassistant
Copy link

CLAassistant commented May 9, 2025

CLA assistant check
All committers have signed the CLA.

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 (8)
src/libs/AutoSDK/Helpers/Box.cs (1)

54-63: Missing ToString override for debugging

The class implements equality operators correctly but is missing a ToString override which would be helpful for debugging.

Consider adding a ToString override to make debugging easier:

+ public override string ToString()
+ {
+     return Value?.ToString() ?? "null";
+ }
README.md (1)

115-122: Fix grammatical and formatting issues in "Known Errors" section

The new section correctly documents the long path issue but contains several grammar and formatting errors.

 ## Known Errors
 
 ### Generator error: "Could not write to output file 'Path/to/file'. Could not find part of the path"
 
-This error happens if the generated file path is too long. This happens if you didn't activated long path support on windows.
-To enable it follow the offical docs:
-https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry#registry-setting-to-enable-long-paths
+This error happens if the generated file path is too long. This happens if you haven't activated long path support on Windows.
+To enable it, follow the official docs:
+[Enable long path support in Windows](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry#registry-setting-to-enable-long-paths)
🧰 Tools
🪛 LanguageTool

[uncategorized] ~119-~119: Did you mean “activate”?
Context: ...is too long. This happens if you didn't activated long path support on windows. To enable...

(DOESNT_WITH_WRONG_VERB_FORM)


[grammar] ~119-~119: “Windows” (operating system by Microsoft) is a proper noun and needs to be capitalized.
Context: ...u didn't activated long path support on windows. To enable it follow the offical docs: ...

(A_WINDOWS)


[uncategorized] ~120-~120: A comma might be missing here.
Context: ...long path support on windows. To enable it follow the offical docs: https://learn....

(AI_EN_LECTOR_MISSING_PUNCTUATION_COMMA)


[uncategorized] ~120-~120: A punctuation mark might be missing here.
Context: ...s. To enable it follow the offical docs: https://learn.microsoft.com/en-us/window...

(AI_EN_LECTOR_MISSING_PUNCTUATION)

🪛 markdownlint-cli2 (0.17.2)

121-121: Bare URL used
null

(MD034, no-bare-urls)

src/libs/AutoSDK/Models/PropertyData.cs (1)

48-52: Avoid duplicate unboxing for readability & micro-perf

type.SubTypes[0].Unbox<TypeData>() is executed twice. Caching the unboxed value trims a method call, makes the intent clearer, and prevents accidental divergence if future edits mutate the copy.

-            type = type.SubTypes[0].Unbox<TypeData>() with
-            {
-                CSharpTypeRaw = type.SubTypes[0].Unbox<TypeData>().CSharpTypeRaw,
+            var metadataType = type.SubTypes[0].Unbox<TypeData>();
+            type = metadataType with
+            {
+                CSharpTypeRaw = metadataType.CSharpTypeRaw,
src/libs/AutoSDK/Sources/Sources.Models.cs (1)

44-47: Cache the unboxed parent to cut repetition

modelData.Parents[level].Unbox<ModelData>() is evaluated twice in this small block (inside the interpolated string and again inside GenerateModel). Pulling it into a local variable both simplifies the interpolation and avoids an extra struct copy:

-public sealed partial class {modelData.Parents[level].Unbox<ModelData>().ClassName}
+{
+    var parent = modelData.Parents[level].Unbox<ModelData>();
+}
+public sealed partial class {parent.ClassName}

(Adjust surrounding code accordingly.)

src/libs/AutoSDK/Models/TypeData.cs (1)

86-91: Pre-compute sub-type strings to avoid multiple enumerations

SubTypes.Select(y => y.Unbox<TypeData>().CSharpTypeWithNullabilityForValueTypes) is evaluated up to three times in this conditional chain. For large unions this results in repeated allocations & enumerations.

-                : AnyOfCount > 0
-                    ? $"global::{Settings.Namespace}.JsonConverters.AnyOfJsonConverter<{string.Join(", ", SubTypes.Select(y => y.Unbox<TypeData>().CSharpTypeWithNullabilityForValueTypes))}>"
-                    : OneOfCount > 0
-                        ? $"global::{Settings.Namespace}.JsonConverters.OneOfJsonConverter<{string.Join(", ", SubTypes.Select(y => y.Unbox<TypeData>().CSharpTypeWithNullabilityForValueTypes))}>"
-                        : AllOfCount > 0
-                            ? $"global::{Settings.Namespace}.JsonConverters.AllOfJsonConverter<{string.Join(", ", SubTypes.Select(y => y.Unbox<TypeData>().CSharpTypeWithNullabilityForValueTypes))}>"
+                : SubTypes.Length == 0
+                    ? string.Empty
+                    : BuildCompositeConverter(
+                        string.Join(", ", SubTypes
+                            .Select(static y => y.Unbox<TypeData>().CSharpTypeWithNullabilityForValueTypes)))

and then introduce a small helper BuildCompositeConverter(...) to pick the correct generic type.

Besides the perf gain, the resulting string interpolation becomes easier to read.

src/libs/AutoSDK/Sources/Sources.Methods.cs (3)

238-244: Avoid repeated unboxing & tighten null-safety

subType.Unbox<TypeData>() is invoked twice in very close proximity.
Besides the tiny performance hit, it slightly obscures readability and makes it easier to miss a possible null-return of Unbox<T>().

-var subType = property.Type.SubTypes.First();
-var additionalConvertSubtype = subType.Unbox<TypeData>().IsEnum
+var subTypeBox  = property.Type.SubTypes.First();
+var subType     = subTypeBox.Unbox<TypeData>(); // unbox once
+var additionalConvertSubtype = subType.IsEnum

The same pattern occurs further below (see lines 275-295).
Extracting the unboxed value once – or introducing a small helper such as GetFirstSubType() – will improve clarity and remove duplicated calls.


275-280: Duplicated Unbox<>() and possible out-of-range access

(!x.Type.IsArray || (x.Type.SubTypes[0].Unbox<TypeData>().Properties.Length == 0 &&
                     !x.Type.SubTypes[0].Unbox<TypeData>().IsArray))
  1. SubTypes[0] is accessed twice and assumes the array is non-empty.
    Although an array type should have at least one subtype, it is safer (and clearer) to cache the first item or guard against an empty collection.

  2. Two identical Unbox<TypeData>() calls are executed back-to-back – the second yields no new information.

A readable & safe alternative:

-var cond = !x.Type.IsArray || (x.Type.SubTypes[0].Unbox<TypeData>().Properties.Length == 0 &&
-                               !x.Type.SubTypes[0].Unbox<TypeData>().IsArray);
+var cond = !x.Type.IsArray || x.Type.SubTypes.Length == 0 ||
+           (x.Type.SubTypes[0].Unbox<TypeData>() is { Properties.Length: 0, IsArray: false });

This eliminates the duplicate unboxing and removes the hidden assumption that SubTypes is always populated.


290-296: Single unboxing preferred for selector condition

Same observation as above: the expression

parameter.Type.SubTypes[0].Unbox<TypeData>().CSharpTypeWithoutNullability

is evaluated twice (once in the if and once in the interpolated string).
Store the unboxed instance in a local variable so that the intention (“only non-string element arrays need a selector”) is more explicit and the code performs just one unboxing call.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 56fb5f8 and b3e97d1.

📒 Files selected for processing (9)
  • README.md (1 hunks)
  • src/libs/AutoSDK/Helpers/Box.cs (1 hunks)
  • src/libs/AutoSDK/Models/ModelData.cs (4 hunks)
  • src/libs/AutoSDK/Models/PropertyData.cs (4 hunks)
  • src/libs/AutoSDK/Models/TypeData.cs (12 hunks)
  • src/libs/AutoSDK/Serialization/Form/ParameterSerializer.cs (7 hunks)
  • src/libs/AutoSDK/Serialization/Json/SystemTextJsonSerializer.cs (6 hunks)
  • src/libs/AutoSDK/Sources/Sources.Methods.cs (20 hunks)
  • src/libs/AutoSDK/Sources/Sources.Models.cs (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/libs/AutoSDK/Serialization/Form/ParameterSerializer.cs (1)
src/libs/AutoSDK/Models/TypeData.cs (1)
  • TypeData (93-199)
src/libs/AutoSDK/Serialization/Json/SystemTextJsonSerializer.cs (3)
src/libs/AutoSDK.CLI/Helpers.cs (1)
  • Helpers (3-12)
src/libs/AutoSDK/Extensions/OpenApiSchemaExtensions.cs (3)
  • IsBase64 (64-70)
  • IsBinary (88-94)
  • IsArray (38-45)
src/libs/AutoSDK/Models/TypeData.cs (1)
  • TypeData (93-199)
🪛 LanguageTool
README.md

[uncategorized] ~119-~119: Did you mean “activate”?
Context: ...is too long. This happens if you didn't activated long path support on windows. To enable...

(DOESNT_WITH_WRONG_VERB_FORM)


[grammar] ~119-~119: “Windows” (operating system by Microsoft) is a proper noun and needs to be capitalized.
Context: ...u didn't activated long path support on windows. To enable it follow the offical docs: ...

(A_WINDOWS)


[uncategorized] ~120-~120: A comma might be missing here.
Context: ...long path support on windows. To enable it follow the offical docs: https://learn....

(AI_EN_LECTOR_MISSING_PUNCTUATION_COMMA)


[uncategorized] ~120-~120: A punctuation mark might be missing here.
Context: ...s. To enable it follow the offical docs: https://learn.microsoft.com/en-us/window...

(AI_EN_LECTOR_MISSING_PUNCTUATION)

🪛 markdownlint-cli2 (0.17.2)
README.md

121-121: Bare URL used
null

(MD034, no-bare-urls)

🔇 Additional comments (13)
src/libs/AutoSDK/Helpers/Box.cs (5)

3-13: BoxEtensions class implements clean extension methods for boxing/unboxing

The extension methods are well-designed for their purpose of boxing/unboxing values to avoid generic type cycling issues.


15-22: Well-documented Box struct with clear purpose

The documentation clearly explains the purpose of the Box struct and references the relevant .NET runtime issue. This information is valuable for maintainers who may question why this structure exists.


22-30: Box implementation provides simple value encapsulation

The Box struct is correctly implemented as a lightweight wrapper around an object value. The public property provides direct access to the boxed value.


31-42: Equals implementation uses reference equality for comparison

The Equals method correctly implements reference equality comparison for boxed values. Note that this means two boxes containing equal value types (like int) but boxed separately would be considered not equal.

Consider whether value equality might be more appropriate in some scenarios, especially for value types. Reference equality works well for reference types but could be surprising for value types.


44-52: IEquatable and GetHashCode implementations are correct

Both the IEquatable.Equals implementation and GetHashCode are implemented correctly. GetHashCode properly handles null values.

src/libs/AutoSDK/Serialization/Json/SystemTextJsonSerializer.cs (3)

2-2: Adding required Helpers namespace

Good addition of the AutoSDK.Helpers namespace to support the new Box unboxing functionality.


63-88: Improved readability with pattern matching using braces

The switch expression has been formatted with braces and indentation, making it more readable without changing the functionality.


90-90: Added unboxing for TypeData subtypes

The code now properly unboxes each subtype before passing it to GetContextType, which is necessary due to the move to boxed subtypes throughout the codebase.

src/libs/AutoSDK/Serialization/Form/ParameterSerializer.cs (3)

2-2: Adding required Helpers namespace

Good addition of the AutoSDK.Helpers namespace to support the Box unboxing functionality.


130-130: Added unboxing for array subtypes

The code now properly unboxes the subtype of array parameters using Unbox() before processing it, which is necessary after the move to Box-based subtypes.


149-154: Improved readability with multi-line formatting

The property value construction has been reformatted to use multi-line formatting, improving readability without changing functionality.

src/libs/AutoSDK/Models/PropertyData.cs (1)

55-57: [] collection expression may require LangVersion=preview

[] relies on the C# 12 collection-expression feature. Unless the project is already compiling with /langversion:preview (or using the upcoming .NET 9 SDK where this feature comes out of preview), older toolchains will fail to build here.

If broad compiler compatibility is desired, fall back to the explicit constructor:

-            : []
+            : new HashSet<string>()  // or `HashSet<string>.Empty` when available
src/libs/AutoSDK/Models/ModelData.cs (1)

46-47: LGTM – parents boxed correctly

Converting the parent list with .Select(p => p.Box()) ensures uniform ImmutableArray<Box> storage and keeps the struct cycle breaker localised. No issues spotted.

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.

Source generator misses a type info for ModelData

3 participants