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

Fixes/branch logic improvements #239

Merged
merged 10 commits into from
Jun 15, 2024
Merged

Conversation

0xF6
Copy link
Member

@0xF6 0xF6 commented Jun 15, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new option DisableOptimization for compile commands.
    • Added implicit usings and enabled nullable reference types in project configuration.
  • Improvements

    • Refactored error handling and logging to use more detailed file information.
    • Enhanced scope management with controlled scope creation.
    • Improved code readability and efficiency in multiple methods.
    • Updated type determination logic for unary expressions.
    • Enhanced equality comparisons and conditional jumps in the virtual machine.
  • Bug Fixes

    • Fixed method signature inconsistencies and improved error detection/handling.

@0xF6 0xF6 added area-vm Area of virtual machine area-compiler Area of compiler staff bug labels Jun 15, 2024
@0xF6 0xF6 requested a review from code-maid June 15, 2024 02:39
@0xF6 0xF6 self-assigned this Jun 15, 2024
Copy link
Contributor

coderabbitai bot commented Jun 15, 2024

Walkthrough

The changes consist of various enhancements and optimizations across multiple files. Key modifications include updates to method signatures, additions of new parameters, adjustments in control flow, improved error handling, debugging aids, and refactoring of class constructors and initializations. These alterations aim to improve code clarity, efficiency, and maintainability while introducing new features and settings for optimization control.

Changes

File(s) Change Summary
compiler/Log.cs Modified Error method parameters; updated internal method logic.
compiler/cmd/CompileCommand.cs Added DisableOptimization option; corrected method signatures and loop handling; typos fixed.
compiler/compilation/CompilationTask.cs Adjusted class constructor and property initializations; improved context/module setup.
compiler/compilation/parts/bodies.cs Switched to using var for better scope management in GenerateBody method.
compiler/veinc.csproj Enabled implicit usings and nullable reference types.
lib/ast/stl/VeinParserExtensions.cs Added parameters to VeinParseException constructor; refactored ExchangeWrapper struct.
lib/ast/syntax/ErrorDiff.cs Updated DiffErrorFull and DiffError methods to use FileInfo and handle error detection.
lib/ast/syntax/PreviewParseExtension.cs Refactored PreviewMultiple for improved readability and efficiency.
lib/ast/syntax/ast/expressions/... Modified constructor in CorruptedChainException class for better error handling.
runtime/ishtar.base/emit/ILGenerator.cs Added label definition names for clarity; enhanced label usage for debugging.
runtime/ishtar.base/emit/Label.cs Converted Label struct to record struct; added a Name property.
runtime/ishtar.generator/... Updated GeneratorContext to use a configuration record; added scope management in VeinScope.
runtime/ishtar.generator/generators/... Enhanced conditional and operational logic for various code generation methods.
runtime/ishtar.vm/VirtualMachine.cs Modified equality and conditional jump logic; enhanced stack operations and flow.
runtime/ishtar.vm/stackval.cs Added [DebuggerDisplay] attribute; implemented ToString() for debugging.
runtime/ishtar.vm/vm.shit.cs Introduced comprehensive comparer logic; added new helper methods and error handling.

Poem

In the realm of code so bright,
Changes weave through day and night.
From labels sharp to scopes so tight,
Debugging’s ease is in full sight.
Optimization off or left on,
With these tweaks, our code shall dawn. 🐇✨


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

Outside diff range and nitpick comments (7)
runtime/ishtar.generator/VeinScope.cs (1)

15-15: Add documentation for ScopeId.

It would enhance understanding if there were a comment explaining the purpose of ScopeId and how it is used within VeinScope.

compiler/Log.cs (1)

Line range hint 55-78: Improve error reporting format.

The method _print could benefit from a more structured format for error messages, especially when both posed and doc are not null.

-            var diff_err = posed.Transform.DiffErrorFull(doc);
-            strBuilder.Append($"\t\t{diff_err}");
+            if (posed != null && doc != null)
+            {
+                var diff_err = posed.Transform.DiffErrorFull(doc);
+                strBuilder.AppendLine("\tDetails:");
+                strBuilder.AppendLine($"\t\tFile: {doc.FullName}");
+                strBuilder.AppendLine($"\t\tError: {diff_err}");
+            }
runtime/ishtar.vm/vm.shit.cs (1)

66-67: Clarify the purpose of _true and _false constants.

It's good practice to add comments explaining the purpose of these constants, especially since they are pivotal in the comparison logic.

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

Line range hint 355-430: Refactor exception handling blocks for clarity and robustness.

The methods BeginTryBlock, EndExceptionBlock, and BeginFinallyBlock could be refactored to improve readability and error handling robustness. Consider encapsulating some of the logic into smaller, more focused methods.


Line range hint 453-479: Improve label management in the DefineLabel and UseLabel methods.

These methods could benefit from a more robust management system for labels, potentially using a dedicated class or structure to handle label storage and retrieval, which could improve maintainability and error prevention.


Line range hint 393-393: Address the nullable reference type annotation issue.

Ensure that nullable reference type annotations are used within a '#nullable' annotations context to comply with C# best practices.

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

Line range hint 1-1131: General review: Error handling, performance, and consistency.

This file is critical for the performance and reliability of the virtual machine. It is recommended to:

  1. Review all exception handling paths to ensure they are robust and cover all possible error conditions.
  2. Optimize memory management, particularly in methods that allocate significant resources.
  3. Ensure consistency in the handling of different data types and operations across the entire file.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 33562d3 and 19fb20b.

Files selected for processing (20)
  • compiler/Log.cs (3 hunks)
  • compiler/cmd/CompileCommand.cs (6 hunks)
  • compiler/compilation/CompilationTask.cs (3 hunks)
  • compiler/compilation/parts/bodies.cs (1 hunks)
  • compiler/veinc.csproj (1 hunks)
  • lib/ast/stl/VeinParserExtensions.cs (3 hunks)
  • lib/ast/syntax/ErrorDiff.cs (3 hunks)
  • lib/ast/syntax/PreviewParseExtension.cs (1 hunks)
  • lib/ast/syntax/ast/expressions/functions/CorruptedChainException.cs (1 hunks)
  • runtime/ishtar.base/emit/ILGenerator.cs (6 hunks)
  • runtime/ishtar.base/emit/Label.cs (1 hunks)
  • runtime/ishtar.generator/GeneratorContext.cs (2 hunks)
  • runtime/ishtar.generator/VeinScope.cs (4 hunks)
  • runtime/ishtar.generator/generators/cycles.cs (1 hunks)
  • runtime/ishtar.generator/generators/logic.cs (2 hunks)
  • runtime/ishtar.generator/generators/operators.cs (3 hunks)
  • runtime/ishtar.generator/generators/types.cs (1 hunks)
  • runtime/ishtar.vm/VirtualMachine.cs (3 hunks)
  • runtime/ishtar.vm/stackval.cs (2 hunks)
  • runtime/ishtar.vm/vm.shit.cs (1 hunks)
Files skipped from review due to trivial changes (1)
  • compiler/compilation/parts/bodies.cs
Additional context used
GitHub Check: build_all (ubuntu-latest, linux-x64, true)
lib/ast/syntax/ErrorDiff.cs

[failure] 25-25:
The type or namespace name 'FileInfo' could not be found (are you missing a using directive or an assembly reference?)

runtime/ishtar.vm/stackval.cs

[warning] 9-9:
The type name 'stackval' only contains lower-cased ascii characters. Such names may become reserved for the language.

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.

GitHub Check: Codacy Static Code Analysis
runtime/ishtar.vm/vm.shit.cs

[notice] 59-59: runtime/ishtar.vm/vm.shit.cs#L59
Remove these redundant parentheses.

Additional comments not posted (20)
runtime/ishtar.base/emit/Label.cs (2)

7-7: Proper use of internal access modifier for Value ensures encapsulation within the assembly.


8-8: Good encapsulation with internal access for Name, aligns with the encapsulation strategy of Value.

lib/ast/syntax/ast/expressions/functions/CorruptedChainException.cs (1)

6-7: Excellent use of contextual information in the exception message, enhancing the clarity and utility of error reporting.

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

13-14: Proper use of descriptive labels enhances readability and debuggability of the loop constructs.

Also applies to: 17-17


17-17: Good practice to check the expression type to ensure it's boolean before evaluating it in a conditional context. Prevents runtime type errors.

compiler/veinc.csproj (1)

6-7: Enabling implicit usings and nullable reference types are modern C# practices that enhance code quality and safety.

runtime/ishtar.vm/stackval.cs (2)

8-8: Adding the DebuggerDisplay attribute enhances the debugging experience by providing a clear, custom string representation of stackval instances.


80-107: The expanded ToString method now handles all VeinTypeCode types, providing a comprehensive and informative string representation for each type.

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

56-85: The refactored PreviewMultiple method improves readability and functionality by clearly handling multiple parsers and outcomes. It also optimizes the process of determining the best parsing result.

lib/ast/stl/VeinParserExtensions.cs (2)

64-64: Enhancing the VeinParseException constructor to include detailed position information improves error reporting and diagnostics.


119-121: The introduction of the ExchangeWrapper struct simplifies parser transformations, enhancing modularity and reusability of parsing components.

compiler/cmd/CompileCommand.cs (2)

24-27: Adding the DisableOptimization command option provides users with more control over the compilation process by allowing them to disable optimizations if needed.


Line range hint 55-161: The refactored command execution logic in CompileCommand and related classes improves handling of multiple projects and enhances error reporting, making the compilation process more robust and user-friendly.

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

Line range hint 14-48: Proper implementation of configuration and scope management.

The introduction of GeneratorContextConfig for managing configurations and the changes in scope initialization are well-implemented.

compiler/compilation/CompilationTask.cs (2)

Line range hint 25-39: Well-structured constructor and property initialization.

The restructuring of the CompilationTask constructor to include initialization of properties directly from parameters enhances clarity and maintainability.


209-211: Correct setup of context and module initialization.

The initialization of the Context with GeneratorContextConfig and the setup of the module are correctly implemented to align with the new configuration strategy.

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

31-31: Enhanced handling of binary expressions.

The updated handling of binary expressions to include both numeric and non-numeric types, along with improved error handling, is commendable.


239-239: Improved unary operator handling.

The specific handling of the Not operator for boolean types in the EmitUnary method is a logical and necessary improvement.


286-289: Enhanced handling of equality operators.

The specific handling of NotEqual and Equal operators for boolean types in the EmitBinaryOperator method is well-implemented and enhances clarity.

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

930-930: Ensure correct handling of TYPE_BOOLEAN in jump conditions.

The addition of TYPE_BOOLEAN handling in the jump conditions needs careful verification to ensure it aligns with the expected logical flow and does not introduce any unintended behaviors. Consider adding unit tests specifically targeting these conditions to validate their correctness under various scenarios.

Also applies to: 1131-1131

Verification successful

Ensure correct handling of TYPE_BOOLEAN in jump conditions.

The provided test cases in test/vc_test/expression_test.cs confirm that TYPE_BOOLEAN is being tested. Specifically, the tests validate that the result's type is correctly determined as TYPE_BOOLEAN.

  • test/vc_test/expression_test.cs
    • Assert.AreEqual(VeinTypeCode.TYPE_BOOLEAN, type.TypeCode);

These tests should be sufficient to verify the correct handling of TYPE_BOOLEAN in jump conditions.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the handling of `TYPE_BOOLEAN` in jump conditions.

# Test: Check for unit tests covering the new jump conditions with `TYPE_BOOLEAN`.
rg --type cs $'TYPE_BOOLEAN' --files-with-matches | xargs rg 'test'

Length of output: 182



Script:

#!/bin/bash
# Description: Inspect the contents of `test/vc_test/expression_test.cs` for test cases involving `TYPE_BOOLEAN`.

# Display the lines containing `TYPE_BOOLEAN` and surrounding context in the test file.
rg --type cs --context 5 'TYPE_BOOLEAN' test/vc_test/expression_test.cs

Length of output: 548

Comment on lines +808 to +818
case EQL_T:
case EQL_F:
{
++ip;
--sp;
var first = *sp;
*sp = _comparer(first, default, invocation->last_ip, invocation);
println($"$$$ {invocation->last_ip} : {debug_comparer_get_symbol(first, default, invocation->last_ip)} == {sp->data.i == 1}");
sp++;
}
break;
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine the new comparison operations for clarity and performance.

The new comparison operations introduced in these lines could benefit from a refactoring for clarity. Consider encapsulating the comparison logic into a separate method to improve readability and maintainability. Additionally, ensure that the operations are optimized for performance, given their critical role in the execution flow.

Also applies to: 822-836

Comment on lines +17 to +64
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private stackval _comparer(in stackval first, in stackval second, OpCodeValue operation, CallFrame* frame)
{
if (operation is not EQL_F and not EQL_T && first.type != second.type)
{
switch (first.type)
{
case TYPE_I4 when second.type is TYPE_BOOLEAN:
break;
case TYPE_BOOLEAN when second.type is TYPE_I4:
break;
default:
FastFail(WNE.TYPE_MISMATCH, "", frame);
return default;
}
}

var result = (first.type) switch
{
TYPE_I4 or TYPE_BOOLEAN or TYPE_CHAR
=> comparer(first.data.i, second.data.i, operation),
TYPE_I1 => comparer(first.data.b, second.data.b, operation),
TYPE_U1 => comparer(first.data.ub, second.data.ub, operation),
TYPE_I2 => comparer(first.data.s, second.data.s, operation),
TYPE_U2 => comparer(first.data.us, second.data.us, operation),
TYPE_U4 => comparer(first.data.ui, second.data.ui, operation),
TYPE_I8 => comparer(first.data.l, second.data.l, operation),
TYPE_U8 => comparer(first.data.ul, second.data.ul, operation),
TYPE_R2 => comparer(first.data.hf, second.data.hf, operation),
TYPE_R4 => comparer(first.data.f_r4, second.data.f_r4, operation),
TYPE_R8 => comparer(first.data.f, second.data.f, operation),
TYPE_R16 => comparer(first.data.d, second.data.d, operation),
TYPE_RAW => comparer(first.data.p, second.data.p, operation),
_ => throw new ArgumentOutOfRangeException()
};

if (result is -1)
{
FastFail(WNE.STATE_CORRUPT, "", frame);
return default;
}

return new stackval()
{
data = { i = result },
type = TYPE_BOOLEAN
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor the _comparer method to simplify the switch-case logic.

Consider using a dictionary or a more dynamic dispatch mechanism to handle type comparisons, which could reduce the complexity and improve maintainability of this method.

Tools
GitHub Check: Codacy Static Code Analysis

[notice] 59-59: runtime/ishtar.vm/vm.shit.cs#L59
Remove these redundant parentheses.

Comment on lines +69 to +106
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private string debug_comparer_get_symbol(in stackval first, in stackval second, OpCodeValue operation)
{
return (first.type) switch
{
TYPE_I4 or TYPE_BOOLEAN or TYPE_CHAR
=> debug_comparer_get_symbol(first.data.i, second.data.i, operation),
TYPE_I1 => debug_comparer_get_symbol(first.data.b, second.data.b, operation),
TYPE_U1 => debug_comparer_get_symbol(first.data.ub, second.data.ub, operation),
TYPE_I2 => debug_comparer_get_symbol(first.data.s, second.data.s, operation),
TYPE_U2 => debug_comparer_get_symbol(first.data.us, second.data.us, operation),
TYPE_U4 => debug_comparer_get_symbol(first.data.ui, second.data.ui, operation),
TYPE_I8 => debug_comparer_get_symbol(first.data.l, second.data.l, operation),
TYPE_U8 => debug_comparer_get_symbol(first.data.ul, second.data.ul, operation),
TYPE_R2 => debug_comparer_get_symbol(first.data.hf, second.data.hf, operation),
TYPE_R4 => debug_comparer_get_symbol(first.data.f_r4, second.data.f_r4, operation),
TYPE_R8 => debug_comparer_get_symbol(first.data.f, second.data.f, operation),
TYPE_R16 => debug_comparer_get_symbol(first.data.d, second.data.d, operation),
TYPE_RAW => debug_comparer_get_symbol(first.data.p, second.data.p, operation),
_ => throw new ArgumentOutOfRangeException()
};
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string debug_comparer_get_symbol<TNumber>(TNumber first, TNumber second, OpCodeValue operation)
where TNumber : INumber<TNumber>
=> (operation) switch
{
EQL_F => $"{first} == {TNumber.Zero}",
EQL_H => $"{first} > {second}",
EQL_L => $"{first} < {second}",
EQL_T => $"{first} == {TNumber.One}",
EQL_NN => $"{first} != {second}",
EQL_HQ => $"{first} >= {second}",
EQL_LQ => $"{first} <= {second}",
EQL_NQ => $"{first} == {second}",
_ => "INVALID"
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance readability of the debug_comparer_get_symbol method.

This method could benefit from using a dictionary or a strategy pattern for operation handling to make the code more readable and extensible.

Comment on lines +108 to +141
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int comparer<TNumber>(
TNumber first,
TNumber second,
OpCodeValue operation)
where TNumber : INumber<TNumber> =>
(operation) switch
{

EQL_F when first == TNumber.Zero => _true,
EQL_F => _false,

EQL_H when first > second => _true,
EQL_H => _false,

EQL_L when first < second => _true,
EQL_L => _false,

EQL_T when first == TNumber.One => _true,
EQL_T => _false,

EQL_NN when first != second => _true,
EQL_NN => _false,

EQL_HQ when first >= second => _true,
EQL_HQ => _false,

EQL_LQ when first <= second => _true,
EQL_LQ => _false,

EQL_NQ when first == second => _true,
EQL_NQ => _false,

_ => -1
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize the comparer method to handle edge cases more gracefully.

Consider adding more comprehensive handling for edge cases and potentially using a strategy pattern or similar to handle different types of comparisons.

Comment on lines +59 to +63
return new stackval()
{
data = { i = result },
type = TYPE_BOOLEAN
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove redundant parentheses as suggested by static analysis.

- return new stackval()
+ return new stackval
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
return new stackval()
{
data = { i = result },
type = TYPE_BOOLEAN
};
return new stackval
{
data = { i = result },
type = TYPE_BOOLEAN
};
Tools
GitHub Check: Codacy Static Code Analysis

[notice] 59-59: runtime/ishtar.vm/vm.shit.cs#L59
Remove these redundant parentheses.

Comment on lines +52 to +60
try
{
return ExitScope();
}
catch (CannotExistMainScopeException e)
{
if (!allowExitFromRoot)
throw;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider simplifying exception handling.

The exception handling in ExitScope could be simplified by removing the unnecessary try-catch block if the logic does not specifically require it.

-        try
-        {
-            return ExitScope();
-        }
-        catch (CannotExistMainScopeException e)
-        {
-            if (!allowExitFromRoot)
-                throw;
-        }
+        if (!allowExitFromRoot)
+            throw new CannotExistMainScopeException();
+        return ExitScope();
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
try
{
return ExitScope();
}
catch (CannotExistMainScopeException e)
{
if (!allowExitFromRoot)
throw;
}
if (!allowExitFromRoot)
throw new CannotExistMainScopeException();
return ExitScope();

@@ -22,15 +22,32 @@
}
}

private static (string line, string arrow_line) NewDiffError(Transform t, DocumentDeclaration doc)
public static string DiffErrorFull(this Transform t, FileInfo doc)
Copy link
Contributor

Choose a reason for hiding this comment

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

Add missing import for FileInfo.

The FileInfo class is used but not imported, causing a build failure. Add the necessary using System.IO; directive at the top of the file.

+ using System.IO;
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 string DiffErrorFull(this Transform t, FileInfo doc)
+ using System.IO;
public static string DiffErrorFull(this Transform t, FileInfo doc)
Tools
GitHub Check: build_all (ubuntu-latest, linux-x64, true)

[failure] 25-25:
The type or namespace name 'FileInfo' could not be found (are you missing a using directive or an assembly reference?)

Comment on lines +17 to +24
if (!ctx.DisableOptimization && ifStatement.Expression is BoolLiteralExpressionSyntax @bool)
{
if (@bool.Value)
{
generator.EmitStatement(ifStatement.ThenStatement);
if (ifStatement.ElseStatement is not null)
generator.Emit(OpCodes.JMP, endLabel);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize conditional branches.

The branching logic in EmitIfElse can be optimized by consolidating checks and reducing duplicate code.

-        if (!ctx.DisableOptimization && ifStatement.Expression is BoolLiteralExpressionSyntax @bool)
-        {
-            if (@bool.Value)
-            {
-                generator.EmitStatement(ifStatement.ThenStatement);
-                if (ifStatement.ElseStatement is not null)
-                    generator.Emit(OpCodes.JMP, endLabel);
-            }
-            else
-                generator.Emit(OpCodes.JMP, elseLabel);
-        }
+        if (!ctx.DisableOptimization && ifStatement.Expression is BoolLiteralExpressionSyntax @bool && @bool.Value)
+        {
+            generator.EmitStatement(ifStatement.ThenStatement);
+            if (ifStatement.ElseStatement is not null)
+                generator.Emit(OpCodes.JMP, endLabel);
+        }
+        else if (!ctx.DisableOptimization && ifStatement.Expression is BoolLiteralExpressionSyntax @bool && [email protected])
+            generator.Emit(OpCodes.JMP, elseLabel);

Also applies to: 31-34


public static void Error(string text) => _print(text, null, null, errors);
public static void Error(string text, BaseSyntax posed) => _print(text, posed, null, errors);
public static void Error(string text, BaseSyntax posed, DocumentDeclaration doc)
=> _print(text, posed, doc.FileEntity, errors);
public static void Error(string text, BaseSyntax posed, FileInfo doc)
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure consistent error handling.

The method _print is used in different ways, which could lead to inconsistencies in how logs are handled. Consider standardizing the input parameters and the way errors are logged.

-        public static void Error(string text, BaseSyntax posed, FileInfo doc)
-            => _print(text, posed, doc, errors);
+        public static void Error(string text, BaseSyntax posed, FileInfo doc)
+        {
+            if (doc == null) throw new ArgumentNullException(nameof(doc));
+            _print(text, posed, doc, errors);
+        }
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 void Error(string text, BaseSyntax posed, FileInfo doc)
public static void Error(string text, BaseSyntax posed, FileInfo doc)
{
if (doc == null) throw new ArgumentNullException(nameof(doc));
_print(text, posed, doc, errors);
}

Comment on lines +125 to +130
if (exp is UnaryExpressionSyntax unary)
{
if (unary.OperatorType.IsLogic())
return VeinTypeCode.TYPE_BOOLEAN.AsClass()(Types.Storage);
// todo
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Incomplete implementation of unary operator handling.

Please complete the implementation for unary operators as indicated by the "todo" comment.

@0xF6 0xF6 merged commit fde1ac3 into master Jun 15, 2024
8 of 12 checks passed
@0xF6 0xF6 deleted the fixes/branch-logic-improvements branch June 15, 2024 02:45
@vein-lang vein-lang locked and limited conversation to collaborators Jun 15, 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-vm Area of virtual machine bug
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant