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

Переделаны перечисления для работы в native #1480

Merged
merged 5 commits into from
Dec 31, 2024

Conversation

Mr-Rm
Copy link
Collaborator

@Mr-Rm Mr-Rm commented Dec 30, 2024

Summary by CodeRabbit

Based on the comprehensive summary, here are the release notes:

  • New Features

    • Enhanced enum handling and type conversion mechanisms across multiple components
    • Improved caching and value management for enumeration types
  • Refactoring

    • Simplified enum wrapper classes and instance creation processes
    • Streamlined type conversion and value registration methods
    • Removed redundant caching and wrapper classes
  • Bug Fixes

    • Improved type checking and conversion for enum values
    • Enhanced error handling for enum-related operations
  • Documentation

    • Updated type references and namespaces for better clarity

The changes primarily focus on improving the internal handling of enumeration types, making the code more efficient and maintainable while preserving existing functionality.

Copy link

coderabbitai bot commented Dec 30, 2024

Walkthrough

This pull request introduces a comprehensive refactoring of enumeration handling across the OneScript library. The changes primarily focus on simplifying enum value management, introducing a new caching mechanism for enum values, and standardizing the approach to handling enumeration types. Key modifications include updating inheritance for enum classes, removing redundant wrapper classes, and streamlining the creation and management of enum instances. The changes span multiple namespaces and affect various components of the library, with a particular emphasis on XML-related enumerations and type conversion mechanisms.

Changes

File Path Change Summary
src/OneScript.Core/TypeUtils.cs Modified IsNumeric method to exclude enums from numeric types
src/OneScript.Core/Values/ClrEnumValueWrapper.cs Namespace changed, constructor updated, simplified property implementations
src/OneScript.Native/Compiler/ExpressionHelpers.cs Added logic for handling conversions to enum types
src/ScriptEngine/Machine/Contexts/ClrEnumWrapper.cs Added ClrEnumWrapperCached<T> class, updated Autoregister method
Multiple XML Schema Enumeration Files Removed separate wrapper classes, updated to use ClrEnumWrapperCached<T>
Multiple Test Files Updated type checks to reflect new enum class naming

Poem

🐰 Hop, hop, through the enum's domain,
Refactoring code with algorithmic reign
Cached values, wrappers unwrapped with care
Simplicity blooms everywhere
A rabbit's code dance, clean and bright! 🌟


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>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (8)
src/OneScript.Core/Values/ClrEnumValueWrapper.cs (1)

Line range hint 27-35: Ensure Equals is consistent with GetHashCode
Overriding Equals(BslValue) is correct for type checking. However, consider providing a matching GetHashCode override to preserve equality contract consistency.

 public override bool Equals(BslValue other)
 {
    if (!(other?.GetRawValue() is ClrEnumValueWrapper<T> otherWrapper))
       return false;
    return UnderlyingValue.Equals(otherWrapper.UnderlyingValue);
 }

+public override int GetHashCode()
+{
+    return UnderlyingValue.GetHashCode();
+}
src/ScriptEngine/Machine/Contexts/ClrEnumWrapper.cs (1)

36-40: Commented Benchmark Code
Leaving benchmarking code commented out is acceptable, though removing it entirely might clarify maintenance.

src/OneScript.StandardLibrary/Xml/XmlSpaceEnum.cs (1)

21-22: Localized names vs. English names.
You're using Russian labels ("ПоУмолчанию", "Сохранять") and English equivalents ("Default", "Preserve"). Make sure this bilingual naming is intentional, consistent, and well-documented, or consider standardizing to a single language to avoid confusion.

src/OneScript.StandardLibrary/Xml/XmlValidationTypeEnum.cs (1)

11-11: New import path.
Ensure that using OneScript.StandardLibrary.XMLSchema.Enumerations; is needed and that it doesn’t introduce redundant inclusions.

src/OneScript.StandardLibrary/Text/ConsoleColorEnum.cs (1)

22-38: Console colors wrapped correctly, but consider centralizing color definitions.
The repeated calls to WrapClrValue are valid. If numerous files define similar sets of color enums, consider a shared resource or reference for color naming to prevent typos and improve maintainability.

src/ScriptEngine/Machine/Contexts/EnumContextHelper.cs (1)

55-55: Conditional assignment may need fallback clarity.
metadata.Alias != default ? "Enum" + metadata.Alias : default is correct, but confirm that default for a string is null, which the runtime will handle fine. Just ensure it doesn’t cause confusion.

src/OneScript.StandardLibrary/Binary/FileStreamContext.cs (1)

306-324: Constructor parameter handling for param3
Renaming bufferSize to param3 adds flexibility at the callsite, but it introduces a more generic parameter name. Ensure that the parameter's purpose is still clear to users or that you provide enough documentation.

- public static FileStreamContext Constructor(IValue filename, IValue openMode, IValue param3 = null)
+ /// <summary>
+ /// The third parameter (param3) can be either a numeric buffer size or a FileAccessEnum value, controlling file access or buffering.
+ /// </summary>
src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSProhibitedSubstitutions.cs (1)

21-23: Validate localized string keys
Your calls to MakeValue("Все", "All", ...) rely on string keys for localized usage. Ensure these values match the broader localization requirements and remain consistent across your enum definitions.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72229c7 and bb550fa.

📒 Files selected for processing (41)
  • src/OneScript.Core/TypeUtils.cs (1 hunks)
  • src/OneScript.Core/Values/ClrEnumValueWrapper.cs (1 hunks)
  • src/OneScript.Core/Values/EnumerationValue.cs (1 hunks)
  • src/OneScript.Native/Compiler/ExpressionHelpers.cs (1 hunks)
  • src/OneScript.StandardLibrary/Binary/FileStreamContext.cs (2 hunks)
  • src/OneScript.StandardLibrary/DriveInfo/DriveTypeEnum.cs (2 hunks)
  • src/OneScript.StandardLibrary/Json/JSONWriterSettings.cs (1 hunks)
  • src/OneScript.StandardLibrary/SystemEnvironmentContext.cs (1 hunks)
  • src/OneScript.StandardLibrary/Tasks/BackgroundTasksManager.cs (1 hunks)
  • src/OneScript.StandardLibrary/Text/ConsoleColorEnum.cs (2 hunks)
  • src/OneScript.StandardLibrary/Text/ConsoleContext.cs (1 hunks)
  • src/OneScript.StandardLibrary/Text/TextEncodingEnum.cs (2 hunks)
  • src/OneScript.StandardLibrary/XDTO/XDTOSerializer.cs (2 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Collections/XSComplexFinalUnion.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Collections/XSProhibitedSubstitutionsUnion.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Collections/XSSchemaFinalUnion.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Collections/XSSubstitutionGroupExclusionsUnion.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSComplexFinal.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSDisallowedSubstitutions.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSForm.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSProhibitedSubstitutions.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSSchemaFinal.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSSimpleFinal.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSSubstitutionGroupExclusions.cs (1 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Objects/XMLSchema.cs (2 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Objects/XSAttributeDeclaration.cs (2 hunks)
  • src/OneScript.StandardLibrary/XMLSchema/Objects/XSElementDeclaration.cs (2 hunks)
  • src/OneScript.StandardLibrary/Xml/XmlNodeTypeEnum.cs (2 hunks)
  • src/OneScript.StandardLibrary/Xml/XmlReaderImpl.cs (4 hunks)
  • src/OneScript.StandardLibrary/Xml/XmlReaderSettingsImpl.cs (1 hunks)
  • src/OneScript.StandardLibrary/Xml/XmlSpaceEnum.cs (1 hunks)
  • src/OneScript.StandardLibrary/Xml/XmlValidationTypeEnum.cs (2 hunks)
  • src/OneScript.StandardLibrary/Zip/ZipWriter.cs (1 hunks)
  • src/ScriptEngine/Machine/Contexts/ClrEnumWrapper.cs (5 hunks)
  • src/ScriptEngine/Machine/Contexts/ContextDiscoverer.cs (1 hunks)
  • src/ScriptEngine/Machine/Contexts/EnumContextHelper.cs (4 hunks)
  • src/ScriptEngine/Machine/Contexts/EnumerationContext.cs (2 hunks)
  • src/ScriptEngine/Machine/Contexts/EnumerationValue.cs (0 hunks)
  • tests/XMLSchema/Enumerations/test-XSDisallowedSubstitutions.os (1 hunks)
  • tests/XMLSchema/Enumerations/test-XSForm.os (1 hunks)
  • tests/XMLSchema/Enumerations/test-XSSimpleFinal.os (1 hunks)
💤 Files with no reviewable changes (1)
  • src/ScriptEngine/Machine/Contexts/EnumerationValue.cs
✅ Files skipped from review due to trivial changes (6)
  • src/ScriptEngine/Machine/Contexts/ContextDiscoverer.cs
  • src/OneScript.StandardLibrary/Text/ConsoleContext.cs
  • src/OneScript.StandardLibrary/Json/JSONWriterSettings.cs
  • src/OneScript.StandardLibrary/Zip/ZipWriter.cs
  • src/OneScript.StandardLibrary/SystemEnvironmentContext.cs
  • src/OneScript.StandardLibrary/Tasks/BackgroundTasksManager.cs
🔇 Additional comments (87)
src/OneScript.StandardLibrary/XMLSchema/Collections/XSSchemaFinalUnion.cs (1)

24-24: Switching from an instance-based call to a static method

Using EnumerationXSSchemaFinal.FromNativeValue(value) simplifies the approach by removing the need for a singleton instance. Ensure that any other references to EnumerationXSSchemaFinal.Instance are also updated and verify that FromNativeValue remains thread-safe and reliable in concurrent scenarios, as a static method might be accessed from multiple threads.

src/OneScript.StandardLibrary/XMLSchema/Collections/XSSubstitutionGroupExclusionsUnion.cs (1)

24-24: Validate handling of all enumerations.

Switching to EnumerationXSSubstitutionGroupExclusions is consistent with the broader refactoring to unify enum usage. However, verify that FromNativeValue handles all valid XmlSchemaDerivationMethod values and does not throw unexpected runtime exceptions or omit unusual enumerations (e.g., custom ones).

Here is a helper script to confirm usages and references:

✅ Verification successful

Let me gather more information about the enum implementation.


Enum conversion is properly implemented and handles all relevant values

The verification shows that EnumerationXSSubstitutionGroupExclusions is properly implemented as a cached CLR enum wrapper that handles all relevant XmlSchemaDerivationMethod values for substitution group exclusions. The implementation:

  1. Inherits from ClrEnumWrapperCached<XmlSchemaDerivationMethod>
  2. Explicitly maps all required values:
    • "All" -> XmlSchemaDerivationMethod.All
    • "Restriction" -> XmlSchemaDerivationMethod.Restriction
    • "Extension" -> XmlSchemaDerivationMethod.Extension

These are the complete set of values needed for substitution group exclusions in XML Schema. The FromNativeValue method is part of the base class implementation and will properly handle these mapped values. No custom/unusual enumerations are possible in this context as these values are defined by the XML Schema specification.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for all calls to .FromNativeValue method to confirm consistent usage

rg -A 5 $'\\.FromNativeValue'

Length of output: 12245


Script:

#!/bin/bash
# Check the enum implementation and its values
ast-grep --pattern 'class EnumerationXSSubstitutionGroupExclusions {
  $$$
}'

# Also check the native enum type it's converting from
rg -B2 -A2 "XmlSchemaDerivationMethod"

Length of output: 22371

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSForm.cs (4)

13-13: No functional changes introduced here.
No change in logic or functionality noted.


17-17: Change of base class to ClrEnumWrapperCached<XmlSchemaForm>
Switching from the old EnumerationContext to ClrEnumWrapperCached<XmlSchemaForm> unifies the approach to enumeration caching with the rest of your changes. This increases consistency and is aligned with the new pattern.


22-23: Enum values definition looks correct.
The paired names ("Квалифицированная"/"Qualified", etc.) appear consistent with XmlSchemaForm. No issues found.


28-28: Direct instance creation aligns with new initialization approach.
The concise factory pattern is clear. No issues noted.

src/OneScript.Core/Values/ClrEnumValueWrapper.cs (5)

9-9: New using OneScript.Types; import
This import is straightforward and necessary for referencing TypeDescriptor. No concerns.


11-11: Namespace change to OneScript.Values
Moving this class under OneScript.Values clarifies the domain ownership of enumeration wrappers. This improves organization.


17-19: Constructor signature updates
Accepting TypeDescriptor systemType, a realValue, plus name and alias clarifies initialization. This approach is consistent with the changes to enumeration classes.


23-23: UnderlyingObject property
Exposing _realValue as the UnderlyingObject is appropriate and consistent with your other changes.


25-25: UnderlyingValue property
Providing a strongly typed property for the wrapped enum is clear and eases integration with other parts of the codebase.

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSComplexFinal.cs (3)

16-16: Change of base class to ClrEnumWrapperCached<XmlSchemaDerivationMethod>
Moving away from EnumerationContext simplifies how enum values are managed and cached.


21-23: Enum values correctly defined
"Все"/"All", "Ограничение"/"Restriction", "Список"/"List" mappings look appropriate and match XmlSchemaDerivationMethod.


28-28: Factory method pattern
CreateInstance uses the new concise creation pattern, improving readability.

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSSimpleFinal.cs (3)

16-16: Updated base class for enumeration
Switching to ClrEnumWrapperCached<XmlSchemaDerivationMethod> aligns with the unified enumeration handling approach.


21-24: Mapping of enum values is correct
"Все"/"All", "Объединение"/"Union", "Ограничение"/"Restriction", "Список"/"List" are correct references to XmlSchemaDerivationMethod.


29-29: Instantiating with a lambda
Following the same pattern as other enumerations helps maintain consistency across the codebase.

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSSubstitutionGroupExclusions.cs (3)

16-16: Adoption of ClrEnumWrapperCached<XmlSchemaDerivationMethod>
This eliminates the older wrapper approach, bringing it in line with the revised enum logic.


21-23: Enum value definitions
"Все"/"All", "Ограничение"/"Restriction", "Расширение"/"Extension" references look correct against XmlSchemaDerivationMethod.


28-28: Unified instance creation flow
Consistent factory idiom. No issues found.

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSDisallowedSubstitutions.cs (3)

16-16: Refactored Class Inheritance
Switching to ClrEnumWrapperCached<XmlSchemaDerivationMethod> appears consistent with the new caching approach used throughout the PR.


21-24: Correct Enumeration Value Registration
Enumeration values are properly defined via MakeValue. The naming and aliases look consistent.


29-29: Factory Pattern
Using CreateInstance(typeManager, (t, v) => new EnumerationXSDisallowedSubstitutions(t, v)) matches the updated enum creation approach. This maintains uniformity with other enumerations.

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSSchemaFinal.cs (3)

16-16: Adoption of ClrEnumWrapperCached
The shift to cached wrapper is aligned with the general refactoring for better performance.


21-25: Enumeration Values Consistency
All new MakeValue calls look logically correct for representing schema derivation methods.


31-31: Consistent Factory Method
Maintains a clear pattern with CreateInstance(typeManager, ...). No issues noted.

src/OneScript.Core/Values/EnumerationValue.cs (7)

17-20: New Abstract Class Fields
The fields _systemType, _name, and _alias are well-defined, ensuring strong typing for enumeration values.


22-33: Constructor Validations
Checking identifiers for both name and alias is a solid defensive measure, ensuring valid naming.


35-39: Name, Alias, and IsFilled
Exposing read-only properties and always returning true for IsFilled() is consistent with how enumerations are typically “always filled.”


40-45: SystemType and String Representation
Providing a localized string in ToString() is a good usage of BilingualString.


47-48: Raw Value Return
Returning this as the raw value for enumerations is suitable for runtime usage consistency.


49-52: Comparison Not Supported
Explicitly throwing an exception ensures clarity that enumerations can’t be compared numerically or lexically.


54-57: Reference-based Equality
Equals method referencing the same underlying object is the right approach for enumerations that act as singletons.

src/OneScript.StandardLibrary/Xml/XmlNodeTypeEnum.cs (2)

16-16: Cached Wrapper Introduction
Aligns with the PR’s consistent approach of using ClrEnumWrapperCached<T> for improved performance.


40-40: Instance Factory
Delegating instance creation to a lambda matches the updated pattern used across enumeration classes.

src/ScriptEngine/Machine/Contexts/ClrEnumWrapper.cs (10)

9-9: Additional Namespace
System.Collections.Generic inclusion is justified for caching and dictionary usage.


12-12: Using OneScript.Values
Coherent with the new EnumerationValue architecture.


50-50: Autoregister Method Signature
Changed to accept TypeDescriptor valuesType, which enhances extensibility for different enumeration value representations.


65-66: Alias Handling
Appropriate fallback to field name if alias is not specified.


71-71: Alias Fallback
Maintains consistency with the inherited logic and naming strategies.


73-77: Enum Value Construction
Creating ClrEnumValueWrapper<T> with explicit name and alias is well-structured.


81-81: Static CreateInstance
Simplifies instantiation, consistent with usage across the codebase.


85-85: Autoregister Invocation
Ensures newly created instances automatically populate the enumeration values.


95-103: Generic Factory Method
Allows type managers to create custom wrappers with minimal boilerplate.


106-127: ClrEnumWrapperCached
Introduces a consistent caching mechanism, preventing duplicates and optimizing lookups.

src/OneScript.StandardLibrary/Xml/XmlSpaceEnum.cs (2)

16-16: Adopted caching mechanism.
Switching from ClrEnumWrapper<XmlSpace> to ClrEnumWrapperCached<XmlSpace> can improve performance and streamline enum value handling by leveraging caching. Ensure it’s thread-safe and that it integrates well with the rest of the codebase.


27-27: Streamlined instance creation.
Using the lambda-based constructor call for CreateInstance is a concise approach. Double-check that downstream code doesn't rely on now-removed intermediate logic.

tests/XMLSchema/Enumerations/test-XSForm.os (1)

35-35: Confirm renaming from “EnumerationXSForm” to “EnumXSForm.”
This change aligns with similar enumeration refactoring across the codebase. Ensure that all references to “EnumerationXSForm” are updated consistently to avoid broken references.

src/OneScript.StandardLibrary/Xml/XmlValidationTypeEnum.cs (2)

18-18: Aligned with the new caching class.
Switching to ClrEnumWrapperCached<ValidationType> matches the overall redesign for enumeration handling. Confirm that references to any old caching logic were fully removed.


30-30: Reusable creation pattern.
Following a consistent pattern of instance creation helps maintain uniformity in code. This is good practice for simplifying future maintenance.

src/OneScript.Core/TypeUtils.cs (1)

21-21: Double-check excluding enums from numeric checks.
Returning !type.IsEnum means enums will no longer be treated as numeric, even if their underlying type is a numeric type. Confirm that this aligns with your intended logic and doesn’t break existing behavior.

✅ Verification successful

Let me gather more information about enum usage in the codebase.


Let me check how enums are handled in the codebase, particularly around numeric operations.


Based on the analysis of the codebase, I can now provide a final response regarding the enum exclusion from numeric checks.

Excluding enums from numeric checks is correct and safe

The change to exclude enums from numeric checks by returning !type.IsEnum is correct because:

  1. The codebase handles enums separately through ClrEnumValueWrapper<T> class, which provides proper type-safe enum handling and value conversion.
  2. Enums are wrapped and unwrapped explicitly when needed, as seen in multiple places in the codebase (e.g., in ContextValuesMarshaller.cs and ExpressionHelpers.cs).
  3. The numeric operations in BinaryOperationCompiler.cs and other compiler components expect actual numeric types for arithmetic operations, not enum values.

The change ensures that enums are handled through their dedicated wrapper system rather than being treated as raw numeric values, which is a safer approach that preserves type safety and semantic meaning of enum values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find references to IsNumeric and confirm if they rely on enums being numeric
rg -A 5 $'IsNumeric'

Length of output: 6989


Script:

#!/bin/bash
# Find enum declarations and their base types
ast-grep --pattern 'enum $_ : $_'

# Find any direct enum comparisons or operations
rg -A 3 "IsEnum|GetTypeCode.*Enum"

Length of output: 1128


Script:

#!/bin/bash
# Find enum-related value handling and conversions
rg -A 5 "ClrEnumValueWrapper|ConvertEnum"

# Check for any numeric operations or conversions involving enums
ast-grep --pattern 'class ClrEnumValueWrapper'

Length of output: 65706

tests/XMLSchema/Enumerations/test-XSSimpleFinal.os (1)

Line range hint 37-41: Check for consistent usage of renamed enumeration throughout the codebase
Renaming from "EnumerationXSSimpleFinal" to "EnumXSSimpleFinal" for the base type appears intentional and aligns with the new naming convention. However, the test still compares the derived members (e.g., XSSimpleFinal.All) to the old name "XSSimpleFinal" rather than "EnumXSSimpleFinal". If that is the desired behavior, verify that these references indeed reflect the correct type hierarchy.

tests/XMLSchema/Enumerations/test-XSDisallowedSubstitutions.os (1)

Line range hint 37-41: Confirm the updated type name matches external references
This change from "EnumerationXSDisallowedSubstitutions" to "EnumXSDisallowedSubstitutions" is consistent with the new naming approach. Ensure that all external references, such as type instantiations or documented references, correspond to the updated type name to prevent discrepancies.

src/OneScript.StandardLibrary/XMLSchema/Collections/XSComplexFinalUnion.cs (1)

25-27: Adoption of the new enumeration class looks correct
Switching from XSComplexFinal.FromNativeValue(value) to EnumerationXSComplexFinal.FromNativeValue(value) aligns with the broader refactoring. The implementation is straightforward, and the method’s logic appears intact. Make sure parallel usage in related classes and tests references EnumerationXSComplexFinal consistently.

src/OneScript.StandardLibrary/XMLSchema/Collections/XSProhibitedSubstitutionsUnion.cs (1)

25-27: Use of the updated enumeration wrapper is coherent
Replacing XSProhibitedSubstitutions.FromNativeValue(value) with EnumerationXSProhibitedSubstitutions.FromNativeValue(value) is consistent with the new enumeration handling strategy. The usage of _values.Find(enumValue) remains the same and should function as intended, assuming the rest of the refactoring follows the same pattern.

src/OneScript.StandardLibrary/DriveInfo/DriveTypeEnum.cs (3)

10-10: No issues with the added import.
The using OneScript.Values; statement appears necessary to support the updated enumeration logic (e.g., WrapClrValue).


31-37: Values wrapped correctly, potential naming consistency check.
These calls to WrapClrValue look correct. Consider confirming that the Russian identifiers (e.g., "Неизвестный") consistently match the rest of your codebase for readability and naming conventions.


42-43: Creation method follows new enumeration factory pattern.
Returning from EnumContextHelper.CreateClrEnumInstance<..., ...> is consistent with the updated approach. No issues identified.

src/OneScript.StandardLibrary/Text/ConsoleColorEnum.cs (2)

11-11: Import statement aligns with the new enum wrapper approach.
No concerns; this is consistent with the shift to using OneScript.Values.


43-43: Streamlined instance creation.
The static factory method properly delegates instance creation to the provided delegate. This matches best practices for enumerations in this refactoring.

src/ScriptEngine/Machine/Contexts/EnumerationContext.cs (4)

13-13: New import for enumeration values is consistent with design changes.
It’s needed for referencing EnumerationValue. No issues.


29-29: Method signature simplified.
Removing the need to pass additional parameters (e.g., name, alias) makes the API less error-prone, as the EnumerationValue object now carries these attributes.


33-33: Potential collision check for names and aliases.
While _nameIds.RegisterName is presumably handling collisions, ensure collisions are either disallowed or handled gracefully.


37-37: Expression-bodied property enhances readability.
This reduces boilerplate while keeping the logic clear. No issues.

src/ScriptEngine/Machine/Contexts/EnumContextHelper.cs (3)

10-10: Import statement for OneScript.Values aligns with updated wrapper usage.
No issues here.


74-75: Concise use of pattern decomposition.
The refactoring to a single line, returning creator(...), simplifies the flow. Looks good.


85-86: WrapClrValue directly adds wrapped enum value.
This update streamlines the process of creating and registering new enum values. Confirm _nameIds collision behavior, if relevant.

src/OneScript.StandardLibrary/Xml/XmlReaderSettingsImpl.cs (2)

58-58: Ensure that all code references XmlValidationTypeEnum consistently.
Just like in the Space property, it’s good practice to remove any second reference to .Instance usage or old references if they exist.

Use the following script to detect any mention of XmlValidationTypeEnum.Instance:

✅ Verification successful

No inconsistent usage of XmlValidationTypeEnum found

Based on the search results, there are no instances of XmlValidationTypeEnum.Instance in the codebase. The class is properly used with XmlValidationTypeEnum.FromNativeValue() in the ValidationTypeImpl property, and the class itself follows a factory pattern using CreateInstance. There are no inconsistencies to fix.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
rg -A3 "XmlValidationTypeEnum.Instance"

Length of output: 39


Script:

#!/bin/bash
# Let's first check for any usage of XmlValidationTypeEnum in the codebase
rg -A3 "XmlValidationTypeEnum"

Length of output: 1741


55-55: Remove the leftover comment references to .Instance usage if any.
Although the property access has been simplified, ensure there are no references or comments elsewhere that still suggest usage of the older XmlSpaceEnum.Instance.

Use the following script to detect any mention of XmlSpaceEnum.Instance:

✅ Verification successful

No leftover .Instance references found in the codebase

After checking the codebase, there are no references to XmlSpaceEnum.Instance in either code or comments. The only related instances found are the CreateInstance factory method in XmlSpaceEnum.cs, which is a different concept and not related to the old singleton pattern usage. The file XmlReaderSettingsImpl.cs is also clean of any such references.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
rg -A3 "XmlSpaceEnum.Instance"

Length of output: 30


Script:

#!/bin/bash
# Search for any mentions of XmlSpaceEnum.Instance in comments or code
rg -i "xmlspaceenum.*instance" --type-add 'csharp:*.{cs,csx}' --type csharp

# Also check for any XML documentation or comments containing Instance
rg -i "instance.*xmlspace" --type-add 'csharp:*.{cs,csx}' --type csharp

# Let's also check the specific file for any comments
cat src/OneScript.StandardLibrary/Xml/XmlReaderSettingsImpl.cs

Length of output: 5994

src/OneScript.StandardLibrary/Text/TextEncodingEnum.cs (2)

145-145: Good approach using GlobalsHelper.GetEnum<T> for centralized retrieval.
This central approach helps reduce future code duplication and keeps enumeration management consistent.


14-14: Check for potential merge conflicts with other changes.
This using OneScript.Values; might conflict with other newly added or removed using statements in the same file if they are not consolidated by the merge.

Use the following script to check the final version of the file for multiple or conflicting import lines:

src/OneScript.StandardLibrary/XMLSchema/Objects/XSAttributeDeclaration.cs (1)

194-197: Consistent property type update from XSForm to ClrEnumValueWrapper<XmlSchemaForm> is beneficial.
This change aligns the codebase with the new enumeration handling approach.

src/OneScript.StandardLibrary/XMLSchema/Objects/XSElementDeclaration.cs (1)

197-200: Highly consistent enumeration usage
Changing the Form property to ClrEnumValueWrapper<XmlSchemaForm> and using EnumerationXSForm.FromNativeValue(...) in the getter is consistent with the changes in other files.

src/OneScript.StandardLibrary/XDTO/XDTOSerializer.cs (2)

190-190: Use of XmlNodeTypeEnum.FromNativeValue() is appropriate here
Directly invoking XmlNodeTypeEnum.FromNativeValue(...) to compare with XmlNodeType.Element cleans up the code by removing reliance on a private enum instance. This change is consistent with the broader enum-handling refactor across the codebase.


238-238: Confirm consistency of text node handling
The same logic applies here for XmlNodeType.Text. The updated call to FromNativeValue(XmlNodeType.Text) maintains functional parity with the previous approach while adhering to the new enum-refactoring approach. Ensure that no old references to _xmlNodeEnum remain in your code.

src/OneScript.StandardLibrary/XMLSchema/Objects/XMLSchema.cs (3)

21-21: New using statement
The addition of using OneScript.Values; is consistent with your transition to ClrEnumValueWrapper<XmlSchemaForm>. This ensures that relevant value and enum classes are in scope.


212-215: Property AttributeFormDefault migrated to ClrEnumValueWrapper<XmlSchemaForm>
Switching from a custom enum type to a ClrEnumValueWrapper<XmlSchemaForm> suggests improved caching and consistent usage of enums. This streamlines bridging .NET-native enums and OneScript.


219-222: Property ElementFormDefault updated
Like AttributeFormDefault, refactoring ElementFormDefault to use ClrEnumValueWrapper<XmlSchemaForm> reinforces the uniform approach to enum handling in the codebase.

src/OneScript.StandardLibrary/Binary/FileStreamContext.cs (2)

11-11: Reviewing new using directives
Adding references to OneScript.Exceptions and OneScript.Values helps consolidate exception types and the new enum-value wrappers. This is consistent with the updated logic for validating constructor parameters.

Also applies to: 13-13


331-333: Validation for bufferSize
Throwing an exception if bufferSize is not numeric is a good step toward robust parameter handling. Be sure the error message and documentation clarify correct usage.

src/OneScript.StandardLibrary/Xml/XmlReaderImpl.cs (4)

14-14: Namespace import for additional value helpers
Importing OneScript.Values aligns with the new approach to enum conversions and value wrappers.


215-215: Simplified enum translation in NodeType
Replacing instance-based logic with the static XmlNodeTypeEnum.FromNativeValue(...) call eliminates the need for a separate enum instance property, enhancing readability.


434-434: Ensure correctness of IsEndElement logic
Using XmlNodeTypeEnum.FromNativeValue(XmlNodeType.EndElement) is consistent with the approach across the file. Confirm no subtle differences remain from the original private field approach (e.g., caching or fallback).


487-487: Consistent usage in MoveToContent
Transitioning to direct calls to XmlNodeTypeEnum.FromNativeValue(nodeType) clarifies the code. The logic appears sound for MoveToContent.

src/OneScript.Native/Compiler/ExpressionHelpers.cs (1)

270-287: Ensure robust handling of invalid enum values or other exceptions
This block relies on InvalidOperationException to catch invalid conversions, rethrowing a localized error. If the underlying enum value or type is invalid in another way, that error might not be caught or surfaced clearly. Consider additional validation, such as checking for defined enum values, or expanding the exception handling to catch and rethrow other relevant exceptions.

src/OneScript.StandardLibrary/XMLSchema/Enumerations/XSProhibitedSubstitutions.cs (2)

15-16: Renamed class and updated base class
Switching the inheritance to ClrEnumWrapperCached<XmlSchemaDerivationMethod> and renaming the class to EnumerationXSProhibitedSubstitutions is consistent with the new caching approach. This aids in streamlined enum management.


28-28: Factory method usage looks good
Creating the instance with a lambda maintains flexibility and readability. The approach aligns well with a more extensible factory pattern.

@EvilBeaver EvilBeaver merged commit 5a45a40 into EvilBeaver:develop Dec 31, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants