Skip to content

Commit

Permalink
Unsafe warning
Browse files Browse the repository at this point in the history
  • Loading branch information
kzrnm committed May 10, 2024
1 parent 38236fc commit 92d4b25
Show file tree
Hide file tree
Showing 21 changed files with 271 additions and 286 deletions.
13 changes: 13 additions & 0 deletions Source/Sandbox/SampleApp/Program2.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using SampleLibrary;

namespace SampleApp
{
class Program2
{
static void Main()
{
Console.WriteLine(UnsafeBlock.Convert(3.14));
}
}
}
5 changes: 5 additions & 0 deletions Source/Sandbox/SampleApp/SampleApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
</ProjectReference>
</ItemGroup>

<PropertyGroup>
<StartupObject>SampleApp.Program</StartupObject>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
Expand Down
1 change: 1 addition & 0 deletions Source/Sandbox/SampleLibrary/SampleLibrary.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

<PropertyGroup>
<TargetFrameworks>net8.0;netstandard2.1</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<SourceExpander_Embedder_Enabled>True</SourceExpander_Embedder_Enabled>
<SourceExpander_Embedder_EmbeddingType>raw</SourceExpander_Embedder_EmbeddingType>
Expand Down
11 changes: 11 additions & 0 deletions Source/Sandbox/SampleLibrary/UnsafeBlock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace SampleLibrary
{
public static unsafe class UnsafeBlock
{
public static ulong Convert(double d)
{
double* p = &d;
return *(ulong*)p;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -75,11 +74,7 @@ public async Task Dependency(
TypeNames = Enumerable.Empty<string>(),
}));
}
var result = JsonSerializer.Serialize(infos, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
});
var result = JsonSerializer.Serialize(infos, DefaultSerializerOptions);
Console.WriteLine(result);
}
}
11 changes: 3 additions & 8 deletions Source/SourceExpander.Console/SourceExpanderCommand.Expand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -82,13 +81,9 @@ public async Task ExpandAll(

var result = JsonSerializer.Serialize(expanded.Select(t => new
{
t.FilePath,
ExpandedCode = t.expandedCode,
}), new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
});
t.SyntaxTree.FilePath,
t.ExpandedCode,
}), DefaultSerializerOptions);
Console.WriteLine(result);
}

Expand Down
11 changes: 11 additions & 0 deletions Source/SourceExpander.Console/SourceExpanderCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Text.Encodings.Web;
using System.Text.Json;

internal partial class SourceExpanderCommand : ConsoleAppBase
{
private static JsonSerializerOptions DefaultSerializerOptions = new()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
}
31 changes: 20 additions & 11 deletions Source/SourceExpander.Generating.Common/EmbeddedLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,48 +74,48 @@ SyntaxTree Rewrited(SyntaxTree tree)
/// <summary>
/// get expanded codes
/// </summary>
public ImmutableArray<(string FilePath, string expandedCode)> ExpandedCodes()
public ImmutableArray<ExpandedResult> ExpandedCodes()
{
if (!config.Enabled) return ImmutableArray<(string FilePath, string expandedCode)>.Empty;
if (!config.Enabled) return ImmutableArray<ExpandedResult>.Empty;
UpdateCompilation();
cancellationToken.ThrowIfCancellationRequested();

return Impl();

ImmutableArray<(string, string)> Impl()
ImmutableArray<ExpandedResult> Impl()
{
var expander = new CompilationExpander(compilation, container, config);
if (compilation.Options.ConcurrentBuild)
return compilation.SyntaxTrees.AsParallel(cancellationToken)
.Where(tree => config.IsMatch(tree.FilePath))
.Select(tree => (tree.FilePath, expander.ExpandCode(tree, cancellationToken)))
.OrderBy(tree => tree.FilePath, StringComparer.Ordinal)
.Select(tree => new ExpandedResult(tree, expander.ExpandCode(tree, cancellationToken)))
.OrderBy(rt => rt.SyntaxTree.FilePath, StringComparer.Ordinal)
.ToImmutableArray();
else
return compilation.SyntaxTrees.Do(_ => cancellationToken.ThrowIfCancellationRequested())
.Where(tree => config.IsMatch(tree.FilePath))
.Select(tree => (tree.FilePath, expander.ExpandCode(tree, cancellationToken)))
.OrderBy(tree => tree.FilePath, StringComparer.Ordinal)
.Select(tree => new ExpandedResult(tree, expander.ExpandCode(tree, cancellationToken)))
.OrderBy(rt => rt.SyntaxTree.FilePath, StringComparer.Ordinal)
.ToImmutableArray();
}
}

/// <summary>
/// get dependencies
/// </summary>
public ImmutableArray<(string FilePath, ImmutableArray<string> Dependencies)> Dependencies()
public ImmutableArray<ResolvedDependencies> Dependencies()
{
if (!config.Enabled) return ImmutableArray<(string FilePath, ImmutableArray<string> Dependencies)>.Empty;
if (!config.Enabled) return ImmutableArray<ResolvedDependencies>.Empty;
UpdateCompilation();
cancellationToken.ThrowIfCancellationRequested();

var expander = new CompilationExpander(compilation, container, config);
(string FilePath, ImmutableArray<string> Dependencies) ResolveDependency(SyntaxTree tree)
ResolvedDependencies ResolveDependency(SyntaxTree tree)
{
if (expander is null)
throw new InvalidProgramException("expander must not be null.");
var deps = expander.ResolveDependency(tree, cancellationToken).Select(s => s.FileName);
return (tree.FilePath, ImmutableArray.CreateRange(deps));
return new(tree.FilePath, ImmutableArray.CreateRange(deps));
}

if (compilation.Options.ConcurrentBuild)
Expand All @@ -138,4 +138,13 @@ SyntaxTree Rewrited(SyntaxTree tree)
/// </summary>
public string ExpandAllForTesting(CancellationToken token) => new CompilationExpander(compilation, container, config).ExpandAllForTesting(token);
}

/// <summary>
/// Result of Expanding
/// </summary>
public record struct ExpandedResult(SyntaxTree SyntaxTree, string ExpandedCode);
/// <summary>
/// Dependencies
/// </summary>
public record struct ResolvedDependencies(string FilePath, ImmutableArray<string> Dependencies);
}
2 changes: 1 addition & 1 deletion Source/SourceExpander.Generator.Roslyn3/ExpandGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void Execute(GeneratorExecutionContext context)
var (config, diagnostic) = ParseAdditionalTextAndAnalyzerOptions(
context.AdditionalFiles.Where(a => StringComparer.OrdinalIgnoreCase.Compare(Path.GetFileName(a.Path), CONFIG_FILE_NAME) == 0)
.FirstOrDefault(), context.AnalyzerConfigOptions, context.CancellationToken);
Execute(new GeneratorExecutionContextWrapper(context), (CSharpCompilation)context.Compilation, context.ParseOptions, config, diagnostic);
Execute(new GeneratorExecutionContextWrapper(context), (CSharpCompilation)context.Compilation, (CSharpParseOptions)context.ParseOptions, config, diagnostic);
}
}
}
13 changes: 13 additions & 0 deletions Source/SourceExpander.Generator/AnalyzerReleases.Shipped.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
; Shipped analyzer releases
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md

## Release 7.0.0

### New Rules
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
EXPAND0010 | Usage | Warning | Expanded code has unsafe block

### Removed Rules

Rule ID | Category | Severity | Notes
--------|----------|----------|--------------------
EXPAND0006 | Usage | Warning | Needs AllowUnsafeBlocks

## Release 3.2.0

### New Rules
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static class DiagnosticDescriptors

public static Diagnostic EXPAND0001_UnknownError(string message)
=> Diagnostic.Create(EXPAND0001_UnknownError_Descriptor, Location.None, message);
private static readonly DiagnosticDescriptor EXPAND0001_UnknownError_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0001_UnknownError_Descriptor = new(
"EXPAND0001",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0001_Title),
Expand All @@ -30,7 +30,7 @@ public static Diagnostic EXPAND0001_UnknownError(string message)
true);
public static Diagnostic EXPAND0002_ExpanderVersion(Version expanderVersion, string assemblyName, Version assemblyEmbedderVersion)
=> Diagnostic.Create(EXPAND0002_ExpanderVersion_Descriptor, Location.None, expanderVersion.ToString(), assemblyName, assemblyEmbedderVersion.ToString());
private static readonly DiagnosticDescriptor EXPAND0002_ExpanderVersion_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0002_ExpanderVersion_Descriptor = new(
"EXPAND0002",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0002_Title),
Expand All @@ -45,7 +45,7 @@ public static Diagnostic EXPAND0002_ExpanderVersion(Version expanderVersion, str
true);
public static Diagnostic EXPAND0003_NotFoundEmbedded()
=> Diagnostic.Create(EXPAND0003_NotFoundEmbedded_Descriptor, Location.None);
private static readonly DiagnosticDescriptor EXPAND0003_NotFoundEmbedded_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0003_NotFoundEmbedded_Descriptor = new(
"EXPAND0003",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0003_Title),
Expand All @@ -60,7 +60,7 @@ public static Diagnostic EXPAND0003_NotFoundEmbedded()
true);
public static Diagnostic EXPAND0004_MustBeNewerThanCSharp3()
=> Diagnostic.Create(EXPAND0004_MustBeNewerThanCSharp3_Descriptor, Location.None);
private static readonly DiagnosticDescriptor EXPAND0004_MustBeNewerThanCSharp3_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0004_MustBeNewerThanCSharp3_Descriptor = new(
"EXPAND0004",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0004_Title),
Expand All @@ -75,7 +75,7 @@ public static Diagnostic EXPAND0004_MustBeNewerThanCSharp3()
true);
public static Diagnostic EXPAND0005_NewerCSharpVersion(LanguageVersion expanderVersion, string assemblyName, LanguageVersion assemblyEmbedderVersion)
=> Diagnostic.Create(EXPAND0005_NewerCSharpVersion_Descriptor, Location.None, expanderVersion.ToDisplayString(), assemblyName, assemblyEmbedderVersion.ToDisplayString());
private static readonly DiagnosticDescriptor EXPAND0005_NewerCSharpVersion_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0005_NewerCSharpVersion_Descriptor = new(
"EXPAND0005",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0005_Title),
Expand All @@ -88,25 +88,10 @@ public static Diagnostic EXPAND0005_NewerCSharpVersion(LanguageVersion expanderV
"Usage",
DiagnosticSeverity.Warning,
true);
public static Diagnostic EXPAND0006_AllowUnsafe(string assemblyName)
=> Diagnostic.Create(EXPAND0006_AllowUnsafe_Descriptor, Location.None, assemblyName);
private static readonly DiagnosticDescriptor EXPAND0006_AllowUnsafe_Descriptor = new DiagnosticDescriptor(
"EXPAND0006",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0006_Title),
DiagnosticsResources.ResourceManager,
typeof(DiagnosticsResources)),
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0006_Body),
DiagnosticsResources.ResourceManager,
typeof(DiagnosticsResources)),
"Usage",
DiagnosticSeverity.Warning,
true);
public static Diagnostic EXPAND0007_ParseConfigError(string? configFile, string message)
=> Diagnostic.Create(EXPAND0007_ParseConfigError_Descriptor,
AdditionalFileLocation(configFile), configFile ?? "Any of configs", message);
private static readonly DiagnosticDescriptor EXPAND0007_ParseConfigError_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0007_ParseConfigError_Descriptor = new(
"EXPAND0007",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0007_Title),
Expand All @@ -121,7 +106,7 @@ public static Diagnostic EXPAND0007_ParseConfigError(string? configFile, string
true);
public static Diagnostic EXPAND0008_EmbeddedDataError(string? assemblyName, string key, string value)
=> Diagnostic.Create(EXPAND0008_EmbeddedDataError_Descriptor, Location.None, assemblyName, key, value);
private static readonly DiagnosticDescriptor EXPAND0008_EmbeddedDataError_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0008_EmbeddedDataError_Descriptor = new(
"EXPAND0008",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0008_Title),
Expand All @@ -136,7 +121,7 @@ public static Diagnostic EXPAND0008_EmbeddedDataError(string? assemblyName, stri
true);
public static Diagnostic EXPAND0009_MetadataEmbeddingFileNotFound(string fileName)
=> Diagnostic.Create(EXPAND0009_MetadataEmbeddingFileNotFound_Descriptor, Location.None, fileName);
private static readonly DiagnosticDescriptor EXPAND0009_MetadataEmbeddingFileNotFound_Descriptor = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor EXPAND0009_MetadataEmbeddingFileNotFound_Descriptor = new(
"EXPAND0009",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0009_Title),
Expand All @@ -149,5 +134,20 @@ public static Diagnostic EXPAND0009_MetadataEmbeddingFileNotFound(string fileNam
"Error",
DiagnosticSeverity.Warning,
true);
public static Diagnostic EXPAND0010_UnsafeBlock(string fileName)
=> Diagnostic.Create(EXPAND0010_UnsafeBlock_Descriptor, Location.None, fileName);
private static readonly DiagnosticDescriptor EXPAND0010_UnsafeBlock_Descriptor = new(
"EXPAND0010",
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0010_Title),
DiagnosticsResources.ResourceManager,
typeof(DiagnosticsResources)),
new LocalizableResourceString(
nameof(DiagnosticsResources.EXPAND0010_Body),
DiagnosticsResources.ResourceManager,
typeof(DiagnosticsResources)),
"Usage",
DiagnosticSeverity.Warning,
true);
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,4 @@
<data name="EXPAND0006_Body" xml:space="preserve">
<value>{0} が AllowUnsafeBlocks を持っているので AllowUnsafeBlocks が必要です</value>
</data>
<data name="EXPAND0006_Title" xml:space="preserve">
<value>AllowUnsafeBlocks が必要です</value>
</data>
</root>
Loading

0 comments on commit 92d4b25

Please sign in to comment.