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

Generic behaviour adaptations #249

Merged
merged 7 commits into from
Jun 26, 2024
Merged

Generic behaviour adaptations #249

merged 7 commits into from
Jun 26, 2024

Conversation

0xF6
Copy link
Member

@0xF6 0xF6 commented Jun 26, 2024

Summary by CodeRabbit

  • New Features

    • Consolidated print method in the Out class into a single generic method for increased flexibility.
    • Added new delMethod and abobus methods, and a global alias testMethod in the Testable class.
  • Bug Fixes

    • Improved type handling and validation for generic types in field generation.
  • Improvements

    • Enhanced exception messages in ConvertNotSupportedException by using template strings.
    • Refined type compatibility checks across multiple runtime components to support generic types.
    • Simplified method and field type handling by switching to a unified VeinComplexType.
  • Refactor

    • Updated method signatures and internal logic to handle complex and generic types more effectively.
    • Optimized field and method definition processes to streamline the runtime's reflection capabilities.
  • Documentation

    • Updated method and property signatures across various classes for clarity and consistency.

@0xF6 0xF6 added area-vm Area of virtual machine area-lexer Area of lexer tree labels Jun 26, 2024
Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Walkthrough

The changes introduce improvements to generic type handling, error logging, and type compatibility in various components of the system. Key updates include modifying method signatures and type checks to accommodate VeinComplexType, refactoring field and method handling, and simplifying method definitions using generics. The improvements primarily focus on ensuring better compatibility and robustness when dealing with generic types across compilation, runtime, and reflection modules.

Changes

File/Path Change Summary
compiler/compilation/parts/bodies.cs Updated the logic for emitting OpCodes.RET considering generics.
compiler/compilation/parts/fields.cs Modified field flag generation and type validation for generics.
lib/vein.std/std/Out.vein Consolidated print methods into a single generic method.
lib/vein.std/std/Testable.vein Added new methods and a global alias, updated existing methods.
runtime/common/exceptions/... Refactored exception message construction with generics.
runtime/common/reflection/Vein... Updated to use VeinComplexType instead of VeinClass.
runtime/ishtar.base/emit/... Refactored type handling to use WriteComplexType.
runtime/ishtar.generator/generators/... Added generic type handling and error logging in statements.
runtime/ishtar.vm/runtime/vm/... Updated field type and method handling with RuntimeComplexType.

Sequence Diagram(s)

Sequence Diagram for PostgenerateBody Method Changes

sequenceDiagram
    participant MB as MethodBuilder
    participant G as ILGenerator
    participant M as Method

    MB ->> G: Check _opcodes
    alt No opcodes and ReturnType is generic
        G ->> MB: Emit RET
    else No opcodes and ReturnType is not generic and VOID
        G ->> MB: Emit RET
    end
    MB ->> M: Finalize Method
Loading

Sequence Diagram for Field Type Validation

sequenceDiagram
    participant FC as FieldComparator
    participant FT as FieldType Validator
    participant F as Field

    FC ->> FT: Validate Field Type (with generics)
    FT -->> FC: Valid/Invalid Type
    FC ->> F: Update Field Flags
Loading

Poem

In fields of code where changes sweep,
The generics now in method deep,
Fields refactored, methods bright,
Bugs are hunted in the night.
Complex types now lead the way,
For a smoother, clearer, coding day.
🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

Copy link
Contributor

@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: 11

Outside diff range and nitpick comments (4)
runtime/ishtar.vm/runtime/vm/RuntimeIshtarField.cs (1)

Line range hint 25-41: Approve changes related to FieldType handling and suggest improvement.

The changes to use RuntimeComplexType for FieldType are in line with the enhancements to the type system. Consider improving the ToString method to handle more complex scenarios.

+ if (FieldType.IsComplex())
+ {
+     return $"Field '{FullName->Name}': Complex Type Handling Needed";
+ }

Also applies to: 127-132

runtime/common/reflection/VeinMethod.cs (1)

Line range hint 68-77: Approve changes related to method signature handling and suggest enhancements.

The updates to handle VeinComplexType in method signatures are well-implemented. Consider further enhancements to improve the flexibility and robustness of method signature generation.

+ public static bool TryParseSignature(string signature, out VeinMethodSignature parsedSignature)
+ {
+     // Implementation to parse a string signature into a VeinMethodSignature
+ }

Also applies to: 93-95

