本文整理汇总了C#中ImmutableArray类的典型用法代码示例。如果您正苦于以下问题:C# ImmutableArray类的具体用法?C# ImmutableArray怎么用?C# ImmutableArray使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ImmutableArray类属于命名空间,在下文中一共展示了ImmutableArray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: VerifyFixInternalAsync
private async Task VerifyFixInternalAsync(string language, ImmutableArray<DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex,
bool allowNewCompilerDiagnostics, int maxNumberOfIterations, Func<ImmutableArray<DiagnosticAnalyzer>, CodeFixProvider, int?, CancellationToken, Document, int, Task<Document>> getFixedDocument, CancellationToken cancellationToken)
{
var document = this.CreateDocument(oldSource, language);
var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false);
document = await getFixedDocument(analyzers, codeFixProvider, codeFixIndex, cancellationToken, document, maxNumberOfIterations).ConfigureAwait(false);
var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false));
// check if applying the code fix introduced any new compiler diagnostics
if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
{
// Format and get the compiler diagnostics again so that the locations make sense in the output
document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false));
string message =
string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).ToFullString());
Assert.True(false, message);
}
// after applying all of the code fixes, compare the resulting string to the inputted one
var actual = await GetStringFromDocumentAsync(document, cancellationToken).ConfigureAwait(false);
Assert.Equal(newSource, actual);
}
示例2: FixAllAsync
private async Task<Document> FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Create an editor to do all the transformations. This allows us to fix all
// the diagnostics in a clean manner. If we used the normal batch fix provider
// then it might fail to apply all the individual text changes as many of the
// changes produced by the diff might end up overlapping others.
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
var options = document.Project.Solution.Workspace.Options;
// Attempt to use an out-var declaration if that's the style the user prefers.
// Note: if using 'var' would cause a problem, we will use the actual type
// of hte local. This is necessary in some cases (for example, when the
// type of the out-var-decl affects overload resolution or generic instantiation).
var useVarWhenDeclaringLocals = options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals);
var useImplicitTypeForIntrinsicTypes = options.GetOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes).Value;
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
await AddEditsAsync(document, editor, diagnostic,
useVarWhenDeclaringLocals, useImplicitTypeForIntrinsicTypes,
cancellationToken).ConfigureAwait(false);
}
var newRoot = editor.GetChangedRoot();
return document.WithSyntaxRoot(newRoot);
}
示例3: GetExpectedDescendants
protected IList<SyntaxNode> GetExpectedDescendants(IEnumerable<SyntaxNode> nodes, ImmutableArray<SyntaxKind> expected)
{
var descendants = new List<SyntaxNode>();
foreach (var node in nodes)
{
if (expected.Any(e => e == node.Kind()))
{
descendants.Add(node);
continue;
}
foreach (var child in node.ChildNodes())
{
if (expected.Any(e => e == child.Kind()))
{
descendants.Add(child);
continue;
}
if (child.ChildNodes().Count() > 0)
descendants.AddRange(GetExpectedDescendants(child.ChildNodes(), expected));
}
}
return descendants;
}
示例4: FilterSuppressedDiagnostics
private static ImmutableArray<DiagnosticData> FilterSuppressedDiagnostics(ImmutableArray<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics)
{
if (includeSuppressedDiagnostics || diagnostics.IsDefaultOrEmpty)
{
return diagnostics;
}
ImmutableArray<DiagnosticData>.Builder builder = null;
for (int i = 0; i < diagnostics.Length; i++)
{
var diagnostic = diagnostics[i];
if (diagnostic.IsSuppressed)
{
if (builder == null)
{
builder = ImmutableArray.CreateBuilder<DiagnosticData>();
for (int j = 0; j < i; j++)
{
builder.Add(diagnostics[j]);
}
}
}
else if (builder != null)
{
builder.Add(diagnostic);
}
}
return builder != null ? builder.ToImmutable() : diagnostics;
}
示例5: SynthesizedImplementationMethod
public SynthesizedImplementationMethod(
MethodSymbol interfaceMethod,
NamedTypeSymbol implementingType,
string name = null,
bool generateDebugInfo = true,
PropertySymbol associatedProperty = null)
{
//it does not make sense to add methods to substituted types
Debug.Assert(implementingType.IsDefinition);
_name = name ?? ExplicitInterfaceHelpers.GetMemberName(interfaceMethod.Name, interfaceMethod.ContainingType, aliasQualifierOpt: null);
_interfaceMethod = interfaceMethod;
_implementingType = implementingType;
_generateDebugInfo = generateDebugInfo;
_associatedProperty = associatedProperty;
_explicitInterfaceImplementations = ImmutableArray.Create<MethodSymbol>(interfaceMethod);
// alpha-rename to get the implementation's type parameters
var typeMap = interfaceMethod.ContainingType.TypeSubstitution ?? TypeMap.Empty;
typeMap.WithAlphaRename(interfaceMethod, this, out _typeParameters);
var substitutedInterfaceMethod = interfaceMethod.ConstructIfGeneric(_typeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
_returnType = substitutedInterfaceMethod.ReturnType;
_parameters = SynthesizedParameterSymbol.DeriveParameters(substitutedInterfaceMethod, this);
}
示例6: InteractiveEvaluator
internal InteractiveEvaluator(
IContentType contentType,
HostServices hostServices,
IViewClassifierAggregatorService classifierAggregator,
IInteractiveWindowCommandsFactory commandsFactory,
ImmutableArray<IInteractiveWindowCommand> commands,
string responseFilePath,
string initialWorkingDirectory,
string interactiveHostPath,
Type replType)
{
Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));
_contentType = contentType;
_responseFilePath = responseFilePath;
_workspace = new InteractiveWorkspace(this, hostServices);
_contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
_classifierAggregator = classifierAggregator;
_initialWorkingDirectory = initialWorkingDirectory;
_commandsFactory = commandsFactory;
_commands = commands;
var hostPath = interactiveHostPath;
_interactiveHost = new InteractiveHost(replType, hostPath, initialWorkingDirectory);
_interactiveHost.ProcessStarting += ProcessStarting;
}
示例7: FileSystemCompletionHelper
public FileSystemCompletionHelper(
CompletionListProvider completionProvider,
TextSpan textChangeSpan,
ICurrentWorkingDirectoryDiscoveryService fileSystemDiscoveryService,
Glyph folderGlyph,
Glyph fileGlyph,
ImmutableArray<string> searchPaths,
IEnumerable<string> allowableExtensions,
Func<string, bool> exclude = null,
CompletionItemRules itemRules = null)
{
Debug.Assert(searchPaths.All(path => PathUtilities.IsAbsolute(path)));
_completionProvider = completionProvider;
_textChangeSpan = textChangeSpan;
_searchPaths = searchPaths;
_allowableExtensions = allowableExtensions.Select(e => e.ToLowerInvariant()).ToSet();
_fileSystemDiscoveryService = fileSystemDiscoveryService;
_folderGlyph = folderGlyph;
_fileGlyph = fileGlyph;
_exclude = exclude;
_itemRules = itemRules;
_lazyGetDrives = new Lazy<string[]>(() =>
IOUtilities.PerformIO(Directory.GetLogicalDrives, SpecializedCollections.EmptyArray<string>()));
}
示例8: CreateEnum
private static NavInfoNodeEnum CreateEnum(ref ImmutableArray<NavInfoNode> nodes, ImmutableArray<NavInfoNode> baseNodes, bool isCanonical, bool isObjectBrowser)
{
if (nodes.IsDefault)
{
var builder = ImmutableArray.CreateBuilder<NavInfoNode>();
var startIndex = 0;
// In some cases, Class View presentation NavInfo objects will have extra nodes (LLT_PACKAGE & LLT_HIERARCHY) up front.
// When this NavInfo is consumed by Object Browser (for 'Browse to Definition'), we need to skip first two nodes
if (isObjectBrowser && !isCanonical && baseNodes.Length >= 2 && baseNodes[1].ListType == _LIB_LISTTYPE.LLT_HIERARCHY)
{
startIndex = 2;
}
for (int i = startIndex; i < baseNodes.Length; i++)
{
if (isCanonical && baseNodes[i].ListType == _LIB_LISTTYPE.LLT_HIERARCHY)
{
continue;
}
builder.Add(baseNodes[i]);
}
nodes = builder.ToImmutable();
}
return new NavInfoNodeEnum(nodes);
}
示例9: NetworkAddressKey
public NetworkAddressKey(ImmutableArray<byte> IPv6Address, UInt16 Port)
{
this.IPv6Address = IPv6Address;
this.Port = Port;
this._hashCode = Port.GetHashCode() ^ new BigInteger(IPv6Address.ToArray()).GetHashCode();
}
示例10: WriteTo
private void WriteTo(Stream stream, ImmutableArray<DiagnosticData> items, CancellationToken cancellationToken)
{
using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken))
{
writer.WriteInt32(FormatVersion);
AnalyzerVersion.WriteTo(writer);
Version.WriteTo(writer);
writer.WriteInt32(items.Length);
foreach (var item in items)
{
cancellationToken.ThrowIfCancellationRequested();
writer.WriteString(item.Id);
writer.WriteString(item.Category);
writer.WriteString(item.Message);
writer.WriteString(item.ENUMessageForBingSearch);
writer.WriteString(item.Title);
writer.WriteString(item.Description);
writer.WriteString(item.HelpLink);
writer.WriteInt32((int)item.Severity);
writer.WriteInt32((int)item.DefaultSeverity);
writer.WriteBoolean(item.IsEnabledByDefault);
writer.WriteBoolean(item.IsSuppressed);
writer.WriteInt32(item.WarningLevel);
if (item.HasTextSpan)
{
// document state
writer.WriteInt32(item.TextSpan.Start);
writer.WriteInt32(item.TextSpan.Length);
}
else
{
// project state
writer.WriteInt32(0);
writer.WriteInt32(0);
}
WriteTo(writer, item.DataLocation, cancellationToken);
WriteTo(writer, item.AdditionalLocations, cancellationToken);
writer.WriteInt32(item.CustomTags.Count);
foreach (var tag in item.CustomTags)
{
writer.WriteString(tag);
}
writer.WriteInt32(item.Properties.Count);
foreach (var property in item.Properties)
{
writer.WriteString(property.Key);
writer.WriteString(property.Value);
}
}
}
}
示例11: AppendTodoComments
protected override void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, List<TodoComment> todoList)
{
if (PreprocessorHasComment(trivia))
{
var message = trivia.ToFullString();
var index = message.IndexOf(SingleLineCommentPrefix);
var start = trivia.FullSpan.Start + index;
AppendTodoCommentInfoFromSingleLine(commentDescriptors, document, message.Substring(index), start, todoList);
return;
}
if (IsSingleLineComment(trivia))
{
ProcessMultilineComment(commentDescriptors, document, trivia, postfixLength: 0, todoList: todoList);
return;
}
if (IsMultilineComment(trivia))
{
ProcessMultilineComment(commentDescriptors, document, trivia, s_multilineCommentPostfixLength, todoList);
return;
}
throw ExceptionUtilities.Unreachable;
}
示例12: EELocalSymbol
public EELocalSymbol(
MethodSymbol method,
ImmutableArray<Location> locations,
string nameOpt,
int ordinal,
LocalDeclarationKind declarationKind,
TypeSymbol type,
RefKind refKind,
bool isPinned,
bool isCompilerGenerated,
bool canScheduleToStack)
{
Debug.Assert(method != null);
Debug.Assert(ordinal >= -1);
Debug.Assert(!locations.IsDefault);
Debug.Assert(type != null);
_method = method;
_locations = locations;
_nameOpt = nameOpt;
_ordinal = ordinal;
_declarationKind = declarationKind;
_type = type;
_refKind = refKind;
_isPinned = isPinned;
_isCompilerGenerated = isCompilerGenerated;
_canScheduleToStack = canScheduleToStack;
}
示例13: GetSortedDiagnosticsFromDocumentsAsync
/// <summary>
/// Given an analyzer and a collection of documents to apply it to, run the analyzer and gather an array of
/// diagnostics found. The returned diagnostics are then ordered by location in the source documents.
/// </summary>
/// <param name="analyzers">The analyzer to run on the documents.</param>
/// <param name="documents">The <see cref="Document"/>s that the analyzer will be run on.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
/// <returns>A collection of <see cref="Diagnostic"/>s that surfaced in the source code, sorted by
/// <see cref="Diagnostic.Location"/>.</returns>
protected static async Task<ImmutableArray<Diagnostic>> GetSortedDiagnosticsFromDocumentsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Document[] documents, CancellationToken cancellationToken)
{
var projects = new HashSet<Project>();
foreach (var document in documents)
{
projects.Add(document.Project);
}
var supportedDiagnosticsSpecificOptions = new Dictionary<string, ReportDiagnostic>();
foreach (var analyzer in analyzers)
{
foreach (var diagnostic in analyzer.SupportedDiagnostics)
{
// make sure the analyzers we are testing are enabled
supportedDiagnosticsSpecificOptions[diagnostic.Id] = ReportDiagnostic.Default;
}
}
// Report exceptions during the analysis process as errors
supportedDiagnosticsSpecificOptions.Add("AD0001", ReportDiagnostic.Error);
var diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
foreach (var project in projects)
{
// update the project compilation options
var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions);
var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions);
var processedProject = project.WithCompilationOptions(modifiedCompilationOptions);
var compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, processedProject.AnalyzerOptions, cancellationToken);
var compilerDiagnostics = compilation.GetDiagnostics(cancellationToken);
var compilerErrors = compilerDiagnostics.Where(i => i.Severity == DiagnosticSeverity.Error);
var diags = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false);
var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync().ConfigureAwait(false);
var failureDiagnostics = allDiagnostics.Where(diagnostic => diagnostic.Id == "AD0001");
foreach (var diag in diags.Concat(compilerErrors).Concat(failureDiagnostics))
{
if (diag.Location == Location.None || diag.Location.IsInMetadata)
{
diagnostics.Add(diag);
}
else
{
for (int i = 0; i < documents.Length; i++)
{
var document = documents[i];
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (tree == diag.Location.SourceTree)
{
diagnostics.Add(diag);
}
}
}
}
}
var results = SortDistinctDiagnostics(diagnostics);
return results.ToImmutableArray();
}
示例14: ProcessCode
protected Info ProcessCode(DiagnosticAnalyzer analyzer, string sampleProgram,
ImmutableArray<SyntaxKind> expected, bool allowBuildErrors = false)
{
var options = new CSharpParseOptions(kind: SourceCodeKind.Script); //, languageVersion: LanguageVersion.CSharp5);
var tree = CSharpSyntaxTree.ParseText(sampleProgram, options);
var compilation = CSharpCompilation.Create("Test", new[] { tree }, references);
var diagnostics = compilation.GetDiagnostics();
if (diagnostics.Count(d => d.Severity == DiagnosticSeverity.Error) > 0)
{
var msg = "There were Errors in the sample code\n";
if (allowBuildErrors == false)
Assert.Fail(msg + string.Join("\n", diagnostics));
else
Console.WriteLine(msg + string.Join("\n", diagnostics));
}
var semanticModel = compilation.GetSemanticModel(tree);
var matches = GetExpectedDescendants(tree.GetRoot().ChildNodes(), expected);
// Run the code tree through the analyzer and record the allocations it reports
var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer));
var allocations = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().GetAwaiter().GetResult().Distinct(DiagnosticEqualityComparer.Instance).ToList();
return new Info
{
Options = options,
Tree = tree,
Compilation = compilation,
Diagnostics = diagnostics,
SemanticModel = semanticModel,
Matches = matches,
Allocations = allocations,
};
}
示例15: SynchronizeWithBuildAsync
public override async Task SynchronizeWithBuildAsync(Project project, ImmutableArray<DiagnosticData> diagnostics)
{
if (!PreferBuildErrors(project.Solution.Workspace))
{
// prefer live errors over build errors
return;
}
using (var poolObject = SharedPools.Default<HashSet<string>>().GetPooledObject())
{
var lookup = CreateDiagnosticIdLookup(diagnostics);
foreach (var stateSet in _stateManager.GetStateSets(project))
{
var descriptors = HostAnalyzerManager.GetDiagnosticDescriptors(stateSet.Analyzer);
var liveDiagnostics = ConvertToLiveDiagnostics(lookup, descriptors, poolObject.Object);
// we are using Default so that things like LB can't use cached information
var projectTextVersion = VersionStamp.Default;
var semanticVersion = await project.GetDependentSemanticVersionAsync(CancellationToken.None).ConfigureAwait(false);
var state = stateSet.GetState(StateType.Project);
var existingDiagnostics = await state.TryGetExistingDataAsync(project, CancellationToken.None).ConfigureAwait(false);
var mergedDiagnostics = MergeDiagnostics(liveDiagnostics, GetExistingDiagnostics(existingDiagnostics));
await state.PersistAsync(project, new AnalysisData(projectTextVersion, semanticVersion, mergedDiagnostics), CancellationToken.None).ConfigureAwait(false);
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), mergedDiagnostics);
}
}
}