Ejemplo n.º 1
0
        private async Task<ImmutableArray<TaggedText>> TryAddSnippetInvocationPart(
            Document document, CompletionItem item, 
            ImmutableArray<TaggedText> parts, CancellationToken cancellationToken)
        {
            var languageServices = document.Project.LanguageServices;
            var snippetService = languageServices.GetService<ISnippetInfoService>();
            if (snippetService != null)
            {
                var change = await GetTextChangeAsync(document, item, ch: '\t', cancellationToken: cancellationToken).ConfigureAwait(false) ??
                    new TextChange(item.Span, item.DisplayText);
                var insertionText = change.NewText;

                if (snippetService != null && snippetService.SnippetShortcutExists_NonBlocking(insertionText))
                {
                    var note = string.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, insertionText);

                    if (parts.Any())
                    {
                        parts = parts.Add(new TaggedText(TextTags.LineBreak, Environment.NewLine));
                    }

                    parts = parts.Add(new TaggedText(TextTags.Text, note));
                }
            }

            return parts;
        }
Ejemplo n.º 2
0
        public static CompletionItem Create(
            string displayText,
            TextSpan span,
            Glyph? glyph = null,
            ImmutableArray<SymbolDisplayPart> description = default(ImmutableArray<SymbolDisplayPart>),
            string sortText = null,
            string filterText = null,
            bool preselect = false,
            bool showsWarningIcon = false,
            bool shouldFormatOnCommit = false,
            bool isArgumentName = false,
            ImmutableDictionary<string, string> properties = null,
            ImmutableArray<string> tags = default(ImmutableArray<string>),
            CompletionItemRules rules = null)
        {
            tags = tags.IsDefault ? ImmutableArray<string>.Empty : tags;

            if (glyph != null)
            {
                // put glyph tags first
                tags = GlyphTags.GetTags(glyph.Value).AddRange(tags);
            }

            if (showsWarningIcon)
            {
                tags = tags.Add(CompletionTags.Warning);
            }

            if (isArgumentName)
            {
                tags = tags.Add(CompletionTags.ArgumentName);
            }

            properties = properties ?? ImmutableDictionary<string, string>.Empty;
            if (!description.IsDefault && description.Length > 0)
            {
                properties = properties.Add("Description", EncodeDescription(description));
            }

            rules = rules ?? CompletionItemRules.Default;
            rules = rules.WithPreselect(preselect)
                         .WithFormatOnCommit(shouldFormatOnCommit);

            return CompletionItem.Create(
                displayText: displayText,
                filterText: filterText,
                sortText: sortText,
                span: span,
                properties: properties,
                tags: tags,
                rules: rules);
        }
Ejemplo n.º 3
0
        protected virtual BoundStatement RewriteBlockStatement(BoundBlockStatement node)
        {
            ImmutableArray <BoundStatement> .Builder builder = null;

            for (var i = 0; i < node.Statements.Length; i++)
            {
                var oldStatement = node.Statements[i];
                var newStatement = RewriteStatement(oldStatement);
                if (newStatement != oldStatement)
                {
                    if (builder == null)
                    {
                        builder = ImmutableArray.CreateBuilder <BoundStatement>(node.Statements.Length);

                        for (var j = 0; j < i; j++)
                        {
                            builder.Add(node.Statements[j]);
                        }
                    }
                }

                builder?.Add(newStatement);
            }

            return(builder == null ? node : new BoundBlockStatement(builder.MoveToImmutable()));
        }
Ejemplo n.º 4
0
        protected virtual BoundExpression RewriteCallExpression(BoundCallExpression node)
        {
            ImmutableArray <BoundExpression> .Builder?builder = null;

            for (var i = 0; i < node.Arguments.Length; i++)
            {
                var oldArgument = node.Arguments[i];
                var newArgument = RewriteExpression(oldArgument);

                if (newArgument != oldArgument)
                {
                    if (builder == null)
                    {
                        builder = ImmutableArray.CreateBuilder <BoundExpression>(node.Arguments.Length);

                        for (var j = 0; j < i; j++)
                        {
                            builder.Add(node.Arguments[j]);
                        }
                    }
                }

                builder?.Add(newArgument);
            }

            if (builder == null)
            {
                return(node);
            }

            return(new BoundCallExpression(node.Syntax, node.Function, builder.MoveToImmutable()));
        }
Ejemplo n.º 5
0
        private void AddNode(ImmutableArray<NavInfoNode>.Builder builder, string name, uint type)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }

            builder.Add(new NavInfoNode(name, type));
        }
Ejemplo n.º 6
0
        public static CompletionItem Create(
            string displayText,
            Glyph? glyph = null,
            ImmutableArray<SymbolDisplayPart> description = default(ImmutableArray<SymbolDisplayPart>),
            string sortText = null,
            string filterText = null,
            int? matchPriority = null,
            bool showsWarningIcon = false,
            bool shouldFormatOnCommit = false,
            ImmutableDictionary<string, string> properties = null,
            ImmutableArray<string> tags = default(ImmutableArray<string>),
            CompletionItemRules rules = null)
        {
            tags = tags.NullToEmpty();

            if (glyph != null)
            {
                // put glyph tags first
                tags = GlyphTags.GetTags(glyph.Value).AddRange(tags);
            }

            if (showsWarningIcon)
            {
                tags = tags.Add(CompletionTags.Warning);
            }

            properties = properties ?? ImmutableDictionary<string, string>.Empty;
            if (!description.IsDefault && description.Length > 0)
            {
                properties = properties.Add("Description", EncodeDescription(description));
            }

            rules = rules ?? CompletionItemRules.Default;
            rules = rules.WithMatchPriority(matchPriority.GetValueOrDefault())
                         .WithFormatOnCommit(shouldFormatOnCommit);

            return CompletionItem.Create(
                displayText: displayText,
                filterText: filterText,
                sortText: sortText,
                properties: properties,
                tags: tags,
                rules: rules);
        }
Ejemplo n.º 7
0
        protected virtual BoundStatement RewriteBlockStatement(BoundStatement node)
        {
            ImmutableArray <BoundStatement> .Builder?builder = null;

            var boundStatements = node switch
            {
                BoundBlockStatement bbs => bbs.Statements,
                BoundMemberBlockStatement bmbs => bmbs.Statements,
                _ => throw new Exception($"Unexpected block statement type '{node.Kind}'."),
            };

            for (var i = 0; i < boundStatements.Length; i++)
            {
                var oldStatement = boundStatements[i];
                var newStatement = RewriteStatement(oldStatement);
                if (newStatement != oldStatement)
                {
                    if (builder == null)
                    {
                        builder = ImmutableArray.CreateBuilder <BoundStatement>(boundStatements.Length);

                        for (var j = 0; j < i; j++)
                        {
                            builder.Add(boundStatements[j]);
                        }
                    }
                }

                builder?.Add(newStatement);
            }

            if (builder == null)
            {
                return(node);
            }

            return(new BoundBlockStatement(node.Syntax, builder.MoveToImmutable()));
        }
Ejemplo n.º 8
0
 static ReferenceFinders()
 {
     DefaultRenameReferenceFinders = ImmutableArray.Create(
         Constructor,
         Destructor,
         Event,
         ExplicitInterfaceMethod,
         Field,
         Label,
         LinkedFiles,
         Local,
         MethodTypeParameter,
         NamedType,
         Namespace,
         Operator,
         OrdinaryMethod,
         Parameter,
         Property,
         PropertyAccessor,
         RangeVariable,
         TypeParameter);
     DefaultReferenceFinders = DefaultRenameReferenceFinders.Add(ConstructorInitializer);
 }
            private async Task <Project> UpdateDocumentsAsync(
                Project project,
                IEnumerable <TextDocumentState> existingTextDocumentStates,
                ChecksumCollection oldChecksums,
                ChecksumCollection newChecksums,
                Func <Solution, ImmutableArray <DocumentInfo>, Solution> addDocuments,
                Func <Solution, DocumentId, Solution> removeDocument)
            {
                using var olds = SharedPools.Default <HashSet <Checksum> >().GetPooledObject();
                using var news = SharedPools.Default <HashSet <Checksum> >().GetPooledObject();

                olds.Object.UnionWith(oldChecksums);
                news.Object.UnionWith(newChecksums);

                // remove documents that exist in both side
                olds.Object.ExceptWith(newChecksums);
                news.Object.ExceptWith(oldChecksums);

                var oldMap = await GetDocumentMapAsync(existingTextDocumentStates, olds.Object).ConfigureAwait(false);

                var newMap = await GetDocumentMapAsync(_assetProvider, news.Object).ConfigureAwait(false);

                // added document
                ImmutableArray <DocumentInfo> .Builder?lazyDocumentsToAdd = null;
                foreach (var(documentId, newDocumentChecksums) in newMap)
                {
                    if (!oldMap.ContainsKey(documentId))
                    {
                        lazyDocumentsToAdd ??= ImmutableArray.CreateBuilder <DocumentInfo>();

                        // we have new document added
                        var documentInfo = await _assetProvider.CreateDocumentInfoAsync(newDocumentChecksums.Checksum, _cancellationToken).ConfigureAwait(false);

                        lazyDocumentsToAdd.Add(documentInfo);
                    }
                }

                if (lazyDocumentsToAdd != null)
                {
                    project = addDocuments(project.Solution, lazyDocumentsToAdd.ToImmutable()).GetProject(project.Id) !;
                }

                // changed document
                foreach (var(documentId, newDocumentChecksums) in newMap)
                {
                    if (!oldMap.TryGetValue(documentId, out var oldDocumentChecksums))
                    {
                        continue;
                    }

                    Contract.ThrowIfTrue(oldDocumentChecksums.Checksum == newDocumentChecksums.Checksum);

                    var document = project.GetDocument(documentId) ?? project.GetAdditionalDocument(documentId) ?? project.GetAnalyzerConfigDocument(documentId);
                    Contract.ThrowIfNull(document);

                    project = await UpdateDocumentAsync(document, oldDocumentChecksums, newDocumentChecksums).ConfigureAwait(false);
                }

                // removed document
                foreach (var(documentId, _) in oldMap)
                {
                    if (!newMap.ContainsKey(documentId))
                    {
                        // we have a document removed
                        project = removeDocument(project.Solution, documentId).GetProject(project.Id) !;
                    }
                }

                return(project);
            }
 private static void AddKeyword(this ImmutableArray <SymbolDisplayPart> .Builder builder, string text)
 {
     builder.Add(SymbolDisplayPartFactory.Keyword(text));
 }
Ejemplo n.º 11
0
            //this runs as a glib idle handler so it can add/remove text editor markers
            //in order to to block the GUI thread, we batch them in UPDATE_COUNT
            bool IdleHandler()
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }
                var editor = ext.Editor;

                if (editor == null)
                {
                    return(false);
                }
                //clear the old results out at the same rate we add in the new ones
                for (int i = 0; oldMarkers > 0 && i < UPDATE_COUNT; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    editor.RemoveMarker(ext.markers.Dequeue());
                    oldMarkers--;
                }
                //add in the new markers
                for (int i = 0; i < UPDATE_COUNT; i++)
                {
                    if (!enumerator.MoveNext())
                    {
                        ext.tasks = builder.ToImmutable();
                        ext.OnTasksUpdated(EventArgs.Empty);
                        return(false);
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    var currentResult = (Result)enumerator.Current;
                    if (currentResult.InspectionMark != IssueMarker.None)
                    {
                        int start = currentResult.Region.Start;
                        int end   = currentResult.Region.End;
                        if (start >= end)
                        {
                            continue;
                        }
                        if (currentResult.InspectionMark == IssueMarker.GrayOut)
                        {
                            var marker = TextMarkerFactory.CreateGenericTextSegmentMarker(editor, TextSegmentMarkerEffect.GrayOut, TextSegment.FromBounds(start, end));
                            marker.IsVisible = currentResult.Underline;
                            marker.Tag       = currentResult;
                            editor.AddMarker(marker);
                            ext.markers.Enqueue(marker);
//							editor.Parent.TextViewMargin.RemoveCachedLine (editor.GetLineByOffset (start));
//							editor.Parent.QueueDraw ();
                        }
                        else
                        {
                            var effect = currentResult.InspectionMark == IssueMarker.DottedLine ? TextSegmentMarkerEffect.DottedLine : TextSegmentMarkerEffect.WavedLine;
                            var marker = TextMarkerFactory.CreateGenericTextSegmentMarker(editor, effect, TextSegment.FromBounds(start, end));
                            marker.Color     = GetColor(editor, currentResult);
                            marker.IsVisible = currentResult.Underline;
                            marker.Tag       = currentResult;
                            editor.AddMarker(marker);
                            ext.markers.Enqueue(marker);
                        }
                    }
                    builder.Add(new QuickTask(currentResult.Message, currentResult.Region.Start, currentResult.Level));
                }

                return(true);
            }
Ejemplo n.º 12
0
        private static async Task <int> FindSymbolsAsync(FindSymbolsCommandLineOptions options)
        {
            if (!options.TryGetProjectFilter(out ProjectFilter projectFilter))
            {
                return(1);
            }

            if (!TryParseOptionValueAsEnumFlags(options.SymbolGroups, ParameterNames.SymbolGroups, out SymbolGroupFilter symbolGroups, SymbolFinderOptions.Default.SymbolGroups))
            {
                return(1);
            }

            if (!TryParseOptionValueAsEnumFlags(options.Visibility, ParameterNames.Visibility, out VisibilityFilter visibility, SymbolFinderOptions.Default.Visibility))
            {
                return(1);
            }

            if (!TryParseMetadataNames(options.WithAttributes, out ImmutableArray <MetadataName> withAttributes))
            {
                return(1);
            }

            if (!TryParseMetadataNames(options.WithoutAttributes, out ImmutableArray <MetadataName> withoutAttributes))
            {
                return(1);
            }

            if (!TryParseOptionValueAsEnumFlags(options.WithFlags, ParameterNames.WithFlags, out SymbolFlags withFlags, SymbolFlags.None))
            {
                return(1);
            }

            if (!TryParseOptionValueAsEnumFlags(options.WithoutFlags, ParameterNames.WithoutFlags, out SymbolFlags withoutFlags, SymbolFlags.None))
            {
                return(1);
            }

            ImmutableArray <SymbolFilterRule> .Builder rules = ImmutableArray.CreateBuilder <SymbolFilterRule>();

            if (withAttributes.Any())
            {
                rules.Add(new WithAttributeFilterRule(withAttributes));
            }

            if (withoutAttributes.Any())
            {
                rules.Add(new WithoutAttributeFilterRule(withoutAttributes));
            }

            if (withFlags != SymbolFlags.None)
            {
                rules.AddRange(SymbolFilterRuleFactory.FromFlags(withFlags));
            }

            if (withoutFlags != SymbolFlags.None)
            {
                rules.AddRange(SymbolFilterRuleFactory.FromFlags(withoutFlags, invert: true));
            }

            var symbolFinderOptions = new SymbolFinderOptions(
                visibility: visibility,
                symbolGroups: symbolGroups,
                rules: rules,
                ignoreGeneratedCode: options.IgnoreGeneratedCode,
                unusedOnly: options.UnusedOnly);

            var command = new FindSymbolsCommand(
                options: options,
                symbolFinderOptions: symbolFinderOptions,
                projectFilter: projectFilter);

            CommandResult result = await command.ExecuteAsync(options.Path, options.MSBuildPath, options.Properties);

            return((result.Kind == CommandResultKind.Success) ? 0 : 1);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="IDiagnosticAnalyzer"/> defined in this assembly reference.
        /// </summary>
        internal void AddAnalyzers(ImmutableArray<IDiagnosticAnalyzer>.Builder builder, List<DiagnosticInfo> diagnosticsOpt, CommonMessageProvider messageProviderOpt)
        {
            // We handle loading of analyzer assemblies ourselves. This allows us to avoid locking the assembly
            // file on disk.
            Type[] types = null;
            Exception ex = null;

            try
            {
                Assembly analyzerAssembly = GetAssembly();
                types = analyzerAssembly.GetTypes();
            }
            catch (FileLoadException e)
            { ex = e; }
            catch (BadImageFormatException e)
            { ex = e; }
            catch (SecurityException e)
            { ex = e; }
            catch (ArgumentException e)
            { ex = e; }
            catch (PathTooLongException e)
            { ex = e; }
            catch (ReflectionTypeLoadException e)
            { ex = e; }

            if (ex != null)
            {
                var typeLoadEx = ex as ReflectionTypeLoadException;
                if (diagnosticsOpt != null && messageProviderOpt != null)
                {
                    var message = typeLoadEx == null ?
                        messageProviderOpt.WRN_UnableToLoadAnalyzer :
                        messageProviderOpt.INF_UnableToLoadSomeTypesInAnalyzer;
                    diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, message, fullPath, ex.Message));
                }

                if (typeLoadEx != null)
                {
                    types = typeLoadEx.Types.Where(t => t != null).ToArray();
                }
                else
                {
                    return;
                }
            }

            bool hasAnalyzers = false;
            foreach (var type in types)
            {
                try
                {
                    if (type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IDiagnosticAnalyzer)) && type.IsDefined(typeof(DiagnosticAnalyzerAttribute)))
                    {
                        hasAnalyzers = true;
                        builder.Add((IDiagnosticAnalyzer)Activator.CreateInstance(type));
                    }
                }
                catch (Exception e)
                {
                    if (diagnosticsOpt != null && messageProviderOpt != null)
                    {
                        diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.WRN_AnalyzerCannotBeCreated, type.FullName, fullPath, e.Message));
                    }
                }
            }

            if (!hasAnalyzers && ex == null && diagnosticsOpt != null && messageProviderOpt != null)
            {
                // If there are no analyzers in this assembly, let the user know.
                diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.WRN_NoAnalyzerInAssembly, fullPath));
            }
        }
Ejemplo n.º 14
0
        private void ReadSectionDetails(ArchiveSectionMetadataBuilder[] sections)
        {
            #region Counts

            bool hasStreamCounts = false;

            ArchiveMetadataToken token;
            for (;;)
            {
                token = ReadToken();
                if (token == ArchiveMetadataToken.End || token == ArchiveMetadataToken.CRC || token == ArchiveMetadataToken.Size)
                {
                    break;
                }

                if (token == ArchiveMetadataToken.NumUnpackStream)
                {
                    hasStreamCounts = true;

                    foreach (var section in sections)
                    {
                        section.SubStreamCount = ReadNumberAsInt32();
                    }
                }
                else
                {
                    SkipDataBlock();
                }
            }

            if (!hasStreamCounts)
            {
                foreach (var section in sections)
                {
                    section.SubStreamCount = 1;
                }
            }

            #endregion

            #region Sizes

            foreach (var section in sections)
            {
                // v3.13 was broken and wrote empty sections
                // v4.07 added compat code to skip empty sections
                if (section.SubStreamCount.Value == 0)
                {
                    continue;
                }

                var remaining   = section.OutputLength;
                var subsections = new DecodedStreamMetadata[section.SubStreamCount.Value];

                for (int i = 0; i < subsections.Length - 1; i++)
                {
                    if (token == ArchiveMetadataToken.Size)
                    {
                        var size = ReadNumberAsInt64();
                        if (size == 0 || size >= remaining)
                        {
                            throw new InvalidDataException();
                        }

                        subsections[i] = new DecodedStreamMetadata(size, null);
                        remaining     -= size;
                    }
                }

                if (remaining == 0)
                {
                    throw new InvalidDataException();
                }

                subsections[subsections.Length - 1] = new DecodedStreamMetadata(remaining, null);
                section.Subsections = subsections;
            }

            if (token == ArchiveMetadataToken.Size)
            {
                token = ReadToken();
            }

            #endregion

            #region Checksums

            int requiredChecksumCount = 0;
            int totalChecksumCount    = 0;

            ImmutableArray <Checksum?> .Builder checksums = null;

            foreach (var section in sections)
            {
                // If there is only one stream and we have a section checksum 7z doesn't store the checksum again.
                if (!(section.SubStreamCount == 1 && section.OutputChecksum.HasValue))
                {
                    requiredChecksumCount += section.SubStreamCount.Value;
                }

                totalChecksumCount += section.SubStreamCount.Value;
            }

            for (;;)
            {
                if (token == ArchiveMetadataToken.End)
                {
                    if (checksums == null)
                    {
                        checksums = ImmutableArray.CreateBuilder <Checksum?>(totalChecksumCount);
                        for (int i = 0; i < totalChecksumCount; i++)
                        {
                            checksums.Add(null);
                        }
                    }

                    break;
                }
                else if (token == ArchiveMetadataToken.CRC)
                {
                    checksums = ImmutableArray.CreateBuilder <Checksum?>(totalChecksumCount);

                    var vector = ReadOptionalBitVector(requiredChecksumCount);
                    int requiredChecksumIndex = 0;

                    foreach (var section in sections)
                    {
                        if (section.SubStreamCount == 1 && section.OutputChecksum.HasValue)
                        {
                            checksums.Add(section.OutputChecksum.Value);
                        }
                        else
                        {
                            for (int i = 0; i < section.SubStreamCount; i++)
                            {
                                if (vector[requiredChecksumIndex++])
                                {
                                    checksums.Add(new Checksum(ReadInt32()));
                                }
                                else
                                {
                                    checksums.Add(null);
                                }
                            }
                        }
                    }

                    System.Diagnostics.Debug.Assert(requiredChecksumIndex == requiredChecksumCount);
                    System.Diagnostics.Debug.Assert(checksums.Count == totalChecksumCount);
                }
                else
                {
                    SkipDataBlock();
                }

                token = ReadToken();
            }

            #endregion
        }
Ejemplo n.º 15
0
 private void AddAnalyzerExpressionCOmplexity(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     var analyzer = new ExpressionComplexity();
     if (!AnalyzerIds.Contains(analyzer.SupportedDiagnostics.Single().Id))
     {
         return;
     }
     analyzer.Maximum = int.Parse(
         Parameters[analyzer.SupportedDiagnostics.Single().Id].Single()["max"],
         NumberStyles.None, CultureInfo.InvariantCulture);
     builder.Add(analyzer);
 }
        private static void CreateReferences(
            ReferencedSymbol referencedSymbol,
            ImmutableArray<SourceReferenceItem>.Builder references,
            DefinitionItem definitionItem,
            HashSet<DocumentLocation> uniqueLocations)
        {
            foreach (var referenceLocation in referencedSymbol.Locations)
            {
                var location = referenceLocation.Location;
                Debug.Assert(location.IsInSource);

                var document = referenceLocation.Document;
                var sourceSpan = location.SourceSpan;

                var documentLocation = new DocumentLocation(document, sourceSpan);
                if (!documentLocation.CanNavigateTo())
                {
                    continue;
                }

                if (uniqueLocations.Add(documentLocation))
                {
                    references.Add(new SourceReferenceItem(definitionItem, documentLocation));
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Adds the <see cref="ImmutableArray{IDiagnosticAnalyzer}"/> defined in this assembly reference
        /// </summary>
        internal void AddAnalyzers(ImmutableArray<IDiagnosticAnalyzer>.Builder builder, List<DiagnosticInfo> diagnosticsOpt, CommonMessageProvider messageProviderOpt)
        {
            // Using Assembly.LoadFrom to load into the Load-From context. This ensures that:
            // 1 . The analyzer and it's dependencies don't have to be in the probing path of this process
            // 2 . When multiple assemblies with the same identity are loaded (even from different paths), we return
            // the same assembly and avoid bloat. This does mean that strong identity for analyzers is important.
            Type[] types = null;
            Exception ex = null;

            try
            {
                Assembly analyzerAssembly = Assembly.LoadFrom(fullPath);
                types = analyzerAssembly.GetTypes();
            }
            catch (FileLoadException e)
            { ex = e; }
            catch (BadImageFormatException e)
            { ex = e; }
            catch (SecurityException e)
            { ex = e; }
            catch (ArgumentException e)
            { ex = e; }
            catch (PathTooLongException e)
            { ex = e; }

            if (ex != null)
            {
                if (diagnosticsOpt != null && messageProviderOpt != null)
                {
                    diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.WRN_UnableToLoadAnalyzer, fullPath, ex.Message));
                }

                return;
            }

            bool hasAnalyzers = false;
            foreach (var type in types)
            {
                if (type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IDiagnosticAnalyzer)) && type.IsDefined(typeof(DiagnosticAnalyzerAttribute)))
                {
                    hasAnalyzers = true;

                    try
                    {
                        builder.Add((IDiagnosticAnalyzer)Activator.CreateInstance(type));
                    }
                    catch (Exception e)
                    {
                        if (diagnosticsOpt != null && messageProviderOpt != null)
                        {
                            diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.WRN_AnalyzerCannotBeCreated, type, fullPath, e.Message));
                        }
                    }
                }
            }

            if (!hasAnalyzers && diagnosticsOpt != null && messageProviderOpt != null)
            {
                // If there are no analyzers in this assembly, let the user know.
                diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.WRN_NoAnalyzerInAssembly, fullPath));
            }
        }
Ejemplo n.º 18
0
        public static void CollectCommentRegions(
            SyntaxTriviaList triviaList, ImmutableArray<BlockSpan>.Builder spans)
        {
            if (triviaList.Count > 0)
            {
                SyntaxTrivia? startComment = null;
                SyntaxTrivia? endComment = null;

                Action completeSingleLineCommentGroup = () =>
                {
                    if (startComment != null)
                    {
                        var singleLineCommentGroupRegion = CreateCommentRegion(startComment.Value, endComment.Value);
                        spans.Add(singleLineCommentGroupRegion);
                        startComment = null;
                        endComment = null;
                    }
                };

                // Iterate through trivia and collect the following:
                //    1. Groups of contiguous single-line comments that are only separated by whitespace
                //    2. Multi-line comments
                foreach (var trivia in triviaList)
                {
                    if (trivia.IsSingleLineComment())
                    {
                        startComment = startComment ?? trivia;
                        endComment = trivia;
                    }
                    else if (trivia.IsMultiLineComment())
                    {
                        completeSingleLineCommentGroup();

                        var multilineCommentRegion = CreateCommentRegion(trivia, trivia);
                        spans.Add(multilineCommentRegion);
                    }
                    else if (!trivia.MatchesKind(SyntaxKind.WhitespaceTrivia,
                                                 SyntaxKind.EndOfLineTrivia,
                                                 SyntaxKind.EndOfFileToken))
                    {
                        completeSingleLineCommentGroup();
                    }
                }

                completeSingleLineCommentGroup();
            }
        }
            private static void SplitRawLineIntoFormattedLines(string line, ImmutableArray<string>.Builder lines)
            {
                var indent = new StringBuilder().Append(' ', s_indentSize * 2).ToString();

                var words = line.Split(' ');
                bool firstInLine = true;

                var sb = new StringBuilder();
                sb.Append(indent);
                foreach (var word in words)
                {
                    // We must always append at least one word to ensure progress.
                    if (firstInLine)
                    {
                        firstInLine = false;
                    }
                    else
                    {
                        sb.Append(' ');
                    }

                    sb.Append(word);

                    if (sb.Length >= s_wrapLength)
                    {
                        lines.Add(sb.ToString());
                        sb.Clear();
                        sb.Append(indent);
                        firstInLine = true;
                    }
                }

                if (sb.ToString().Trim() != string.Empty)
                {
                    lines.Add(sb.ToString());
                }
            }
 private static void AddComponentsFlat(ImmutableArray<Type>.Builder result, Type t)
 {
     if (HarshTuple.IsTupleType(t))
     {
         foreach (var ct in HarshTuple.GetComponentTypes(t))
         {
             AddComponentsFlat(result, ct);
         }
     }
     else if (HarshGrouping.IsGroupingType(t))
     {
         AddComponentsFlat(result, t.GenericTypeArguments[0]);
         AddComponentsFlat(result, t.GenericTypeArguments[1]);
     }
     else
     {
         result.Add(t);
     }
 }
Ejemplo n.º 21
0
        private static void LzmaEnc_WriteProperties(Master.LZMA.CLzmaEncProps settings, ImmutableArray<byte>.Builder props)
        {
            settings.LzmaEncProps_Normalize();

            uint dictSize = settings.mDictSize;
            props.Add((byte)((settings.mPB * 5 + settings.mLP) * 9 + settings.mLC));

            for (int i = 11; i <= 30; i++)
            {
                if (dictSize <= (2u << i))
                {
                    dictSize = (2u << i);
                    break;
                }
                if (dictSize <= (3u << i))
                {
                    dictSize = (3u << i);
                    break;
                }
            }

            for (int i = 0; i < 4; i++)
                props.Add((byte)(dictSize >> (8 * i)));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Update the destination database using data from source database using Id column as identification.
        /// </summary>
        /// <param name="destination">The destination database.</param>
        /// <param name="source">The source database.</param>
        /// <param name="records">The updated records from destination database.</param>
        /// <returns>True if destination database was updated.</returns>
        public static bool Update(XDatabase destination, XDatabase source, out ImmutableArray<XRecord>.Builder records)
        {
            bool isDirty = false;
            records = null;

            if (source == null || destination == null)
            {
                return isDirty;
            }

            // Check the number of source database columns.
            if (source.Columns.Length <= 1)
            {
                return isDirty;
            }

            // Check for presence of the Id column in the source database.
            if (source.Columns[0].Name != destination.IdColumnName)
            {
                return isDirty;
            }

            // Check for matching columns length.
            if (source.Columns.Length - 1 != destination.Columns.Length)
            {
                return isDirty;
            }

            // Check for matching column names.
            for (int i = 1; i < source.Columns.Length; i++)
            {
                if (source.Columns[i].Name != destination.Columns[i - 1].Name)
                {
                    return isDirty;
                }
            }

            // Create updated records builder.
            records = destination.Records.ToBuilder();

            // Update or remove existing records.
            for (int i = 0; i < destination.Records.Length; i++)
            {
                var record = destination.Records[i];
                var result = source.Records.FirstOrDefault(r => r.Id == record.Id);
                if (result != null)
                {
                    // Update existing record.
                    for (int j = 1; j < result.Values.Length; j++)
                    {
                        var valuesBuilder = record.Values.ToBuilder();
                        valuesBuilder[j - 1] = result.Values[j];
                        record.Values = valuesBuilder.ToImmutable();
                    }
                    isDirty = true;
                }
                else
                {
                    // Remove existing record.
                    records.Remove(record);
                    isDirty = true;
                }
            }

            // Add new records.
            for (int i = 0; i < source.Records.Length; i++)
            {
                var record = source.Records[i];
                var result = destination.Records.FirstOrDefault(r => r.Id == record.Id);
                if (result == null)
                {
                    var r = source.Records[i];

                    // Use existing columns.
                    r.Columns = destination.Columns;

                    // Skip Id column.
                    r.Values = r.Values.Skip(1).ToImmutableArray();

                    // Add new record.
                    records.Add(r);
                    isDirty = true;
                }
            }

            return isDirty;
        }
Ejemplo n.º 23
0
        public RoslynCompilationWorkspace(
            InteractiveDependencyResolver dependencyResolver,
            TargetCompilationConfiguration compilationConfiguration,
            AgentType agentType,
            Type hostObjectType = null,
            bool includePeImagesInResolution = false)
        {
            if (dependencyResolver == null)
            {
                throw new ArgumentNullException(nameof(dependencyResolver));
            }

            if (compilationConfiguration == null)
            {
                throw new ArgumentNullException(nameof(compilationConfiguration));
            }

            workspace = new InteractiveWorkspace();
            sourceReferenceResolver      = new InteractiveSourceReferenceResolver(dependencyResolver);
            metadataReferenceResolver    = new InteractiveMetadataReferenceResolver(dependencyResolver);
            monoScriptCompilationPatcher = new MonoScriptCompilationPatcher(
                assemblyNamePrefixBytes);

            DependencyResolver = dependencyResolver;

            this.hostObjectType        = hostObjectType;
            EvaluationContextId        = compilationConfiguration.EvaluationContextId;
            initialImports             = compilationConfiguration.DefaultUsings.ToImmutableArray();
            initialWarningSuppressions = compilationConfiguration.DefaultWarningSuppressions.ToImmutableArray();
            initialDiagnosticOptions   = initialWarningSuppressions.ToImmutableDictionary(
                warningId => warningId,
                warningId => ReportDiagnostic.Suppress);
            initialReferences = dependencyResolver.ResolveDefaultReferences();

            var byNameImplicitReferences = new Tuple <string, Func <bool> > [] {
                Tuple.Create <string, Func <bool> > ("Microsoft.CSharp", () => true),

                // Add an implicit by name reference to System.ValueTuple if and only if the
                // agent is Console or WPF, and the current runtime does not have SVT in corlib.
                // This check makes sense because the Console and WPF agents run on the same
                // runtime as the current client. The other agents are on runtimes controlled
                // by us, and we can be sure that System.ValueTuple will be part of corlib on
                // those agents. A bug in .NET 4.7 means we can't just always implicitly add
                // the reference and have the runtime figure out what should be done. This bug
                // is fixed in .NET 4.7.1.
                Tuple.Create <string, Func <bool> > ("System.ValueTuple", () => {
                    return((agentType == AgentType.Console || agentType == AgentType.WPF) &&
                           typeof(object).Assembly.GetType("System.ValueTuple") == null);
                })
            };

            foreach (var implicitReference in byNameImplicitReferences)
            {
                if (!implicitReference.Item2())
                {
                    continue;
                }

                var assembly = DependencyResolver.ResolveWithoutReferences(
                    new AssemblyName(implicitReference.Item1));
                if (assembly != null)
                {
                    initialReferences = initialReferences.Add(
                        MetadataReference.CreateFromFile(assembly.Path));
                }
            }

            this.includePeImagesInResolution = includePeImagesInResolution;

            CompletionService = workspace
                                .Services
                                .GetLanguageServices(LanguageNames.CSharp)
                                .GetService <CompletionService> ();
        }
Ejemplo n.º 24
0
            private void BuildArrays(ImmutableArray<Node>.Builder nodes, ImmutableArray<Edge>.Builder edges)
            {
                var currentEdgeIndex = 0;
                for (var i = 0; i < _builderNodes.Length; i++)
                {
                    var builderNode = _builderNodes[i];
                    var edgeCount = builderNode.EdgeCount;

                    nodes.Add(new Node(builderNode.CharacterSpan, edgeCount, currentEdgeIndex));

                    if (edgeCount > 0)
                    {
                        // First, copy any edges that are in the compact array.
                        var start = i * CompactEdgeAllocationSize;
                        var end = start + Math.Min(edgeCount, CompactEdgeAllocationSize);
                        for (var j = start; j < end; j++)
                        {
                            edges.Add(_compactEdges[j]);
                        }

                        // Then, if we've spilled over any edges, copy them as well.
                        var spilledEdges = builderNode.SpilloverEdges;
                        if (spilledEdges != null)
                        {
                            Debug.Assert(spilledEdges.Count == (edgeCount - CompactEdgeAllocationSize));

                            foreach (var kvp in spilledEdges)
                            {
                                edges.Add(new Edge(kvp.Key, kvp.Value));
                            }
                        }
                    }

                    currentEdgeIndex += edgeCount;
                }

                Debug.Assert(currentEdgeIndex == edges.Capacity);
                Debug.Assert(currentEdgeIndex == edges.Count);
            }
Ejemplo n.º 25
0
 internal LabelHandle AddLabel()
 {
     _labels.Add(-1);
     return(new LabelHandle(_labels.Count));
 }
        private static void CreateReferences(
            ReferencedSymbol referencedSymbol,
            ImmutableArray<SourceReferenceItem>.Builder references,
            DefinitionItem definitionItem,
            HashSet<DocumentSpan> uniqueSpans)
        {
            foreach (var referenceLocation in referencedSymbol.Locations)
            {
                var sourceReferenceItem = referenceLocation.TryCreateSourceReferenceItem(definitionItem);
                if (sourceReferenceItem == null)
                {
                    continue;
                }

                if (uniqueSpans.Add(sourceReferenceItem.SourceSpan))
                {
                    references.Add(sourceReferenceItem);
                }
            }
        }
Ejemplo n.º 27
0
 private void AddAnalyzerMagicNumber(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     var analyzer = new MagicNumber();
     if (!AnalyzerIds.Contains(analyzer.SupportedDiagnostics.Single().Id))
     {
         return;
     }
     analyzer.Exceptions =
         Parameters[analyzer.SupportedDiagnostics.Single().Id].Single()["exceptions"]
             .Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries)
             .Select(e => e.Trim())
             .ToImmutableHashSet();
     builder.Add(analyzer);
 }
        private void ProcessReferencedSymbol(
            Solution solution,
            ReferencedSymbol referencedSymbol,
            ImmutableArray<DefinitionItem>.Builder definitions,
            ImmutableArray<SourceReferenceItem>.Builder references,
            HashSet<DocumentSpan> uniqueSpans)
        {
            // See if this is a symbol we even want to present to the user.  If not,
            // ignore it entirely (including all its reference locations).
            if (!referencedSymbol.ShouldShow())
            {
                return;
            }

            var definitionItem = referencedSymbol.Definition.ToDefinitionItem(solution, uniqueSpans);
            definitions.Add(definitionItem);

            // Now, create the SourceReferenceItems for all the reference locations
            // for this definition.
            CreateReferences(referencedSymbol, references, definitionItem, uniqueSpans);

            // Finally, see if there are any third parties that want to add their
            // own result to our collection.
            var thirdPartyItem = GetThirdPartyDefinitionItem(solution, referencedSymbol.Definition);
            if (thirdPartyItem != null)
            {
                definitions.Add(thirdPartyItem);
            }
        }
Ejemplo n.º 29
0
 private void AddAnalyzerFileLines(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     var analyzer = new FileLines();
     if (!AnalyzerIds.Contains(analyzer.SupportedDiagnostics.Single().Id))
     {
         return;
     }
     analyzer.Maximum = int.Parse(
         Parameters[analyzer.SupportedDiagnostics.Single().Id].Single()["maximumFileLocThreshold"],
         NumberStyles.None, CultureInfo.InvariantCulture);
     builder.Add(analyzer);
 }
Ejemplo n.º 30
0
        private void FillNodeList(NavInfoList navInfoList, bool isObjectBrowser, bool isCanonical, ImmutableArray<IVsNavInfoNode>.Builder builder)
        {
            var index = 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)
            {
                if (navInfoList.Count >= 2 && navInfoList[1].ListType == (uint)_LIB_LISTTYPE.LLT_HIERARCHY)
                {
                    index = 2;
                }
            }

            while (index < navInfoList.Count)
            {
                if (!isCanonical || navInfoList[index].ListType != (uint)_LIB_LISTTYPE.LLT_HIERARCHY)
                {
                    builder.Add(navInfoList[index]);
                }

                index++;
            }
        }
        protected void Add(string name)
        {
            ValidateName(name);

            _builder.Add($"/{name}");
        }
Ejemplo n.º 32
0
        private void GetEffectiveIncludesCore(ImmutableArray<string>.Builder arrayBuilder)
        {
            arrayBuilder.Add(this.FilePath);

            foreach (var ruleSetInclude in _includes)
            {
                var ruleSet = ruleSetInclude.LoadRuleSet(this);

                // If we couldn't load the ruleset file, then there's nothing to do.
                if (ruleSet == null)
                {
                    continue;
                }

                // If this file has already been included don't recurse into it.
                if (!arrayBuilder.Contains(ruleSet.FilePath, StringComparer.OrdinalIgnoreCase))
                {
                    ruleSet.GetEffectiveIncludesCore(arrayBuilder);
                }
            }
        }
 private static void AddPunctuation(this ImmutableArray <SymbolDisplayPart> .Builder builder, string text)
 {
     builder.Add(SymbolDisplayPartFactory.Punctuation(text));
 }
Ejemplo n.º 34
0
        public async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions perms, RequestOptions options = null)
        {
            await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, perms, options).ConfigureAwait(false);

            _overwrites = _overwrites.Add(new Overwrite(user.Id, PermissionTarget.User, new OverwritePermissions(perms.AllowValue, perms.DenyValue)));
        }
Ejemplo n.º 35
0
        private MetadataLoadedInfo LoadMetadata()
        {
            HashSet <ModuleDesc> metadataModules          = new HashSet <ModuleDesc>();
            MetadataType         typeWithMetadataMappings = (MetadataType)_metadataDescribingModule.GetTypeByCustomAttributeTypeName(MetadataMappingTypeName);

            MethodDesc fullMetadataMethod = typeWithMetadataMappings.GetMethod("Metadata", null);
            MethodDesc weakMetadataMethod = typeWithMetadataMappings.GetMethod("WeakMetadata", null);

            ILProvider ilProvider = new ILProvider(null);

            MetadataLoadedInfo result = new MetadataLoadedInfo();

            if (fullMetadataMethod != null)
            {
                MethodIL fullMethodIL = ilProvider.GetMethodIL(fullMetadataMethod);
                ReadMetadataMethod(fullMethodIL, out result.StrongTypeMappings, out result.MethodMappings, out result.FieldMappings, ref metadataModules);
            }

            if (weakMetadataMethod != null)
            {
                MethodIL weakMethodIL = ilProvider.GetMethodIL(weakMetadataMethod);
                List <MetadataMapping <MethodDesc> > weakMethodMappings = new List <MetadataMapping <MethodDesc> >();
                List <MetadataMapping <FieldDesc> >  weakFieldMappings  = new List <MetadataMapping <FieldDesc> >();
                ReadMetadataMethod(weakMethodIL, out result.AllTypeMappings, out weakMethodMappings, out weakFieldMappings, ref metadataModules);
                if ((weakMethodMappings.Count > 0) || (weakFieldMappings.Count > 0))
                {
                    // the format does not permit weak field/method mappings
                    throw new BadImageFormatException();
                }
            }

#if DEBUG
            // No duplicates are permitted in metadata mappings
            HashSet <TypeSystemEntity> mappingsDuplicateChecker = new HashSet <TypeSystemEntity>();
            foreach (MetadataMapping <MetadataType> mapping in result.AllTypeMappings)
            {
                if (!mappingsDuplicateChecker.Add(mapping.Entity))
                {
                    throw new BadImageFormatException();
                }
            }

            foreach (MetadataMapping <MetadataType> mapping in result.StrongTypeMappings)
            {
                if (!mappingsDuplicateChecker.Add(mapping.Entity))
                {
                    throw new BadImageFormatException();
                }
            }

            foreach (MetadataMapping <FieldDesc> mapping in result.FieldMappings)
            {
                if (!mappingsDuplicateChecker.Add(mapping.Entity))
                {
                    throw new BadImageFormatException();
                }
            }

            foreach (MetadataMapping <MethodDesc> mapping in result.MethodMappings)
            {
                if (!mappingsDuplicateChecker.Add(mapping.Entity))
                {
                    throw new BadImageFormatException();
                }
            }
#endif

            // All type mappings is the combination of strong and weak type mappings.
            result.AllTypeMappings.AddRange(result.StrongTypeMappings);

            result.MetadataModules = ImmutableArray.CreateRange(metadataModules);

            ImmutableArray <ModuleDesc> .Builder externalMetadataModulesBuilder = ImmutableArray.CreateBuilder <ModuleDesc>();
            ImmutableArray <ModuleDesc> .Builder localMetadataModulesBuilder    = ImmutableArray.CreateBuilder <ModuleDesc>();
            foreach (ModuleDesc module in result.MetadataModules)
            {
                if (!_compilationModules.Contains(module))
                {
                    externalMetadataModulesBuilder.Add(module);
                }
                else
                {
                    localMetadataModulesBuilder.Add(module);
                }
            }
            result.ExternalMetadataModules = externalMetadataModulesBuilder.ToImmutable();
            result.LocalMetadataModules    = localMetadataModulesBuilder.ToImmutable();

            return(result);
        }
Ejemplo n.º 36
0
 public Node AddChild(Node child) => new Node(Name, Children.Add(child), ModulePath, FullModuleName);
Ejemplo n.º 37
0
 public SubscribedList(IObservable <T> source)
 {
     _subscription = source.Subscribe(x => { _list = _list.Add(x); });
 }
Ejemplo n.º 38
0
        public static Either <ParseException, Pair <List <IToken>, BodyNode> > Parse(List <IToken> tokens, SymT symT, IScopedTable <IEntityType, string> parentTypeTable)
        {
            Console.WriteLine("BodyNode");

            ImmutableArray <IAstNode> elements = ImmutableArray <IAstNode> .Empty;
            var typeTable = new Dictionary <string, IEntityType>();
            var result    = new BodyNode(ImmutableArray <IAstNode> .Empty, typeTable, parentTypeTable);

            while (tokens.Count > 0)
            {
                if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken ||
                    tokens[0] is SemicolonSymbolToken)
                {
                    tokens = tokens.Skip(1).ToList();
                }
                else
                {
                    break;
                }
            }

            while (true)
            {
                var maybeSimpleDeclaration1 = VariableDeclarationNode.Parse(tokens, symT, result);
                if (maybeSimpleDeclaration1.IsRight)
                {
                    tokens = maybeSimpleDeclaration1.RightToList()[0].First;
                    var varDecl = maybeSimpleDeclaration1.RightToList()[0].Second;
                    elements = elements.Add(varDecl);
                    typeTable.TryAdd(varDecl.Identifier.Lexeme, varDecl.ToVariableType());
                    while (tokens.Count > 0)
                    {
                        if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken ||
                            tokens[0] is SemicolonSymbolToken)
                        {
                            tokens = tokens.Skip(1).ToList();
                        }
                        else
                        {
                            break;
                        }
                    }
                    continue;
                }

                var maybeSimpleDeclaration2 = TypeDeclarationNode.Parse(tokens, symT, result);
                if (maybeSimpleDeclaration2.IsRight)
                {
                    tokens = maybeSimpleDeclaration2.RightToList()[0].First;
                    var typeDecl = maybeSimpleDeclaration2.RightToList()[0].Second;
                    elements = elements.Add(typeDecl);
                    typeTable.TryAdd(typeDecl.Identifier.Lexeme, typeDecl.ToTypeAliasType());
                    while (tokens.Count > 0)
                    {
                        if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken ||
                            tokens[0] is SemicolonSymbolToken)
                        {
                            tokens = tokens.Skip(1).ToList();
                        }
                        else
                        {
                            break;
                        }
                    }
                    continue;
                }

                var maybeStatement = StatementNode.Parse(tokens, symT, result);
                if (maybeStatement.IsRight)
                {
                    tokens   = maybeStatement.RightToList()[0].First;
                    elements = elements.Add(maybeStatement.RightToList()[0].Second);
                    while (tokens.Count > 0)
                    {
                        if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken ||
                            tokens[0] is SemicolonSymbolToken)
                        {
                            tokens = tokens.Skip(1).ToList();
                        }
                        else
                        {
                            break;
                        }
                    }
                    continue;
                }

                var maybeExpression = StatementNode.Parse(tokens, symT, result);
                if (maybeExpression.IsRight)
                {
                    tokens   = maybeExpression.RightToList()[0].First;
                    elements = elements.Add(maybeExpression.RightToList()[0].Second);
                    while (tokens.Count > 0)
                    {
                        if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken ||
                            tokens[0] is SemicolonSymbolToken)
                        {
                            tokens = tokens.Skip(1).ToList();
                        }
                        else
                        {
                            break;
                        }
                    }
                    continue;
                }

                break;
            }


            if (tokens.Count < 1)
            {
                return(NotABodyException);
            }
            if (!(tokens[0] is ReturnKeywordToken))
            {
                return(NotABodyException);
            }
            tokens = tokens.Skip(1).ToList();
            var maybeExpression1 = ExpressionNode.Parse(tokens, result);

            if (maybeExpression1.IsRight)
            {
                while (tokens.Count > 0)
                {
                    if (tokens[0] is NewLineSymbolToken || tokens[0] is CommentToken ||
                        tokens[0] is SemicolonSymbolToken)
                    {
                        tokens = tokens.Skip(1).ToList();
                    }
                    else
                    {
                        break;
                    }
                }
                tokens = maybeExpression1.RightToList()[0].First;

                result.Elements             = elements;
                result.ReturnExpressionNode = maybeExpression1.RightToList()[0].Second;
                var res = new Pair <List <IToken>, BodyNode>(tokens, result);

                return(res);
            }



            result.Elements = elements;
            return(new Pair <List <IToken>, BodyNode>(tokens, result));
        }
Ejemplo n.º 39
0
        public Dependency(IDependencyModel dependencyModel, ITargetFramework targetFramework, string containingProjectPath)
        {
            Requires.NotNull(dependencyModel, nameof(dependencyModel));
            Requires.NotNullOrEmpty(dependencyModel.ProviderType, nameof(dependencyModel.ProviderType));
            Requires.NotNullOrEmpty(dependencyModel.Id, nameof(dependencyModel.Id));
            Requires.NotNull(targetFramework, nameof(targetFramework));
            Requires.NotNullOrEmpty(containingProjectPath, nameof(containingProjectPath));

            TargetFramework = targetFramework;

            _modelId = dependencyModel.Id;
            _containingProjectPath = containingProjectPath;

            ProviderType     = dependencyModel.ProviderType;
            Name             = dependencyModel.Name ?? string.Empty;
            Caption          = dependencyModel.Caption ?? string.Empty;
            OriginalItemSpec = dependencyModel.OriginalItemSpec ?? string.Empty;
            Path             = dependencyModel.Path ?? string.Empty;
            SchemaName       = dependencyModel.SchemaName ?? Folder.SchemaName;
            _schemaItemType  = dependencyModel.SchemaItemType ?? Folder.PrimaryDataSourceItemType;
            Resolved         = dependencyModel.Resolved;
            TopLevel         = dependencyModel.TopLevel;
            Implicit         = dependencyModel.Implicit;
            Visible          = dependencyModel.Visible;
            Priority         = dependencyModel.Priority;
            Flags            = dependencyModel.Flags;

            // Just in case custom providers don't do it, add corresponding flags for Resolved state.
            // This is needed for tree update logic to track if tree node changing state from unresolved
            // to resolved or vice-versa (it helps to decide if we need to remove it or update in-place
            // in the tree to avoid flicks).
            if (Resolved)
            {
                if (!Flags.Contains(DependencyTreeFlags.ResolvedFlags))
                {
                    Flags += DependencyTreeFlags.ResolvedFlags;
                }
            }
            else
            {
                if (!Flags.Contains(DependencyTreeFlags.UnresolvedFlags))
                {
                    Flags += DependencyTreeFlags.UnresolvedFlags;
                }
            }

            // If this is one of our implementations of IDependencyModel then we can just reuse the icon
            // set rather than creating a new one.
            if (dependencyModel is DependencyModel model)
            {
                IconSet = model.IconSet;
            }
            else
            {
                IconSet = DependencyIconSetCache.Instance.GetOrAddIconSet(dependencyModel.Icon, dependencyModel.ExpandedIcon, dependencyModel.UnresolvedIcon, dependencyModel.UnresolvedExpandedIcon);
            }

            Properties = dependencyModel.Properties
                         ?? ImmutableStringDictionary <string> .EmptyOrdinal
                         .Add(Folder.IdentityProperty, Caption)
                         .Add(Folder.FullPathProperty, Path);

            if (dependencyModel.DependencyIDs == null || dependencyModel.DependencyIDs.Count == 0)
            {
                DependencyIDs = ImmutableArray <string> .Empty;
            }
            else
            {
                int count = dependencyModel.DependencyIDs.Count;
                ImmutableArray <string> .Builder ids = ImmutableArray.CreateBuilder <string>(count);
                for (int i = 0; i < count; i++)
                {
                    ids.Add(GetID(TargetFramework, ProviderType, dependencyModel.DependencyIDs[i]));
                }
                DependencyIDs = ids.MoveToImmutable();
            }
        }
Ejemplo n.º 40
0
        private static Command CreateCommand(Type type, VerbAttribute verbAttribute)
        {
            ImmutableArray <CommandArgument> .Builder arguments = ImmutableArray.CreateBuilder <CommandArgument>();
            ImmutableArray <CommandOption> .Builder   options   = ImmutableArray.CreateBuilder <CommandOption>();

            Dictionary <string, string> providerMap = type
                                                      .GetCustomAttributes <OptionValueProviderAttribute>()
                                                      .ToDictionary(f => f.PropertyName, f => f.ProviderName);

            foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                OptionAttribute optionAttribute = null;

                foreach (Attribute attribute in propertyInfo.GetCustomAttributes())
                {
                    if (attribute is HiddenAttribute)
                    {
                        optionAttribute = null;
                        break;
                    }
                    else if (attribute is ValueAttribute valueAttribute)
                    {
                        var argument = new CommandArgument(
                            index: valueAttribute.Index,
                            name: valueAttribute.MetaName,
                            description: valueAttribute.HelpText,
                            isRequired: valueAttribute.Required);

                        arguments.Add(argument);
                        break;
                    }
                    else if (optionAttribute == null)
                    {
                        optionAttribute = attribute as OptionAttribute;

                        if (optionAttribute != null)
                        {
                            continue;
                        }
                    }
                }

                if (optionAttribute != null)
                {
                    Debug.Assert(
                        propertyInfo.PropertyType != typeof(bool) || string.IsNullOrEmpty(optionAttribute.MetaValue),
                        $"{type.Name}.{propertyInfo.Name}");

                    var option = new CommandOption(
                        name: optionAttribute.LongName,
                        shortName: optionAttribute.ShortName,
                        metaValue: optionAttribute.MetaValue,
                        description: optionAttribute.HelpText,
                        additionalDescription: propertyInfo.GetCustomAttribute <AdditionalDescriptionAttribute>()?.Text,
                        isRequired: optionAttribute.Required,
                        valueProviderName: (providerMap.TryGetValue(propertyInfo.Name, out string valueProviderName))
                            ? valueProviderName
                            : null);

                    options.Add(option);
                }
            }

            CommandGroupAttribute commandGroupAttribute = type.GetCustomAttribute <CommandGroupAttribute>() !;

            return(new Command(
                       verbAttribute.Name,
                       verbAttribute.HelpText,
                       (commandGroupAttribute != null)
                    ? new CommandGroup(commandGroupAttribute.Name, commandGroupAttribute.Ordinal)
                    : CommandGroup.Default,
                       arguments.OrderBy(f => f.Index),
                       options.OrderBy(f => f, CommandOptionComparer.Name)));
        }
Ejemplo n.º 41
0
 internal static ImmutableArray <T> Concat <T>(this ImmutableArray <T> first, T second)
 {
     return(first.Add(second));
 }
Ejemplo n.º 42
0
 public void Add(T subscriber)
 {
     lock (_subLock)
         _subscriptions = _subscriptions.Add(subscriber);
 }
Ejemplo n.º 43
0
        private ImmutableArray <ArchiveFileSection> ReadRawStreamList()
        {
            var rawStreamBaseOffset = ReadNumberAsInt64() + ArchiveMetadataFormat.kHeaderLength;

            if (rawStreamBaseOffset < 0)
            {
                throw new InvalidDataException();
            }

            var rawStreamCount = ReadNumberAsInt32();

            SkipToToken(ArchiveMetadataToken.Size);

            var rawStreamSizes = new long[rawStreamCount];

            for (int i = 0; i < rawStreamCount; i++)
            {
                rawStreamSizes[i] = ReadNumberAsInt64();
            }

            ImmutableArray <ArchiveFileSection> .Builder rawStreamListBuilder = null;

            for (;;)
            {
                var token = ReadToken();
                if (token == ArchiveMetadataToken.CRC)
                {
                    var vector          = ReadOptionalBitVector(rawStreamCount);
                    var rawStreamOffset = rawStreamBaseOffset;
                    rawStreamListBuilder = ImmutableArray.CreateBuilder <ArchiveFileSection>(rawStreamCount);

                    for (int i = 0; i < rawStreamCount; i++)
                    {
                        var length   = rawStreamSizes[i];
                        var checksum = default(Checksum?);
                        if (vector[i])
                        {
                            checksum = new Checksum(ReadInt32());
                        }

                        rawStreamListBuilder.Add(new ArchiveFileSection(rawStreamOffset, length, checksum));
                        rawStreamOffset += length;
                    }
                }
                else if (token == ArchiveMetadataToken.End)
                {
                    if (rawStreamListBuilder == null)
                    {
                        var rawStreamOffset = rawStreamBaseOffset;
                        rawStreamListBuilder = ImmutableArray.CreateBuilder <ArchiveFileSection>(rawStreamCount);

                        for (int i = 0; i < rawStreamCount; i++)
                        {
                            var length = rawStreamSizes[i];
                            rawStreamListBuilder.Add(new ArchiveFileSection(rawStreamOffset, length, null));
                            rawStreamOffset += length;
                        }
                    }

                    return(rawStreamListBuilder.MoveToImmutable());
                }
                else
                {
                    SkipDataBlock();
                }
            }
        }
Ejemplo n.º 44
0
 public void Add(T item)
 {
     _builder.Add(item);
 }
Ejemplo n.º 45
0
 private void AddAnalyzerCommentRegularExpression(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     if (!AnalyzerIds.Contains(CommentRegularExpression.DiagnosticId))
     {
         return;
     }
     var rules = ImmutableArray.CreateBuilder<CommentRegularExpressionRule>();
     foreach (var parameters in Parameters[CommentRegularExpression.DiagnosticId])
     {
         rules.Add(
             new CommentRegularExpressionRule
             {
                 // TODO: Add rule description
                 Descriptor = CommentRegularExpression.CreateDiagnosticDescriptor(parameters["RuleKey"], parameters["message"]),
                 RegularExpression = parameters["regularExpression"]
             });
     }
     var analyzer = new CommentRegularExpression {RuleInstances = rules.ToImmutable()};
     builder.Add(analyzer);
 }
Ejemplo n.º 46
0
        private static void ParseMethodOrPropertySignature(ImmutableArray<byte>.Builder builder, Stream stream)
        {
            int paramCount = stream.ReadByte();
            builder.Add((byte)paramCount);

            // Return type
            ParseType(builder, stream);

            // Parameters
            for (int i = 0; i < paramCount; i++)
            {
                ParseType(builder, stream, allowByRef: true);
            }
        }
Ejemplo n.º 47
0
 private void AddAnalyzerClassName(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     var analyzer = new ClassName();
     if (!AnalyzerIds.Contains(analyzer.SupportedDiagnostics.Single().Id))
     {
         return;
     }
     analyzer.Convention = Parameters[analyzer.SupportedDiagnostics.Single().Id].Single()["format"];
     builder.Add(analyzer);
 }
Ejemplo n.º 48
0
        private static void ParseGenericTypeInstance(ImmutableArray<byte>.Builder builder, Stream stream)
        {
            ParseType(builder, stream);

            // Generic type parameters
            int argumentCount = stream.ReadByte();
            builder.Add((byte)argumentCount);
            for (int i = 0; i < argumentCount; i++)
            {
                ParseType(builder, stream);
            }
        }
Ejemplo n.º 49
0
 private void AddAnalyzerTooManyLabelsInSwitch(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     var analyzer = new TooManyLabelsInSwitch();
     if (!AnalyzerIds.Contains(analyzer.SupportedDiagnostics.Single().Id))
     {
         return;
     }
     analyzer.Maximum = int.Parse(
         Parameters[analyzer.SupportedDiagnostics.Single().Id].Single()["maximum"],
         NumberStyles.None, CultureInfo.InvariantCulture);
     builder.Add(analyzer);
 }
        public void CollectBlockSpans(SyntaxTree syntaxTree, SyntaxTrivia trivia, ImmutableArray<BlockSpan>.Builder spans, CancellationToken cancellationToken)
        {
            // We'll always be leading trivia of some token.
            var startPos = trivia.FullSpan.Start;
            var endPos = trivia.FullSpan.End;

            // Look through our parent token's trivia, to:
            // 1. See if we're the first disabled trivia attached to the token.
            // 2. To extend the span to the end of the last disabled trivia.
            //
            // The issue is that if there are other pre-processor directives (like #regions or
            // #lines) mixed in the disabled code, they will be interleaved.  Keep walking past
            // them to the next thing that will actually end a disabled block. When we encounter
            // one, we must also consider which opening block they end. In case of nested pre-processor
            // directives, the inner most end block should match the inner most open block and so on.
            var parentTriviaList = trivia.Token.LeadingTrivia;
            var indexInParent = parentTriviaList.IndexOf(trivia);

            // Note: in some error cases (for example when all future tokens end up being skipped)
            // the parser may end up attaching pre-processor directives as trailing trivia to a 
            // preceding token.
            if (indexInParent < 0)
            {
                parentTriviaList = trivia.Token.TrailingTrivia;
                indexInParent = parentTriviaList.IndexOf(trivia);
            }

            if (indexInParent <= 0 ||
                (!parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.IfDirectiveTrivia) &&
                 !parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.ElifDirectiveTrivia) &&
                 !parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.ElseDirectiveTrivia)))
            {
                return;
            }

            var nestedIfDirectiveTrivia = 0;
            for (int i = indexInParent; i < parentTriviaList.Count; i++)
            {
                if (parentTriviaList[i].IsKind(SyntaxKind.IfDirectiveTrivia))
                {
                    nestedIfDirectiveTrivia++;
                }

                if (parentTriviaList[i].IsKind(SyntaxKind.EndIfDirectiveTrivia) ||
                    parentTriviaList[i].IsKind(SyntaxKind.ElifDirectiveTrivia) ||
                    parentTriviaList[i].IsKind(SyntaxKind.ElseDirectiveTrivia))
                {
                    if (nestedIfDirectiveTrivia > 0)
                    {
                        nestedIfDirectiveTrivia--;
                    }
                    else
                    {
                        endPos = parentTriviaList[i - 1].FullSpan.End;
                        break;
                    }
                }
            }

            // Now, exclude the last newline if there is one.
            var text = syntaxTree.GetText(cancellationToken);
            if (endPos > 1 && text[endPos - 1] == '\n' && text[endPos - 2] == '\r')
            {
                endPos -= 2;
            }
            else if (endPos > 0 && SyntaxFacts.IsNewLine(text[endPos - 1]))
            {
                endPos--;
            }

            var span = TextSpan.FromBounds(startPos, endPos);
            spans.Add(new BlockSpan(
                isCollapsible: true,
                textSpan: span,
                bannerText: CSharpStructureHelpers.Ellipsis,
                autoCollapse: true));
        }
        /// <summary>
        /// Produces the series of statements to build the current HLSL source.
        /// </summary>
        /// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
        /// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
        private static ImmutableArray <StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo)
        {
            ImmutableArray <StatementSyntax> .Builder statements = ImmutableArray.CreateBuilder <StatementSyntax>();
            StringBuilder textBuilder        = new();
            int           capturedDelegates  = 0;
            int           prologueStatements = 0;
            int           sizeHint           = 64;

            void AppendLF()
            {
                textBuilder.Append('\n');
            }

            void AppendLine(string text)
            {
                textBuilder.Append(text);
            }

            void AppendParsedStatement(string text)
            {
                FlushText();

                statements.Add(ParseStatement(text));
            }

            void FlushText()
            {
                if (textBuilder.Length > 0)
                {
                    string text = textBuilder.ToString();

                    textBuilder.Append(text);

                    sizeHint += textBuilder.Length;

                    statements.Add(
                        ExpressionStatement(
                            InvocationExpression(
                                MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
                            .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text))))));

                    textBuilder.Clear();
                }
            }

            // Declare the hashsets to track imported members and types from delegates, if needed
            if (!hlslSourceInfo.Delegates.IsEmpty)
            {
                void DeclareMapping(int index, string name, IEnumerable <string> items)
                {
                    // global::System.Collections.Generic.HashSet<string> <NAME> = new();
                    statements.Insert(index,
                                      LocalDeclarationStatement(VariableDeclaration(
                                                                    GenericName(Identifier("global::System.Collections.Generic.HashSet"))
                                                                    .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
                                                                .AddVariables(
                                                                    VariableDeclarator(Identifier(name))
                                                                    .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));

                    prologueStatements++;

                    // <NAME>.Add("<ITEM>");
                    foreach (var item in items)
                    {
                        statements.Add(
                            ExpressionStatement(
                                InvocationExpression(
                                    MemberAccessExpression(
                                        SyntaxKind.SimpleMemberAccessExpression,
                                        IdentifierName(name),
                                        IdentifierName("Add")))
                                .AddArgumentListArguments(Argument(
                                                              LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));

                        prologueStatements++;
                    }
                }

                DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
                DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
                DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);

                // Go through all existing delegate fields, if any
                foreach (string fieldName in hlslSourceInfo.Delegates)
                {
                    // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
                    statements.Add(
                        LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
                                                  .AddVariables(
                                                      VariableDeclarator(Identifier($"__{fieldName}Attribute"))
                                                      .WithInitializer(
                                                          EqualsValueClause(
                                                              InvocationExpression(
                                                                  MemberAccessExpression(
                                                                      SyntaxKind.SimpleMemberAccessExpression,
                                                                      IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
                                                                      IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
                                                              .AddArgumentListArguments(
                                                                  Argument(IdentifierName(fieldName)),
                                                                  Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));

                    capturedDelegates++;
                    prologueStatements++;
                }
            }

            // Header and thread ids
            AppendLine(hlslSourceInfo.HeaderAndThreadsX);
            AppendParsedStatement("builder.Append(threadsX);");
            AppendLine(hlslSourceInfo.ThreadsY);
            AppendParsedStatement("builder.Append(threadsY);");
            AppendLine(hlslSourceInfo.ThreadsZ);
            AppendParsedStatement("builder.Append(threadsZ);");

            // Define declarations
            AppendLine(hlslSourceInfo.Defines);

            // Defines from captured delegates
            foreach (string fieldName in hlslSourceInfo.Delegates)
            {
                AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
            }

            // Static fields and declared types
            AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);

            // Declared types from captured delegates
            foreach (string fieldName in hlslSourceInfo.Delegates)
            {
                AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
            }

            // Captured variables
            AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);

            // Forward declarations from captured delegates
            foreach (string fieldName in hlslSourceInfo.Delegates)
            {
                AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
            }

            // Remove all forward declarations from methods that are embedded into the shader.
            // This is necessary to avoid duplicate definitions from methods from delegates.
            if (capturedDelegates > 0)
            {
                // <NAME>.Add("<ITEM>");
                foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
                {
                    FlushText();

                    statements.Add(
                        ExpressionStatement(
                            InvocationExpression(
                                MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    IdentifierName("__methodNames"),
                                    IdentifierName("Remove")))
                            .AddArgumentListArguments(Argument(
                                                          LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
                }
            }

            // Captured methods
            AppendLine(hlslSourceInfo.CapturedMethods);

            // Captured methods from captured delegates
            foreach (string fieldName in hlslSourceInfo.Delegates)
            {
                AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
            }

            // Captured delegate methods
            foreach (string fieldName in hlslSourceInfo.Delegates)
            {
                AppendLF();
                AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
                AppendLF();
            }

            // Entry point
            AppendLine(hlslSourceInfo.EntryPoint);

            FlushText();

            // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(<SIZE_HINT>);
            statements.Insert(
                prologueStatements,
                ExpressionStatement(
                    AssignmentExpression(
                        SyntaxKind.SimpleAssignmentExpression,
                        IdentifierName("builder"),
                        InvocationExpression(
                            MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
                                IdentifierName("Create")))
                        .AddArgumentListArguments(
                            Argument(LiteralExpression(
                                         SyntaxKind.NumericLiteralExpression,
                                         Literal(sizeHint)))))));

            return(statements.ToImmutable());
        }
 private static void AddIndentation(this ImmutableArray <SymbolDisplayPart> .Builder builder)
 {
     builder.Add(SymbolDisplayPartFactory.Indentation());
 }
Ejemplo n.º 53
0
        /// <summary>
        /// Gets a sequence of statements to load the input descriptions for a given shader.
        /// </summary>
        /// <param name="inputDescriptions">The array of <see cref="InputDescription"/> values for all available input descriptions.</param>
        /// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
        private static ImmutableArray <StatementSyntax> GetInputDescriptionsLoadingStatements(ImmutableArray <InputDescription> inputDescriptions)
        {
            // If there are no input descriptions available, just load an empty buffer
            if (inputDescriptions.IsEmpty)
            {
                // loader.LoadInputDescriptions(default);
                return
                    (ImmutableArray.Create <StatementSyntax>(
                         ExpressionStatement(
                             InvocationExpression(
                                 MemberAccessExpression(
                                     SyntaxKind.SimpleMemberAccessExpression,
                                     IdentifierName("loader"),
                                     IdentifierName("LoadInputDescriptions")))
                             .AddArgumentListArguments(Argument(
                                                           LiteralExpression(
                                                               SyntaxKind.DefaultLiteralExpression,
                                                               Token(SyntaxKind.DefaultKeyword)))))));
            }

            ImmutableArray <StatementSyntax> .Builder statements = ImmutableArray.CreateBuilder <StatementSyntax>();

            // The size of the buffer with the input descriptions is the number of input descriptions, times the size of each
            // input description, which is a struct containing three int-sized fields (index, filter, and level of detail).
            int inputDescriptionSizeInBytes = inputDescriptions.Length * sizeof(int) * 3;

            // global::System.Span<byte> data = stackalloc byte[<INPUT_DESCRIPTIONS_SIZE>];
            statements.Insert(0,
                              LocalDeclarationStatement(
                                  VariableDeclaration(
                                      GenericName(Identifier("global::System.Span"))
                                      .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
                                  .AddVariables(
                                      VariableDeclarator(Identifier("data"))
                                      .WithInitializer(EqualsValueClause(
                                                           StackAllocArrayCreationExpression(
                                                               ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
                                                               .AddRankSpecifiers(
                                                                   ArrayRankSpecifier(SingletonSeparatedList <ExpressionSyntax>(
                                                                                          LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescriptionSizeInBytes)))))))))));

            // ref byte r0 = ref data[0];
            statements.Insert(1,
                              LocalDeclarationStatement(
                                  VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
                                  .AddVariables(
                                      VariableDeclarator(Identifier("r0"))
                                      .WithInitializer(EqualsValueClause(
                                                           RefExpression(
                                                               ElementAccessExpression(IdentifierName("data"))
                                                               .AddArgumentListArguments(Argument(
                                                                                             LiteralExpression(
                                                                                                 SyntaxKind.NumericLiteralExpression,
                                                                                                 Literal(0))))))))));

            int offset = 0;

            // Generate loading statements for each input description
            foreach (InputDescription inputDescription in inputDescriptions)
            {
                // Write the index of the current input description:
                //
                // global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <INDEX>;
                statements.Add(ExpressionStatement(
                                   AssignmentExpression(
                                       SyntaxKind.SimpleAssignmentExpression,
                                       ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset}))"),
                                       LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.Index)))));

                // Write the filter of the current input description:
                //
                // global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET> + 4)) = <FILTER>;
                statements.Add(ExpressionStatement(
                                   AssignmentExpression(
                                       SyntaxKind.SimpleAssignmentExpression,
                                       ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 4}))"),
                                       LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.Filter)))));

                // Write the level of detail of the current input description:
                //
                // global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET> + 8)) = <LEVEL_OF_DETAIL>;
                statements.Add(ExpressionStatement(
                                   AssignmentExpression(
                                       SyntaxKind.SimpleAssignmentExpression,
                                       ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 8}))"),
                                       LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.LevelOfDetail)))));

                offset += sizeof(int) * 3;
            }

            // loader.LoadInputDescriptions(data);
            statements.Add(
                ExpressionStatement(
                    InvocationExpression(
                        MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            IdentifierName("loader"),
                            IdentifierName("LoadInputDescriptions")))
                    .AddArgumentListArguments(Argument(IdentifierName("data")))));

            return(statements.ToImmutable());
        }
 private static void AddLineBreak(this ImmutableArray <SymbolDisplayPart> .Builder builder)
 {
     builder.Add(SymbolDisplayPartFactory.LineBreak());
 }
        public static ImmutableArray <SymbolDisplayPart> GetDisplayParts(
            ISymbol symbol,
            SymbolDisplayFormat format,
            SymbolDisplayTypeDeclarationOptions typeDeclarationOptions = SymbolDisplayTypeDeclarationOptions.None,
            Func <INamedTypeSymbol, bool> isVisibleAttribute           = null,
            bool formatBaseList            = false,
            bool formatConstraints         = false,
            bool formatParameters          = false,
            bool splitAttributes           = true,
            bool includeAttributeArguments = false,
            bool omitIEnumerable           = false,
            bool useNameOnlyIfPossible     = false)
        {
            ImmutableArray <SymbolDisplayPart> parts;

            if (symbol is INamedTypeSymbol typeSymbol)
            {
                parts = typeSymbol.ToDisplayParts(format, typeDeclarationOptions);
            }
            else
            {
                parts      = symbol.ToDisplayParts(format);
                typeSymbol = null;
            }

            ImmutableArray <AttributeData> attributes = ImmutableArray <AttributeData> .Empty;
            bool hasAttributes = false;

            if (isVisibleAttribute != null)
            {
                attributes = symbol.GetAttributes();

                hasAttributes = attributes.Any(f => isVisibleAttribute(f.AttributeClass));
            }

            int baseListCount         = 0;
            INamedTypeSymbol baseType = null;
            ImmutableArray <INamedTypeSymbol> interfaces = default;

            if (typeSymbol != null)
            {
                if (typeSymbol.TypeKind.Is(TypeKind.Class, TypeKind.Interface))
                {
                    baseType = typeSymbol.BaseType;

                    if (baseType?.SpecialType == SpecialType.System_Object)
                    {
                        baseType = null;
                    }
                }

                interfaces = typeSymbol.Interfaces;

                if (omitIEnumerable &&
                    interfaces.Any(f => f.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T))
                {
                    interfaces = interfaces.RemoveAll(f => f.SpecialType == SpecialType.System_Collections_IEnumerable);
                }

                baseListCount = interfaces.Length;

                if (baseType != null)
                {
                    baseListCount++;
                }
            }

            int constraintCount = 0;
            int whereIndex      = -1;

            for (int i = 0; i < parts.Length; i++)
            {
                if (parts[i].IsKeyword("where"))
                {
                    if (whereIndex == -1)
                    {
                        whereIndex = i;
                    }

                    constraintCount++;
                }
            }

            if (!hasAttributes &&
                baseListCount == 0 &&
                constraintCount == 0 &&
                (!formatParameters || symbol.GetParameters().Length <= 1))
            {
                return(parts);
            }

            INamespaceSymbol containingNamespace = (useNameOnlyIfPossible) ? symbol.ContainingNamespace : null;

            ImmutableArray <SymbolDisplayPart> .Builder builder = ImmutableArray.CreateBuilder <SymbolDisplayPart>(parts.Length);

            AddAttributes(builder, attributes, isVisibleAttribute, containingNamespace, splitAttributes: splitAttributes, includeAttributeArguments: includeAttributeArguments);

            if (baseListCount > 0)
            {
                if (whereIndex != -1)
                {
                    builder.AddRange(parts, whereIndex);
                }
                else
                {
                    builder.AddRange(parts);
                    builder.AddSpace();
                }

                builder.AddPunctuation(":");
                builder.AddSpace();

                if (baseType != null)
                {
                    builder.AddDisplayParts(baseType, containingNamespace);

                    if (interfaces.Any())
                    {
                        builder.AddPunctuation(",");

                        if (formatBaseList)
                        {
                            builder.AddLineBreak();
                            builder.AddIndentation();
                        }
                        else
                        {
                            builder.AddSpace();
                        }
                    }
                }

                interfaces = interfaces.Sort((x, y) =>
                {
                    INamespaceSymbol n1 = x.ContainingNamespace;
                    INamespaceSymbol n2 = y.ContainingNamespace;

                    if (!MetadataNameEqualityComparer <INamespaceSymbol> .Instance.Equals(n1, n2))
                    {
                        return(string.CompareOrdinal(
                                   n1.ToDisplayString(SymbolDisplayFormats.TypeNameAndContainingTypesAndNamespaces),
                                   n2.ToDisplayString(SymbolDisplayFormats.TypeNameAndContainingTypesAndNamespaces)));
                    }

                    return(string.CompareOrdinal(
                               ToDisplayString(x, containingNamespace),
                               ToDisplayString(y, containingNamespace)));
                });

                ImmutableArray <INamedTypeSymbol> .Enumerator en = interfaces.GetEnumerator();

                if (en.MoveNext())
                {
                    while (true)
                    {
                        builder.AddDisplayParts(en.Current, containingNamespace);

                        if (en.MoveNext())
                        {
                            builder.AddPunctuation(",");

                            if (formatBaseList)
                            {
                                builder.AddLineBreak();
                                builder.AddIndentation();
                            }
                            else
                            {
                                builder.AddSpace();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if (whereIndex != -1)
                {
                    if (!formatConstraints ||
                        (baseListCount == 1 && constraintCount == 1))
                    {
                        builder.AddSpace();
                    }
                }
            }
            else if (whereIndex != -1)
            {
                builder.AddRange(parts, whereIndex);
            }
            else
            {
                builder.AddRange(parts);
            }

            if (whereIndex != -1)
            {
                for (int i = whereIndex; i < parts.Length; i++)
                {
                    if (parts[i].IsKeyword("where"))
                    {
                        if (formatConstraints &&
                            (baseListCount > 1 || constraintCount > 1))
                        {
                            builder.AddLineBreak();
                            builder.AddIndentation();
                        }

                        builder.Add(parts[i]);
                    }
                    else if (parts[i].IsTypeName() &&
                             parts[i].Symbol is INamedTypeSymbol namedTypeSymbol)
                    {
                        builder.AddDisplayParts(namedTypeSymbol, containingNamespace);
                    }
                    else
                    {
                        builder.Add(parts[i]);
                    }
                }
            }

            if (formatParameters)
            {
                ImmutableArray <IParameterSymbol> parameters = symbol.GetParameters();

                if (parameters.Length > 1)
                {
                    FormatParameters(symbol, builder, DeclarationListOptions.DefaultValues.IndentChars);
                }
            }

            return(builder.ToImmutableArray());
        }
Ejemplo n.º 56
0
 private void AddAnalyzerCommentRegularExpression(ImmutableArray<DiagnosticAnalyzer>.Builder builder)
 {
     if (!AnalyzerIds.Contains(Rules.CSharp.CommentRegularExpression.TemplateDiagnosticId))
     {
         return;
     }
     var rules = ImmutableArray.CreateBuilder<CommentRegularExpression.CommentRegularExpressionRule>();
     foreach (var parameterValues in parameters
         .Where(p => p.RuleId == CommentRegularExpression.TemplateDiagnosticId)
         .Select(p => p.ParameterValues))
     {
         rules.Add(
             new CommentRegularExpression.CommentRegularExpressionRule(
                 parameterValues.Single(pv => pv.ParameterKey == "RuleKey").ParameterValue,
                 parameterValues.Single(pv => pv.ParameterKey == "regularExpression").ParameterValue,
                 parameterValues.Single(pv => pv.ParameterKey == "message").ParameterValue));
     }
     var analyzer = new CommentRegularExpression {RuleInstances = rules.ToImmutable()};
     builder.Add(analyzer);
 }
Ejemplo n.º 57
0
        private static void ParseType(ImmutableArray<byte>.Builder builder, Stream stream, bool allowByRef = false)
        {
            while (true)
            {
                var typeCode = (SignatureTypeCode)stream.ReadByte();
                builder.Add((byte)typeCode);

                switch (typeCode)
                {
                    default:
                        throw ExceptionUtilities.UnexpectedValue(typeCode);

                    case SignatureTypeCode.TypeHandle:
                    case SignatureTypeCode.GenericTypeParameter:
                    case SignatureTypeCode.GenericMethodParameter:
                        builder.Add((byte)stream.ReadByte());
                        return;

                    case SignatureTypeCode.ByReference:
                        if (!allowByRef) goto default;
                        break;

                    case SignatureTypeCode.SZArray:
                        break;

                    case SignatureTypeCode.Pointer:
                        break;

                    case SignatureTypeCode.GenericTypeInstance:
                        ParseGenericTypeInstance(builder, stream);
                        return;
                }

                allowByRef = false;
            }
        }
        private static void AddAttributes(
            ImmutableArray <SymbolDisplayPart> .Builder builder,
            ImmutableArray <AttributeData> attributes,
            Func <INamedTypeSymbol, bool> predicate = null,
            INamespaceSymbol containingNamespace    = null,
            bool splitAttributes           = true,
            bool includeAttributeArguments = false,
            bool isAssemblyAttribute       = false,
            bool addNewLine = true)
        {
            using (IEnumerator <AttributeData> en = attributes
                                                    .Where(f => predicate(f.AttributeClass))
                                                    .OrderBy(f => ToDisplayString(f.AttributeClass, containingNamespace)).GetEnumerator())
            {
                if (en.MoveNext())
                {
                    builder.AddPunctuation("[");

                    if (isAssemblyAttribute)
                    {
                        builder.AddKeyword("assembly");
                        builder.AddPunctuation(":");
                        builder.AddSpace();
                    }

                    while (true)
                    {
                        builder.AddDisplayParts(en.Current.AttributeClass, containingNamespace);

                        if (includeAttributeArguments)
                        {
                            AddAttributeArguments(en.Current);
                        }

                        if (en.MoveNext())
                        {
                            if (splitAttributes)
                            {
                                builder.AddPunctuation("]");

                                if (addNewLine)
                                {
                                    builder.AddLineBreak();
                                }
                                else
                                {
                                    builder.AddSpace();
                                }

                                builder.AddPunctuation("[");

                                if (isAssemblyAttribute)
                                {
                                    builder.AddKeyword("assembly");
                                    builder.AddPunctuation(":");
                                    builder.AddSpace();
                                }
                            }
                            else
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    builder.AddPunctuation("]");

                    if (addNewLine)
                    {
                        builder.AddLineBreak();
                    }
                }
            }

            void AddAttributeArguments(AttributeData attributeData)
            {
                bool hasConstructorArgument = false;
                bool hasNamedArgument       = false;

                AppendConstructorArguments();
                AppendNamedArguments();

                if (hasConstructorArgument || hasNamedArgument)
                {
                    builder.AddPunctuation(")");
                }

                void AppendConstructorArguments()
                {
                    ImmutableArray <TypedConstant> .Enumerator en = attributeData.ConstructorArguments.GetEnumerator();

                    if (en.MoveNext())
                    {
                        hasConstructorArgument = true;
                        builder.AddPunctuation("(");

                        while (true)
                        {
                            AddConstantValue(en.Current);

                            if (en.MoveNext())
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                void AppendNamedArguments()
                {
                    ImmutableArray <KeyValuePair <string, TypedConstant> > .Enumerator en = attributeData.NamedArguments.GetEnumerator();

                    if (en.MoveNext())
                    {
                        hasNamedArgument = true;

                        if (hasConstructorArgument)
                        {
                            builder.AddPunctuation(",");
                            builder.AddSpace();
                        }
                        else
                        {
                            builder.AddPunctuation("(");
                        }

                        while (true)
                        {
                            builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, null, en.Current.Key));
                            builder.AddSpace();
                            builder.AddPunctuation("=");
                            builder.AddSpace();
                            AddConstantValue(en.Current.Value);

                            if (en.MoveNext())
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }

            void AddConstantValue(TypedConstant typedConstant)
            {
                switch (typedConstant.Kind)
                {
                case TypedConstantKind.Primitive:
                {
                    builder.Add(new SymbolDisplayPart(
                                    GetSymbolDisplayPart(typedConstant.Type.SpecialType),
                                    null,
                                    SymbolDisplay.FormatPrimitive(typedConstant.Value, quoteStrings: true, useHexadecimalNumbers: false)));

                    break;
                }

                case TypedConstantKind.Enum:
                {
                    OneOrMany <EnumFieldInfo> oneOrMany = EnumUtility.GetConstituentFields(typedConstant.Value, (INamedTypeSymbol)typedConstant.Type);

                    OneOrMany <EnumFieldInfo> .Enumerator en = oneOrMany.GetEnumerator();

                    if (en.MoveNext())
                    {
                        while (true)
                        {
                            AddDisplayParts(builder, en.Current.Symbol, containingNamespace);

                            if (en.MoveNext())
                            {
                                builder.AddSpace();
                                builder.AddPunctuation("|");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        builder.AddPunctuation("(");
                        AddDisplayParts(builder, (INamedTypeSymbol)typedConstant.Type, containingNamespace);
                        builder.AddPunctuation(")");
                        builder.Add(new SymbolDisplayPart(SymbolDisplayPartKind.NumericLiteral, null, typedConstant.Value.ToString()));
                    }

                    break;
                }

                case TypedConstantKind.Type:
                {
                    builder.AddKeyword("typeof");
                    builder.AddPunctuation("(");
                    AddDisplayParts(builder, (ISymbol)typedConstant.Value, containingNamespace);
                    builder.AddPunctuation(")");

                    break;
                }

                case TypedConstantKind.Array:
                {
                    var arrayType = (IArrayTypeSymbol)typedConstant.Type;

                    builder.AddKeyword("new");
                    builder.AddSpace();
                    AddDisplayParts(builder, arrayType.ElementType, containingNamespace);

                    builder.AddPunctuation("[");
                    builder.AddPunctuation("]");
                    builder.AddSpace();
                    builder.AddPunctuation("{");
                    builder.AddSpace();

                    ImmutableArray <TypedConstant> .Enumerator en = typedConstant.Values.GetEnumerator();

                    if (en.MoveNext())
                    {
                        while (true)
                        {
                            AddConstantValue(en.Current);

                            if (en.MoveNext())
                            {
                                builder.AddPunctuation(",");
                                builder.AddSpace();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    builder.AddSpace();
                    builder.AddPunctuation("}");
                    break;
                }

                default:
                {
                    throw new InvalidOperationException();
                }
                }

                SymbolDisplayPartKind GetSymbolDisplayPart(SpecialType specialType)
                {
                    switch (specialType)
                    {
                    case SpecialType.System_Boolean:
                        return(SymbolDisplayPartKind.Keyword);

                    case SpecialType.System_SByte:
                    case SpecialType.System_Byte:
                    case SpecialType.System_Int16:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_UInt64:
                    case SpecialType.System_Single:
                    case SpecialType.System_Double:
                        return(SymbolDisplayPartKind.NumericLiteral);

                    case SpecialType.System_Char:
                    case SpecialType.System_String:
                        return(SymbolDisplayPartKind.StringLiteral);

                    default:
                        throw new InvalidOperationException();
                    }
                }
            }
        }
Ejemplo n.º 59
0
        private void AddInheritanceName(
            ImmutableArray<string>.Builder builder, TypeSyntax type,
            List<Dictionary<string, string>> aliasMaps)
        {
            var name = GetTypeName(type);
            if (name != null)
            {
                // First, add the name that the typename that the type directly says it inherits from.
                builder.Add(name);

                // Now, walk the alias chain and add any names this alias may eventually map to.
                var currentName = name;
                foreach (var aliasMap in aliasMaps)
                {
                    string mappedName;
                    if (aliasMap.TryGetValue(currentName, out mappedName))
                    {
                        // Looks like this could be an alias.  Also include the name the alias points to
                        builder.Add(mappedName);

                        // Keep on searching.  An alias in an inner namespcae can refer to an 
                        // alias in an outer namespace.  
                        currentName = mappedName;
                    }
                }
            }
        }
 private static void AddSpace(this ImmutableArray <SymbolDisplayPart> .Builder builder)
 {
     builder.Add(SymbolDisplayPartFactory.Space());
 }