runtime/ishtar.generator/generators/types.cs (1)

Line range hint 95-143: Optimize and refactor DetermineType.

This method is quite complex and could benefit from breaking down into smaller parts or using a strategy pattern for handling different expression types.

compiler/compilation/parts/fields.cs (1)

Line range hint 174-204: Issue: Generic type compatibility check needs refinement.

The logic for checking type compatibility, especially for generics, is crucial but the current implementation might be too restrictive and could benefit from more nuanced handling.

- if (field.FieldType.IsGeneric)
+ if (field.FieldType.IsGeneric && !IsCompatibleGenericType(field.FieldType, literal.GetTypeCode().AsClass()(Types.Storage)))
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2d48e14 and 29f248b.

Files selected for processing (20)
  • compiler/compilation/parts/bodies.cs (1 hunks)
  • compiler/compilation/parts/fields.cs (3 hunks)
  • lib/vein.std/std/Out.vein (1 hunks)
  • lib/vein.std/std/Testable.vein (1 hunks)
  • runtime/common/exceptions/ConvertNotSupportedException.cs (1 hunks)
  • runtime/common/reflection/VeinArgumentRef.cs (2 hunks)
  • runtime/common/reflection/VeinClass.cs (4 hunks)
  • runtime/common/reflection/VeinField.cs (4 hunks)
  • runtime/common/reflection/VeinMethod.cs (3 hunks)
  • runtime/ishtar.base/emit/ClassBuilder.cs (3 hunks)
  • runtime/ishtar.base/emit/MethodBuilder.cs (2 hunks)
  • runtime/ishtar.base/emit/ModuleReader.cs (4 hunks)
  • runtime/ishtar.generator/GeneratorContext.cs (1 hunks)
  • runtime/ishtar.generator/generators/cycles.cs (2 hunks)
  • runtime/ishtar.generator/generators/logic.cs (2 hunks)
  • runtime/ishtar.generator/generators/operators.cs (1 hunks)
  • runtime/ishtar.generator/generators/types.cs (4 hunks)
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarClass.cs (2 hunks)
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarField.cs (4 hunks)
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarModule.cs (5 hunks)
Additional context used
GitHub Check: Codacy Static Code Analysis
runtime/ishtar.generator/GeneratorContext.cs

[notice] 117-117: runtime/ishtar.generator/GeneratorContext.cs#L117
Remove the unused local variable 'index'.

GitHub Check: build_all (windows-latest, win-x64, false)
runtime/ishtar.vm/runtime/vm/RuntimeIshtarModule.cs

[warning] 1153-1153:
The local function 'getTarget' is declared but never used

GitHub Check: build_all (macos-latest, osx-x64, false)
runtime/ishtar.vm/runtime/vm/RuntimeIshtarModule.cs

[warning] 1153-1153:
The local function 'getTarget' is declared but never used

Additional comments not posted (22)
lib/vein.std/std/Out.vein (1)

8-9: Approval of the generic print method

The update to a generic print method simplifies the interface and enhances flexibility by allowing any type to be printed.

runtime/common/exceptions/ConvertNotSupportedException.cs (1)

12-13: Enhanced error message for type conversion issues

The use of ToTemplateString() in the exception message provides a clearer, more informative error description, which is beneficial for debugging. Ensure that ToTemplateString() is robust and handles all expected types correctly.

lib/vein.std/std/Testable.vein (3)

12-13: New method abobus introduced

The introduction of abobus in the master method enhances the testability by allowing dynamic method testing. Ensure that delMethod is properly defined and accessible as expected.


16-17: Addition of delMethod and usage in abobus

The new delMethod function is used within abobus, showcasing an example of how dynamic methods can be tested. This is a good practice for modular testing.

Also applies to: 26-28


31-31: Global alias testMethod defined

Defining a global alias for commonly used test methods can simplify test scripts and enhance readability. Ensure that this alias is used consistently across the project.

runtime/ishtar.generator/generators/cycles.cs (1)

18-22: Improved type checking in loop statements

The introduction of checks for generic types in while and for statements, and the associated error logging, enhances the robustness and debuggability of the language.

Also applies to: 54-59

compiler/compilation/parts/bodies.cs (1)

28-32: Ensure correct handling of return types in bytecode generation.

The changes to handle generic return types are appropriate. However, the comments in the code are unprofessional and should be revised to maintain a professional codebase.

- // fucking shit fucking
+ // TODO: Review and refine the approach for handling return operations in VOID methods.
runtime/ishtar.base/emit/MethodBuilder.cs (1)

Line range hint 47-60: Verify handling of complex return types in method bytecode serialization.

The change to use WriteComplexType for handling complex return types is appropriate. Ensure that this does not introduce serialization or deserialization issues.

Would you like me to write unit tests to ensure the correctness of WriteComplexType?

Verification successful

The handling of complex return types in method bytecode serialization appears to be correctly implemented. The WriteComplexType method properly distinguishes between generic and non-generic types and writes the appropriate information to the binary writer. Therefore, no serialization or deserialization issues are expected from this change.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `WriteComplexType` method correctly handles complex return types during serialization.

# Test: Serialize a method with a complex return type and check the output.
rg --type csharp $'WriteComplexType'

Length of output: 652



Script:

#!/bin/bash
# Extracting the implementation of the WriteComplexType method to verify its logic
ast-grep --lang csharp --pattern $'public static void WriteComplexType(this BinaryWriter bin, VeinComplexType type, VeinModuleBuilder module) {
  $$$
}' 

Length of output: 153



Script:

#!/bin/bash
# Searching for the WriteComplexType method and extracting its implementation
rg --type cs --pcre2 --context 10 'public static void WriteComplexType\(this BinaryWriter bin, VeinComplexType type, VeinModuleBuilder module\)' 

Length of output: 1988

runtime/common/reflection/VeinField.cs (2)

133-137: Approved the changes in VeinField constructor.

The modifications to use VeinComplexType are consistent with the overall goal of enhancing type handling.


116-117: Verify static property handling in VeinProperty.RestoreFrom.

The handling of static properties using different argument arrays for getter and setter methods seems correct, but ensure that this logic is consistently applied wherever similar patterns are used.

runtime/ishtar.generator/generators/types.cs (2)

85-93: Approved the changes in DetermineTypes.

The method's conversion to use VeinComplexType and the filtering logic for non-null types are both sound.


167-170: Verify generic type handling in ResolveReturnType.

Ensure that the handling of generic types in this method is consistent with other parts of the system that resolve return types.

runtime/ishtar.base/emit/ClassBuilder.cs (1)

Line range hint 198-217: Approved the changes in binary writing and debug string generation.

The modifications to use WriteComplexType for field types and the update to debug string output are well-implemented and align with the overall improvements in type handling.

runtime/ishtar.generator/generators/operators.cs (1)

33-46: Improved handling of generic types in binary expressions.

The changes introduce error handling for implicit conversions of generic types, which enhances type safety. Consider providing more specific error messages based on the context of the conversion failure.

runtime/common/reflection/VeinClass.cs (1)

38-41: Addition of a debug-only constructor.

The new constructor captures the stack trace, which is useful for debugging object creation. This is correctly wrapped in a DEBUG directive, ensuring no impact on production performance.

runtime/ishtar.base/emit/ModuleReader.cs (1)

Line range hint 289-313: Proper handling of generic types in module reading.

The changes ensure that unresolved generic types are correctly replaced with resolved types, enhancing the robustness of type handling in the system. Ensure that similar handling is consistently applied throughout all components that perform type resolution.
[APROVED]

Also applies to: 407-407, 423-427

Verification successful

Line range hint 289-313: Proper handling of generic types in module reading.

The changes ensure that unresolved generic types are correctly replaced with resolved types, enhancing the robustness of type handling in the system. The search results indicate that generic types are handled in various parts of the codebase. Ensure that unresolved types are consistently resolved using the FindType method as observed in the following locations:

  • runtime/ishtar.base/emit/ModuleReader.cs
  • compiler/compilation/parts/bodies.cs
  • runtime/ishtar.base/emit/MethodBuilder.cs
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarClass.cs
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarField.cs
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarModule.cs
  • runtime/common/reflection/VeinField.cs
  • compiler/compilation/parts/fields.cs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify consistent handling of generic types across the system.

# Test: Search for inconsistent handling of generic types.
rg --type csharp 'FindType' | rg --type csharp '!IsGeneric'

Length of output: 59



Script:

#!/bin/bash
# Description: Verify consistent handling of generic types across the system.

# Test 1: Search for handling of generic types in method return types.
rg --type csharp 'ReturnType' | rg --type csharp 'IsGeneric'

# Test 2: Search for handling of generic types in method arguments.
rg --type csharp 'Signature.Arguments' | rg --type csharp 'IsGeneric'

# Test 3: Search for handling of generic types in field types.
rg --type csharp 'FieldType' | rg --type csharp 'IsGeneric'

# Test 4: Search for unresolved types being resolved.
rg --type csharp 'UnresolvedVeinClass' | rg --type csharp 'FindType'

Length of output: 1935

runtime/ishtar.vm/runtime/vm/RuntimeIshtarClass.cs (1)

416-419: Improve debug information for generic types in init_vtable.

The changes made to debug information output in init_vtable help in understanding the handling of generic types during runtime. Consider adding detailed comments explaining the conditions under which each branch of debug information is used, to enhance maintainability and readability.

+ // Check if the field type is generic and adjust debug information accordingly
  if (field->FieldType.IsGeneric)
    dvtable.vtable_info[vtable_offset] = $"DEFAULT_VALUE OF [{field->FullName->ToString()}::{StringStorage.GetStringUnsafe(field->FieldType.TypeArg->Name)}]";
  else
    dvtable.vtable_info[vtable_offset] = $"DEFAULT_VALUE OF [{field->FullName->ToString()}::{field->FieldType.Class->FullName->ToString()}]";
runtime/ishtar.vm/runtime/vm/RuntimeIshtarModule.cs (5)

452-459: Field Type Resolution Logic Updated

The changes to field type resolution to handle generic and unresolved types appear correct and align with the broader updates to use RuntimeComplexType. This should enhance the module's ability to dynamically resolve types at runtime.


478-478: Use of RuntimeComplexType in Field Definition

Implementing RuntimeComplexType in field definitions is a direct and effective use of the new type system, ensuring better type handling and consistency across the module.


708-711: Introduction of DeferClassFieldData

The new DeferClassFieldData class encapsulates field definitions using RuntimeComplexType, which enhances modularity and aligns with the new type system. This is a positive change for the codebase.


721-724: Field Decoding with RuntimeComplexType

The updates to field decoding to utilize RuntimeComplexType ensure that fields are correctly typed upon loading, which is crucial for the system's type integrity.


742-746: Method Decoding Update

Updating method decoding to use RuntimeComplexType is a necessary change that ensures methods are correctly typed, aligning with the new type system's requirements.

@@ -153,7 +153,7 @@ internal void ReplaceParent(RuntimeIshtarClass* parent)
return f;
}

internal RuntimeIshtarField* DefineField(RuntimeFieldName* name, FieldFlags flags, RuntimeIshtarClass* type)
internal RuntimeIshtarField* DefineField(RuntimeFieldName* name, FieldFlags flags, RuntimeComplexType type)
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor suggestion for method DefineField.

The method DefineField has been updated to accept RuntimeComplexType instead of RuntimeIshtarClass*. This is in line with the ongoing effort to handle generic types more effectively. However, consider adding a null check for type to prevent potential null reference exceptions.

+ if (type == null) throw new ArgumentNullException(nameof(type));
  internal RuntimeIshtarField* DefineField(RuntimeFieldName* name, FieldFlags flags, RuntimeComplexType type)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
internal RuntimeIshtarField* DefineField(RuntimeFieldName* name, FieldFlags flags, RuntimeComplexType type)
if (type == null) throw new ArgumentNullException(nameof(type));
internal RuntimeIshtarField* DefineField(RuntimeFieldName* name, FieldFlags flags, RuntimeComplexType type)


