PolySharp

repository·main·Indexed 24 days ago

https://github.com/sergio0694/polysharp

A C# source generator that provides polyfills for modern language features, enabling the use of latest C# syntax and attributes on older .NET runtimes such as .NET Framework or UWP. It automatically generates necessary types for nullability annotations, indices, ranges, and required members, among others. Includes configurable MSBuild properties for code generation behavior and built-in analyzer rules for configuration validation.

Tokens
1.1K
Snippets
1
Records
4
Agent score
31%

What's inside PolySharp

  1. Setup PolySharp to use modern C# features on older runtimes

    main

    PolySharp allows you to use modern C# language features (like nullability annotations, pattern matching, etc.) on older runtimes such as .NET Framework or UWP. It works as a source generator that automatically detects and generates the necessary 'magic types' required by the compiler.

    To use PolySharp, follow these two steps:

    1. Add a reference to the PolySharp NuGet package to your project.
    2. Set your C# language version to the latest (or your desired version) by updating the <LangVersion> MSBuild property in your .csproj file.

    Limitations:

    • Features requiring actual runtime support (e.g., static abstract members) cannot be polyfilled and will not work.
    • On .NET Framework 3.5, usage is limited. System.Range requires a reference to System.ValueTuple to be generated, and features like records may not work due to missing compiler APIs.
    <PropertyGroup>
      <LangVersion>14.0</LangVersion>
    </PropertyGroup>
  2. Configure PolySharp via MSBuild properties

    main

    You can customize PolySharp's code generation behavior by setting specific MSBuild properties in your .csproj file.

    PropertyDescription
    PolySharpUsePublicAccessibilityForGeneratedTypesMakes all generated types public
    PolySharpUseEmbeddedAttributeForGeneratedTypesAdds the [Embedded] attribute to generated types
    PolySharpIncludeRuntimeSupportedAttributesEnables polyfills for runtime-supported attributes (e.g., Trimming/Platform attributes)
    PolySharpUseInteropServices2NamespaceForUnmanagedCallersOnlyAttributeMoves [UnmanagedCallersOnly] to the System.Runtime.InteropServices namespace
    PolySharpExcludeGeneratedTypesExcludes specific types from generation (use ; or , as separators)
    PolySharpIncludeGeneratedTypesOnly includes specific types for generation (use ; or , as separators)
    PolySharpExcludeTypeForwardedToDeclarationsPrevents the generation of any [TypeForwardedTo] declarations
  3. Reference shipped PolySharp analyzer rules

    main

    PolySharp includes built-in analyzers that provide warnings for configuration errors. The following rules are available in the current release:

    Rule IDCategorySeverityNotes
    POLYSP0001PolySharp.SourceGenerators.InvalidPolySharpMSBuildOptionAnalyzerWarningInvalid MSBuild option
    POLYSP0002PolySharp.SourceGenerators.InvalidPolySharpMSBuildOptionAnalyzerWarningInvalid MSBuild option
    POLYSP0003PolySharp.SourceGenerators.UnsupportedCSharpLanguageVersionAnalyzerWarningUnsupported C# language version
  4. PolySharp generated attributes and types reference

    main

    PolySharp generates several categories of polyfills. The primary category includes attributes required for language features to compile on older runtimes.

    Language Feature Polyfills

    • Nullability: [AllowNull], [DisallowNull], [DoesNotReturn], [DoesNotReturnIf], [MaybeNull], [MaybeNullWhen], [MemberNotNull], [MemberNotNullWhen], [NotNull], [NotNullIfNotNull], [NotNullWhen]
    • Indices and Ranges: Index, Range
    • Required Members: [RequiredMember], [SetsRequiredMembers]
    • Init-only properties: [IsExternalInit]
    • Interpolated String Handlers: [InterpolatedStringHandler], [InterpolatedStringHandlerArgument]
    • Other Language Features: [UnscopedRef], [CompilerFeatureRequired], [SkipLocalsInit], [CallerArgumentExpression], [RequiresPreviewFeatures], [AsyncMethodBuilder], [StringSyntax], [ModuleInitializer], [RequiresLocation], [CollectionBuilder], [Experimental], [OverloadResolutionPriority], [ParamsCollection], [ConstantExpected], [CompilerLoweringPreserve], [ExtensionMarker]

    Optional Runtime-Supported Polyfills

    These can be enabled via configuration (see Options:) and include:

    • Reflection/Trimming: [DynamicallyAccessedMembers], [DynamicDependency], [RequiresUnreferencedCode], [RequiresDynamicCode], [UnconditionalSuppressMessage], [RequiresAssemblyFiles]
    • Platform/OS: [ObsoletedOSPlatform], [SupportedOSPlatform], [SupportedOSPlatformGuard], [TargetPlatform], [UnsupportedOSPlatform], [UnsupportedOSPlatformGuard]
    • Interop/Low-level: [StackTraceHidden], [UnmanagedCallersOnly], [SuppressGCTransition], [DisableRuntimeMarshalling], [UnsafeAccessor], [InlineArray], [UnsafeAccessorType], [WasmImportLinkage]
    • Feature Switches: [FeatureGuard], [FeatureSwitchDefinition]