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

[methods aliases] Features for Function Type and load function as argument #250

Merged
merged 9 commits into from
Jun 29, 2024

Conversation

0xF6
Copy link
Member

@0xF6 0xF6 commented Jun 29, 2024

Summary by CodeRabbit

  • New Features

    • Added new opcodes CALL_SP and LDFN for enhanced operation handling.
    • Introduced methods for improved function class compatibility checks.
    • Added functionality to create and manage function multicast groups.
  • Bug Fixes

    • Enhanced error logging for conflicts in declaration generic types.
  • Refactor

    • Replaced hardcoded method names with constants for better maintainability.
    • Streamlined compatibility checking methods for improved performance.
  • Chores

    • Incremented metadata version from 18 to 20.

@0xF6 0xF6 added area-vm Area of virtual machine area-IL Area of intermediate language area-compiler Area of compiler staff priority 1 important area-runtime Area of runtime forge feature size: S small task (< 1 week) labels Jun 29, 2024
@0xF6 0xF6 requested a review from code-maid June 29, 2024 01:33
@0xF6 0xF6 self-assigned this Jun 29, 2024
Copy link
Contributor

coderabbitai bot commented Jun 29, 2024

Walkthrough

The updates span core compiler functionalities, including handling of generics, method compatibility checks, and opcode definitions. Key enhancements involve concatenating and regenerating aliases, defining delegate classes, improving type handling for method arguments, and introducing new opcodes (CALL_SP, LDFN). Additionally, version increments, reflection adjustments, and IL generation refinements contribute to a more robust and flexible compilation process.

Changes

File Path Change Summary
compiler/compilation/CompilationTask.cs Added steps to concatenate aliasesQueue items and regenerate aliases before proceeding with existing compilation logic
compiler/compilation/parts/args.cs Introduced conditional checks based on method.IsMethodType, modifying generics handling, constraints, and VeinArgumentRef generation
compiler/compilation/parts/classes.cs Added methods like DefineDelegateClass and adjusted LinkClasses and RegenerateAliases for alias handling
compiler/compilation/parts/methods.cs Used constants for constructor method names
lib/ast/syntax/VeinSyntax.cs Adjusted parsing of method bodies by introducing a Positioned() method call
metadata/db_opcodes.json Added new entries for "CALL_SP": 114 and "LDFN": 115
metadata/opcodes.def.cs Added new opcodes CALL_SP and LDFN to OpCodeValue enum
metadata/opcodes.list.def.cs Updated SetVersion value to 20, added new opcodes CALL_SP and LDFN
metadata/opcodes.yaml Added entries for CALL_SP and LDFN
metadata/version Incremented version number from 18 to 20
runtime/common/reflection/VeinClass.cs Introduced FindAnyMethods and extended compatibility checks. Removed outdated compatibility check methods
runtime/common/reflection/VeinMethod.cs Added method NotThis, HasCompatibility, and constants for method names. Updated method name checks to use constants
runtime/common/reflection/VeinTypeCode.cs Added TYPE_RAW case to type code mapping
runtime/ishtar.base/emit/ClassBuilder.cs Modified DefineMethod to change returnType parameter to VeinComplexType
runtime/ishtar.base/emit/ILGenerator.cs Introduced handling for new LDFN opcode
runtime/ishtar.base/emit/MethodBuilder.cs Updated returnType parameter type from VeinClass to VeinComplexType in constructor
runtime/ishtar.base/emit/VeinModuleBuilder.cs Added method DefineClass with parent class
runtime/ishtar.generator/GeneratorContext.cs Extensive changes for handling method creation, field resolution, and error handling
runtime/ishtar.generator/generators/access.cs Updated EmitAccess method to call GetTypeCode(ctx)
runtime/ishtar.generator/generators/call.cs Added IsCallingDelegate method
runtime/ishtar.generator/generators/emitters.cs Updated EmitCreateObject method to use constant for constructor method name
runtime/ishtar.generator/generators/operators.cs Added context handling for unary expressions
runtime/ishtar.generator/generators/types.cs Enhanced type code determination to handle different expressions

Poem

In code's vast realm, we weave anew,
With opcodes fresh and constructs, too.
Aliases linked and methods clear,
A rabbit's touch, no bugs to fear.
A poet's heart within our bytes,
We celebrate these new heights! 🎉


Tip

Early access features
  • OpenAI gpt-4o model for reviews and chat.

Note:

  • You can disable early access features from the CodeRabbit UI or by setting early_access: false in the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are always opted into early access features.

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: 6

Outside diff range and nitpick comments (1)
runtime/ishtar.base/emit/ILGenerator.cs (1)

Line range hint 393-393: Remove unnecessary nullable annotation.

The nullable annotation should only be used within a #nullable annotations context.

- public virtual ILGenerator Emit(OpCode opcode, VeinMethod method)
+ public virtual ILGenerator Emit(OpCode opcode, VeinMethod method)
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8f089a6 and 594cd24.

Files selected for processing (25)
  • compiler/compilation/CompilationTask.cs (1 hunks)
  • compiler/compilation/parts/args.cs (2 hunks)
  • compiler/compilation/parts/classes.cs (4 hunks)
  • compiler/compilation/parts/methods.cs (1 hunks)
  • lib/ast/syntax/VeinSyntax.cs (1 hunks)
  • lib/ast/syntax/ast/MethodDeclarationSyntax.cs (2 hunks)
  • lib/ast/syntax/ast/ReturnStatementSyntax.cs (1 hunks)
  • metadata/db_opcodes.json (1 hunks)
  • metadata/opcodes.def.cs (1 hunks)
  • metadata/opcodes.list.def.cs (3 hunks)
  • metadata/opcodes.yaml (1 hunks)
  • metadata/version (1 hunks)
  • runtime/common/reflection/VeinClass.cs (4 hunks)
  • runtime/common/reflection/VeinMethod.cs (3 hunks)
  • runtime/common/reflection/VeinTypeCode.cs (1 hunks)
  • runtime/ishtar.base/emit/ClassBuilder.cs (1 hunks)
  • runtime/ishtar.base/emit/ILGenerator.cs (1 hunks)
  • runtime/ishtar.base/emit/MethodBuilder.cs (1 hunks)
  • runtime/ishtar.base/emit/VeinModuleBuilder.cs (1 hunks)
  • runtime/ishtar.generator/GeneratorContext.cs (3 hunks)
  • runtime/ishtar.generator/generators/access.cs (1 hunks)
  • runtime/ishtar.generator/generators/call.cs (3 hunks)
  • runtime/ishtar.generator/generators/emitters.cs (1 hunks)
  • runtime/ishtar.generator/generators/operators.cs (3 hunks)
  • runtime/ishtar.generator/generators/types.cs (3 hunks)
Files skipped from review due to trivial changes (2)
  • compiler/compilation/CompilationTask.cs
  • metadata/version
Additional context used
GitHub Check: build_all (ubuntu-latest, linux-x64, true)
runtime/ishtar.base/emit/ILGenerator.cs

[warning] 393-393:
The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Additional comments not posted (41)
lib/ast/syntax/ast/ReturnStatementSyntax.cs (3)

1-1: Consider adding a file-level docstring.

Adding a file-level docstring can provide context on the purpose of this file.

// This file defines the ReturnStatementSyntax class which represents a return statement in the syntax tree.

6-6: Ensure proper formatting for class declaration.

The class declaration should follow standard formatting conventions for readability.