if (left_type.TypeCode.HasNumber() && right_type.TypeCode.HasNumber())
gen.EmitBinaryOperator(op);
else
{
var name = $"op_{op}";
var args = new[] { left_type, right_type };
var args = new[] { (VeinComplexType)left_type, (VeinComplexType)right_type };
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Verify method lookup consistency.

The following instances of FindMethod calls do not use VeinComplexType. Please review and update them if necessary to ensure consistency with the updated type system:

  • test/ishtar_test/NotCompletedValidateCallTest.cs
  • test/ishtar_test/FECallTest.cs
  • runtime/ishtar.vm/vm.shit.cs
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarClass.cs
  • runtime/ishtar.vm/VirtualMachine.cs
  • runtime/ishtar.generator/GeneratorContext.cs
  • runtime/ishtar.generator/generators/array.cs
  • runtime/ishtar.generator/generators/emitters.cs
  • runtime/common/reflection/VeinField.cs
Analysis chain

Use of complex types in method lookup.

Casting arguments to VeinComplexType ensures consistency with the updated type system. Verify that similar updates are applied consistently across other parts of the codebase where method lookup occurs.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify consistency of method lookup changes across the codebase.

# Test: Search for method lookups that might not use `VeinComplexType`.
rg --type csharp 'FindMethod' | rg --type csharp '!VeinComplexType'

Length of output: 67



Script:

#!/bin/bash
# Description: Verify consistency of method lookup changes across the codebase.

# Step 1: Search for all instances of `FindMethod` in C# files.
rg --type csharp 'FindMethod' -l | xargs -I {} sh -c "echo {}; rg 'FindMethod' {}"

# Step 2: Inspect the arguments used in these `FindMethod` calls to ensure they use `VeinComplexType`.

Length of output: 2277

public static print(value: i32): Void
|> Out.@_println(value);
}
public extern static _println(value: Object): Void;
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Inconsistent annotation usage: @_println found

The old annotation @_println is still present in the codebase. Please update all instances of @_println to _println to ensure consistency throughout the project.

  • Located in: native("__internal__", "@_println")
Analysis chain

Updated external function annotation

The change from @_println to _println might be to align with internal naming conventions or to simplify the API. It's important to ensure that this new annotation is consistent throughout all references in the project.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `_println` is consistently used across the project.

# Test: Search for the old annotation '@_println' and expect no occurrences.
rg --type vein '@_println'

Length of output: 55



Script:

#!/bin/bash
# Description: Verify that `_println` is consistently used across the project.

# Find all .vein files and search for the old annotation '@_println'
fd -e vein -x rg '@_println' {}

Length of output: 75

Comment on lines +17 to +22
if (expType.IsGeneric)
{
ctx.LogError($"Cannot implicitly convert generic type '{expType.ToTemplateString()}' to 'Boolean'", ifStatement.Expression);
return;
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Improve handling of generic types in conditional expressions.

The addition of error logging for generic types in conditional expressions is a good practice. However, consider adding more comprehensive type checking or conversion mechanisms to handle these cases more gracefully.

+ if (!expType.CanBeConvertedToBoolean())
+ {
+     ctx.LogError($"Type '{expType}' cannot be implicitly converted to 'Boolean'.", ifStatement.Expression);
+     return;
+ }
- ctx.LogError($"Cannot implicitly convert generic type '{expType.ToTemplateString()}' to 'Boolean'", ifStatement.Expression);
- return;

Also applies to: 34-34

Comment on lines +198 to +202
if (field.FieldType.IsGeneric)
throw new ConvertNotSupportedException(field); // generic not support convert
try
{
return GetConverter(field.FieldType.TypeCode);
return GetConverter(field.FieldType.Class.TypeCode);
Copy link
Contributor

Choose a reason for hiding this comment

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

Issue: Generic type conversion not supported.

The exception thrown when trying to convert a generic type is appropriate, but consider providing more detailed error information to aid debugging.

- throw new ConvertNotSupportedException(field); // generic not support convert
+ throw new ConvertNotSupportedException($"Conversion for generic type '{field.FieldType}' is not supported.", field);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (field.FieldType.IsGeneric)
throw new ConvertNotSupportedException(field); // generic not support convert
try
{
return GetConverter(field.FieldType.TypeCode);
return GetConverter(field.FieldType.Class.TypeCode);
if (field.FieldType.IsGeneric)
throw new ConvertNotSupportedException($"Conversion for generic type '{field.FieldType}' is not supported.", field); // generic not support convert
try
{
return GetConverter(field.FieldType.Class.TypeCode);

Comment on lines +54 to +56
public static VeinComplexType ResolveMemberType(this IEnumerable<ExpressionSyntax> chain, GeneratorContext context)
{
var t = default(VeinClass);
var t = default(VeinComplexType);
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor suggestion for ResolveMemberType.

The method uses a complex loop to resolve types. Consider refactoring for clarity and possibly breaking down into smaller, more manageable methods.

- while (enumerator.MoveNext())
+ foreach (var exp in chain)

Committable suggestion was skipped due to low confidence.

{
if (ResolveArgument(id) is not null)
{
var a = ResolveArgument(id);
return a.Value.Item1.Type;
var (arg, index) = ResolveArgument(id)!.Value;
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unused local variable 'index'.

As per static analysis tool hint, the variable 'index' is declared but not used which could be removed to clean up the code.

- var (arg, index) = ResolveArgument(id)!.Value;
+ var arg = ResolveArgument(id)!.Value.arg;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var (arg, index) = ResolveArgument(id)!.Value;
var arg = ResolveArgument(id)!.Value.arg;
Tools
GitHub Check: Codacy Static Code Analysis

[notice] 117-117: runtime/ishtar.generator/GeneratorContext.cs#L117
Remove the unused local variable 'index'.

Comment on lines +113 to +121
public VeinComplexType ResolveScopedIdentifierType(IdentifierExpression id)
{
if (ResolveArgument(id) is not null)
{
var a = ResolveArgument(id);
return a.Value.Item1.Type;
var (arg, index) = ResolveArgument(id)!.Value;

if (arg.IsGeneric)
return arg.TypeArg;
return arg.Type;
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor and optimize ResolveScopedIdentifierType.

The method handles different scenarios for resolving types but could be optimized by avoiding redundant calls to ResolveArgument.

- if (ResolveArgument(id) is not null)
+ var resolvedArg = ResolveArgument(id);
+ if (resolvedArg is not null)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public VeinComplexType ResolveScopedIdentifierType(IdentifierExpression id)
{
if (ResolveArgument(id) is not null)
{
var a = ResolveArgument(id);
return a.Value.Item1.Type;
var (arg, index) = ResolveArgument(id)!.Value;
if (arg.IsGeneric)
return arg.TypeArg;
return arg.Type;
public VeinComplexType ResolveScopedIdentifierType(IdentifierExpression id)
{
var resolvedArg = ResolveArgument(id);
if (resolvedArg is not null)
{
var (arg, index) = resolvedArg.Value;
if (arg.IsGeneric)
return arg.TypeArg;
return arg.Type;
Tools
GitHub Check: Codacy Static Code Analysis

[notice] 117-117: runtime/ishtar.generator/GeneratorContext.cs#L117
Remove the unused local variable 'index'.

@@ -236,8 +236,7 @@ protected override VeinMethod GetOrCreateTor(string name, bool isStatic = false)
flags |= MethodFlags.Static;

var returnType = isStatic ? VeinTypeCode.TYPE_VOID.AsClass(moduleBuilder) : this;
var args = isStatic || name == "dtor" ? new VeinArgumentRef[0] :
new VeinArgumentRef[1] { new VeinArgumentRef(VeinArgumentRef.THIS_ARGUMENT, this) };
var args = isStatic || name == "dtor" ? Array.Empty<VeinArgumentRef>() : [new VeinArgumentRef(VeinArgumentRef.THIS_ARGUMENT, this)];
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor suggestion for constructor generation in GetOrCreateTor.

The method could be simplified by separating the static and instance constructor logic into different methods to improve readability and maintainability.

- var args = isStatic || name == "dtor" ? Array.Empty<VeinArgumentRef>() : [new VeinArgumentRef(VeinArgumentRef.THIS_ARGUMENT, this)];
+ var args = DetermineConstructorArguments(isStatic, name);

Committable suggestion was skipped due to low confidence.

@@ -140,7 +140,7 @@ private FieldFlags GenerateFieldFlags(MemberDeclarationSyntax member)
if (@override is not null && @override.Args.Any())
{
var exp = @override.Args[0];
if (exp is ArgumentExpression { Value: StringLiteralExpressionSyntax value })
if (exp is { Value: StringLiteralExpressionSyntax value })
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor suggestion for field name override handling.

The method for handling field name overrides is convoluted and could be simplified to improve readability and maintainability.

- if (exp is { Value: StringLiteralExpressionSyntax value })
+ if (exp.Value is StringLiteralExpressionSyntax value)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (exp is { Value: StringLiteralExpressionSyntax value })
if (exp.Value is StringLiteralExpressionSyntax value)

@0xF6 0xF6 merged commit 8f089a6 into master Jun 26, 2024
9 of 11 checks passed
@0xF6 0xF6 deleted the fixes/generic-adaptation branch June 26, 2024 21:51
@vein-lang vein-lang locked and limited conversation to collaborators Jun 26, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-lexer Area of lexer tree area-vm Area of virtual machine
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants