Giter Site home page Giter Site logo

sergio0694 / polysharp Goto Github PK

View Code? Open in Web Editor NEW
1.6K 18.0 44.0 240 KB

PolySharp provides generated, source-only polyfills for C# language features, to easily use all runtime-agnostic features downlevel. Add a reference, set your C# version to latest and have fun! 🚀

License: MIT License

C# 100.00%
csharp dotnet dotnet-core dotnet-framework dotnet-standard roslyn roslyn-analyzer roslyn-generator

polysharp's People

Contributors

0xced avatar dongle-the-gadget avatar hugener avatar jnyrup avatar kzu avatar piotrstenke avatar sergio0694 avatar sliekens avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

polysharp's Issues

Add optional polyfill (alias) to support getsubarray

Rationale

Slicing arrays is a fairly common task, and a workaround is simple.

Proposed API

Optional property flag in .csproj to alias System.Runtime.CompilerServices.RuntimeHelpers

<PolySharpAliasRuntimeHelpers>true</PolySharpAliasRuntimeHelpers>

Drawbacks

Obvious, see previous discussion in #8

Alternatives

Not sure there's any other way to support modern C# range syntax for arrays and spans.

Proposed hack

minimal example, excluding everything else from RuntimeHelpers

public static partial class RuntimeHelpers {
  // runtime support for range operator eg `myarray[0..5]`
  public static T[] GetSubArray<T>(T[] array, System.Range range) {
    var (offset, length) = range.GetOffsetAndLength(array.Length);
    if (length == 0)
      return Array.Empty<T>();

    T[] dest;
    if (typeof(T).IsValueType || typeof(T[]) == array.GetType()) {
      // We know the type of the array to be exactly T[] or an array variance
      // compatible value type substitution like int[] <-> uint[].
      if (length == 0)
        return Array.Empty<T>();

      dest = new T[length];
    }
    else {
      // The array is actually a U[] where U:T. We'll make sure to create
      // an array of the exact same backing type. The cast to T[] will
      // never fail.
      dest = (T[])(Array.CreateInstance(array.GetType().GetElementType(), length));
    }

    Array.Copy(array, offset, dest, 0, length);
    return dest;
  }
}

Compiler error (Init-only setters) when using LangVersion 8.0 in a .NET Standard 2.0 library

Description (optional)

I got compiler error CS8400 Feature 'init-only setters' is not available in C# 8.0. Please use language version 9.0 or greater. when compiling a .NET Standard 2.0 class library with C# 8.0 as the LangVersion. Upgrading to 9.0 fixed the issue but should not be nesessary.

image

Reproduction Steps

Create a Class Library using the following .csproj content and this class Product.cs

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<TargetFramework>netstandard2.0</TargetFramework>
		<LangVersion>8.0</LangVersion>
		<Nullable>enable</Nullable>
	</PropertyGroup>
	<ItemGroup>
	  <PackageReference Include="PolySharp" Version="1.6.0" />
	</ItemGroup>
</Project>
using System.Diagnostics.CodeAnalysis;

namespace ClassLibrary19 {
    public class Product {

        [AllowNull]
        public string ProductName { get; set; }
    }
}

Expected Behavior

No compiler error

Actual Behavior

error CS8400

System info

This section should contain useful info such as:

  • PolySharp NuGet version 1.6

Additional context (optional)

Any additional info that might be useful to resolve the issue.

Provider a clearer explanation?

PolySharp provides generated, source-only polyfills for C# language features, to easily use all runtime-agnostic features downlevel

I know what source generators are, and I know what polyfills are (in general). But I do not know what it means when you say "source-only polyfills for C# language features, to easily use all runtime-agnostic features downlevel"

Being someone who is well versed in .NET and C#, I can't help but think that you'll get more interest in your project if you explain these concepts better in your readme. Maybe even provide some examples.

The names of the attributes listed in the readme peak my interest, but I do know that some of those attributes already exist... And without further information, I can't invest the time to see if it makes sense for me.

I figured it was worth writing this issue, thinking that maybe there are others like me.

GeneratedRegex attribute

Description (optional)

Support for [GeneratedRegex] attribute. MS Docs

Rationale

This is the new .Net 8 way of having static readonly regexes in code:

[GeneratedRegex(@"^by\(\s*(?<var>[a-zA-Z_][a-zA-Z0-9_]*)\s*\)")]
private static partial Regex MyRegex();
private static readonly Regex _byForm = MyRegex();

Prior to .Net 8, this is required:

private static readonly Regex _byForm = new(@"^by\(\s*(?<var>[a-zA-Z_][a-zA-Z0-9_]*)\s*\)");

which is arguably cleaner, but it means that regex table lookups are performed at runtime instead of at compile time. (I expect my usage isn't an ideal example.)

Proposed API

No proposal

Drawbacks

None

Alternatives

None

Other thoughts

None.

InternalsVisibleTo from two other projects leads to not being able to use PolySharp

Description

If one project references two other projects that both have InternalsVisibleTo to the first project defined, the first project can't use C# features that should be enabled by PolySharp.

Reproduction Steps

  1. Create a new solution with 3 projects using an older .NET version.
  2. Set <LangVersion>11.0</LangVersion> for all projects.
  3. Add PolySharp to all projects.
  4. Try to use a C# 11 feature, e.g. required properties, in all projects. See that it works as expected.
  5. Add a project reference from two projects to the third one.
  6. Add <ItemGroup><InternalsVisibleTo Include="ThirdProjectName" /></ItemGroup> to the referenced projects.

Expected Behavior

Should be able to compile the code.

Actual Behavior

I get compile errors about missing compiler required members.

System info

This section should contain useful info such as:

  • PolySharp NuGet version 1.10.0
  • Operating system version Windows 10 22H2
  • Visual Studio version, or .NET SDK/runtime version VS 17.4.4, SDK 7.0.102, runtime 7.0.2

Additional context

It looks like the compiler error is missleading. The members are not missing, they are there multiple times (so the compiler sees the internal types from both referenced projects). If only one referenced project with InternalsVisibleTo exists then no error happens.

It looks like PolySharp also sees the internal types of the other projects and doesn't generate any additional types. (It only generates the TypeForwards.)
But I can actually fix the problem and compile my code when I manually add the required compiler types. Then the compiler doesn't error any more, even though it should then actually see each type 3 times.
So maybe the fix for this would be to still generate the required types if the source generator only finds an internal type from another assembly in the current project?

In my actual solution I don't add PolySharp to each project individually but instead use Global Package References. But it seems like this doesn't change anything for this problem.

What's the purpose of adding `TypeForwardedTo` attributes?

In #86 you said

generate type forwards to ensure things work as expected in multi-targeting scenarios

Could you please elaborate a little bit more on this? What exact problem does it solve to add TypeForwardedTo attributes in target frameworks where the type exists?

For example, when multi-targeting net7.0;net6.0;netstandard2.0 the source generator produces this for .NET 6 and .NET 7 targets:

[assembly: global::System.Runtime.CompilerServices.TypeForwardedTo(typeof(global::System.Runtime.CompilerServices.IsExternalInit))]

If I add <PolySharpExcludeTypeForwardedToDeclarations>true</PolySharpExcludeTypeForwardedToDeclarations> they are not generated and everything seems to work fine. Am I missing something?

Fails to get subarray

Thanks for the project, looking forward its evolution!

Reproduction Steps

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>Latest</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="PolySharp" Pack="false" Version="1.3.0" />
  </ItemGroup>

</Project>
namespace Poly;

internal class Class1
{
    readonly string[] ns = "Foo.Bar.Baz".Split('.')[..^1];
}

This works with PolyFill.NET but not
PolyShary. Build error is:

Class1.cs(9,53,9,57): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray'

image

Deconstruct extension for KeyValuePair<TKey, TValue>

Description (optional)

Add an extension to KeyValuePair<TKey, TValue> that mirrors https://learn.microsoft.com/en-US/dotnet/api/system.collections.generic.keyvaluepair-2.deconstruct?view=net-7.0

Rationale

The extension allows for KeyValuePairs to be deconstructed in scenarios such as

foreach ((var k, var v) in dict)
{
    // ...
}

Proposed API

https://learn.microsoft.com/en-US/dotnet/api/system.collections.generic.keyvaluepair-2.deconstruct?view=net-7.0 Allows the compiler to deconstruct KeyValuePairs in tuple patterns or other tuple-like scenarios

Drawbacks

Not known

Alternatives

Not known

Other thoughts

None

How to use it quickly

I reference this package in netframework4.8, but how do I change the language version, by adding a [Directory.Build.props] file?

Polysharp didn't work for me

I created Console App for .NET Framework 4.7.2 and added to the project file 11.0. I installed the PolySharp package .I don't see that it produces some source generators files and i got the exceptions from the compiler.. will be appreciate for advise what i did wrong. I didn't see the Polysharp in my References list but there is packages.config file and there is a reference there. I attached zip file with a solution. There are 2 projects in solution. Please look on ConsolePolysharp2. Thank you!
ConsolePolySharp.zip

polysharp dont generate source

in my netframework4.8 console project, after added reference to polysharp, and set language version to C#11.0, there is no source file generated, and when i use required and init in my code, there is build error occured

Would it be possible to use C# 11 language features in .cshtml files?

I have a legacy ASP.NET MVC application built with .NET Framework 4.8, and I'm unable to use constructors of types with required members in a .cshtml file. I have installed PolySharp in this project, but I have a feeling something else is required to make it work in .cshtml files.

The error message I'm getting is: 'Constructors of types with required members are not supported in this version of your compiler.'.

Detailed compiler output:

Microsoft (R) Visual C# Compiler version 4.1.0-5.22114.11 (260d16a8)
Copyright (C) Microsoft Corporation. All rights reserved.

C:\Projects\MyProject\MyProject.Web.Mvc\Views\Shared\_Layout.cshtml(228,123): error CS0619: 'App.App()' is obsolete: 'Constructors of types with required members are not supported in this version of your compiler.'

I'm using the latest Roslyn CodeDOM provider (4.1.0), which is updated to support /langversion:11.0.

I have the following configuration in my Web.config:

  <system.codedom>
    <compilers>
      <compiler extension=".cs" language="c#;cs;csharp" warningLevel="4"
        compilerOptions="/langversion:11.0"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <compiler extension=".vb" language="vb;vbs;visualbasic;vbscript" warningLevel="4"
        compilerOptions="/langversion:11.0 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </compilers>
  </system.codedom>

So far I haven't been able to get constructors of types with required members to work in .cshtml files. I wonder if it's even possible? Maybe the Roslyn CodeDOM provider needs to reference PolySharp as well?

Compiler error in .NET Framework 3.5 with new sdk style

There is no error with project using packages.config, but there is an error with projects using new SDK msbuild.

I don't know about that how csproj file works. what I should do to solve this? or it is bug?

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS8179	Predefined type 'System.ValueTuple`2' is not defined or imported	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Range.g.cs	76	Active
Error	CS8137	Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Range.g.cs	76	Active
Error	CS0117	'MethodImplOptions' does not contain a definition for 'AggressiveInlining'	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Index.g.cs	28	Active
Error	CS0117	'MethodImplOptions' does not contain a definition for 'AggressiveInlining'	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Index.g.cs	56	Active
Error	CS0117	'MethodImplOptions' does not contain a definition for 'AggressiveInlining'	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Index.g.cs	69	Active
Error	CS0117	'MethodImplOptions' does not contain a definition for 'AggressiveInlining'	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Index.g.cs	103	Active
Error	CS0117	'MethodImplOptions' does not contain a definition for 'AggressiveInlining'	NET35LibraryNewProj	C:\Users\02jy0\source\repos\NET35LibraryNewProj\PolySharp.SourceGenerators\PolySharp.SourceGenerators.PolyfillsGenerator\System.Range.g.cs	75	Active

화면 캡처 2022-11-21 020859
with packages.config

화면 캡처 2022-11-21 021128
with new SDK

Static analyzer ignores Nullability attributes

Description

I have added your library to my WinFroms project (.NEt Framework) to use Nullability attributes with static analyzers. Even though I added the attribute, the analyzer still analyzes nulls incorrectly.

Reproduction Steps

See code below

Expected Behavior

Static analyzer do not trigger CS8602 Dereference of a possibly null reference.

Actual Behavior

dereference of a possibly null

System info

This section should contain useful info such as:

  • PolySharp 1.8.1
  • .NET Framework
  • Windows 11 22H2
  • Visual Studio 2022 (17.4.0)

Requires last .NET and VS. What is the sense?

It doesn't work on my environment with VS 2019 (last version) and .NET 4.8
error : The PolySharp source generators have been disabled on the current configuration, as they need Roslyn 4.3 in order to work. PolySharp requires the source generators to run in order to process shaders, so the library cannot be used without a more up to date IDE (eg. VS 2022 17.3 or greater) or .NET SDK version (.NET 6.0.400 SDK or greater).
========== Build: 0 succeeded, 1 failed ==========

If I use VS2022 and .NET 7 I can use all features without this package, so what the sense of using this package if it doesn't work for lower .NET/VS?

Documentation for unsupported, runtime-dependent features.

Is there any documentation here (or elsewhere) on which C# language features depend on runtime support, and therefore can never be polyfilled?

I know the readme mentions static abstract members, and I'm pretty sure default interface methods are out too.

It would be helpful to have some list of the features that we should not expect this project to ever be able to polyfill, (if only to preempt people opening feature requests for them 😆).

Is it possible to use PolySharp on a github Ubuntu Runner ?

Basically, I just started using PolySharp on a project and find it amazing. Now that project repository is setup to build on Ubuntu runners on github actions and I am getting this error:

     /home/runner/.nuget/packages/polysharp/1.14.1/buildTransitive/PolySharp.targets(45,5): error POLYSPCFG0001: The PolySharp source generators have been disabled on the current configuration, as they need Roslyn 4.3 in order to work. PolySharp requires the source generators to run in order to generate polyfills, so the library cannot be used without a more up to date IDE (eg. VS 2022 17.3 or greater) or .NET SDK version (.NET 6.0.400 SDK or greater). [/home/runner/work/some-module/some-module/Module.csproj]

The build process uses .Net 7 but the actual built project is .Net Framework.

Is there thing I could try to fix that or is this scenario just not a supported one ?

PolySharp.SourceGenerators.PolyfillGenerator is not generating files

In our solution of about 200 projects, all targeting .NET 4.7.2 and using SDK Style format, one project does not have any polyfills generated, see the screenshot. I have no idea why it's not working for this one specific project.
PXL_20230609_132001143

It should generate polyfills in all projects.
Is there a way how can I debug this package or polyfill? Is there any logging that I can read or exception that is thrown?

System info

Polysharp 1.13.2, VS 2022 17.6.2, project targeting .NET 4.7.2 in SDK style.
(Have you tested Polysharp in .NET 4.7.2 SDK style projects?)

Additional context (optional)

Note in each of our projects I can see this error/warning in the Analyzers section: POLYSP0003 Unsupported C# version, even though it works in all but one project. Possibly false positive?

Update/fix XML docs for generated types

Rationale

The XML documentation of the generated types - at least the types which are directly used by developers - should match the documentation which is available on learn.microsoft.com and in the IDE when the "native" types are used.

I haven't checked all types, but I've found differences in:

  • CallerArgumentExpressionAttribute
    • class summary
    • class remarks
    • ctor paramter
    • property summary
  • Index
    • class summary
    • class remarks
    • various small differences in members

Does PolySharp support multitargeting?

I recently saw this package and decided to try.

Config:

<PackageReference Include="PolySharp" Version="1.10.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

Output:
изображение

If I change reference to

 <PackageReference Include="PolySharp" Version="1.10.0" Condition="'$(TargetFramework)' != 'net5' AND '$(TargetFramework)' != 'net6' AND '$(TargetFramework)' != 'net7'">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

then there are no errors.

I would like PolySharp does not require Conditional attribute on TFMs where all necessary attributes are present.

Matrix of Supported Language Features

Description (optional)

In the README (or another document) it would be good if we had a matrix/table/checklist of all of the features added with each language version (post 7) indicating whether it is supported out-of-the-box, supported with polysharp, not supported (yet), and not supported (and can't be supported).

Rationale

It would be a useful reference so people know exactly what features do and don't work. Yes, there's a list of the available polyfills but that doesn't actually tell us what features work when we add polysharp to our project, it tells us what extra features will work.

Proposed API

Documentation

.Net Framework 3.5 and ValueTuple

In the Readme is states
"Note: use on .NET Framework 3.5 is particularly limited due to shortcomings of the BCL there. In particular, the System.Range type will not be generated unless System.ValueTuple is referenced"
I tried referencing System.ValueTuple but it doesn't seem to support .NET 3.5 accoring to https://www.nuget.org/packages/System.ValueTuple.
Before I was using the ValueTupleBridge nuget package, should I still use this.
In general is there some reason why PolySharp can't generate the System.ValueTuple types for 3.5?

Sad that I still have to support some .Net 3.5 stuff.

`UnreachableException` polyfill

This exception is not really intended to be caught as it being thrown indicates that something has gone horribly wrong, like a Debug.Assert() failing or Environment.FailFast() being called.

I have several code paths in some of my analyzer and source generator projects where throwing UnreachableException is the obvious thing to do, but the type is net7.0 only.

Generate InAttribute for .NET Standard 1.0

Reproduction Steps

Can not compile the next code for .NET Standard 1.0 without InAttribute.

public static class Foo
{
    public static ref readonly object GetPinnableReference(this object bar) => throw new();
}

Expected Behavior

Successful compilation.

Actual Behavior

Next compiler error

Error CS0518 Predefined type 'System.Runtime.InteropServices.InAttribute' is not defined or imported (netstandard1.0)

System info

  • PolySharp NuGet version LAST STABLE
  • Operating system version Windows 10
  • Visual Studio version LAST STABLE

StringSyntaxAttribute not valid with frameworks that do not have Array.Empty

Description (optional)

Some older frameworks do not have Array.Empty, which causes a compilation failure when including StringSyntaxAttribute.

Reproduction Steps

Target < NET Standard 1.3 or < NET Framework 4.6.

Expected Behaviour

Compilation succeeds.

Actual Behaviour

The compilation fails with an error => error CS0117: 'Array' does not contain a definition for 'Empty'

System info

This section should contain useful info such as:

  • PolySharp 1.6.0
  • Windows 11
  • Visual Studio 17.3/.NET SDK 6.0.402

Additional context (optional)

This can be worked around by excluding that generation, but it would be expected to build out of the box.

Compatibility with <LangVersion>11.0</LangVersion> in VS

Hello,

I have tried to use your package, but when I use 11.0 as a parameter in .csproj and I don't have .NET 7 installed, it says: error CS1617: Invalid option '11.0' for /langversion. Use '/langversion:?' to list supported values.

When I install .NET 7, everything works fine. In my .csproj I am using net6.0 in all cases.

Is there a workaround?

Thank you.

support dateonly type

there is a struct type named DateOnly in net7.0 under System namespace.

while i installed polysharp in net48 project , it still appears: type 'DateOnly' could not be found

my project is a sdk project and other features are OK.

Polyfill instance methods with extensions

Description (optional)

First off, awesome idea for the project. I was hoping someone would do it :)

I was wondering if you had any plans to polyfill certain built-in instance methods with extensions.
For example, these are some of the polyfills I have in my projects:

https://github.com/Tyrrrz/CliWrap/blob/ccc3087f0744dce17899a433591b3e50fd18e90b/CliWrap/Utils/Polyfills.Collections.cs#L1-L17

https://github.com/Tyrrrz/CliWrap/blob/ccc3087f0744dce17899a433591b3e50fd18e90b/CliWrap/Utils/Polyfills.Streams.cs#L1-L57

They allow me to seamlessly call methods only available on newer frameworks, while polyfilling the functionality on older frameworks.

Rationale

Besides attributes, this could be an additional aspect of polyfilling that might be worth exploring. As a user, I can see great benefit in this as it would allow me to replace my own polyfills that I copy around between projects with a single package.

Proposed API

I propose a similar approach that I've been using: extensions in a global namespace. This makes the polyfill callsites fully source-compatible with natural callsites.

Drawbacks

This would require to figure out how to actually implement certain polyfills using existing functionality, and might not be trivial in some cases.

Alternatives

Just writing polyfills manually.

Other thoughts

None.

NuGet PackageReference should recommend PrivateAssets=all

Description

PolySharp's NuGet PackageReference recommendation is currently:

<PackageReference Include="PolySharp" Version="1.7.1" />

Since PolySharp is a source-only polyfill provider, it should recommend a more restricted scope PackageReference like this:

<PackageReference Include="PolySharp" Version="1.7.1">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>

Rationale

This prevents any package dependencies from flowing to parent projects as described at Controlling dependency assets. It's also the recommendation of every other source-only polyfill project I'm familiar with (e.g., PolyKit.Embedded, Polyfill.NET, and Nullable).

Drawbacks

None that I'm aware of.

System.Range not included in NetFramework 4.6.2 projects

Description (optional)

I have several NetFramework 4.6.2 projects in a solution and when compiling them, I noticed build issues when using the new range syntax for strings. I replaced the usages of range with SubString calls and compiled the solution then opened the compiled assembly and noticed that the System.Range has not been included.
image

Maybe I'm doing something wrong? but, I wasn't able to find anything about this in the docs.

Reproduction Steps

  1. Build a .Net Framework 4.6.2 Library project.
  2. Use range syntax in a method (e.g. "string"[..2]).
  3. Build the project.
  4. Build will fails, saying that System.Range does not exist.
  5. Replace the range with SubString.
  6. Build again.
  7. Use a decompiler to open the assembly.
  8. You will notice System.Range is not included.

Expected Behavior

The assembly should contain System.Range and the range syntax should work.

Actual Behavior

If range syntax is used the build will fail. If range syntax is not used, build is successful, but the System.Range won't be included.

System info

This section should contain useful info such as:

  • PolySharp NuGet version (or branch/commit, if building from source)
  • Operating system version
  • Visual Studio version, or .NET SDK/runtime version
    • VS Version: 17.8.6
    • Polysharp: 1.14.1
    • .NET: 4.6.2
    • LangVersion: 12.0
    • Project is using the new PackageReference syntax.

Additional context (optional)

I did not notice any messages from Polysharp in the build log, even when building with detailed logging.

`AsyncMethodBuilderAttribute` and `ModuleInitializerAttribute` declared as `public` rather than `internal`

Description

AsyncMethodBuilderAttribute and ModuleInitializerAttribute are declared as public rather than internal unlike all the other types produced by the source generator, which causes conflicts when PolySharp is used in a library that is referenced by a project which already uses those types.

Reproduction Steps

  • Reference PolySharp in a netstandard2.0 project (ProjectA)
  • Reference ProjectA in a net6.0 project (ProjectB)
  • Attempt to use [ModuleInitializer] in ProjectB

Expected Behavior

The projects should compile and ModuleInitializerAttribute be resolved from System.Runtime in ProjectB.

Actual Behavior

There is a CS0433 error in ProjectB because ModuleInitializerAttribute is declared publicly in both ProjectA and System.Runtime.

System info

  • PolySharp NuGet version 1.7.0

Thanks for making this, it's neat having all the polyfills in one place and generated as-required via a source generator 🙂.

Help: attempting to get access to DynamicallyAccessedMembers but not working

I'm trying to annotate https://github.com/peteroupc/CBOR .
I gather the way to do this is to use PolySharp to get access to DynamicallyAccessedMembers , and install this and set langversion to 11.0. But I did this and it doesn't work. Am I doing this wrong?

Attempt is in: https://github.com/charlesroddie/CBOR/pull/1/files
Build error:

CBOR\PeterO\Cbor\PropertyMap.cs(548,6,548,32): error CS0246: The type or namespace name 'DynamicallyAccessedMembersAttribute' could not be found (are you missing a using directive or an assembly reference?)
CBOR\PeterO\Cbor\PropertyMap.cs(548,6,548,32): error CS0246: The type or namespace name 'DynamicallyAccessedMembers' could not be found (are you missing a using directive or an assembly reference?)

How are all the polyfill source files generated?

Looking inside src/PolySharp.SourceGenerators/EmbeddedResources all polyfill source files are marked as // <auto-generated/> but I could not figure out how exactly those files are generated. I was expecting to find a tool inside this repository that was responsible for automatically generating those files, but could not find one! I even tried looking at the commit history to find clues but it did not help.

@Sergio0694 Could you please shed some light?

Some context: I wanted to contribute a polyfill for UnreachableException (issue #60) and I had to copy/paste the code from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Diagnostics/UnreachableException.cs It felt very much cheating to not use automatic code generation like all other polyfills.

Using PolySharap with Visual Studio Build Tools 2022

Is it possible to build PolySharp-enabled project using only Visual Studio Build Tools?. I'm on 17.5.4, yet it complains:

packages\PolySharp.1.13.1\build\PolySharp.targets(45,5): Error : The PolySharp source generators have been disabled on the current configuration, as they need Roslyn 4.3 in order to work. PolySharp requires the source generators to run in order to process shaders, so the library cannot be used without a more up to date IDE (eg. VS 2022 17.3 or greater) or .NET SDK version (.NET 6.0.400 SDK or greater).

I suspect it won't work without full IDE? Using Visual Studio Installer, I cannot find component "C# and Visual Basic Roslyn compilers" (Microsoft.VisualStudio.Component.Roslyn.LanguageServices). Can .NET6/7 somehow be used for language services when targeting .NET Framework? Or is it just for targeting older .NET Core versions? I have installed .NET6/7 on the host too, but the error is still there.

Perhaps if Build Tools are not supported, should be documented as it would help to decide to use PolySharp or no. it happens that my devops agent uses build tools and not the full IDE.

Add `System.Collections.Generic.PriorityQueue<TElement, TPriority>` polyfill

Description

Add a polyfill for the System.Collections.Generic.PriorityQueue<TElement, TPriority> added in .NET 6.0.

Rationale

Polyfilling System.Collections.Generic.PriorityQueue<TElement, TPriority> helps developers using the same priority queue API in older tfms without the need for preprocessor directives.

Proposed API

According to the .NET 7.0 implementation.

Drawbacks

Another polyfill to maintain.

Alternatives

Not supporting System.Collections.Generic.PriorityQueue<TElement, TPriority>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.