private static bool IsMultidimensionalInitializer(ImmutableArray<BoundExpression> inits) { Debug.Assert(inits.All((init) => init.Kind != BoundKind.ArrayInitialization) || inits.All((init) => init.Kind == BoundKind.ArrayInitialization), "all or none should be nested"); return inits.Length != 0 && inits[0].Kind == BoundKind.ArrayInitialization; }
/// <summary> /// If we should cover the assembly. /// </summary> /// <param name="assemblyName">The name of the assembly.</param> /// <returns>If we should include the assembly in the coverage or not.</returns> public bool ShouldCoverAssembly(string assemblyName) { if (_coverageFilters.IsDefaultOrEmpty) { return(false); } return(_coverageFilters.All(x => x.ShouldCoverAssembly(assemblyName))); }
public TaggedRuleCollection(IEnumerable <TaggedRule> rules) { if (rules == null) { throw new ArgumentNullException(nameof(rules)); } _rules = ImmutableArray <TaggedRule> .Empty.AddRange(rules); DoAllHaveNames = _rules.All(r => r.HasTag); DoAllNotHaveNames = _rules.All(r => !r.HasTag); }
public InvalidOperation(ImmutableArray <IOperation> children, SemanticModel semanticModel, SyntaxNode syntax, ITypeSymbol type, Optional <object> constantValue, bool isImplicit) : base(semanticModel, syntax, type, constantValue, isImplicit) { // we don't allow null children. Debug.Assert(children.All(o => o != null)); Children = SetParentOperation(children, this); }
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>())); }
internal State( ImmutableArray <SyntaxTree> syntaxTrees, ImmutableDictionary <SyntaxTree, int> syntaxTreeOrdinalMap, ImmutableDictionary <SyntaxTree, ImmutableArray <LoadDirective> > loadDirectiveMap, ImmutableDictionary <string, SyntaxTree> loadedSyntaxTreeMap, ImmutableDictionary < SyntaxTree, Lazy <RootSingleNamespaceDeclaration> > rootNamespaces, DeclarationTable declarationTable ) { Debug.Assert( syntaxTrees.All(tree => syntaxTrees[syntaxTreeOrdinalMap[tree]] == tree) ); Debug.Assert( syntaxTrees.SetEquals( rootNamespaces.Keys.AsImmutable(), EqualityComparer <SyntaxTree> .Default ) ); this.SyntaxTrees = syntaxTrees; this.OrdinalMap = syntaxTreeOrdinalMap; this.LoadDirectiveMap = loadDirectiveMap; this.LoadedSyntaxTreeMap = loadedSyntaxTreeMap; this.RootNamespaces = rootNamespaces; this.DeclarationTable = declarationTable; }
private async Task <bool> TryInitializeAsync( AddConstructorParametersFromMembersCodeRefactoringProvider service, ImmutableArray <ISymbol> selectedMembers, Document document, CancellationToken cancellationToken) { ContainingType = selectedMembers[0].ContainingType; var rules = await document.GetNamingRulesAsync(FallbackNamingRules.RefactoringMatchLookupRules, cancellationToken).ConfigureAwait(false); var parametersForSelectedMembers = service.DetermineParameters(selectedMembers, rules); if (!selectedMembers.All(IsWritableInstanceFieldOrProperty) || ContainingType == null || ContainingType.TypeKind == TypeKind.Interface || parametersForSelectedMembers.IsEmpty) { return(false); } ConstructorCandidates = await GetConstructorCandidatesInfoAsync( ContainingType, service, selectedMembers, document, parametersForSelectedMembers, cancellationToken).ConfigureAwait(false); return(!ConstructorCandidates.IsEmpty); }
private static TCompilation GetCompilationWithAnalyzerDiagnostics <TCompilation>( this TCompilation c, DiagnosticAnalyzer[] analyzers, AnalyzerOptions options, Action <Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException, bool reportSuppressedDiagnostics, bool includeCompilerDiagnostics, out ImmutableArray <Diagnostic> diagnostics) where TCompilation : Compilation { var analyzersArray = analyzers.ToImmutableArray(); if (reportSuppressedDiagnostics != c.Options.ReportSuppressedDiagnostics) { c = (TCompilation)c.WithOptions(c.Options.WithReportSuppressedDiagnostics(reportSuppressedDiagnostics)); } var analyzerManager = new AnalyzerManager(analyzersArray); var driver = AnalyzerDriver.CreateAndAttachToCompilation(c, analyzersArray, options, analyzerManager, onAnalyzerException, null, false, out var newCompilation, CancellationToken.None); var compilerDiagnostics = newCompilation.GetDiagnostics(); var analyzerDiagnostics = driver.GetDiagnosticsAsync(newCompilation).Result; var allDiagnostics = includeCompilerDiagnostics ? compilerDiagnostics.AddRange(analyzerDiagnostics) : analyzerDiagnostics; diagnostics = driver.ApplyProgrammaticSuppressions(allDiagnostics, newCompilation); if (!reportSuppressedDiagnostics) { Assert.True(diagnostics.All(d => !d.IsSuppressed)); } return((TCompilation)newCompilation); // note this is a new compilation }
private async Task <bool> TryInitializeAsync( Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray <ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return(false); } SelectedMembers = selectedMembers; ContainingType = containingType; TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return(false); } var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return(true); }
internal WithTypeArgumentsBinder(ImmutableArray<TypeSymbol> typeArguments, Binder next) : base(next) { Debug.Assert(!typeArguments.IsDefaultOrEmpty); Debug.Assert(typeArguments.All(ta => ta.Kind == SymbolKind.TypeParameter)); _typeArguments = typeArguments; }
private NodeStateTable(ImmutableArray <TableEntry> states, bool isCompacted) { Debug.Assert(!isCompacted || states.All(s => s.IsCached)); _states = states; IsCached = isCompacted; }
private async Task <bool> TryInitializeAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, Accessibility?desiredAccessibility, ImmutableArray <ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return(false); } SelectedMembers = selectedMembers; ContainingType = containingType; Accessibility = desiredAccessibility ?? (ContainingType.IsAbstractClass() ? Accessibility.Protected : Accessibility.Public); TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return(false); } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType); var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return(true); }
/// <inheritdoc/> public async Task <Solution> SyncNamespacesAsync( ImmutableArray <Project> projects, CodeActionOptionsProvider options, CancellationToken cancellationToken) { // all projects must be of the same language Debug.Assert(projects.All(project => project.Language == projects[0].Language)); var solution = projects[0].Solution; var diagnosticAnalyzers = ImmutableArray.Create <DiagnosticAnalyzer>(DiagnosticAnalyzer); var diagnosticsByProject = await GetDiagnosticsByProjectAsync(projects, diagnosticAnalyzers, cancellationToken).ConfigureAwait(false); // If no diagnostics are reported, then there is nothing to fix. if (diagnosticsByProject.Values.All(diagnostics => diagnostics.IsEmpty)) { return(solution); } var fixAllContext = await GetFixAllContextAsync(solution, CodeFixProvider, diagnosticsByProject, options, cancellationToken).ConfigureAwait(false); var fixAllProvider = CodeFixProvider.GetFixAllProvider(); RoslynDebug.AssertNotNull(fixAllProvider); return(await ApplyCodeFixAsync(fixAllProvider, fixAllContext, cancellationToken).ConfigureAwait(false)); }
internal NamedTypeSymbol Construct(ImmutableArray <TypeSymbol> arguments, bool unbound) { if (!ReferenceEquals(this, ConstructedFrom) || this.Arity == 0) { throw new InvalidOperationException(); } if (arguments.IsDefault) { throw new ArgumentNullException("typeArguments"); } if (arguments.Any(NamedTypeSymbol.TypeSymbolIsNullFunction)) { throw new ArgumentException(CSharpResources.TypeArgumentCannotBeNull, "typeArguments"); } if (arguments.Length != this.Arity) { throw new ArgumentException(CSharpResources.WrongNumberOfTypeArguments, "typeArguments"); } Debug.Assert(!unbound || arguments.All(NamedTypeSymbol.TypeSymbolIsErrorType)); if (ConstructedNamedTypeSymbol.TypeParametersMatchTypeArguments(this.TypeParameters, arguments)) { return(this); } return(this.ConstructCore(arguments, unbound)); }
private bool TryInitialize( GenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray <ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return(false); } this.SelectedMembers = selectedMembers; this.ContainingType = containingType; this.TextSpan = textSpan; if (this.ContainingType == null || this.ContainingType.TypeKind == TypeKind.Interface) { return(false); } this.Parameters = service.DetermineParameters(selectedMembers); this.MatchingConstructor = service.GetMatchingConstructor(this.ContainingType, this.Parameters); this.DelegatedConstructor = service.GetDelegatedConstructor(this.ContainingType, this.Parameters); return(true); }
public MethodOrInterfaceMethod(IMethod method, ImmutableArray <IType> typeArguments) : this() { _method = method; _typeArguments = typeArguments.All(x => x is ITypeParameter) ? typeArguments.Cast <ITypeParameter>().ToImmutableArray() : ImmutableArray <ITypeParameter> .Empty; }
private ImmutableArray <Symbol> BindIndexerMemberCref(IndexerMemberCrefSyntax syntax, NamespaceOrTypeSymbol containerOpt, out Symbol ambiguityWinner, DiagnosticBag diagnostics) { const int arity = 0; ImmutableArray <Symbol> sortedSymbols = ComputeSortedCrefMembers(syntax, containerOpt, WellKnownMemberNames.Indexer, arity, syntax.Parameters != null, diagnostics); if (sortedSymbols.IsEmpty) { ambiguityWinner = null; return(ImmutableArray <Symbol> .Empty); } // Since only indexers are named WellKnownMemberNames.Indexer. Debug.Assert(sortedSymbols.All(SymbolExtensions.IsIndexer)); // NOTE: guaranteed to be a property, because only indexers are considered. return(ProcessCrefMemberLookupResults( sortedSymbols, arity, syntax, typeArgumentListSyntax: null, parameterListSyntax: syntax.Parameters, ambiguityWinner: out ambiguityWinner, diagnostics: diagnostics)); }
public FileSystemCompletionHelper( CompletionProvider 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>())); }
/// <summary> Concatenates the specified <paramref name="expressions" /> as strings. The expressions don't have to be of type string. </summary> public static Expression String_Concat(ImmutableArray <Expression> expressions) { expressions = Concat_MergeFollowingConstants(expressions); var allString = expressions.All(e => e.Type() == TypeSignature.String); if (expressions.Length == 0) { return(Expression.Constant("")); } if (expressions.Length == 1 && expressions[0] is Expression.ConstantCase ce) { // string concat replaces nulls with empty strings, which is a big difference from object.ToString return(Expression.Constant("" + ce.Item.Value)); } if (expressions.Length == 1) { expressions = expressions.Add(Expression.Constant("")); } if (allString) { return(String_Concat_Strings(expressions)); } else { return(String_Concat_Objects( expressions.EagerSelect(FluentExpression.Box) )); } }
/// <summary> /// Returns true if all type parameter references within the given /// types belong to containingSymbol or its containing types. /// </summary> public static bool IsContainingSymbolOfAllTypeParameters( this Symbol containingSymbol, ImmutableArray <TypeSymbol> types ) { return(types.All(containingSymbol.IsContainingSymbolOfAllTypeParameters)); }
private bool TryInitialize( GenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray <ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return(false); } this.SelectedMembers = selectedMembers; this.ContainingType = containingType; this.TextSpan = textSpan; if (this.ContainingType == null || this.ContainingType.TypeKind == TypeKind.Interface) { return(false); } this.Parameters = service.DetermineParameters(selectedMembers); this.MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(this.ContainingType, this.Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. this.DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(this.ContainingType, this.Parameters); return(true); }
internal WithTypeArgumentsBinder(ImmutableArray <TypeSymbol> typeArguments, Binder next) : base(next) { Debug.Assert(!typeArguments.IsDefaultOrEmpty); Debug.Assert(typeArguments.All(ta => ta.Kind == SymbolKind.TypeParameter)); _typeArguments = typeArguments; }
private bool IsNonLocalizableMessageType(ITypeSymbol messageType) { Cancellation.ThrowIfCancellationRequested(); ImmutableArray <AttributeData> attributes = messageType.GetAttributes(); return(attributes.All(a => !a.AttributeClass.Equals(Localization.PXLocalizableAttribute))); }
/// <summary> /// Initializes a new instance of the <see cref="RelativePathResolver"/> class. /// </summary> /// <param name="searchPaths">An ordered set of fully qualified /// paths which are searched when resolving assembly names.</param> /// <param name="baseDirectory">Directory used when resolving relative paths.</param> public RelativePathResolver(ImmutableArray <string> searchPaths, string baseDirectory) { Debug.Assert(searchPaths.All(PathUtilities.IsAbsolute)); Debug.Assert(baseDirectory == null || PathUtilities.GetPathKind(baseDirectory) == PathKind.Absolute); SearchPaths = searchPaths; BaseDirectory = baseDirectory; }
public bool CacheNames(ImmutableArray <MetadataReferenceInfo> references) { if (references.All(r => _cache.ContainsKey(r.Mvid))) { // All references have already been cached, no reason to look in the file system return(true); } foreach (var directory in _indexDirectories) { foreach (var file in directory.GetFiles("*.*", SearchOption.AllDirectories)) { // A single file name can have multiple MVID, so compare by name first then // open the files to check the MVID foreach (var reference in references) { if (reference.FileInfo.Name != file.Name) { continue; } if (GetMvidForFile(file) is not { } mvid) { _logger.LogWarning($@"Could not read MVID from ""{file.FullName}"""); continue; } if (_cache.ContainsKey(mvid)) { continue; } if (mvid != reference.Mvid) { continue; } _logger.LogTrace($"Caching [{mvid}, {file.FullName}]"); _cache[mvid] = file.FullName; } } } var uncached = references.Where(m => !_cache.ContainsKey(m.Mvid)).ToArray(); if (uncached.Any()) { using var _ = _logger.BeginScope($"Missing {uncached.Length} metadata references:"); foreach (var missingReference in uncached) { _logger.LogError($@"{missingReference.Name} - {missingReference.Mvid}"); } return(false); } return(true); }
static void AddDiagnosticsToResult( ImmutableArray <Diagnostic> diagnostics, ref DiagnosticAnalysisResultBuilder result, Compilation compilation, SyntaxTree?tree, DocumentId?additionalDocumentId, TextSpan?span, AnalysisKind kind, ImmutableArray <string> diagnosticIdsToFilter, bool includeSuppressedDiagnostics) { if (diagnostics.IsEmpty) { return; } diagnostics = diagnostics.Filter(diagnosticIdsToFilter, includeSuppressedDiagnostics, span); Debug.Assert(diagnostics.Length == CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).Count()); switch (kind) { case AnalysisKind.Syntax: if (tree != null) { Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree)); result.AddSyntaxDiagnostics(tree !, diagnostics); } else { RoslynDebug.Assert(additionalDocumentId != null); result.AddExternalSyntaxDiagnostics(additionalDocumentId, diagnostics); } break; case AnalysisKind.Semantic: Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree)); result.AddSemanticDiagnostics(tree !, diagnostics); break; default: result.AddCompilationDiagnostics(diagnostics); break; } }
public ReplaceZeroFix(ImmutableArray <int> replacements, bool nested) { Debug.Assert( replacements.All(replacement => replacement >= 0), $"Assertion failed: {nameof(replacements)}.All(replacement => replacement >= 0)" ); _replacements = replacements; _nested = nested; }
private static void AnalyzeSymbol(SymbolAnalysisContext context, ImmutableArray <KeyValuePair <INamedTypeSymbol, INamedTypeSymbol> > interfacePairs) { Debug.Assert(interfacePairs.All(kvp => kvp.Key.TypeKind == TypeKind.Interface && kvp.Value.TypeKind == TypeKind.Interface)); var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // FxCop compat: only fire on externally visible types by default. if (!context.Options.MatchesConfiguredVisibility(Rule, namedTypeSymbol, context.Compilation, context.CancellationToken)) { return; } using var allInterfaces = PooledHashSet <INamedTypeSymbol> .GetInstance(); foreach (var @interface in namedTypeSymbol.AllInterfaces.Select(i => i.OriginalDefinition)) { allInterfaces.Add(@interface); } // First we need to try to match all types from the user definition... var userMap = context.Options.GetAdditionalRequiredGenericInterfaces(Rule, context.Symbol, context.Compilation, context.CancellationToken); if (!userMap.IsEmpty) { foreach (var @interface in allInterfaces) { if ([email protected] && userMap.TryGetValue(@interface, out var genericInterface) && genericInterface?.IsGenericType == true) { ReportDiagnostic(@interface, genericInterface); return; } } } // ...Then we can proceed with the hardcoded ones keeping the declaration order for (int i = 0; i < interfacePairs.Length; i++) { var kvp = interfacePairs[i]; if (allInterfaces.Contains(kvp.Key) && !allInterfaces.Contains(kvp.Value)) { ReportDiagnostic(kvp.Key, kvp.Value); return; } } return; void ReportDiagnostic(INamedTypeSymbol @interface, INamedTypeSymbol genericInterface) { context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(Rule, namedTypeSymbol.Name, @interface.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), genericInterface.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat))); } }
public InvalidOperation(ImmutableArray <IOperation> children, SemanticModel?semanticModel, SyntaxNode syntax, ITypeSymbol?type, ConstantValue?constantValue, bool isImplicit) : base(semanticModel, syntax, isImplicit) { // we don't allow null children. Debug.Assert(children.All(o => o != null)); Children = SetParentOperation(children, this); Type = type; OperationConstantValue = constantValue; }
private static void AssertItemsEqual(ImmutableArray <CompletionItem> actual, params string[] expected) { AssertEx.Equal( expected, actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.Properties["Description"]}'"), itemInspector: c => $"@\"{c}\""); Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules)); }
public LoadDirective(string resolvedPath, ImmutableArray <Diagnostic> diagnostics) { Debug.Assert((resolvedPath != null) || !diagnostics.IsEmpty); Debug.Assert(!diagnostics.IsDefault); Debug.Assert(diagnostics.IsEmpty || diagnostics.All(d => d.Severity == DiagnosticSeverity.Error)); ResolvedPath = resolvedPath; Diagnostics = diagnostics; }
private static (bool gameEnded, Option <string> winner) CheckEndGame(ImmutableArray <Cell> cells) { // Check rows var rowsGroups = cells.GroupBy(c => c.Row); foreach (var rowsGroup in rowsGroups) { if (HasPlayerWon(rowsGroup)) { return(true, "You"); } if (HasBotWon(rowsGroup)) { return(true, "Bot"); } } // Check columns var columnsGroups = cells.GroupBy(c => c.Column); foreach (var columnsGroup in columnsGroups) { if (HasPlayerWon(columnsGroup)) { return(true, "You"); } if (HasBotWon(columnsGroup)) { return(true, "Bot"); } } // Check diagonals var diagonalOne = cells.Where(c => c.Row == c.Column); if (HasPlayerWon(diagonalOne)) { return(true, "You"); } if (HasBotWon(diagonalOne)) { return(true, "Bot"); } var diagonalTwo = cells.Where(c => (2 - c.Row) == c.Column); if (HasPlayerWon(diagonalTwo)) { return(true, "You"); } if (HasBotWon(diagonalTwo)) { return(true, "Bot"); } return(cells.All(c => c.Mine.HasValue), Option <string> .None()); }
internal DeclarationInfo(SyntaxNode declaredNode, ImmutableArray<SyntaxNode> executableCodeBlocks, ISymbol declaredSymbol) { Debug.Assert(declaredNode != null); Debug.Assert(!executableCodeBlocks.IsDefault); Debug.Assert(executableCodeBlocks.All(n => n.Ancestors().Contains(declaredNode))); this.declaredNode = declaredNode; this.executableCodeBlocks = executableCodeBlocks; this.declaredSymbol = declaredSymbol; }
public CompositeText(ImmutableArray<SourceText> texts) { Debug.Assert(!texts.IsDefaultOrEmpty); Debug.Assert(texts.All(t => texts.First().Encoding == t.Encoding)); this.texts = texts; int len = 0; foreach (var text in texts) { len += text.Length; } this.length = len; }
internal static void ValidateSearchPaths(ImmutableArray<string> paths, string argName) { if (paths.IsDefault) { throw ExceptionUtilities.Unreachable; ////throw new ArgumentNullException(argName); } if (!paths.All(PathUtilities.IsAbsolute)) { throw ExceptionUtilities.Unreachable; ////throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, argName); } }
public CompositeText(ImmutableArray<SourceText> texts) : base(checksumAlgorithm: texts[0].ChecksumAlgorithm) { Debug.Assert(!texts.IsDefaultOrEmpty); Debug.Assert(texts.All(t => texts.First().Encoding == t.Encoding && texts.First().ChecksumAlgorithm == t.ChecksumAlgorithm)); _texts = texts; int len = 0; foreach (var text in texts) { len += text.Length; } _length = len; }
internal State( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableDictionary<SyntaxTree, int> syntaxTreeOrdinalMap, ImmutableDictionary<SyntaxTree, ImmutableArray<LoadDirective>> loadDirectiveMap, ImmutableDictionary<string, SyntaxTree> loadedSyntaxTreeMap, ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces, DeclarationTable declarationTable) { Debug.Assert(syntaxTrees.All(tree => syntaxTrees[syntaxTreeOrdinalMap[tree]] == tree)); Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer<SyntaxTree>.Default)); this.SyntaxTrees = syntaxTrees; this.OrdinalMap = syntaxTreeOrdinalMap; this.LoadDirectiveMap = loadDirectiveMap; this.LoadedSyntaxTreeMap = loadedSyntaxTreeMap; this.RootNamespaces = rootNamespaces; this.DeclarationTable = declarationTable; }
internal static ImmutableArray<ParameterSymbol> CopyParameterCustomModifiers(ImmutableArray<ParameterSymbol> sourceParameters, ImmutableArray<ParameterSymbol> destinationParameters, bool alsoCopyParamsModifier) { Debug.Assert(!destinationParameters.IsDefault); Debug.Assert(destinationParameters.All(p => p is SourceParameterSymbolBase)); Debug.Assert(sourceParameters.Length == destinationParameters.Length); // Nearly all of the time, there will be no custom modifiers to copy, so don't // allocate the builder until we know that we need it. ArrayBuilder<ParameterSymbol> builder = null; int numParams = destinationParameters.Length; for (int i = 0; i < numParams; i++) { SourceParameterSymbolBase destinationParameter = (SourceParameterSymbolBase)destinationParameters[i]; ParameterSymbol sourceParameter = sourceParameters[i]; if (sourceParameter.CustomModifiers.Any() || sourceParameter.Type.HasCustomModifiers() || destinationParameter.CustomModifiers.Any() || destinationParameter.Type.HasCustomModifiers() || // Could happen if the associated property has custom modifiers. (alsoCopyParamsModifier && (sourceParameter.IsParams != destinationParameter.IsParams))) { if (builder == null) { builder = ArrayBuilder<ParameterSymbol>.GetInstance(); builder.AddRange(destinationParameters, i); //add up to, but not including, the current parameter } bool newParams = alsoCopyParamsModifier ? sourceParameter.IsParams : destinationParameter.IsParams; builder.Add(destinationParameter.WithCustomModifiersAndParams(sourceParameter.Type, sourceParameter.CustomModifiers, destinationParameter.RefKind != RefKind.None ? sourceParameter.CountOfCustomModifiersPrecedingByRef : (ushort)0, newParams)); } else if (builder != null) { builder.Add(destinationParameter); } } return builder == null ? destinationParameters : builder.ToImmutableAndFree(); }
private CSharpCompilation( string assemblyName, CSharpCompilationOptions options, ImmutableArray<MetadataReference> references, ImmutableArray<SyntaxTree> syntaxTrees, ImmutableDictionary<SyntaxTree, int> syntaxTreeOrdinalMap, ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces, DeclarationTable declarationTable, CSharpCompilation previousSubmission, Type submissionReturnType, Type hostObjectType, bool isSubmission, ReferenceManager referenceManager, bool reuseReferenceManager, AsyncQueue<CompilationEvent> eventQueue = null) : base(assemblyName, references, submissionReturnType, hostObjectType, isSubmission, syntaxTreeOrdinalMap, eventQueue) { using (Logger.LogBlock(FunctionId.CSharp_Compilation_Create, message: assemblyName)) { this.wellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this); this.options = options; this.syntaxTrees = syntaxTrees; this.rootNamespaces = rootNamespaces; this.declarationTable = declarationTable; Debug.Assert(syntaxTrees.All(tree => syntaxTrees[syntaxTreeOrdinalMap[tree]] == tree)); Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer<SyntaxTree>.Default)); this.builtInOperators = new BuiltInOperators(this); this.scriptClass = new Lazy<ImplicitNamedTypeSymbol>(BindScriptClass); this.globalImports = new Lazy<Imports>(BindGlobalUsings); this.globalNamespaceAlias = new Lazy<AliasSymbol>(CreateGlobalNamespaceAlias); this.anonymousTypeManager = new AnonymousTypeManager(this); if (isSubmission) { Debug.Assert(previousSubmission == null || previousSubmission.HostObjectType == hostObjectType); this.previousSubmission = previousSubmission; } else { Debug.Assert(previousSubmission == null && submissionReturnType == null && hostObjectType == null); } if (reuseReferenceManager) { referenceManager.AssertCanReuseForCompilation(this); this.referenceManager = referenceManager; } else { this.referenceManager = new ReferenceManager( MakeSourceAssemblySimpleName(), options.AssemblyIdentityComparer, (referenceManager != null) ? referenceManager.ObservedMetadata : null); } Debug.Assert((object)this.lazyAssemblySymbol == null); if (EventQueue != null) EventQueue.Enqueue(new CompilationStartedEvent(this)); } }
private static CompletionItem CreateSymbolCompletionGroup(string name, ImmutableArray<Symbol> symbols) { var multiple = symbols.Skip(1).Any(); if (!multiple) return CreateSymbolCompletion(symbols.First()); var hasNonInvocables = symbols.Any(s => !(s is InvocableSymbol)); if (!hasNonInvocables) return CreateInvocableCompletionGroup(symbols); if (symbols.All(s => (s is TypeSymbol && ((TypeSymbol) s).IsIntrinsicNumericType()) || (s is FunctionSymbol && ((FunctionSymbol) s).IsNumericConstructor))) return CreateSymbolCompletion(symbols.First(s => s is TypeSymbol)); var displayText = name; var insertionText = name; var sb = new StringBuilder(); sb.Append(Resources.AmbiguousName); foreach (var symbol in symbols) { sb.AppendLine(); sb.Append(@" "); sb.Append(symbol); } var description = sb.ToString(); return new CompletionItem(displayText, insertionText, description, Glyph.CompletionWarning); }
internal EEMethodSymbol( EENamedTypeSymbol container, string name, Location location, MethodSymbol sourceMethod, ImmutableArray<LocalSymbol> sourceLocals, ImmutableArray<LocalSymbol> sourceLocalsForBinding, ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables, GenerateMethodBody generateMethodBody) { Debug.Assert(sourceMethod.IsDefinition); Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition); Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod)); _container = container; _name = name; _locations = ImmutableArray.Create(location); // What we want is to map all original type parameters to the corresponding new type parameters // (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: // 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. // 2) The map cannot be constructed until all new type parameters exist. // Our solution is to pass each new type parameter a lazy reference to the type map. We then // initialize the map as soon as the new type parameters are available - and before they are // handed out - so that there is never a period where they can require the type map and find // it uninitialized. var sourceMethodTypeParameters = sourceMethod.TypeParameters; var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters); var getTypeMap = new Func<TypeMap>(() => this.TypeMap); _typeParameters = sourceMethodTypeParameters.SelectAsArray( (tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap), (object)null); _allTypeParameters = container.TypeParameters.Concat(_typeParameters); this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters); EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters); var substitutedSourceType = container.SubstitutedSourceType; this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType); if (sourceMethod.Arity > 0) { this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>()); } TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters); // Create a map from original parameter to target parameter. var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(); var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter; var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null; if (substitutedSourceHasThisParameter) { _thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter); Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType); parameterBuilder.Add(_thisParameter); } var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0); foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters) { var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset; Debug.Assert(ordinal == parameterBuilder.Count); var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter); parameterBuilder.Add(parameter); } _parameters = parameterBuilder.ToImmutableAndFree(); var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocals) { var local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); localsBuilder.Add(local); } this.Locals = localsBuilder.ToImmutableAndFree(); localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocalsForBinding) { LocalSymbol local; if (!localsMap.TryGetValue(sourceLocal, out local)) { local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); } localsBuilder.Add(local); } this.LocalsForBinding = localsBuilder.ToImmutableAndFree(); // Create a map from variable name to display class field. var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var pair in sourceDisplayClassVariables) { var variable = pair.Value; var displayClassInstanceFromLocal = variable.DisplayClassInstance as DisplayClassInstanceFromLocal; var displayClassInstance = (displayClassInstanceFromLocal == null) ? (DisplayClassInstance)new DisplayClassInstanceFromThis(_parameters[0]) : new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[displayClassInstanceFromLocal.Local]); variable = variable.SubstituteFields(displayClassInstance, this.TypeMap); displayClassVariables.Add(pair.Key, variable); } _displayClassVariables = displayClassVariables.ToImmutableDictionary(); displayClassVariables.Free(); localsMap.Free(); _generateMethodBody = generateMethodBody; }
/// <summary> /// Check if it is a regular collection of expressions or there are nested initializers. /// </summary> private static bool IsMultidimensionalInitializer(ImmutableArray<BoundExpression> inits) { Debug.Assert(inits.All((init) => init.Kind != BoundKind.ArrayInitialization) || inits.All((init) => init.Kind == BoundKind.ArrayInitialization), "all or none should be nested"); return inits.Length != 0 && inits[0].Kind == BoundKind.ArrayInitialization; }
public static void ProcessIncludes( string unprocessed, Symbol memberSymbol, ImmutableArray<CSharpSyntaxNode> sourceIncludeElementNodes, CSharpCompilation compilation, ref HashSet<ParameterSymbol> documentedParameters, ref HashSet<TypeParameterSymbol> documentedTypeParameters, ref DocumentationCommentIncludeCache includedFileCache, TextWriter writer, DiagnosticBag diagnostics, CancellationToken cancellationToken) { // If there are no include elements, then there's nothing to expand. // NOTE: By skipping parsing and re-writing, we avoid slightly // modifying the whitespace, as we would if we let the XmlWriter // do the writing. This saves us a lot of work in the common case // but slightly reduces consistency when include elements are // present. if (sourceIncludeElementNodes.IsEmpty) { if (writer != null) { writer.Write(unprocessed); } return; } XDocument doc; try { // NOTE: XDocument.Parse seems to do a better job of preserving whitespace // than XElement.Parse. doc = XDocument.Parse(unprocessed, LoadOptions.PreserveWhitespace); } catch (XmlException e) { // If one of the trees wasn't diagnosing doc comments, then an error might have slipped through. // Otherwise, we shouldn't see exceptions from XDocument.Parse. Debug.Assert(sourceIncludeElementNodes.All(syntax => syntax.SyntaxTree.Options.DocumentationMode < DocumentationMode.Diagnose), "Why didn't our parser catch this exception? " + e); if (writer != null) { writer.Write(unprocessed); } return; } cancellationToken.ThrowIfCancellationRequested(); IncludeElementExpander expander = new IncludeElementExpander( memberSymbol, sourceIncludeElementNodes, compilation, documentedParameters, documentedTypeParameters, includedFileCache, diagnostics, cancellationToken); foreach (XNode node in expander.Rewrite(doc, currentXmlFilePath: null, originatingSyntax: null)) { cancellationToken.ThrowIfCancellationRequested(); if (writer != null) { writer.Write(node); } } Debug.Assert(expander.nextSourceIncludeElementIndex == expander.sourceIncludeElementNodes.Length); documentedParameters = expander.documentedParameters; documentedTypeParameters = expander.documentedTypeParameters; includedFileCache = expander.includedFileCache; }
private BoundExpression RewriteStringConcatenationManyExprs(CSharpSyntaxNode syntax, ImmutableArray<BoundExpression> loweredArgs) { Debug.Assert(loweredArgs.Length > 3); Debug.Assert(loweredArgs.All(a => a.Type.SpecialType == SpecialType.System_Object || a.Type.SpecialType == SpecialType.System_String)); bool isObject = false; TypeSymbol elementType = null; foreach (var arg in loweredArgs) { elementType = arg.Type; if (elementType.SpecialType != SpecialType.System_String) { isObject = true; break; } } // Count == 4 is handled differently because there is a Concat method with 4 arguments // for strings, but there is no such method for objects. if (!isObject && loweredArgs.Length == 4) { SpecialMember member = SpecialMember.System_String__ConcatStringStringStringString; var method = GetSpecialTypeMethod(syntax, member); Debug.Assert((object)method != null); return (BoundExpression)BoundCall.Synthesized(syntax, null, method, loweredArgs); } else { SpecialMember member = isObject ? SpecialMember.System_String__ConcatObjectArray : SpecialMember.System_String__ConcatStringArray; var method = GetSpecialTypeMethod(syntax, member); Debug.Assert((object)method != null); var array = _factory.Array(elementType, loweredArgs); return (BoundExpression)BoundCall.Synthesized(syntax, null, method, array); } }
private static SymbolInfo GetCrefSymbolInfo(ImmutableArray<Symbol> symbols, SymbolInfoOptions options, bool hasParameterList) { switch (symbols.Length) { case 0: return SymbolInfo.None; case 1: // Might have to expand an ExtendedErrorTypeSymbol into multiple candidates. return GetSymbolInfoForSymbol(symbols[0], options); default: if ((options & SymbolInfoOptions.ResolveAliases) == SymbolInfoOptions.ResolveAliases) { symbols = UnwrapAliases(symbols); } LookupResultKind resultKind = LookupResultKind.Ambiguous; // The boundary between Ambiguous and OverloadResolutionFailure is let clear-cut for crefs. // We'll say that overload resolution failed if the syntax has a parameter list and if // all of the candidates have the same kind. SymbolKind firstCandidateKind = symbols[0].Kind; if (hasParameterList && symbols.All(s => s.Kind == firstCandidateKind)) { resultKind = LookupResultKind.OverloadResolutionFailure; } return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false); } }