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);
        }
Exemplo n.º 2
1
        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);
        }
 public PathSyntaxReference(SyntaxNode node)
 {
     _tree = node.SyntaxTree;
     _kind = node.Kind();
     _textSpan = node.Span;
     _pathFromRoot = ComputePathFromRoot(node);
 }
Exemplo n.º 4
0
        public static PatternSearch Create(string text, ImmutableArray<PatternVariable> variables)
        {
            if (text == null)
                throw new ArgumentNullException(nameof(text));

            return new PatternSearch(text, variables);
        }
        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;
        }
        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,
            };
        }
        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;
        }
Exemplo n.º 8
0
 public static BracketedParameterListSyntax GenerateBracketedParameterList(
     ImmutableArray<IParameterSymbol> parameterDefinitions,
     bool isExplicit,
     CodeGenerationOptions options)
 {
     return GenerateBracketedParameterList((IList<IParameterSymbol>)parameterDefinitions, isExplicit, options);
 }
        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);
        }
Exemplo n.º 10
0
        public ProjectFileReference(string path, ImmutableArray<string> aliases)
        {
            Debug.Assert(!aliases.IsDefault);

            this.Path = path;
            this.Aliases = aliases;
        }
            public ReferencedAssembly(TAssemblySymbol symbol, ImmutableArray<string> aliases)
            {
                Debug.Assert(symbol != null && !aliases.IsDefault);

                this.Symbol = symbol;
                this.Aliases = aliases;
            }
Exemplo n.º 12
0
        public static Block Create(BlockHeader header, ImmutableArray<DecodedTx> transactions)
        {
            var blockTxes = ImmutableArray.CreateRange(transactions.Select((tx, txIndex) =>
                new BlockTx(txIndex, tx)));

            return new Block(header, blockTxes);
        }
Exemplo n.º 13
0
        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;
        }
        public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker)
        {
            this.AssertIsForeground();

            imageMoniker = GetImageMoniker(tags);
            return !imageMoniker.IsNullImage();
        }
Exemplo n.º 15
0
        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>()));
        }
            public override async Task AddDocumentFixesAsync(Document document, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction> addFix, FixAllContext fixAllContext)
            {
                var pragmaActionsBuilder = ImmutableArray.CreateBuilder<IPragmaBasedCodeAction>();
                var pragmaDiagnosticsBuilder = ImmutableArray.CreateBuilder<Diagnostic>();

                foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && !d.IsSuppressed))
                {
                    var span = diagnostic.Location.SourceSpan;
                    var pragmaSuppressions = await _suppressionFixProvider.GetPragmaSuppressionsAsync(document, span, SpecializedCollections.SingletonEnumerable(diagnostic), fixAllContext.CancellationToken).ConfigureAwait(false);
                    var pragmaSuppression = pragmaSuppressions.SingleOrDefault();
                    if (pragmaSuppression != null)
                    {
                        if (fixAllContext is FixMultipleContext)
                        {
                            pragmaSuppression = pragmaSuppression.CloneForFixMultipleContext();
                        }

                        pragmaActionsBuilder.Add(pragmaSuppression);
                        pragmaDiagnosticsBuilder.Add(diagnostic);
                    }
                }

                // Get the pragma batch fix.
                if (pragmaActionsBuilder.Count > 0)
                {
                    var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix(_suppressionFixProvider, document,
                        pragmaActionsBuilder.ToImmutable(), pragmaDiagnosticsBuilder.ToImmutable(), fixAllContext);

                    addFix(pragmaBatchFix);
                }
            }
        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);
                }
            }
        }
Exemplo n.º 18
0
        private TypeMap WithAlphaRename(ImmutableArray<TypeParameterSymbol> oldTypeParameters, Symbol newOwner, out ImmutableArray<TypeParameterSymbol> newTypeParameters)
        {
            if (oldTypeParameters.Length == 0)
            {
                newTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
                return this;
            }

            // Note: the below assertion doesn't hold while rewriting async lambdas defined inside generic methods.
            // The async rewriter adds a synthesized struct inside the lambda frame and construct a typemap from
            // the lambda frame's substituted type parameters.
            // Debug.Assert(!oldTypeParameters.Any(tp => tp is SubstitutedTypeParameterSymbol));

            // warning: we expose result to the SubstitutedTypeParameterSymbol constructor, below, even before it's all filled in.
            TypeMap result = new TypeMap(this.Mapping);
            ArrayBuilder<TypeParameterSymbol> newTypeParametersBuilder = ArrayBuilder<TypeParameterSymbol>.GetInstance();

            // The case where it is "synthesized" is when we're creating type parameters for a synthesized (generic)
            // class or method for a lambda appearing in a generic method.
            bool synthesized = !ReferenceEquals(oldTypeParameters[0].ContainingSymbol.OriginalDefinition, newOwner.OriginalDefinition);

            foreach (var tp in oldTypeParameters)
            {
                var newTp = synthesized ?
                    new SynthesizedSubstitutedTypeParameterSymbol(newOwner, result, tp) :
                    new SubstitutedTypeParameterSymbol(newOwner, result, tp);
                result.Mapping.Add(tp, new TypeWithModifiers(newTp));
                newTypeParametersBuilder.Add(newTp);
            }

            newTypeParameters = newTypeParametersBuilder.ToImmutableAndFree();
            return result;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Determine the effective base type, effective interface set, and set of type
        /// parameters (excluding cycles) from the type parameter constraints. Conflicts
        /// within the constraints and constraint types are returned as diagnostics.
        /// 'inherited' should be true if the type parameters are from an overridden
        /// generic method. In those cases, additional constraint checks are applied.
        /// </summary>
        public static TypeParameterBounds ResolveBounds(
            this TypeParameterSymbol typeParameter,
            AssemblySymbol corLibrary,
            ConsList<TypeParameterSymbol> inProgress,
            ImmutableArray<TypeSymbol> constraintTypes,
            bool inherited,
            CSharpCompilation currentCompilation,
            DiagnosticBag diagnostics)
        {
            var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance();
            ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null;
            var bounds = typeParameter.ResolveBounds(corLibrary, inProgress, constraintTypes, inherited, currentCompilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder);

            if (useSiteDiagnosticsBuilder != null)
            {
                diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder);
            }

            foreach (var pair in diagnosticsBuilder)
            {
                diagnostics.Add(new CSDiagnostic(pair.DiagnosticInfo, pair.TypeParameter.Locations[0]));
            }

            diagnosticsBuilder.Free();
            return bounds;
        }
Exemplo n.º 20
0
 public AddressPayload With(ImmutableArray<NetworkAddressWithTime>? NetworkAddresses = null)
 {
     return new AddressPayload
     (
         NetworkAddresses ?? this.NetworkAddresses
     );
 }
        internal SourceAttributeData(
            SyntaxReference applicationNode,
            NamedTypeSymbol attributeClass,
            MethodSymbol attributeConstructor,
            ImmutableArray<TypedConstant> constructorArguments,
            ImmutableArray<int> constructorArgumentsSourceIndices,
            ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments,
            bool hasErrors,
            bool isConditionallyOmitted)
        {
            Debug.Assert(!isConditionallyOmitted || (object)attributeClass != null && attributeClass.IsConditional);
            Debug.Assert(!constructorArguments.IsDefault);
            Debug.Assert(!namedArguments.IsDefault);
            Debug.Assert(constructorArgumentsSourceIndices.IsDefault ||
                constructorArgumentsSourceIndices.Any() && constructorArgumentsSourceIndices.Length == constructorArguments.Length);

            this.attributeClass = attributeClass;
            this.attributeConstructor = attributeConstructor;
            this.constructorArguments = constructorArguments;
            this.constructorArgumentsSourceIndices = constructorArgumentsSourceIndices;
            this.namedArguments = namedArguments;
            this.isConditionallyOmitted = isConditionallyOmitted;
            this.hasErrors = hasErrors;
            this.applicationNode = applicationNode;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Create a context for evaluating expressions at a type scope.
        /// </summary>
        /// <param name="previous">Previous context, if any, for possible re-use.</param>
        /// <param name="metadataBlocks">Module metadata</param>
        /// <param name="moduleVersionId">Module containing type</param>
        /// <param name="typeToken">Type metadata token</param>
        /// <returns>Evaluation context</returns>
        /// <remarks>
        /// No locals since locals are associated with methods, not types.
        /// </remarks>
        internal static EvaluationContext CreateTypeContext(
            CSharpMetadataContext previous,
            ImmutableArray<MetadataBlock> metadataBlocks,
            Guid moduleVersionId,
            int typeToken)
        {
            Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition);

            // Re-use the previous compilation if possible.
            var compilation = metadataBlocks.HaveNotChanged(previous) ?
                previous.Compilation :
                metadataBlocks.ToCompilation();

            MetadataDecoder metadataDecoder;
            var currentType = compilation.GetType(moduleVersionId, typeToken, out metadataDecoder);
            Debug.Assert((object)currentType != null);
            Debug.Assert(metadataDecoder != null);
            var currentFrame = new SynthesizedContextMethodSymbol(currentType);
            return new EvaluationContext(
                metadataBlocks,
                null,
                compilation,
                metadataDecoder,
                currentFrame,
                default(ImmutableArray<LocalSymbol>),
                ImmutableSortedSet<int>.Empty,
                default(ImmutableArray<ImmutableArray<string>>),
                default(ImmutableArray<string>));
        }
Exemplo n.º 23
0
        public NetworkAddressKey(ImmutableArray<byte> IPv6Address, UInt16 Port)
        {
            this.IPv6Address = IPv6Address;
            this.Port = Port;

            this._hashCode = Port.GetHashCode() ^ new BigInteger(IPv6Address.ToArray()).GetHashCode();
        }
        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;
        }
Exemplo n.º 25
0
        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);
                    }
                }
            }
        }
        /// <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();
        }
Exemplo n.º 27
0
        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;
        }
Exemplo n.º 28
0
        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);
        }
Exemplo n.º 29
0
		public void AllAttributed( ImmutableArray<Type> types )
		{
			Assert.Equal( 2, types.Length );
			var names = types.Select( type => type.FullName ).ToArray();
			Assert.Contains( "DragonSpark.Testing.Parts.PublicClass", names );
			Assert.Contains( "DragonSpark.Testing.Parts.NonPublicClass", names );
		}
        public SynthesizedIntrinsicOperatorSymbol(TypeSymbol leftType, string name, TypeSymbol rightType, TypeSymbol returnType, bool isCheckedBuiltin)
        {
            if (leftType.Equals(rightType, ignoreCustomModifiers: true))
            {
                this.containingType = leftType;
            }
            else if (rightType.Equals(returnType, ignoreCustomModifiers: true))
            {
                this.containingType = rightType;
            }
            else
            {
                Debug.Assert(leftType.Equals(returnType, ignoreCustomModifiers: true));
                this.containingType = leftType;
            }

            this.name = name;
            this.returnType = returnType;

            Debug.Assert((leftType.IsDynamic() || rightType.IsDynamic()) == returnType.IsDynamic());
            Debug.Assert(containingType.IsDynamic() == returnType.IsDynamic());

            this.parameters = (new ParameterSymbol[] {new SynthesizedOperatorParameterSymbol(this, leftType, 0, "left"),
                                                      new SynthesizedOperatorParameterSymbol(this, rightType, 1, "right")}).AsImmutableOrNull();
            this.isCheckedBuiltin = isCheckedBuiltin;
        }
Exemplo n.º 31
0
 protected sealed override ImmutableArray <CodeAction> MassageActions(ImmutableArray <CodeAction> actions)
 => FlattenActions(actions);
 public override void RegisterSyntaxNodeAction <TLanguageKindEnum>(Action <SyntaxNodeAnalysisContext> action, ImmutableArray <TLanguageKindEnum> syntaxKinds)
 {
 }
 private void RaiseDocumentDiagnosticsIfNeeded(
     TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray <DiagnosticData> oldItems, ImmutableArray <DiagnosticData> newItems)
 {
     RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, AnalyzerService.RaiseDiagnosticsUpdated, forceUpdate: false);
 }
 private void RaiseDocumentDiagnosticsIfNeeded(TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray <DiagnosticData> items)
 => RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, ImmutableArray <DiagnosticData> .Empty, items);
Exemplo n.º 35
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddTypeArgument))
            {
                return;
            }

            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            TypeSyntax type = root
                              .FindNode(context.Span, getInnermostNodeForTie: true)?
                              .FirstAncestorOrSelf <TypeSyntax>();

            Debug.Assert(type != null, $"{nameof(type)} is null");

            if (type == null)
            {
                return;
            }

            if (!type.IsKind(SyntaxKind.IdentifierName))
            {
                return;
            }

            foreach (Diagnostic diagnostic in context.Diagnostics)
            {
                switch (diagnostic.Id)
                {
                case CompilerDiagnosticIdentifiers.UsingGenericTypeRequiresTypeArguments:
                {
                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(type, context.CancellationToken);

                    foreach (ISymbol symbol in symbolInfo.CandidateSymbols)
                    {
                        var namedTypeSymbol = symbol as INamedTypeSymbol;

                        if (namedTypeSymbol != null)
                        {
                            ImmutableArray <ITypeParameterSymbol> typeParameters = namedTypeSymbol.TypeParameters;

                            if (typeParameters.Any())
                            {
                                CodeAction codeAction = CodeAction.Create(
                                    GetTitle(typeParameters),
                                    cancellationToken =>
                                    {
                                        SeparatedSyntaxList <TypeSyntax> typeArguments = CreateTypeArguments(typeParameters, type.SpanStart, semanticModel).ToSeparatedSyntaxList();

                                        var identifierName = (IdentifierNameSyntax)type;

                                        GenericNameSyntax newNode = SyntaxFactory.GenericName(identifierName.Identifier, SyntaxFactory.TypeArgumentList(typeArguments));

                                        return(context.Document.ReplaceNodeAsync(type, newNode, context.CancellationToken));
                                    },
                                    GetEquivalenceKey(diagnostic, SymbolDisplay.GetString(namedTypeSymbol)));

                                context.RegisterCodeFix(codeAction, diagnostic);
                            }
                        }
                    }

                    break;
                }
                }
            }
        }
Exemplo n.º 36
0
        public void ShadowInvariants()
        {
            TestHiddenProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary);
            TestHiddenProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "goo.dll");
            TestHiddenProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Goo.Bar");
            TestHiddenProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>");
            TestHiddenProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release);
            TestHiddenProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true);
            TestHiddenProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "goo");
            TestHiddenProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "goo");
            TestHiddenProperty((old, value) => old.WithCryptoPublicKey(value), opt => opt.CryptoPublicKey, ImmutableArray.Create <byte>(0, 1, 2, 3));
            TestHiddenProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true);
            TestHiddenProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium);
            TestHiddenProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress);

            TestHiddenProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions,
                               new Dictionary <string, ReportDiagnostic> {
                { "CS0001", ReportDiagnostic.Error }
            }.ToImmutableDictionary());
            TestHiddenProperty((old, value) => old.WithReportSuppressedDiagnostics(value), opt => opt.ReportSuppressedDiagnostics, true);

            TestHiddenProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false);

            TestHiddenProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null));
            TestHiddenProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new TestMetadataReferenceResolver());
            TestHiddenProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy()));
            TestHiddenProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider());
        }
Exemplo n.º 37
0
        public void Invariants()
        {
            TestProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary);
            TestProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "goo.dll");
            TestProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Goo.Bar");
            TestProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>");
            TestProperty((old, value) => old.WithUsings(value), opt => opt.Usings, ImmutableArray.Create("A", "B"));
            TestProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release);
            TestProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true);
            TestProperty((old, value) => old.WithAllowUnsafe(value), opt => opt.AllowUnsafe, true);
            TestProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "goo");
            TestProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "goo");
            TestProperty((old, value) => old.WithCryptoPublicKey(value), opt => opt.CryptoPublicKey, ImmutableArray.Create <byte>(0, 1, 2, 3));
            TestProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true);
            TestProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium);
            TestProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress);
            TestProperty((old, value) => old.WithWarningLevel(value), opt => opt.WarningLevel, 3);

            TestProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions,
                         new Dictionary <string, ReportDiagnostic> {
                { "CS0001", ReportDiagnostic.Error }
            }.ToImmutableDictionary());
            TestProperty((old, value) => old.WithReportSuppressedDiagnostics(value), opt => opt.ReportSuppressedDiagnostics, true);

            TestProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false);
            TestProperty((old, value) => old.WithCurrentLocalTime(value), opt => opt.CurrentLocalTime, new DateTime(2005, 1, 1));
            TestProperty((old, value) => old.WithDebugPlusMode(value), opt => opt.DebugPlusMode, true);

            TestProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null));
            TestProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new TestMetadataReferenceResolver());
            TestProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy()));
            TestProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider());

            TestProperty((old, value) => old.WithTopLevelBinderFlags(value), opt => opt.TopLevelBinderFlags, BinderFlags.IgnoreCorLibraryDuplicatedTypes);
            TestProperty((old, value) => old.WithMetadataImportOptions(value), opt => opt.MetadataImportOptions, MetadataImportOptions.Internal);
            TestProperty((old, value) => old.WithReferencesSupersedeLowerVersions(value), opt => opt.ReferencesSupersedeLowerVersions, true);
            TestProperty((old, value) => old.WithNullableContextOptions(value), opt => opt.NullableContextOptions, NullableContextOptions.Enable);
        }
 private static Task <Document> UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken);
            protected override bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray <CompletionProvider> extensions)
            {
                // check whether the analyzer reference knows how to return completion providers directly.
                if (reference is ICompletionProviderFactory completionProviderFactory)
                {
                    extensions = completionProviderFactory.GetCompletionProviders();
                    return(true);
                }

                extensions = default;
                return(false);
            }
 /// <summary>
 /// Register a per-compilation symbol action. This pattern is often used by analyzers that inspect some compilation-level
 /// data (such as whether certain analysis-relevant types are, in fact, available due to targeting or other settings)
 /// to drive registration of symbol actions.
 /// </summary>
 /// <param name="action"></param>
 /// <param name="symbolKinds"></param>
 public override void RegisterSymbolAction(Action <SymbolAnalysisContext> action, ImmutableArray <SymbolKind> symbolKinds)
 {
     SymbolActions.Add(action, symbolKinds);
 }
Exemplo n.º 41
0
 public bool Equals(ImmutableArray<byte> x, ImmutableArray<byte> y)
 {
     return x.SequenceEqual(y);
 }
Exemplo n.º 42
0
 public int GetHashCode(ImmutableArray<byte> obj)
 {
     return obj.GetHashCode();
 }
Exemplo n.º 43
0
        public void Generate(out int asyncCatchHandlerOffset, out ImmutableArray <int> asyncYieldPoints, out ImmutableArray <int> asyncResumePoints)
        {
            this.GenerateImpl();
            Debug.Assert(_asyncCatchHandlerOffset >= 0);

            asyncCatchHandlerOffset = _builder.GetILOffsetFromMarker(_asyncCatchHandlerOffset);

            ArrayBuilder <int> yieldPoints  = _asyncYieldPoints;
            ArrayBuilder <int> resumePoints = _asyncResumePoints;

            Debug.Assert((yieldPoints == null) == (resumePoints == null));

            if (yieldPoints == null)
            {
                asyncYieldPoints  = ImmutableArray <int> .Empty;
                asyncResumePoints = ImmutableArray <int> .Empty;
            }
            else
            {
                var yieldPointBuilder = ArrayBuilder <int> .GetInstance();

                var resumePointBuilder = ArrayBuilder <int> .GetInstance();

                int n = yieldPoints.Count;
                for (int i = 0; i < n; i++)
                {
                    int yieldOffset  = _builder.GetILOffsetFromMarker(yieldPoints[i]);
                    int resumeOffset = _builder.GetILOffsetFromMarker(resumePoints[i]);
                    Debug.Assert(resumeOffset >= 0); // resume marker should always be reachable from dispatch

                    // yield point may not be reachable if the whole
                    // await is not reachable; we just ignore such awaits
                    if (yieldOffset > 0)
                    {
                        yieldPointBuilder.Add(yieldOffset);
                        resumePointBuilder.Add(resumeOffset);
                    }
                }

                asyncYieldPoints  = yieldPointBuilder.ToImmutableAndFree();
                asyncResumePoints = resumePointBuilder.ToImmutableAndFree();

                yieldPoints.Free();
                resumePoints.Free();
            }
        }
Exemplo n.º 44
0
 private IList <SerializableNavigateToSearchResult> Convert(
     ImmutableArray <INavigateToSearchResult> result)
 {
     return(result.SelectAsArray(SerializableNavigateToSearchResult.Dehydrate));
 }
Exemplo n.º 45
0
 /// <summary>
 /// Returns an instance of the reference with specified aliases.
 /// </summary>
 /// <param name="aliases">The new aliases for the reference.</param>
 /// <exception cref="ArgumentException">Alias is invalid for the metadata kind.</exception>
 public new PortableExecutableReference WithAliases(IEnumerable <string> aliases)
 {
     return(this.WithAliases(ImmutableArray.CreateRange(aliases)));
 }
Exemplo n.º 46
0
 /// <summary>
 /// Returns an instance of the reference with specified aliases.
 /// </summary>
 /// <param name="aliases">The new aliases for the reference.</param>
 /// <exception cref="ArgumentException">Alias is invalid for the metadata kind.</exception>
 public new PortableExecutableReference WithAliases(ImmutableArray <string> aliases)
 {
     return(WithProperties(new MetadataReferenceProperties(this.Properties.Kind, aliases, this.Properties.EmbedInteropTypes)));
 }
Exemplo n.º 47
0
        public async Task RolemeAsync(
            [Summary("A case-insensitive, space-delimited list of roles to toggle.")][Remainder]
            string roles = null)
        {
            if (string.IsNullOrWhiteSpace(roles))
            {
                await ReplyAsync(
                    $"Toggleable roles are:```\n{string.Join("\n", _dataService.RoleMeWhiteList.Select(r => r.Name))}```\n" +
                    "`Example: >roleme Level Designer Programmer` will give you both `Level Designer` and `Programmer` roles.");

                return;
            }

            var rolesValid = new List <SocketRole>();

            foreach (SocketRole role in _dataService.RoleMeWhiteList)
            {
                Match match = Regex.Match(roles, $@"\b{role.Name}\b", RegexOptions.IgnoreCase);

                if (!match.Success)
                {
                    continue;
                }

                // Finds and removes all occurrences of the whitelisted role in the input string.
                while (match.Success)
                {
                    roles = roles.Remove(match.Index, match.Length);
                    match = Regex.Match(roles, $@"\b{role.Name}\b", RegexOptions.IgnoreCase);
                }

                rolesValid.Add(role);
            }

            // Splits the remaining roles not found in the whitelist. Filters out empty elements.
            ImmutableArray <string> rolesInvalid = roles.Split(' ').Where(r => !string.IsNullOrWhiteSpace(r)).ToImmutableArray();

            var user         = (SocketGuildUser)Context.User;
            var rolesAdded   = new List <SocketRole>();
            var rolesRemoved = new List <SocketRole>();

            // Updates roles.
            foreach (SocketRole role in rolesValid)
            {
                if (user.Roles.Contains(role))
                {
                    await user.RemoveRoleAsync(role);

                    rolesRemoved.Add(role);
                }
                else
                {
                    await user.AddRoleAsync(role);

                    rolesAdded.Add(role);
                }
            }

            // Builds the response.
            var logMessage = new StringBuilder();

            var embed = new EmbedBuilder();

            embed.WithTitle("`roleme` Results");
            embed.WithDescription($"Results of toggled roles for {Context.User.Mention}:");

            if (rolesAdded.Any())
            {
                string name = $"Added ({rolesAdded.Count})";

                embed.AddInlineField(name, string.Join("\n", rolesAdded.Select(r => r.Mention)));
                logMessage.AppendLine($"{name}\n    " + string.Join("\n    ", rolesAdded.Select(r => r.Name)));
            }

            if (rolesRemoved.Any())
            {
                string name = $"Removed ({rolesRemoved.Count})";

                embed.AddInlineField(name, string.Join("\n", rolesRemoved.Select(r => r.Mention)));
                logMessage.AppendLine($"{name}\n    " + string.Join("\n    ", rolesRemoved.Select(r => r.Name)));
            }

            if (rolesInvalid.Any())
            {
                string name = $"Failed ({rolesInvalid.Count()})";

                embed.AddInlineField(name, string.Join("\n", rolesInvalid));
                embed.WithFooter("Failures occur when roles don't exist or toggling them is disallowed.");
                logMessage.Append($"{name}\n    " + string.Join("\n    ", rolesInvalid));
            }

            await ReplyAsync(string.Empty, false, embed.Build());

            await _dataService.ChannelLog($"Toggled Roles for {Context.User}", logMessage.ToString());

            await DataBaseUtil.AddCommandAsync("RoleMe", Context);
        }
 protected abstract ImmutableArray<SyntaxNode> MergeImports(ImmutableArray<SyntaxNode> unnecessaryImports);
Exemplo n.º 49
0
    /// <summary>
    /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
    /// The returned diagnostics are then ordered by location in the source document.
    /// </summary>
    /// <param name="analyzer">The analyzer to run on the documents</param>
    /// <param name="documents">The Documents that the analyzer will be run on</param>
    /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
    protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, Document[] documents)
    {
        var projects = new HashSet <Project>();

        foreach (var document in documents)
        {
            projects.Add(document.Project);
        }

        var diagnostics = new List <Diagnostic>();

        foreach (var project in projects)
        {
            var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
            var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
            foreach (var diag in diags)
            {
                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     = document.GetSyntaxTreeAsync().Result;
                        if (tree == diag.Location.SourceTree)
                        {
                            diagnostics.Add(diag);
                        }
                    }
                }
            }
        }

        var results = SortDiagnostics(diagnostics);

        diagnostics.Clear();
        return(results);
    }
Exemplo n.º 50
0
 private B2BPartnerContentResponse(ImmutableArray <Outputs.BusinessIdentityResponse> businessIdentities)
 {
     BusinessIdentities = businessIdentities;
 }
Exemplo n.º 51
0
 /// <summary>
 /// Constructs a new parameter collection.
 /// </summary>
 /// <param name="nodeReferences">The source parameters.</param>
 internal ParameterCollection(ImmutableArray <Parameter> nodeReferences)
 {
     parameters = nodeReferences;
 }
Exemplo n.º 52
0
 internal static ConcatImmutableArray <T> ConcatFast <T>(this ImmutableArray <T> first, ImmutableArray <T> second)
 {
     return(new ConcatImmutableArray <T>(first, second));
 }
Exemplo n.º 53
0
 internal static bool Contains <T>(this ImmutableArray <T> items, T item, IEqualityComparer <T>?equalityComparer)
 => items.IndexOf(item, 0, equalityComparer) >= 0;
Exemplo n.º 54
0
        private GetDiskResult(
            bool?burstingEnabled,

            Outputs.CreationDataResponse creationData,

            string?diskAccessId,

            double?diskIOPSReadOnly,

            double?diskIOPSReadWrite,

            double?diskMBpsReadOnly,

            double?diskMBpsReadWrite,

            double diskSizeBytes,

            int?diskSizeGB,

            string diskState,

            Outputs.EncryptionResponse?encryption,

            Outputs.EncryptionSettingsCollectionResponse?encryptionSettingsCollection,

            Outputs.ExtendedLocationResponse?extendedLocation,

            string?hyperVGeneration,

            string id,

            string location,

            string managedBy,

            ImmutableArray <string> managedByExtended,

            int?maxShares,

            string name,

            string?networkAccessPolicy,

            string?osType,

            string provisioningState,

            Outputs.PurchasePlanResponse?purchasePlan,

            ImmutableArray <Outputs.ShareInfoElementResponse> shareInfo,

            Outputs.DiskSkuResponse?sku,

            ImmutableDictionary <string, string>?tags,

            string?tier,

            string timeCreated,

            string type,

            string uniqueId,

            ImmutableArray <string> zones)
        {
            BurstingEnabled              = burstingEnabled;
            CreationData                 = creationData;
            DiskAccessId                 = diskAccessId;
            DiskIOPSReadOnly             = diskIOPSReadOnly;
            DiskIOPSReadWrite            = diskIOPSReadWrite;
            DiskMBpsReadOnly             = diskMBpsReadOnly;
            DiskMBpsReadWrite            = diskMBpsReadWrite;
            DiskSizeBytes                = diskSizeBytes;
            DiskSizeGB                   = diskSizeGB;
            DiskState                    = diskState;
            Encryption                   = encryption;
            EncryptionSettingsCollection = encryptionSettingsCollection;
            ExtendedLocation             = extendedLocation;
            HyperVGeneration             = hyperVGeneration;
            Id                  = id;
            Location            = location;
            ManagedBy           = managedBy;
            ManagedByExtended   = managedByExtended;
            MaxShares           = maxShares;
            Name                = name;
            NetworkAccessPolicy = networkAccessPolicy;
            OsType              = osType;
            ProvisioningState   = provisioningState;
            PurchasePlan        = purchasePlan;
            ShareInfo           = shareInfo;
            Sku                 = sku;
            Tags                = tags;
            Tier                = tier;
            TimeCreated         = timeCreated;
            Type                = type;
            UniqueId            = uniqueId;
            Zones               = zones;
        }
Exemplo n.º 55
0
 private BKTree(char[] concatenatedLowerCaseWords, ImmutableArray<Node> nodes, ImmutableArray<Edge> edges)
 {
     _concatenatedLowerCaseWords = concatenatedLowerCaseWords;
     _nodes = nodes;
     _edges = edges;
 }
Exemplo n.º 56
0
 internal static ImmutableArray <T> ToImmutableArrayOrEmpty <T>(this ImmutableArray <T> items)
 => items.IsDefault ? ImmutableArray <T> .Empty : items;
Exemplo n.º 57
0
 /// <summary>
 /// Constructs a new parameter enumerator.
 /// </summary>
 /// <param name="arguments">The parent source array.</param>
 internal Enumerator(ImmutableArray <Parameter> arguments)
 {
     parameters = arguments;
     enumerator = parameters.GetEnumerator();
 }
 protected virtual async Task AddDocumentFixesAsync(
     Document document, ImmutableArray <Diagnostic> diagnostics,
     ConcurrentBag <(Diagnostic diagnostic, CodeAction action)> fixes,
Exemplo n.º 59
0
 private ImmutableArray <CodeRefactoring> FilterOnUIThread(ImmutableArray <CodeRefactoring> refactorings, Workspace workspace)
 {
     return(refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToImmutableArray());
 }
Exemplo n.º 60
0
		public GetLocalsAssemblyBuilder(LanguageExpressionCompiler language, MethodDef method, ImmutableArray<string> localVariableNames, ImmutableArray<string> parameterNames) {
			this.language = language;
			sourceMethod = method;
			this.localVariableNames = localVariableNames;
			this.parameterNames = parameterNames;
			methodNameIndex = 0;
			lastMethodSig = null;
			localAndMethodBuilder = new List<DSEELocalAndMethod>();
			if (method.Parameters.Count == 0 && (method.Body?.Variables.Count ?? 0) == 0) {
				generatedModule = null;
				getLocalsType = null;
			}
			else {
				var methodModule = method.Module;
				generatedModule = new ModuleDefUser(Guid.NewGuid().ToString(), Guid.NewGuid(), methodModule.CorLibTypes.AssemblyRef);
				generatedModule.RuntimeVersion = methodModule.RuntimeVersion;
				generatedModule.Machine = methodModule.Machine;
				var asm = new AssemblyDefUser(Guid.NewGuid().ToString());
				asm.Modules.Add(generatedModule);
				getLocalsType = new TypeDefUser(getLocalsTypeNamespace, getLocalsTypeName, generatedModule.CorLibTypes.Object.TypeDefOrRef);
				getLocalsType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.SpecialName | TypeAttributes.BeforeFieldInit | TypeAttributes.AnsiClass;
				generatedModule.Types.Add(getLocalsType);
				foreach (var gp in method.DeclaringType.GenericParameters)
					getLocalsType.GenericParameters.Add(Clone(gp));
			}
		}