Skip to content

Commit a53ba3b

Browse files
erikzhangshargonJim8y
authored
Set nullableContextOptions (#687)
* Set nullableContextOptions * Read NullableContextOptions from csproj * Add --nullable option * Update template * Update CompilationContext.cs * Revert some changes * Remove most of the MSBuild logic --------- Co-authored-by: Shargon <shargon@gmail.com> Co-authored-by: Jimmy <jimmy@r3e.network>
1 parent 5302960 commit a53ba3b

5 files changed

Lines changed: 19 additions & 14 deletions

File tree

src/Neo.Compiler.CSharp/CompilationContext.cs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class CompilationContext
3838
private static readonly MetadataReference[] commonReferences;
3939
private static readonly Dictionary<string, MetadataReference> metaReferences = new();
4040
private readonly Compilation compilation;
41-
private string? assemblyName, displayName, className;
41+
private string? displayName, className;
4242
private bool scTypeFound;
4343
private readonly List<Diagnostic> diagnostics = new();
4444
private readonly HashSet<string> supportedStandards = new();
@@ -57,8 +57,7 @@ public class CompilationContext
5757

5858
public bool Success => diagnostics.All(p => p.Severity != DiagnosticSeverity.Error);
5959
public IReadOnlyList<Diagnostic> Diagnostics => diagnostics;
60-
public string? ContractName => displayName ?? assemblyName ?? className;
61-
public bool Checked { get; private set; } = false;
60+
public string? ContractName => displayName ?? Options.BaseName ?? className;
6261
private string? Source { get; set; }
6362
internal Options Options { get; private set; }
6463
internal IEnumerable<IFieldSymbol> StaticFieldSymbols => staticFields.OrderBy(p => p.Value).Select(p => p.Key);
@@ -153,8 +152,7 @@ internal static CompilationContext Compile(IEnumerable<string> sourceFiles, IEnu
153152
{
154153
IEnumerable<SyntaxTree> syntaxTrees = sourceFiles.OrderBy(p => p).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), options: options.GetParseOptions(), path: p));
155154
if (IsSingleAbstractClass(syntaxTrees)) throw new FormatException("The given class is abstract, no valid neo SmartContract found.");
156-
157-
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true);
155+
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true, nullableContextOptions: options.Nullable);
158156
CSharpCompilation compilation = CSharpCompilation.Create(null, syntaxTrees, references, compilationOptions);
159157
CompilationContext context = new(compilation, options);
160158
context.Compile();
@@ -168,16 +166,16 @@ public static CompilationContext CompileSources(string[] sourceFiles, Options op
168166
return Compile(sourceFiles, references, options);
169167
}
170168

171-
public static Compilation GetCompilation(string csproj, Options options, out XDocument document)
169+
public static Compilation GetCompilation(string csproj, Options options)
172170
{
173171
string folder = Path.GetDirectoryName(csproj)!;
174172
string obj = Path.Combine(folder, "obj");
175173
HashSet<string> sourceFiles = Directory.EnumerateFiles(folder, "*.cs", SearchOption.AllDirectories)
176174
.Where(p => !p.StartsWith(obj))
177175
.ToHashSet(StringComparer.OrdinalIgnoreCase);
178176
List<MetadataReference> references = new(commonReferences);
179-
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true);
180-
document = XDocument.Load(csproj);
177+
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true, nullableContextOptions: options.Nullable);
178+
XDocument document = XDocument.Load(csproj);
181179
sourceFiles.UnionWith(document.Root!.Elements("ItemGroup").Elements("Compile").Attributes("Include").Select(p => Path.GetFullPath(p.Value, folder)));
182180
Process.Start(new ProcessStartInfo
183181
{
@@ -234,7 +232,7 @@ public static Compilation GetCompilation(string csproj, Options options, out XDo
234232
case "project":
235233
string msbuildProject = assets["libraries"]![name]!["msbuildProject"]!.GetString();
236234
msbuildProject = Path.GetFullPath(msbuildProject, folder);
237-
reference = GetCompilation(msbuildProject, options, out _).ToMetadataReference();
235+
reference = GetCompilation(msbuildProject, options).ToMetadataReference();
238236
break;
239237
default:
240238
throw new NotSupportedException();
@@ -246,10 +244,8 @@ public static Compilation GetCompilation(string csproj, Options options, out XDo
246244

247245
public static CompilationContext CompileProject(string csproj, Options options)
248246
{
249-
Compilation compilation = GetCompilation(csproj, options, out XDocument document);
247+
Compilation compilation = GetCompilation(csproj, options);
250248
CompilationContext context = new(compilation, options);
251-
context.assemblyName = document.Root!.Elements("PropertyGroup").Elements("AssemblyName").Select(p => p.Value).FirstOrDefault() ?? Path.GetFileNameWithoutExtension(csproj);
252-
context.Checked = document.Root!.Elements("PropertyGroup").Elements("CheckForOverflowUnderflow").Select(p => bool.Parse(p.Value)).FirstOrDefault();
253249
context.Compile();
254250
return context;
255251
}

src/Neo.Compiler.CSharp/MethodConvert.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public MethodConvert(CompilationContext context, IMethodSymbol symbol)
6767
{
6868
this.Symbol = symbol;
6969
this.context = context;
70-
this._checkedStack.Push(context.Checked);
70+
this._checkedStack.Push(context.Options.Checked);
7171
}
7272

7373
private byte AddLocalVariable(ILocalSymbol symbol)

src/Neo.Compiler.CSharp/Options.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
// Redistribution and use in source and binary forms with or without
99
// modifications are permitted.
1010

11+
using Microsoft.CodeAnalysis;
1112
using Microsoft.CodeAnalysis.CSharp;
1213
using System.Collections.Generic;
1314

@@ -17,6 +18,8 @@ public class Options
1718
{
1819
public string? Output { get; set; }
1920
public string? BaseName { get; set; }
21+
public NullableContextOptions Nullable { get; set; }
22+
public bool Checked { get; set; }
2023
public bool Debug { get; set; }
2124
public bool Assembly { get; set; }
2225
public bool NoOptimize { get; set; }

src/Neo.Compiler.CSharp/Program.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ static int Main(string[] args)
3030
new Argument<string[]>("paths", "The path of the project file, project directory or source files."),
3131
new Option<string>(new[] { "-o", "--output" }, "Specifies the output directory."),
3232
new Option<string>("--base-name", "Specifies the base name of the output files."),
33+
new Option<NullableContextOptions>("--nullable", () => NullableContextOptions.Annotations, "Represents the default state of nullable analysis in this compilation."),
34+
new Option<bool>("--checked", "Indicates whether to check for overflow and underflow."),
3335
new Option<bool>(new[] { "-d", "--debug" }, "Indicates whether to generate debugging information."),
3436
new Option<bool>("--assembly", "Indicates whether to generate assembly."),
3537
new Option<bool>("--no-optimize", "Instruct the compiler not to optimize the code."),

src/Neo.SmartContract.Template/templates/neocontract/ProjectName.csproj

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,17 @@
99
</ItemGroup>
1010

1111
<PropertyGroup>
12+
<BaseNameArgument Condition="'$(AssemblyName)' != ''">--base-name $(AssemblyName)</BaseNameArgument>
13+
<BaseNameArgument Condition="'$(AssemblyName)' == ''">--base-name $(MSBuildProjectName)</BaseNameArgument>
14+
<NullableArgument Condition="'$(Nullable)' != ''">--nullable $(Nullable)</NullableArgument>
15+
<CheckedArgument Condition="'$(CheckForOverflowUnderflow)' == 'true'">--checked</CheckedArgument>
1216
<DebugArgument Condition="'$(Configuration)' == 'Debug'">-d</DebugArgument>
1317
</PropertyGroup>
1418

1519
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
1620
<Message Text="Start NeoContract converter, Source File: $(ProjectPath)" Importance="high">
1721
</Message>
18-
<Exec Command="nccs $(DebugArgument) &quot;$(ProjectPath)&quot;" />
22+
<Exec Command="nccs $(BaseNameArgument) $(NullableArgument) $(CheckedArgument) $(DebugArgument) &quot;$(ProjectPath)&quot;" />
1923
</Target>
2024

2125
</Project>

0 commit comments

Comments
 (0)