- public class ReturnStatementSyntax(ExpressionSyntax e) : StatementSyntax, IPositionAware<ReturnStatementSyntax>
+ public class ReturnStatementSyntax : StatementSyntax, IPositionAware<ReturnStatementSyntax>
+ {
+     public ReturnStatementSyntax(ExpressionSyntax e)
+     {
+         Expression = e;
+     }

10-10: Consider making ChildNodes a read-only property.

Since ChildNodes is a derived property, it should be marked as read-only to prevent accidental modification.

- public override IEnumerable<BaseSyntax> ChildNodes => GetNodes(Expression);
+ public override IEnumerable<BaseSyntax> ChildNodes { get => GetNodes(Expression); }
metadata/db_opcodes.json (1)

115-117: Ensure new opcodes are documented and tested.

Make sure the new opcodes CALL_SP and LDFN are properly documented and covered by unit tests.

lib/ast/syntax/ast/MethodDeclarationSyntax.cs (1)

23-23: Consider providing a more descriptive property name.

IsAbstract might be misleading since it checks if the body is null or an empty block. Consider renaming it to something more descriptive.

- public bool IsAbstract => Body is null or EmptyBlockSyntax;
+ public bool HasNoImplementation => Body is null or EmptyBlockSyntax;
runtime/ishtar.generator/generators/call.cs (2)

16-30: LGTM!

The changes correctly handle delegate invocations within the EmitCall method.


43-56: LGTM!

The IsCallingDelegate method correctly identifies delegate calls based on the current method's signature arguments.

compiler/compilation/parts/args.cs (2)

22-26: LGTM!

The changes correctly handle the addition of the THIS_ARGUMENT for non-static methods that are not linked to a class.


46-86: LGTM!

The changes correctly handle generics and constraints for methods that are not of type IsMethodType. Error logging and exception handling are appropriately implemented.

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

Line range hint 20-28: LGTM!

The changes correctly update the MethodBuilder constructor to accept a VeinComplexType as the returnType parameter.

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

58-58: Visibility change: NotThis method

The NotThis method is now public static. This change allows the method to be accessed more broadly. Ensure that this change is intentional and does not expose the method to unintended usage.


99-100: New constants for method names

The constants METHOD_NAME_CONSTRUCTOR and METHOD_NAME_DECONSTRUCTOR are added. This improves maintainability and reduces the risk of typographical errors when referring to these method names.


136-136: Use of constant for constructor name

The IsConstructor property now uses the METHOD_NAME_CONSTRUCTOR constant. This change improves consistency and maintainability.


138-138: Use of constant for deconstructor name

The IsDeconstructor property now uses the METHOD_NAME_DECONSTRUCTOR constant. This change improves consistency and maintainability.

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

92-92: Use of constant for constructor name

The FindMethod call now uses the METHOD_NAME_CONSTRUCTOR constant. This change improves consistency and maintainability.

metadata/opcodes.yaml (2)

59-60: New opcode: CALL_SP

The CALL_SP opcode is added with a description. Ensure that this opcode is correctly implemented and tested in the relevant parts of the codebase.


61-63: New opcode: LDFN

The LDFN opcode is added with a description and override size. Ensure that this opcode is correctly implemented and tested in the relevant parts of the codebase.

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

Line range hint 1-1: LGTM!

However, ensure that the new type TYPE_RAW is correctly handled in all relevant parts of the codebase.

Verification successful

The new type TYPE_RAW is correctly handled in all relevant parts of the codebase.

The TYPE_RAW type is used in various files and contexts, indicating that it has been integrated properly.

  • runtime/ishtar.generator/GeneratorContext.cs
  • runtime/ishtar.vm/stackval.cs
  • runtime/ishtar.vm/vm.shit.cs
  • runtime/ishtar.vm/runtime/vm/IshtarTypes.cs
  • runtime/ishtar.base/emit/TypeForwarder.cs
  • runtime/ishtar.vm/runtime/vm/RuntimeIshtarClass.cs
  • runtime/ishtar.vm/runtime/jit/IshtarJIT.cs
  • runtime/ishtar.vm/runtime/jit/@llmv/LLVMContext.cs
  • runtime/ishtar.vm/runtime/IshtarMarshal.cs
  • runtime/ishtar.generator/generators/operators.cs
  • runtime/common/reflection/VeinTypeCode.cs
  • runtime/common/reflection/VeinCore.cs
  • compiler/compilation/parts/classes.cs

These usages cover a wide range of functionalities, from JIT compilation to marshalling and type reflection.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of TYPE_RAW in the codebase.

# Test: Search for the usage of TYPE_RAW. Expect: Proper handling of new type in all relevant parts.
rg --type-add 'cs' --type cs 'TYPE_RAW'

Length of output: 97



Script:

#!/bin/bash
# Description: Verify the usage of TYPE_RAW in the codebase.

# Test: Search for the usage of TYPE_RAW. Expect: Proper handling of new type in all relevant parts.
rg 'TYPE_RAW' --glob '*.cs'

Length of output: 3182

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

176-179: LGTM!

However, ensure that all references to method names are updated to use the constants.

Verification successful

Ensure all method name references are updated to use constants.

The verification shows that the method name constants are properly used in the relevant parts of the codebase.

  • runtime/ishtar.generator/GeneratorContext.cs
  • runtime/ishtar.generator/generators/operators.cs
  • runtime/ishtar.generator/generators/emitters.cs
  • runtime/common/reflection/VeinClass.cs
  • compiler/compilation/parts/methods.cs
  • compiler/compilation/parts/classes.cs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of method name constants in the codebase.

# Test: Search for the usage of method name constants. Expect: Proper usage of constants in all relevant parts.
rg --type-add 'cs' --type cs 'VeinMethod.METHOD_NAME_CONSTRUCTOR'

Length of output: 123



Script:

#!/bin/bash
# Description: Verify the usage of method name constants in the codebase.

# Test: Search for the usage of method name constants. Expect: Proper usage of constants in all relevant parts.
rg --type-add 'cs:*.cs' --type cs 'VeinMethod.METHOD_NAME_CONSTRUCTOR'

Length of output: 1104

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

58-58: LGTM!

However, ensure that all references to DefineMethod are updated to use the new signature.

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

167-167: Ensure the GetTypeCode method is called with the correct context.

The change introduces a call to literal.GetTypeCode(ctx). Ensure that ctx is correctly initialized and passed to avoid runtime errors.

Verification successful

The ctx variable is properly initialized and used consistently throughout the access.cs file. No issues found.

  • The ctx variable is initialized with gen.ConsumeFromMetadata<GeneratorContext>("context").
  • It is used multiple times in different contexts, indicating proper management.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the initialization and usage of `ctx` in the `access.cs` file.

# Test: Search for the definition and usage of `ctx`. Expect: Proper initialization and usage.
rg --type-add 'cs' --type 'cs' 'ctx' runtime/ishtar.generator/generators/access.cs

Length of output: 138



Script:

#!/bin/bash
# Description: Verify the initialization and usage of `ctx` in the `access.cs` file.

# Test: Search for the definition and usage of `ctx`. Expect: Proper initialization and usage.
rg 'ctx' runtime/ishtar.generator/generators/access.cs

Length of output: 2334

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

5-5: Remove unnecessary System.Threading.Tasks import.

The System.Threading.Tasks import is not used in the file and should be removed to keep the code clean.

-using System.Threading.Tasks;

13-13: Ensure GeneratorContext is nullable.

The GeneratorContext parameter in the GetTypeCode method is nullable. Ensure that the method handles null values appropriately to avoid potential null reference exceptions.

Verification successful

Ensure GeneratorContext is nullable.

The GetTypeCode method handles the GeneratorContext parameter correctly by checking if gen is not null before using it. This prevents potential null reference exceptions.

  • Line 23: if (exp is IdentifierExpression id && gen is not null)
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the handling of null values in the `GetTypeCode` method.

# Test: Search for the usage of `gen` in the `GetTypeCode` method. Expect: Proper null checks and handling.
rg --type-add 'cs' --type 'cs' 'gen' runtime/ishtar.generator/generators/types.cs

Length of output: 137



Script:

#!/bin/bash
# Description: Verify the handling of null values in the `GetTypeCode` method.

# Corrected command to search for the usage of `gen` in the `GetTypeCode` method.
rg 'gen' runtime/ishtar.generator/generators/types.cs -n -A 10 -B 10

Length of output: 2452


182-208: Ensure proper handling of postfix unary expressions.

The changes introduce logic for handling postfix unary expressions. Ensure that the error messages and logic are consistent and handle all edge cases appropriately.

Verification successful

Ensure proper handling of postfix unary expressions.

The code correctly identifies and logs errors for various edge cases involving postfix unary expressions. The logic is consistent and handles the following scenarios appropriately:

  • Non-IdentifierExpression operand

  • Use with a Generic Type

  • Use with a non-function type

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the handling of postfix unary expressions in the `DetermineType` method.

# Test: Search for the handling of postfix unary expressions. Expect: Proper error messages and logic.
rg --type-add 'cs' --type 'cs' 'PostfixUnary' runtime/ishtar.generator/generators/types.cs

Length of output: 146



Script:

#!/bin/bash
# Description: Verify the handling of postfix unary expressions in the `DetermineType` method.

# Test: Search for the handling of postfix unary expressions. Expect: Proper error messages and logic.
rg 'PostfixUnary' runtime/ishtar.generator/generators/types.cs

Length of output: 549

metadata/opcodes.def.cs (1)

211-217: Ensure the new opcodes CALL_SP and LDFN are handled correctly.

The new opcodes CALL_SP and LDFN are added to the OpCodeValue enum. Ensure that these opcodes are handled correctly in the relevant parts of the codebase.

Verification successful

The new opcodes CALL_SP and LDFN are handled correctly.

The search results show that the new opcodes CALL_SP and LDFN are present and being used in various parts of the codebase, indicating proper handling.

  • runtime/ishtar.generator/generators/operators.cs
  • runtime/ishtar.generator/GeneratorContext.cs
  • runtime/ishtar.base/emit/ILGenerator.cs
  • metadata/opcodes.list.def.cs
  • metadata/opcodes.def.cs
  • compiler/compilation/parts/classes.cs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the handling of the new opcodes `CALL_SP` and `LDFN`.

# Test: Search for the usage of `CALL_SP` and `LDFN` opcodes. Expect: Proper handling in the codebase.
rg --type-add 'cs' --type 'cs' 'CALL_SP|LDFN' runtime/

Length of output: 112



Script:

#!/bin/bash
# Description: Verify the handling of the new opcodes `CALL_SP` and `LDFN`.

# Test: Search for the usage of `CALL_SP` and `LDFN` opcodes. Expect: Proper handling in the codebase.
rg --type-add 'cs:*.cs' --type 'cs' 'CALL_SP|LDFN'

Length of output: 808

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

71-84: LGTM!

The function DefineClass properly handles the creation of a class with a parent class, including duplicate checks and interning strings.

However, ensure that all calls to DefineClass with a parent class are correct.

Verification successful

To ensure that all calls to DefineClass with a parent class are correct, we need to inspect the context of each call found. Specifically, we should check if the parent class argument is provided where it is required.


LGTM!

The function DefineClass properly handles the creation of a class with a parent class, including duplicate checks and interning strings. The context of the calls to DefineClass confirms that the parent class argument is correctly used where necessary.

  • Ensure that all calls to DefineClass with a parent class are correct.
  • Verify the integration of the new function signature in the relevant parts of the code.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `DefineClass` with a parent class.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type cs $'DefineClass'

Length of output: 3096



Script:

#!/bin/bash
# Description: Verify the context of each call to `DefineClass` to ensure the parent class argument is used correctly.

# Extract the lines surrounding each occurrence of DefineClass to understand the context.
rg --type cs --context 5 'DefineClass' > define_class_usage_context.txt

# Output the relevant lines for manual inspection.
cat define_class_usage_context.txt

Length of output: 22916

runtime/ishtar.generator/GeneratorContext.cs (2)

99-110: LGTM!

The function CreateHiddenType correctly handles the creation of a hidden type with a parent class, including duplicate checks and setting class flags.

However, ensure that all calls to CreateHiddenType with a parent class are correct.


169-223: LGTM!

The function CreateFunctionMulticastGroup correctly handles the creation of a function multicast group, including resolving the base type, defining fields and methods, and generating the method body.

However, ensure that all calls to CreateFunctionMulticastGroup are correct.

Verification successful

The call to CreateFunctionMulticastGroup is correctly used.

The function CreateFunctionMulticastGroup is called within a context that ensures only one method is found with the given name, making its usage appropriate and safe.

  • runtime/ishtar.generator/GeneratorContext.cs:
    • Line 1: return CreateFunctionMulticastGroup(methods.Single().Signature);
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `CreateFunctionMulticastGroup`.

# Test: Search for the function usage. Expect: Only occurrences of the new function.
rg --type cs $'CreateFunctionMulticastGroup'

Length of output: 285



Script:

#!/bin/bash
# Description: Extract the context around the call to `CreateFunctionMulticastGroup`.

# Extract 10 lines before and after the function call.
rg --type cs -A 10 -B 10 $'CreateFunctionMulticastGroup' runtime/ishtar.generator/GeneratorContext.cs

Length of output: 1312

compiler/compilation/parts/classes.cs (2)

Line range hint 153-188: LGTM!

The function LinkClasses correctly handles the compilation of classes and aspects, adding them to the context's class dictionary, and enqueuing documents with aliases.

However, ensure that all calls to LinkClasses are correct.

Verification successful

Function LinkClasses usage verified

The function LinkClasses is correctly used in:

  • compiler/compilation/CompilationTask.cs
  • compiler/compilation/parts/classes.cs

These usages integrate well with the rest of the codebase.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `LinkClasses`.

# Test: Search for the function usage. Expect: Only occurrences of the new function.
rg --type cs $'LinkClasses'

Length of output: 457



Script:

#!/bin/bash
# Get context around the usage of LinkClasses in CompilationTask.cs
rg --type cs --context 10 'LinkClasses' compiler/compilation/CompilationTask.cs

# Get context around the usage of LinkClasses in classes.cs
rg --type cs --context 10 'LinkClasses' compiler/compilation/parts/classes.cs

Length of output: 1977


190-218: LGTM!

The function RegenerateAliases correctly handles the regeneration of type and method aliases, adding them to the context's alias table, and adding regenerated classes to the context's class dictionary.

However, ensure that all calls to RegenerateAliases are correct.

Verification successful

Verification Successful

The function RegenerateAliases is correctly integrated into the processing pipeline. The aliasesQueue is appropriately defined and used to store document and type pairs for alias regeneration.

  • compiler/compilation/CompilationTask.cs: Correct usage of RegenerateAliases in the pipeline.
  • compiler/compilation/parts/classes.cs: Proper definition and usage of aliasesQueue.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `RegenerateAliases`.

# Test: Search for the function usage. Expect: Only occurrences of the new function.
rg --type cs $'RegenerateAliases'

Length of output: 526



Script:

#!/bin/bash
# Extract lines around the usage of RegenerateAliases in CompilationTask.cs for context
rg --type cs --context 10 'RegenerateAliases' compiler/compilation/CompilationTask.cs

Length of output: 855



Script:

#!/bin/bash
# Extract information about aliasesQueue and its role in the pipeline
rg --type cs 'aliasesQueue' compiler/compilation/CompilationTask.cs

Length of output: 135



Script:

#!/bin/bash
# Search for the definition or initialization of aliasesQueue in the entire codebase
rg --type cs 'aliasesQueue'

Length of output: 370

lib/ast/syntax/VeinSyntax.cs (1)

144-145: Ensure correct positioning of method bodies.

The addition of the Positioned() method ensures that the method body is correctly positioned within the syntax tree. This is a good practice for accurate error reporting and debugging.

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

73-74: Use of constants for method names.

The use of constants VeinMethod.METHOD_NAME_DECONSTRUCTOR and VeinMethod.METHOD_NAME_CONSTRUCTOR improves code readability and maintainability.


105-113: Method FindAnyMethods looks good.

The method correctly concatenates methods from the current class and its parents, filtering by name.


116-125: Method CheckCompatibilityFunctionClass looks good.

The method correctly checks for the presence of invoke methods and compares their signatures for compatibility.


145-147: Extension of compatibility checks.

The added check for function class compatibility within CheckCompatibility is a logical and necessary extension.


Line range hint 126-148: Removal of CheckCompatibilityV4.

The removal of CheckCompatibilityV4 simplifies the codebase, relying on the updated CheckCompatibility method to handle all cases.

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

246-247: Context consumption for unary expressions.

The addition of consuming GeneratorContext from metadata ensures that the context is available for type determination and error handling.


269-299: Implementation for function type handling in unary expressions.

The added implementation for handling function types in unary expressions is a significant enhancement. It correctly identifies the function type, finds the invoke method, and emits the appropriate opcodes.

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

303-303: Verify the new opcode check.

The new opcode check for LDFN is added alongside CALL. Ensure that this opcode is handled correctly in all relevant parts of the codebase.

Verification successful

Verified the new opcode check.

The new opcode check for LDFN is correctly integrated and handled appropriately in the relevant parts of the codebase.

  • ILGenerator.cs: The Emit method includes a check to ensure LDFN is a valid opcode.
  • operators.cs: The LDFN opcode is used to emit a method found by the FindMethod function.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify handling of LDFN opcode across the codebase.

# Test: Search for all usages of the LDFN opcode. Expect: Proper handling in all relevant parts.
rg --type-add 'cs' --type cs 'OpCodes.LDFN'

Length of output: 101



Script:

#!/bin/bash
# Description: Verify handling of LDFN opcode across the codebase.

# Test: Search for all usages of the LDFN opcode. Expect: Proper handling in all relevant parts.
rg 'OpCodes.LDFN'

Length of output: 220



Script:

#!/bin/bash
# Description: Extract the context around the usage of OpCodes.LDFN in operators.cs.

# Test: Display lines around the usage of OpCodes.LDFN for context.
rg -A 5 -B 5 'OpCodes.LDFN' runtime/ishtar.generator/generators/operators.cs

Length of output: 446



Script:

#!/bin/bash
# Description: Verify handling of LDFN opcode within ILGenerator class.

# Test: Search for all usages of the LDFN opcode within ILGenerator class. Expect: Proper handling in all relevant parts.
rg 'OpCodes.LDFN' runtime/ishtar.base/emit/ILGenerator.cs

Length of output: 123



Script:

#!/bin/bash
# Description: Extract the context around the usage of OpCodes.LDFN in ILGenerator.cs.

# Test: Display lines around the usage of OpCodes.LDFN for context.
rg -A 10 -B 10 'OpCodes.LDFN' runtime/ishtar.base/emit/ILGenerator.cs

Length of output: 1059

metadata/opcodes.list.def.cs (2)

374-380: Review the addition of the LDFN opcode.

The LDFN opcode has been added to handle loading function pointers into the stack. Ensure that all relevant parts of the codebase handle this opcode correctly.

Verification successful

The LDFN opcode is handled correctly in the codebase.

The LDFN opcode is properly emitted and validated in the following files:

  • runtime/ishtar.generator/generators/operators.cs
  • runtime/ishtar.base/emit/ILGenerator.cs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify handling of LDFN opcode across the codebase.

# Test: Search for all usages of the LDFN opcode. Expect: Proper handling in all relevant parts.
rg --type-add 'cs' --type cs 'OpCodes.LDFN'

Length of output: 101



Script:

#!/bin/bash
# Description: Verify handling of LDFN opcode across the codebase.

# Test: Search for all usages of the LDFN opcode. Expect: Proper handling in all relevant parts.
rg 'OpCodes.LDFN'

Length of output: 220



Script:

#!/bin/bash
# Extract lines around the usage of OpCodes.LDFN in runtime/ishtar.generator/generators/operators.cs
rg --context 10 'OpCodes.LDFN' runtime/ishtar.generator/generators/operators.cs

# Extract lines around the usage of OpCodes.LDFN in runtime/ishtar.base/emit/ILGenerator.cs
rg --context 10 'OpCodes.LDFN' runtime/ishtar.base/emit/ILGenerator.cs

Length of output: 1836


368-373: Review the addition of the CALL_SP opcode.

The CALL_SP opcode has been added to handle call operations that load a pointer from the stack. Ensure that all relevant parts of the codebase handle this opcode correctly.

Verification successful

The CALL_SP opcode is correctly handled in the codebase.

The opcode is integrated into the opcode emission process in both GeneratorContext.cs and classes.cs.

  • runtime/ishtar.generator/GeneratorContext.cs
  • compiler/compilation/parts/classes.cs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify handling of CALL_SP opcode across the codebase.

# Test: Search for all usages of the CALL_SP opcode. Expect: Proper handling in all relevant parts.
rg --type-add 'cs' --type cs 'OpCodes.CALL_SP'

Length of output: 104



Script:

#!/bin/bash
# Description: Verify handling of CALL_SP opcode across the codebase.

# Test: Search for all usages of the CALL_SP opcode. Expect: Proper handling in all relevant parts.
rg --type-add 'cs:*.cs' --type cs 'OpCodes.CALL_SP'

Length of output: 216



Script:

#!/bin/bash
# Extract relevant lines from the identified files to examine the handling of CALL_SP opcode.

# Extract lines from runtime/ishtar.generator/GeneratorContext.cs
rg --type-add 'cs:*.cs' --type cs --context 5 'OpCodes.CALL_SP' runtime/ishtar.generator/GeneratorContext.cs

# Extract lines from compiler/compilation/parts/classes.cs
rg --type-add 'cs:*.cs' --type cs --context 5 'OpCodes.CALL_SP' compiler/compilation/parts/classes.cs

Length of output: 937

Comment on lines +14 to +17
public new ReturnStatementSyntax SetPos(Position startPos, int length)
{
base.SetPos(startPos, length);
return this;
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid using the new keyword to hide inherited members.

Using the new keyword to hide inherited members can lead to confusion. Consider renaming the method or using explicit interface implementation.

- public new ReturnStatementSyntax SetPos(Position startPos, int length)
+ public ReturnStatementSyntax SetPosition(Position startPos, int length)

Committable suggestion was skipped due to low confidence.

base.SetPos(startPos, length);
return this;
}
public ExpressionSyntax Expression { get; set; } = e;
Copy link
Contributor

Choose a reason for hiding this comment

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

Initialize properties in the constructor.

It's better to initialize the Expression property in the constructor to ensure it's always set correctly.

- public ExpressionSyntax Expression { get; set; } = e;
+ public ExpressionSyntax Expression { get; set; }
+ public ReturnStatementSyntax(ExpressionSyntax e)
+ {
+     Expression = e;
+ }

Committable suggestion was skipped due to low confidence.

Comment on lines +23 to +38
if (exp is IdentifierExpression id && gen is not null)
{
try
{
var t = id.DetermineType(gen);

if (t.IsGeneric)
return VeinTypeCode.TYPE_CLASS;
return t.Class.TypeCode;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Handle exceptions appropriately.

The GetTypeCode method catches exceptions and writes them to the debug output. Consider handling exceptions more gracefully or providing more context in the error messages.

-            catch (Exception e)
-            {
-                Debug.WriteLine(e);
-            }
+            catch (Exception e)
+            {
+                context.LogError($"Error determining type for identifier '{id}': {e.Message}", id);
+                throw;
+            }
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 IdentifierExpression id && gen is not null)
{
try
{
var t = id.DetermineType(gen);
if (t.IsGeneric)
return VeinTypeCode.TYPE_CLASS;
return t.Class.TypeCode;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
if (exp is IdentifierExpression id && gen is not null)
{
try
{
var t = id.DetermineType(gen);
if (t.IsGeneric)
return VeinTypeCode.TYPE_CLASS;
return t.Class.TypeCode;
}
catch (Exception e)
{
context.LogError($"Error determining type for identifier '{id}': {e.Message}", id);
throw;
}
}

Comment on lines +42 to +69
public static VeinClass GetType(this ExpressionSyntax exp, GeneratorContext gen)
{
if (exp is NumericLiteralExpressionSyntax num)
return GetTypeCodeFromNumber(num).AsClass(gen.Module.Types);
if (exp is BoolLiteralExpressionSyntax)
return VeinTypeCode.TYPE_BOOLEAN.AsClass(gen.Module.Types);
if (exp is StringLiteralExpressionSyntax)
return VeinTypeCode.TYPE_STRING.AsClass(gen.Module.Types);
if (exp is NullLiteralExpressionSyntax)
throw new NotSupportedException("NULL is not a type");
if (exp is IdentifierExpression id && gen is not null)
{
try
{
var t = id.DetermineType(gen);

if (t.IsGeneric)
throw new NotSupportedException($"Cannot summon type from generic declaration");
return t.Class;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}

throw new NotImplementedException();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper exception handling in GetType method.

Similar to the GetTypeCode method, the GetType method catches exceptions and writes them to the debug output. Consider handling exceptions more gracefully or providing more context in the error messages.

-            catch (Exception e)
-            {
-                Debug.WriteLine(e);
-            }
+            catch (Exception e)
+            {
+                context.LogError($"Error determining type for identifier '{id}': {e.Message}", id);
+                throw;
+            }
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 static VeinClass GetType(this ExpressionSyntax exp, GeneratorContext gen)
{
if (exp is NumericLiteralExpressionSyntax num)
return GetTypeCodeFromNumber(num).AsClass(gen.Module.Types);
if (exp is BoolLiteralExpressionSyntax)
return VeinTypeCode.TYPE_BOOLEAN.AsClass(gen.Module.Types);
if (exp is StringLiteralExpressionSyntax)
return VeinTypeCode.TYPE_STRING.AsClass(gen.Module.Types);
if (exp is NullLiteralExpressionSyntax)
throw new NotSupportedException("NULL is not a type");
if (exp is IdentifierExpression id && gen is not null)
{
try
{
var t = id.DetermineType(gen);
if (t.IsGeneric)
throw new NotSupportedException($"Cannot summon type from generic declaration");
return t.Class;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
throw new NotImplementedException();
}
public static VeinClass GetType(this ExpressionSyntax exp, GeneratorContext gen)
{
if (exp is NumericLiteralExpressionSyntax num)
return GetTypeCodeFromNumber(num).AsClass(gen.Module.Types);
if (exp is BoolLiteralExpressionSyntax)
return VeinTypeCode.TYPE_BOOLEAN.AsClass(gen.Module.Types);
if (exp is StringLiteralExpressionSyntax)
return VeinTypeCode.TYPE_STRING.AsClass(gen.Module.Types);
if (exp is NullLiteralExpressionSyntax)
throw new NotSupportedException("NULL is not a type");
if (exp is IdentifierExpression id && gen is not null)
{
try
{
var t = id.DetermineType(gen);
if (t.IsGeneric)
throw new NotSupportedException($"Cannot summon type from generic declaration");
return t.Class;
}
catch (Exception e)
{
context.LogError($"Error determining type for identifier '{id}': {e.Message}", id);
throw;
}
}
throw new NotImplementedException();
}

Comment on lines +46 to +48
public ClassDeclarationSyntax? OwnerClass { get; set; }

public bool IsMethodType => OwnerClass is null && IsAbstract && !Modifiers.Any();
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider initializing OwnerClass in the constructor.

To ensure OwnerClass is always set correctly, consider initializing it in the constructor.

- public ClassDeclarationSyntax? OwnerClass { get; set; }
+ public ClassDeclarationSyntax? OwnerClass { get; set; }
+ public MethodDeclarationSyntax(MemberDeclarationSyntax? heading = null, ClassDeclarationSyntax? ownerClass = null) : base(heading)
+ {
+     OwnerClass = ownerClass;
+ }
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 ClassDeclarationSyntax? OwnerClass { get; set; }
public bool IsMethodType => OwnerClass is null && IsAbstract && !Modifiers.Any();
public ClassDeclarationSyntax? OwnerClass { get; set; }
public MethodDeclarationSyntax(MemberDeclarationSyntax? heading = null, ClassDeclarationSyntax? ownerClass = null) : base(heading)
{
OwnerClass = ownerClass;
}
public bool IsMethodType => OwnerClass is null && IsAbstract && !Modifiers.Any();

Comment on lines +62 to +85
public bool HasCompatibility(VeinMethodSignature otherSig)
{
if (ArgLength != otherSig.ArgLength)
return false;

var argumentsCompatibility = true;
for (int i = 0; i < Arguments.Count; i++)
{
var a1 = Arguments[i];
var a2 = otherSig.Arguments[i];

if (a1.IsGeneric != a2.IsGeneric)
{
argumentsCompatibility = false;
break;
}
if (a1.IsGeneric)
continue;
if (a1.Type.FullName != a2.Type.FullName)
argumentsCompatibility = false;
}

return argumentsCompatibility;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

New method: HasCompatibility

The HasCompatibility method checks for compatibility between method signatures. The logic seems correct, but there are some improvements to consider:

  1. The nested loops and conditionals can be simplified for readability.
  2. The argumentsCompatibility variable can be returned directly instead of using a break statement.
public bool HasCompatibility(VeinMethodSignature otherSig)
{
    if (ArgLength != otherSig.ArgLength)
        return false;

    for (int i = 0; i < Arguments.Count; i++)
    {
        var a1 = Arguments[i];
        var a2 = otherSig.Arguments[i];

        if (a1.IsGeneric != a2.IsGeneric || (!a1.IsGeneric && a1.Type.FullName != a2.Type.FullName))
            return false;
    }

    return true;
}
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 bool HasCompatibility(VeinMethodSignature otherSig)
{
if (ArgLength != otherSig.ArgLength)
return false;
var argumentsCompatibility = true;
for (int i = 0; i < Arguments.Count; i++)
{
var a1 = Arguments[i];
var a2 = otherSig.Arguments[i];
if (a1.IsGeneric != a2.IsGeneric)
{
argumentsCompatibility = false;
break;
}
if (a1.IsGeneric)
continue;
if (a1.Type.FullName != a2.Type.FullName)
argumentsCompatibility = false;
}
return argumentsCompatibility;
}
public bool HasCompatibility(VeinMethodSignature otherSig)
{
if (ArgLength != otherSig.ArgLength)
return false;
for (int i = 0; i < Arguments.Count; i++)
{
var a1 = Arguments[i];
var a2 = otherSig.Arguments[i];
if (a1.IsGeneric != a2.IsGeneric || (!a1.IsGeneric && a1.Type.FullName != a2.Type.FullName))
return false;
}
return true;
}

@0xF6 0xF6 merged commit 8aa6748 into master Jun 29, 2024
15 of 16 checks passed
@0xF6 0xF6 deleted the feature/generic-and-type-aliases-imrovements branch June 29, 2024 01:43
@vein-lang vein-lang locked and limited conversation to collaborators Jun 29, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-compiler Area of compiler staff area-IL Area of intermediate language area-runtime Area of runtime forge area-vm Area of virtual machine feature priority 1 important size: S small task (< 1 week)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant