提交 9e9302ac 编写于 作者: S Srivatsn Narayanan

Merge changes with upstream/master - Roslyn.sln needed merging since a new project was added.

......@@ -38,7 +38,7 @@
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\Core\SystemRuntimeAnalyzers.csproj">
<Project>{d8762a0a-3832-47be-bcf6-8b1060be6b28}</Project>
<Project>{baa0fee4-93c8-46f0-bb36-53a6053776c8}</Project>
<Name>SystemRuntimeAnalyzers</Name>
</ProjectReference>
</ItemGroup>
......
......@@ -49,7 +49,7 @@ public class DeclarePublicAPIAnalyzer : DiagnosticAnalyzer
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.None);
internal static readonly SymbolDisplayFormat PublicApiFormat =
private static readonly SymbolDisplayFormat PublicApiFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
......@@ -110,7 +110,7 @@ public override void Initialize(AnalysisContext context)
return;
}
var publicApiName = symbol.ToDisplayString(PublicApiFormat);
string publicApiName = GetPublicApiName(symbol);
lock (lockObj)
{
......@@ -160,6 +160,36 @@ public override void Initialize(AnalysisContext context)
});
}
internal static string GetPublicApiName(ISymbol symbol)
{
var publicApiName = symbol.ToDisplayString(PublicApiFormat);
ITypeSymbol memberType = null;
if (symbol is IMethodSymbol)
{
memberType = ((IMethodSymbol)symbol).ReturnType;
}
else if (symbol is IPropertySymbol)
{
memberType = ((IPropertySymbol)symbol).Type;
}
else if (symbol is IEventSymbol)
{
memberType = ((IEventSymbol)symbol).Type;
}
else if (symbol is IFieldSymbol)
{
memberType = ((IFieldSymbol)symbol).Type;
}
if (memberType != null)
{
publicApiName = publicApiName + " -> " + memberType.ToDisplayString(PublicApiFormat);
}
return publicApiName;
}
private TextSpan? FindString(SourceText sourceText, string symbol)
{
foreach (var line in sourceText.Lines)
......
......@@ -47,7 +47,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
if (symbol != null)
{
var minimalSymbolName = symbol.ToMinimalDisplayString(semanticModel, location.SourceSpan.Start, DeclarePublicAPIAnalyzer.ShortSymbolNameFormat);
var publicSurfaceAreaSymbolName = symbol.ToDisplayString(DeclarePublicAPIAnalyzer.PublicApiFormat);
var publicSurfaceAreaSymbolName = DeclarePublicAPIAnalyzer.GetPublicApiName(symbol);
context.RegisterCodeFix(
new AdditionalDocumentChangeAction(
......@@ -196,7 +196,7 @@ protected override async Task<Solution> GetChangedSolutionAsync(CancellationToke
if (symbol != null)
{
var publicSurfaceAreaSymbolName = symbol.ToDisplayString(DeclarePublicAPIAnalyzer.PublicApiFormat);
var publicSurfaceAreaSymbolName = DeclarePublicAPIAnalyzer.GetPublicApiName(symbol);
if (symbol != null)
{
......
......@@ -6,7 +6,6 @@ Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text
Imports Roslyn.Test.EditorUtilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Debugger;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// This type exists to protect <see cref="ExpressionEvaluator.EvalResultDataItem"/> from
/// spurious <see cref="DkmDataItem.OnClose"/> calls. We need to attach the same information
/// to <see cref="Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluationResult"/> and
/// <see cref="Microsoft.VisualStudio.Debugger.Evaluation.DkmEvaluationResultEnumContext"/>
/// but they have different lifetimes. Enum contexts (which are effectively child lists)
/// are closed before the corresponding evaluation results. We don't want to actually clean
/// up until the evaluation result is closed.
/// </summary>
internal sealed class EnumContextDataItem : DkmDataItem
{
public readonly EvalResultDataItem EvalResultDataItem;
/// <remarks>
/// Only <see cref="ExpressionEvaluator.EvalResultDataItem"/> is expected to instantiate this type.
/// </remarks>
public EnumContextDataItem(EvalResultDataItem dataItem)
{
this.EvalResultDataItem = dataItem;
}
}
}
......@@ -110,5 +110,11 @@ private static DkmEvaluationResultFlags GetFlags(DkmClrValue value)
return resultFlags;
}
protected override void OnClose()
{
Debug.WriteLine("Closing " + FullName);
Value.Close();
}
}
}
......@@ -89,7 +89,7 @@ void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext,
{
try
{
var dataItem = enumContext.GetDataItem<EvalResultDataItem>();
var dataItem = enumContext.GetDataItem<EnumContextDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
......@@ -97,7 +97,7 @@ void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext,
return;
}
completionRoutine(GetItems(enumContext.InspectionContext, dataItem, startIndex, count));
completionRoutine(GetItems(enumContext.InspectionContext, dataItem.EvalResultDataItem, startIndex, count));
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
......@@ -116,7 +116,7 @@ string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result)
return result.GetUnderlyingString();
}
return dataItem.Value != null ? dataItem.Value.GetUnderlyingString() : null;
return dataItem.Value?.GetUnderlyingString();
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
......@@ -420,7 +420,7 @@ private DkmGetChildrenAsyncResult GetChildren(DkmInspectionContext inspectionCon
var rows = builder.ToArrayAndFree();
Debug.Assert(index >= rows.Length);
Debug.Assert(initialRequestSize >= rows.Length);
var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, evaluationResult.InspectionContext, dataItem);
var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, evaluationResult.InspectionContext, new EnumContextDataItem(dataItem));
return new DkmGetChildrenAsyncResult(rows, enumContext);
}
......
......@@ -101,6 +101,7 @@
<Compile Include="Helpers\ArrayBuilder.cs" />
<Compile Include="Helpers\DkmClrValueFlagsExtensions.cs" />
<Compile Include="Helpers\DkmEvaluationResultFlagsExtensions.cs" />
<Compile Include="Helpers\EnumContextDataItem.cs" />
<Compile Include="Helpers\EvalResultDataItem.cs" />
<Compile Include="Helpers\GeneratedMetadataNames.cs" />
<Compile Include="Helpers\HashFunctions.cs" />
......@@ -136,3 +137,4 @@
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
......@@ -647,5 +647,9 @@ private unsafe static object Dereference(IntPtr ptr, Type elementType)
throw new InvalidOperationException();
}
}
public void Close()
{
}
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
namespace Microsoft.VisualStudio.Debugger
{
public class DkmDataItem
{
protected virtual void OnClose() { }
}
}
\ No newline at end of file
......@@ -7,7 +7,6 @@ namespace Microsoft.VisualStudio.Debugger
{
public delegate void DkmCompletionRoutine<TResult>(TResult result);
public class DkmDataItem { }
public class DkmWorkList { }
public enum DkmDataCreationDisposition
......
......@@ -120,6 +120,9 @@
<Compile Include="..\..\Source\ResultProvider\Helpers\EvalResultDataItem.cs">
<Link>ResultProvider\Helpers\EvalResultDataItem.cs</Link>
</Compile>
<Compile Include="..\..\Source\ResultProvider\Helpers\EnumContextDataItem.cs">
<Link>ResultProvider\Helpers\EnumContextDataItem.cs</Link>
</Compile>
<Compile Include="..\..\Source\ResultProvider\Helpers\GeneratedMetadataNames.cs">
<Link>ResultProvider\Helpers\GeneratedMetadataNames.cs</Link>
</Compile>
......@@ -174,6 +177,7 @@
<Compile Include="Debugger\Engine\DkmEvaluationResultFlags.cs" />
<Compile Include="Debugger\Engine\DkmFailedEvaluationResult.cs" />
<Compile Include="Debugger\Engine\DkmInspectionContext.cs" />
<Compile Include="Debugger\Engine\DkmDataItem.cs" />
<Compile Include="Debugger\Engine\DkmMisc.cs" />
<Compile Include="Debugger\Engine\DkmModule.cs" />
<Compile Include="Debugger\Engine\DkmModuleInstance.cs" />
......@@ -221,3 +225,4 @@
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
......@@ -163,37 +163,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct
updatedProperty = updatedProperty.ReplaceNode(setter, setter.WithEndBlockStatement(SyntaxFactory.EndSetStatement()))
End If
Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim propertySymbol = TryCast(semanticModel.GetDeclaredSymbol(node), IPropertySymbol)
If propertySymbol IsNot Nothing Then
Dim codeGenService = document.GetLanguageService(Of ICodeGenerationService)()
Dim syntaxFactory = document.GetLanguageService(Of SyntaxGenerator)()
Dim generatedAccessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList(Of AttributeData)(),
Accessibility.Public,
SpecializedCollections.EmptyList(Of SyntaxNode)())
Dim generatedProperty = CodeGenerationSymbolFactory.CreatePropertySymbol(attributes:=SpecializedCollections.EmptyList(Of AttributeData)(),
accessibility:=Accessibility.Public,
modifiers:=New DeclarationModifiers(),
explicitInterfaceSymbol:=Nothing,
name:=propertySymbol.Name,
type:=propertySymbol.Type,
parameters:=propertySymbol.Parameters,
getMethod:=generatedAccessor,
setMethod:=generatedAccessor,
isIndexer:=propertySymbol.IsIndexer)
' Generate any missing setter or getter
Dim generatedPropertyCode = DirectCast(codeGenService.CreatePropertyDeclaration(generatedProperty, options:=CodeGenerationOptions.Default), PropertyBlockSyntax)
If getter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then
updatedProperty = updatedProperty.AddAccessors(generatedPropertyCode.Accessors.FirstOrDefault(Function(n) n.Kind = SyntaxKind.GetAccessorBlock))
End If
Dim gen = document.GetLanguageService(Of SyntaxGenerator)()
If setter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) Then
updatedProperty = updatedProperty.AddAccessors(generatedPropertyCode.Accessors.FirstOrDefault(Function(n) n.Kind = SyntaxKind.SetAccessorBlock))
End If
If getter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.WriteOnlyKeyword) Then
updatedProperty = DirectCast(gen.WithGetAccessorStatements(updatedProperty, {}), PropertyBlockSyntax)
End If
If setter Is Nothing AndAlso Not updatedProperty.PropertyStatement.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) Then
updatedProperty = DirectCast(gen.WithSetAccessorStatements(updatedProperty, {}), PropertyBlockSyntax)
End If
Dim updatedDocument = Await document.ReplaceNodeAsync(node, updatedProperty.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False)
......
......@@ -189,21 +189,6 @@
</Button>
<!-- Toolbar Buttons -->
<Button guid="guidInteractiveWindowCmdSet" id="cmdidClearScreen" priority="0x0100" type="Button">
<Parent guid="guidInteractiveWindowCmdSet" id="InteractiveToolbarGroup"/>
<Icon guid="guidInteractiveToolbarImages" id="bmpClearScreen" />
<Strings>
<ButtonText>Clear Screen</ButtonText>
</Strings>
</Button>
<Button guid="guidInteractiveWindowCmdSet" id="cmdidReset" priority="0x0200" type="Button">
<Parent guid="guidInteractiveWindowCmdSet" id="InteractiveToolbarGroup"/>
<Icon guid="guidInteractiveToolbarImages" id="bmpResetSession" />
<Strings>
<ButtonText>Reset</ButtonText>
</Strings>
</Button>
<!--<Button guid="guidInteractiveWindowCmdSet" id="cmdidAbortExecution" priority="0x0300" type="Button">
<Parent guid="guidInteractiveWindowCmdSet" id="InteractiveToolbarGroup"/>
......@@ -255,6 +240,12 @@
</UsedCommands>
<CommandPlacements>
<CommandPlacement guid="guidInteractiveWindowCmdSet" id="cmdidClearScreen" priority="0x0100">
<Parent guid="guidInteractiveWindowCmdSet" id="InteractiveToolbarGroup"/>
</CommandPlacement>
<CommandPlacement guid="guidInteractiveWindowCmdSet" id="cmdidReset" priority="0x0100">
<Parent guid="guidInteractiveWindowCmdSet" id="InteractiveToolbarGroup"/>
</CommandPlacement>
<!-- Cut/copy/paste group -->
<CommandPlacement guid="guidVSStd97" id="cmdidCut" priority="0x0100">
......
此差异已折叠。
此差异已折叠。
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
internal sealed class Arguments
{
public bool Recursive { get; private set; }
public string Path { get; private set; }
public IEnumerable<Tuple<string, string>> EncDeltas { get; private set; }
public HashSet<int> SkipGenerations { get; private set; }
public bool DisplayStatistics { get; private set; }
public bool DisplayAssemblyReferences { get; private set; }
public bool DisplayIL { get; private set; }
public bool DisplayMetadata { get; private set; }
public string OutputPath { get; private set; }
public ImmutableArray<string> FindRefs { get; private set; }
public const string Help = @"
Parameters:
<path> Path to a PE file, metadata blob, or a directory.
The target kind is auto-detected.
/g:<metadata-delta-path>;<il-delta-path> Add generation delta blobs.
/sg:<generation #> Suppress display of specified generation.
/stats[+|-] Display/hide misc statistics.
/assemblyRefs[+|-] Display/hide assembly references.
/il[+|-] Display/hide IL of method bodies.
/md[+|-] Display/hide metadata tables.
/findRef:<MemberRefs> Displays all assemblies containing the specified MemberRefs:
a semicolon separated list of
<assembly display name>:<qualified-type-name>:<member-name>
/out:<path> Write the output to specified file.
If the target path is a directory displays information for all *.dll, *.exe, *.winmd,
and *.netmodule files in the directory and all subdirectories.
If /g is speficied the path must be baseline PE file (generation 0).
";
public static Arguments TryParse(string[] args)
{
if (args.Length < 1)
{
return null;
}
var result = new Arguments();
result.Path = args[0];
result.Recursive = Directory.Exists(args[0]);
result.EncDeltas =
(from arg in args
where arg.StartsWith("/g:", StringComparison.Ordinal)
let value = arg.Substring("/g:".Length).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
select (value.Length >= 1 && value.Length <= 2) ? Tuple.Create(value[0], value.Length > 1 ? value[1] : null) : null).
ToArray();
if (result.EncDeltas.Any(value => value == null))
{
return null;
}
result.SkipGenerations = new HashSet<int>(args.Where(a => a.StartsWith("/sg:", StringComparison.OrdinalIgnoreCase)).Select(a => int.Parse(a.Substring("/sg:".Length))));
if (result.Recursive && (result.EncDeltas.Any() || result.SkipGenerations.Any()))
{
return null;
}
result.FindRefs = ParseValueArg(args, "findref")?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)?.ToImmutableArray() ?? ImmutableArray<string>.Empty;
bool findRefs = result.FindRefs.Any();
result.DisplayIL = ParseFlagArg(args, "il", defaultValue: !result.Recursive && !findRefs);
result.DisplayMetadata = ParseFlagArg(args, "md", defaultValue: !result.Recursive && !findRefs);
result.DisplayStatistics = ParseFlagArg(args, "stats", defaultValue: result.Recursive && !findRefs);
result.DisplayAssemblyReferences = ParseFlagArg(args, "stats", defaultValue: !findRefs);
result.OutputPath = ParseValueArg(args, "out");
return result;
}
private static string ParseValueArg(string[] args, string name)
{
string prefix = "/" + name + ":";
return args.Where(arg => arg.StartsWith(prefix, StringComparison.Ordinal)).Select(arg => arg.Substring(prefix.Length)).LastOrDefault();
}
private static bool ParseFlagArg(string[] args, string name, bool defaultValue)
{
string onStr = "/" + name + "+";
string offStr = "/" + name + "-";
return args.Aggregate(defaultValue, (value, arg) =>
arg.Equals(onStr, StringComparison.OrdinalIgnoreCase) ? true :
arg.Equals(offStr, StringComparison.OrdinalIgnoreCase) ? false :
value);
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="Settings">
<Import Project="..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Settings.targets" />
<Import Project="..\..\..\..\build\VSL.Settings.Closed.targets" />
</ImportGroup>
<PropertyGroup>
<NonShipping>True</NonShipping>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4C7847DB-C412-4D5E-B573-F12FA0A76127}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>MetadataVisualizer</RootNamespace>
<AssemblyName>mdv</AssemblyName>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " />
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " />
<ItemGroup>
<Compile Include="..\..\..\Compilers\Core\Portable\InternalUtilities\Hash.cs">
<Link>Hash.cs</Link>
</Compile>
<Compile Include="Arguments.cs" />
<Compile Include="Program.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Collections.Immutable">
<HintPath>..\..\..\..\packages\System.Collections.Immutable.1.1.33-beta\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Reflection.Metadata">
<HintPath>..\..\..\..\packages\System.Reflection.Metadata.1.0.18-beta\lib\portable-net45+win8\System.Reflection.Metadata.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Test\PdbUtilities\PdbUtilities.csproj">
<Project>{afde6bea-5038-4a4a-a88e-dbd2e4088eed}</Project>
<Name>PdbUtilities</Name>
</ProjectReference>
</ItemGroup>
<ImportGroup Label="Targets">
<Import Project="..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Utilities;
class Program : IDisposable
{
private class GenerationData
{
public MetadataReader MetadataReader;
public PEReader PEReaderOpt;
public byte[] DeltaILOpt;
public object memoryOwner;
}
private readonly Arguments arguments;
private readonly TextWriter writer;
private string pendingTitle;
public Program(Arguments arguments)
{
this.arguments = arguments;
this.writer = (arguments.OutputPath != null) ? new StreamWriter(File.OpenWrite(arguments.OutputPath), Encoding.UTF8) : Console.Out;
}
public void Dispose()
{
writer.Dispose();
}
private void WriteData(string line, params object[] args)
{
if (pendingTitle != null)
{
writer.WriteLine(pendingTitle);
pendingTitle = null;
}
writer.WriteLine(line, args);
}
private static int Main(string[] args)
{
var arguments = Arguments.TryParse(args);
if (arguments == null)
{
Console.WriteLine(Arguments.Help);
return 1;
}
using (var p = new Program(arguments))
{
if (arguments.Recursive)
{
return p.RunRecursive();
}
else
{
return p.RunOne();
}
}
}
private unsafe int RunOne()
{
var generations = new List<GenerationData>();
// gen 0:
var generation = new GenerationData();
try
{
var peStream = File.OpenRead(arguments.Path);
var peReader = new PEReader(peStream);
try
{
// first try if we have a full PE image:
generation.MetadataReader = peReader.GetMetadataReader();
generation.PEReaderOpt = peReader;
}
catch (Exception e) when (e is InvalidOperationException || e is BadImageFormatException)
{
// try metadata only:
var data = peReader.GetEntireImage();
generation.MetadataReader = new MetadataReader(data.Pointer, data.Length);
}
generation.memoryOwner = peReader;
}
catch (Exception e)
{
Console.WriteLine("Error reading '{0}': {1}", arguments.Path, e.Message);
return 1;
}
generations.Add(generation);
// deltas:
int i = 1;
foreach (var delta in arguments.EncDeltas)
{
var metadataPath = delta.Item1;
var ilPathOpt = delta.Item2;
generation = new GenerationData();
try
{
var mdBytes = File.ReadAllBytes(metadataPath);
GCHandle pinnedMetadataBytes = GCHandle.Alloc(mdBytes, GCHandleType.Pinned);
generation.memoryOwner = pinnedMetadataBytes;
generation.MetadataReader = new MetadataReader((byte*)pinnedMetadataBytes.AddrOfPinnedObject(), mdBytes.Length);
}
catch (Exception e)
{
Console.WriteLine("Error reading '{0}': {1}", metadataPath, e.Message);
return 1;
}
if (ilPathOpt != null)
{
try
{
generation.DeltaILOpt = File.ReadAllBytes(ilPathOpt);
}
catch (Exception e)
{
Console.WriteLine("Error reading '{0}': {1}", ilPathOpt, e.Message);
return 1;
}
}
generations.Add(generation);
i++;
}
VisualizeGenerations(generations);
return 0;
}
private unsafe void VisualizeGenerations(List<GenerationData> generations)
{
var mdReaders = generations.Select(g => g.MetadataReader).ToArray();
var visualizer = new MetadataVisualizer(mdReaders, writer);
for (int generationIndex = 0; generationIndex < generations.Count; generationIndex++)
{
if (arguments.SkipGenerations.Contains(generationIndex))
{
continue;
}
var generation = generations[generationIndex];
var mdReader = generation.MetadataReader;
writer.WriteLine(">>>");
writer.WriteLine(string.Format(">>> Generation {0}:", generationIndex));
writer.WriteLine(">>>");
writer.WriteLine();
if (arguments.DisplayMetadata)
{
visualizer.Visualize(generationIndex);
}
if (arguments.DisplayIL)
{
VisualizeGenerationIL(visualizer, generationIndex, generation, mdReader);
}
VisualizeMemberRefs(mdReader);
}
}
private static unsafe void VisualizeGenerationIL(MetadataVisualizer visualizer, int generationIndex, GenerationData generation, MetadataReader mdReader)
{
if (generation.PEReaderOpt != null)
{
foreach (var methodHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(methodHandle);
var rva = method.RelativeVirtualAddress;
if (rva != 0)
{
var body = generation.PEReaderOpt.GetMethodBody(rva);
visualizer.VisualizeMethodBody(body, methodHandle);
}
}
}
else if (generation.DeltaILOpt != null)
{
fixed (byte* deltaILPtr = generation.DeltaILOpt)
{
foreach (var generationHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(generationHandle);
var rva = method.RelativeVirtualAddress;
if (rva != 0)
{
var body = MethodBodyBlock.Create(new BlobReader(deltaILPtr + rva, generation.DeltaILOpt.Length - rva));
visualizer.VisualizeMethodBody(body, generationHandle, generationIndex);
}
}
}
}
}
private static readonly string[] PEExtensions = new[] { "*.dll", "*.exe", "*.netmodule", "*.winmd" };
private static IEnumerable<string> GetAllBinaries(string dir)
{
foreach (var subdir in Directory.GetDirectories(dir))
{
foreach (var file in GetAllBinaries(subdir))
{
yield return file;
}
}
foreach (var file in from extension in PEExtensions
from file in Directory.GetFiles(dir, extension)
select file)
{
yield return file;
}
}
private void VisualizeStatistics(MetadataReader mdReader)
{
if (!arguments.DisplayStatistics)
{
return;
}
WriteData("> method definitions: {0}, {1:F1}% with bodies",
mdReader.MethodDefinitions.Count,
100 * ((double)mdReader.MethodDefinitions.Count(handle => mdReader.GetMethodDefinition(handle).RelativeVirtualAddress != 0) / mdReader.MethodDefinitions.Count));
}
private void VisualizeAssemblyReferences(MetadataReader mdReader)
{
if (!arguments.DisplayAssemblyReferences)
{
return;
}
foreach (var handle in mdReader.AssemblyReferences)
{
var ar = mdReader.GetAssemblyReference(handle);
WriteData("{0}, Version={1}, PKT={2}",
mdReader.GetString(ar.Name),
ar.Version,
BitConverter.ToString(mdReader.GetBlobBytes(ar.PublicKeyOrToken)));
}
}
private void VisualizeMemberRefs(MetadataReader mdReader)
{
if (!arguments.FindRefs.Any())
{
return;
}
var memberRefs = new HashSet<MemberRefKey>(
from arg in arguments.FindRefs
let split = arg.Split(':')
where split.Length == 3
select new MemberRefKey(split[0].Trim(), split[1].Trim(), split[2].Trim()));
foreach (var handle in mdReader.MemberReferences)
{
var memberRef = mdReader.GetMemberReference(handle);
if (memberRef.Parent.Kind != HandleKind.TypeReference)
{
continue;
}
var typeRef = mdReader.GetTypeReference((TypeReferenceHandle)memberRef.Parent);
if (typeRef.ResolutionScope.Kind != HandleKind.AssemblyReference)
{
// TODO: handle nested types
continue;
}
var assemblyRef = mdReader.GetAssemblyReference((AssemblyReferenceHandle)typeRef.ResolutionScope);
var key = new MemberRefKey(
assemblyNameOpt: mdReader.GetString(assemblyRef.Name),
assemblyVersionOpt: assemblyRef.Version,
@namespace: mdReader.GetString(typeRef.Namespace),
typeName: mdReader.GetString(typeRef.Name),
memberName: mdReader.GetString(memberRef.Name)
);
if (memberRefs.Contains(key))
{
WriteData($"0x{MetadataTokens.GetToken(handle):X8}->0x{MetadataTokens.GetToken(memberRef.Parent):X8}:" + $" {key.ToString()}");
}
}
}
private struct MemberRefKey : IEquatable<MemberRefKey>
{
public readonly string AssemblyNameOpt;
public readonly Version AssemblyVersionOpt;
public readonly string Namespace;
public readonly string TypeName;
public readonly string MemberName;
public MemberRefKey(string assemblyName, string qualifiedTypeName, string memberName)
{
if (assemblyName.Length > 0)
{
var an = new AssemblyName(assemblyName);
AssemblyNameOpt = an.Name;
AssemblyVersionOpt = an.Version;
}
else
{
AssemblyNameOpt = null;
AssemblyVersionOpt = null;
}
var lastDot = qualifiedTypeName.LastIndexOf('.');
Namespace = (lastDot >= 0) ? qualifiedTypeName.Substring(0, lastDot) : "";
TypeName = (lastDot >= 0) ? qualifiedTypeName.Substring(lastDot + 1) : "";
MemberName = memberName;
}
public MemberRefKey(
string assemblyNameOpt,
Version assemblyVersionOpt,
string @namespace,
string typeName,
string memberName)
{
AssemblyNameOpt = assemblyNameOpt;
AssemblyVersionOpt = assemblyVersionOpt;
Namespace = @namespace;
TypeName = typeName;
MemberName = memberName;
}
public override bool Equals(object obj)
{
return obj is MemberRefKey && Equals((MemberRefKey)obj);
}
public override int GetHashCode()
{
// don't include assembly name/version
return Hash.Combine(Namespace,
Hash.Combine(TypeName,
Hash.Combine(MemberName, 0)));
}
public bool Equals(MemberRefKey other)
{
return (this.AssemblyNameOpt == null || other.AssemblyNameOpt == null || this.AssemblyNameOpt.Equals(other.AssemblyNameOpt, StringComparison.OrdinalIgnoreCase)) &&
(this.AssemblyVersionOpt == null || other.AssemblyVersionOpt == null || this.AssemblyVersionOpt.Equals(other.AssemblyVersionOpt)) &&
this.Namespace.Equals(other.Namespace) &&
this.TypeName.Equals(other.TypeName) &&
this.MemberName.Equals(other.MemberName);
}
public override string ToString()
{
return (AssemblyNameOpt != null ? $"{AssemblyNameOpt}, Version={AssemblyVersionOpt}" : "") +
$":{Namespace}{(Namespace.Length > 0 ? "." : "")}{TypeName}:{MemberName}";
}
}
private int RunRecursive()
{
bool hasError = false;
foreach (var file in GetAllBinaries(arguments.Path))
{
using (var peReader = new PEReader(File.OpenRead(file)))
{
try
{
if (!peReader.HasMetadata)
{
continue;
}
}
catch (BadImageFormatException e)
{
writer.WriteLine("{0}: {1}", file, e.Message);
hasError = true;
continue;
}
pendingTitle = file;
try
{
var mdReader = peReader.GetMetadataReader();
VisualizeAssemblyReferences(mdReader);
VisualizeStatistics(mdReader);
VisualizeMemberRefs(mdReader);
}
catch (BadImageFormatException e)
{
WriteData("ERROR: {0}", e.Message);
hasError = true;
continue;
}
if (pendingTitle == null)
{
writer.WriteLine();
}
pendingTitle = null;
}
}
return hasError ? 1 : 0;
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.Collections.Immutable" version="1.1.33-beta" targetFramework="net45" />
<package id="System.Reflection.Metadata" version="1.0.18-beta" targetFramework="net45" />
</packages>
......@@ -92,6 +92,9 @@ public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<Syn
DeclarationModifiers modifiers,
SyntaxNode initializer)
{
type = this.ClearTrivia(type);
initializer = this.ClearTrivia(initializer);
return SyntaxFactory.FieldDeclaration(
default(SyntaxList<AttributeListSyntax>),
AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration),
......@@ -106,6 +109,9 @@ public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<Syn
public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind)
{
type = this.ClearTrivia(type);
initializer = this.ClearTrivia(initializer);
return SyntaxFactory.Parameter(
default(SyntaxList<AttributeListSyntax>),
GetParameterModifiers(refKind),
......@@ -137,6 +143,9 @@ private SyntaxTokenList GetParameterModifiers(RefKind refKind)
DeclarationModifiers modifiers,
IEnumerable<SyntaxNode> statements)
{
parameters = this.ClearTrivia(parameters);
returnType = this.ClearTrivia(returnType);
bool hasBody = !modifiers.IsAbstract;
return SyntaxFactory.MethodDeclaration(
......@@ -167,6 +176,9 @@ private ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters)
IEnumerable<SyntaxNode> baseConstructorArguments,
IEnumerable<SyntaxNode> statements)
{
parameters = this.ClearTrivia(parameters);
baseConstructorArguments = this.ClearTrivia(baseConstructorArguments);
return SyntaxFactory.ConstructorDeclaration(
default(SyntaxList<AttributeListSyntax>),
AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration),
......@@ -184,6 +196,8 @@ private ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters)
IEnumerable<SyntaxNode> getAccessorStatements,
IEnumerable<SyntaxNode> setAccessorStatements)
{
type = this.ClearTrivia(type);
var accessors = new List<AccessorDeclarationSyntax>();
var hasSetter = !modifiers.IsReadOnly;
......@@ -229,6 +243,8 @@ private ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters)
IEnumerable<SyntaxNode> getAccessorStatements,
IEnumerable<SyntaxNode> setAccessorStatements)
{
type = this.ClearTrivia(type);
var accessors = new List<AccessorDeclarationSyntax>();
var hasSetter = !modifiers.IsReadOnly;
......@@ -293,6 +309,8 @@ private AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerab
Accessibility accessibility,
DeclarationModifiers modifiers)
{
type = this.ClearTrivia(type);
return SyntaxFactory.EventFieldDeclaration(
default(SyntaxList<AttributeListSyntax>),
AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration),
......@@ -311,6 +329,9 @@ private AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerab
IEnumerable<SyntaxNode> addAccessorStatements,
IEnumerable<SyntaxNode> removeAccessorStatements)
{
type = this.ClearTrivia(type);
parameters = this.ClearTrivia(parameters);
var accessors = new List<AccessorDeclarationSyntax>();
if (modifiers.IsAbstract)
{
......@@ -350,6 +371,8 @@ public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaratio
public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode typeName)
{
typeName = this.ClearTrivia(typeName);
return PreserveTrivia(declaration, d =>
{
var specifier = SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)typeName);
......@@ -468,9 +491,12 @@ private AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor
Accessibility accessibility,
DeclarationModifiers modifiers,
SyntaxNode baseType,
IEnumerable<SyntaxNode> interfaceTypes,
IEnumerable<SyntaxNode> interfaceTypes,
IEnumerable<SyntaxNode> members)
{
baseType = this.ClearTrivia(baseType);
interfaceTypes = this.ClearTrivia(interfaceTypes);
List<BaseTypeSyntax> baseTypes = null;
if (baseType != null || interfaceTypes != null)
{
......@@ -534,6 +560,8 @@ private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className)
IEnumerable<SyntaxNode> interfaceTypes,
IEnumerable<SyntaxNode> members)
{
interfaceTypes = this.ClearTrivia(interfaceTypes);
var itypes = interfaceTypes != null ? interfaceTypes.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList() : null;
if (itypes != null && itypes.Count == 0)
{
......@@ -557,6 +585,8 @@ private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className)
IEnumerable<SyntaxNode> interfaceTypes = null,
IEnumerable<SyntaxNode> members = null)
{
interfaceTypes = this.ClearTrivia(interfaceTypes);
var itypes = interfaceTypes != null ? interfaceTypes.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList() : null;
if (itypes != null && itypes.Count == 0)
{
......@@ -649,6 +679,8 @@ private SyntaxNode AsInterfaceMember(SyntaxNode m)
public override SyntaxNode EnumMember(string name, SyntaxNode expression)
{
expression = this.ClearTrivia(expression);
return SyntaxFactory.EnumMemberDeclaration(
default(SyntaxList<AttributeListSyntax>),
name.ToIdentifierToken(),
......@@ -689,6 +721,9 @@ private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerab
Accessibility accessibility = Accessibility.NotApplicable,
DeclarationModifiers modifiers = default(DeclarationModifiers))
{
parameters = this.ClearTrivia(parameters);
returnType = this.ClearTrivia(returnType);
return SyntaxFactory.DelegateDeclaration(
default(SyntaxList<AttributeListSyntax>),
AsModifierList(accessibility, modifiers),
......@@ -742,8 +777,15 @@ private AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node)
protected override TNode ClearTrivia<TNode>(TNode node)
{
return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker)
.WithTrailingTrivia(SyntaxFactory.ElasticMarker);
if (node != null)
{
return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker)
.WithTrailingTrivia(SyntaxFactory.ElasticMarker);
}
else
{
return null;
}
}
private SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes)
......
......@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
......@@ -78,6 +79,7 @@ private void TestTemporaryStorage(ITemporaryStorageService temporaryStorageServi
Assert.NotSame(text, text2);
Assert.Equal(text.ToString(), text2.ToString());
Assert.Equal(text.Encoding, text2.Encoding);
temporaryStorage.Dispose();
}
......@@ -323,5 +325,24 @@ public void StreamTest3()
}
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/353"), Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestTemporaryStorageTextEncoding()
{
var textFactory = new TextFactoryService();
var service = new TemporaryStorageServiceFactory.TemporaryStorageService(textFactory);
// test normal string
var text = SourceText.From(new string(' ', 4096) + "public class A {}", Encoding.ASCII);
TestTemporaryStorage(service, text);
// test empty string
text = SourceText.From(string.Empty);
TestTemporaryStorage(service, text);
// test large string
text = SourceText.From(new string(' ', 1024 * 1024) + "public class A {}");
TestTemporaryStorage(service, text);
}
}
}
......@@ -576,6 +576,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function FieldDeclaration(name As String, type As SyntaxNode, Optional accessibility As Accessibility = Nothing, Optional modifiers As DeclarationModifiers = Nothing, Optional initializer As SyntaxNode = Nothing) As SyntaxNode
type = Me.ClearTrivia(type)
initializer = Me.ClearTrivia(initializer)
Return SyntaxFactory.FieldDeclaration(
attributeLists:=Nothing,
modifiers:=GetModifierList(accessibility, modifiers And fieldModifiers, isField:=True),
......@@ -591,6 +594,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional modifiers As DeclarationModifiers = Nothing,
Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
parameters = MyBase.ClearTrivia(parameters)
returnType = Me.ClearTrivia(returnType)
Dim statement = SyntaxFactory.MethodStatement(
kind:=If(returnType Is Nothing, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement),
attributeLists:=Nothing,
......@@ -619,6 +625,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function ParameterDeclaration(name As String, Optional type As SyntaxNode = Nothing, Optional initializer As SyntaxNode = Nothing, Optional refKind As RefKind = Nothing) As SyntaxNode
type = Me.ClearTrivia(type)
Return SyntaxFactory.Parameter(
attributeLists:=Nothing,
modifiers:=GetParameterModifiers(refKind, initializer),
......@@ -646,6 +654,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
type = Me.ClearTrivia(type)
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
Dim statement = SyntaxFactory.PropertyStatement(
attributeLists:=Nothing,
......@@ -682,6 +692,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional getAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing,
Optional setAccessorStatements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
type = ClearTrivia(type)
parameters = MyBase.ClearTrivia(parameters)
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
Dim statement = SyntaxFactory.PropertyStatement(
attributeLists:=Nothing,
......@@ -711,6 +724,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Private Function AccessorBlock(kind As SyntaxKind, statements As IEnumerable(Of SyntaxNode), type As SyntaxNode) As AccessorBlockSyntax
type = Me.ClearTrivia(type)
Select Case kind
Case SyntaxKind.GetAccessorBlock
Return CreateGetAccessorBlock(statements)
......@@ -734,6 +749,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Private Function CreateSetAccessorBlock(type As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
type = Me.ClearTrivia(type)
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(type, TypeSyntax))
Dim valueParameter = SyntaxFactory.Parameter(
......@@ -756,6 +773,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Private Function CreateAddHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
delegateType = Me.ClearTrivia(delegateType)
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax))
Dim valueParameter = SyntaxFactory.Parameter(
......@@ -778,6 +797,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Private Function CreateRemoveHandlerAccessorBlock(delegateType As SyntaxNode, statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
delegateType = Me.ClearTrivia(delegateType)
Dim asClause = SyntaxFactory.SimpleAsClause(DirectCast(delegateType, TypeSyntax))
Dim valueParameter = SyntaxFactory.Parameter(
......@@ -800,6 +821,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Private Function CreateRaiseEventAccessorBlock(parameters As IEnumerable(Of SyntaxNode), statements As IEnumerable(Of SyntaxNode)) As AccessorBlockSyntax
parameters = MyBase.ClearTrivia(parameters)
Dim parameterList = GetParameterList(parameters)
Return SyntaxFactory.AccessorBlock(
......@@ -815,6 +837,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function AsPublicInterfaceImplementation(declaration As SyntaxNode, typeName As SyntaxNode) As SyntaxNode
typeName = Me.ClearTrivia(typeName)
Dim type = DirectCast(typeName, NameSyntax)
declaration = AsImplementation(declaration, Accessibility.Public, allowDefault:=True)
......@@ -837,6 +860,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function AsPrivateInterfaceImplementation(declaration As SyntaxNode, typeName As SyntaxNode) As SyntaxNode
typeName = Me.ClearTrivia(typeName)
Dim type = DirectCast(typeName, NameSyntax)
' convert declaration statements to blocks
......@@ -947,6 +971,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional baseConstructorArguments As IEnumerable(Of SyntaxNode) = Nothing,
Optional statements As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
parameters = MyBase.ClearTrivia(parameters)
baseConstructorArguments = MyBase.ClearTrivia(baseConstructorArguments)
Dim stats = GetStatementList(statements)
If (baseConstructorArguments IsNot Nothing) Then
......@@ -971,6 +998,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
baseType = Me.ClearTrivia(baseType)
interfaceTypes = MyBase.ClearTrivia(interfaceTypes)
Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing)
If itypes IsNot Nothing AndAlso itypes.Count = 0 Then
itypes = Nothing
......@@ -1007,6 +1037,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
interfaceTypes = MyBase.ClearTrivia(interfaceTypes)
Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing)
If itypes IsNot Nothing AndAlso itypes.Count = 0 Then
itypes = Nothing
......@@ -1042,6 +1074,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional interfaceTypes As IEnumerable(Of SyntaxNode) = Nothing,
Optional members As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
interfaceTypes = MyBase.ClearTrivia(interfaceTypes)
Dim itypes = If(interfaceTypes IsNot Nothing, interfaceTypes.Cast(Of TypeSyntax), Nothing)
If itypes IsNot Nothing AndAlso itypes.Count = 0 Then
itypes = Nothing
......@@ -1135,6 +1169,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Optional accessibility As Accessibility = Accessibility.NotApplicable,
Optional modifiers As DeclarationModifiers = Nothing) As SyntaxNode
parameters = MyBase.ClearTrivia(parameters)
Dim kind = If(returnType Is Nothing, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement)
Return SyntaxFactory.DelegateStatement(
......@@ -1169,10 +1205,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function NamespaceImportDeclaration(name As SyntaxNode) As SyntaxNode
name = Me.ClearTrivia(name)
Return SyntaxFactory.ImportsStatement(SyntaxFactory.SingletonSeparatedList(Of ImportsClauseSyntax)(SyntaxFactory.SimpleImportsClause(DirectCast(name, NameSyntax))))
End Function
Public Overrides Function NamespaceDeclaration(name As SyntaxNode, nestedDeclarations As IEnumerable(Of SyntaxNode)) As SyntaxNode
name = Me.ClearTrivia(name)
Dim imps As IEnumerable(Of StatementSyntax) = AsImports(nestedDeclarations)
Dim members As IEnumerable(Of StatementSyntax) = AsNamespaceMembers(nestedDeclarations)
......@@ -1185,6 +1224,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function Attribute(name As SyntaxNode, Optional attributeArguments As IEnumerable(Of SyntaxNode) = Nothing) As SyntaxNode
name = Me.ClearTrivia(name)
attributeArguments = MyBase.ClearTrivia(attributeArguments)
Dim attr = SyntaxFactory.Attribute(
target:=Nothing,
name:=DirectCast(name, TypeSyntax),
......@@ -1202,6 +1244,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Public Overrides Function AttributeArgument(name As String, expression As SyntaxNode) As SyntaxNode
expression = Me.ClearTrivia(expression)
Return Argument(name, RefKind.None, expression)
End Function
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册