// Populate the treeview with the contents of the SyntaxTree corresponding to the code document
        // that is currently active in the editor.
        private void RefreshSyntaxVisualizer()
        {
            if (IsVisible && activeWpfTextView != null)
            {
                var snapshot    = activeWpfTextView.TextBuffer.CurrentSnapshot;
                var contentType = snapshot.ContentType;

                if (contentType.IsOfType(VisualBasicContentType) ||
                    contentType.IsOfType(CSharpContentType))
                {
                    // Get the Document corresponding to the currently active text snapshot.
                    var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
                    if (document != null)
                    {
                        // Get the SyntaxTree and SemanticModel corresponding to the Document.
                        activeSyntaxTree = ThreadHelper.JoinableTaskFactory.Run(() => document.GetSyntaxTreeAsync());
                        var activeSemanticModel = ThreadHelper.JoinableTaskFactory.Run(() => document.GetSemanticModelAsync());

                        // Display the SyntaxTree.
                        if ((contentType.IsOfType(VisualBasicContentType) || contentType.IsOfType(CSharpContentType)) && activeSyntaxTree is not null)
                        {
                            syntaxVisualizer.DisplaySyntaxTree(activeSyntaxTree, activeSemanticModel, workspace: document.Project.Solution.Workspace);
                        }

                        NavigateFromSource();
                    }
                }
            }
        }
示例#2
0
        internal TodoCommentData CreateSerializableData(
            Document document, SourceText text, SyntaxTree?tree)
        {
            // make sure given position is within valid text range.
            var textSpan = new TextSpan(Math.Min(text.Length, Math.Max(0, Position)), 0);

            var location = tree == null
                ? Location.Create(document.FilePath !, textSpan, text.Lines.GetLinePositionSpan(textSpan))
                : tree.GetLocation(textSpan);

            var originalLineInfo = location.GetLineSpan();
            var mappedLineInfo   = location.GetMappedLineSpan();

            return(new TodoCommentData
            {
                Priority = Descriptor.Priority,
                Message = Message,
                DocumentId = document.Id,
                OriginalLine = originalLineInfo.StartLinePosition.Line,
                OriginalColumn = originalLineInfo.StartLinePosition.Character,
                OriginalFilePath = document.FilePath,
                MappedLine = mappedLineInfo.StartLinePosition.Line,
                MappedColumn = mappedLineInfo.StartLinePosition.Character,
                MappedFilePath = mappedLineInfo.GetMappedFilePathIfExist(),
            });
        }
示例#3
0
            public CSharpCompilation updateCompilation(CSharpCompilation compilation, CSharpParseOptions options,
                                                       string assemblyName, string generatedFilesDir)
            {
                if (javaFilesDict.Count == 0)
                {
                    return(compilation);
                }
                if (lastUsedJavaVersion != javaVersion)
                {
                    lastUsedJavaVersion = javaVersion;

                    var newTree = generateJavaTree(options, assemblyName, generatedFilesDir);
                    var path    = newTree.FilePath;
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                        File.WriteAllText(path, newTree.GetText().ToString());
                    }
                    // this code smells a little
                    filesDict["GENERATED_JAVA"] = new List <string>(new[] { path });
                    var result =
                        prevousTree == null
              ? compilation.AddSyntaxTrees(newTree)
              : compilation.ReplaceSyntaxTree(prevousTree, newTree);

                    prevousTree = newTree;
                    return(result);
                }

                return(compilation);
            }
示例#4
0
        private TodoCommentData CreateSerializableData(
            Document document,
            SourceText text,
            SyntaxTree?tree
            )
        {
            // make sure given position is within valid text range.
            var textSpan = new TextSpan(Math.Min(text.Length, Math.Max(0, Position)), 0);

            var location =
                tree == null
                    ? Location.Create(
                    document.FilePath !,
                    textSpan,
                    text.Lines.GetLinePositionSpan(textSpan)
                    )
                    : tree.GetLocation(textSpan);

            var originalLineInfo = location.GetLineSpan();
            var mappedLineInfo   = location.GetMappedLineSpan();

            return(new(
                       priority : Descriptor.Priority,
                       message : Message,
                       documentId : document.Id,
                       originalLine : originalLineInfo.StartLinePosition.Line,
                       originalColumn : originalLineInfo.StartLinePosition.Character,
                       originalFilePath : document.FilePath,
                       mappedLine : mappedLineInfo.StartLinePosition.Line,
                       mappedColumn : mappedLineInfo.StartLinePosition.Character,
                       mappedFilePath : mappedLineInfo.GetMappedFilePathIfExist()
                       ));
        }
        internal void Clear()
        {
            if (typingTimer != null)
            {
                typingTimer.Stop();
                typingTimer.Tick -= HandleTypingTimerTimeout;
                typingTimer       = null;
            }

            if (activeWpfTextView != null)
            {
                activeWpfTextView.Selection.SelectionChanged -= HandleSelectionChanged;
                activeWpfTextView.TextBuffer.Changed         -= HandleTextBufferChanged;
                activeWpfTextView.LostAggregateFocus         -= HandleTextViewLostFocus;
                activeWpfTextView = null;
            }

            if (activeClassificationFormatMap != null)
            {
                activeClassificationFormatMap.ClassificationFormatMappingChanged -= HandleFormatMappingChanged;
                activeClassificationFormatMap = null;
            }

            if (activeEditorFormatMap != null)
            {
                activeEditorFormatMap.FormatMappingChanged -= HandleFormatMappingChanged;
                activeEditorFormatMap = null;
            }

            activeSyntaxTree = null;
            syntaxVisualizer.Clear();
        }
示例#6
0
        public static bool OverlapsHiddenPosition(
            [NotNullWhen(returnValue: true)] this SyntaxTree?tree,
            TextSpan span,
            CancellationToken cancellationToken
            )
        {
            if (tree == null)
            {
                return(false);
            }

            var text = tree.GetText(cancellationToken);

            return(text.OverlapsHiddenPosition(
                       span,
                       (position, cancellationToken2) =>
            {
                // implements the ASP.NET IsHidden rule
                var lineVisibility = tree.GetLineVisibility(position, cancellationToken2);
                return lineVisibility == LineVisibility.Hidden ||
                lineVisibility == LineVisibility.BeforeFirstLineDirective;
            },
                       cancellationToken
                       ));
        }
 private void AddDiagnostics(
     ref Dictionary <DocumentId, List <DiagnosticData> >?lazyLocals, SyntaxTree?tree, IEnumerable <Diagnostic> diagnostics)
 {
     foreach (var diagnostic in diagnostics)
     {
         AddDiagnostic(ref lazyLocals, tree, diagnostic);
     }
 }
        private readonly bool Compare_Internal(int index, SyntaxTree?syntaxTree)
        {
            if (syntaxTree is null)
            {
                return(false);
            }

            return(GeneratedSources[index].SyntaxTree.IsEquivalentTo(syntaxTree));
        }
示例#9
0
        private static SyntaxTree ComputeSyntaxTree(LuaSyntaxNode node)
        {
            ArrayBuilder <LuaSyntaxNode>?nodes = null;
            SyntaxTree?tree = null;

            // Find the nearest parent with a non-null syntax tree
            while (true)
            {
                tree = node._syntaxTree;
                if (tree != null)
                {
                    break;
                }

                var parent = node.Parent;
                if (parent == null)
                {
                    // set the tree on the root node atomically
                    Interlocked.CompareExchange(ref node._syntaxTree, LuaSyntaxTree.CreateWithoutClone(node), null);
                    tree = node._syntaxTree;
                    break;
                }

                tree = parent._syntaxTree;
                if (tree != null)
                {
                    node._syntaxTree = tree;
                    break;
                }

                (nodes ?? (nodes = ArrayBuilder <LuaSyntaxNode> .GetInstance())).Add(node);
                node = parent;
            }

            // Propagate the syntax tree downwards if necessary
            if (nodes != null)
            {
                RoslynDebug.Assert(tree != null);

                foreach (var n in nodes)
                {
                    var existingTree = n._syntaxTree;
                    if (existingTree != null)
                    {
                        RoslynDebug.Assert(existingTree == tree, "how could this node belong to a different tree?");

                        // yield the race
                        break;
                    }
                    n._syntaxTree = tree;
                }

                nodes.Free();
            }

            return(tree !);
        }
示例#10
0
        private void AddDiagnostics(
            ref Dictionary <DocumentId, List <DiagnosticData> >?lazyLocals,
            SyntaxTree?tree,
            IEnumerable <Diagnostic> diagnostics
            )
        {
            foreach (var diagnostic in diagnostics)
            {
                // REVIEW: what is our plan for additional locations?
                switch (diagnostic.Location.Kind)
                {
                case LocationKind.ExternalFile:
                    // TODO: currently additional file location is not supported.
                    break;

                case LocationKind.None:
                    AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
                    break;

                case LocationKind.SourceFile:
                    var diagnosticTree = diagnostic.Location.SourceTree;
                    if (tree != null && diagnosticTree == tree)
                    {
                        // local diagnostics to a file
                        AddDocumentDiagnostic(
                            ref lazyLocals,
                            Project.GetDocument(diagnosticTree),
                            diagnostic
                            );
                    }
                    else if (diagnosticTree != null)
                    {
                        // non local diagnostics to a file
                        AddDocumentDiagnostic(
                            ref _lazyNonLocals,
                            Project.GetDocument(diagnosticTree),
                            diagnostic
                            );
                    }
                    else
                    {
                        // non local diagnostics without location
                        AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
                    }
                    break;

                case LocationKind.MetadataFile:
                case LocationKind.XmlFile:
                    // ignore
                    continue;

                default:
                    throw ExceptionUtilities.UnexpectedValue(diagnostic.Location.Kind);
                }
            }
        }
示例#11
0
        public static void DumpCode(string source, Compilation compilation, ImmutableArray <Diagnostic> generatorDiags)
        {
            string prefix = Guid.NewGuid().ToString();
            ImmutableArray <Diagnostic> compDiag = compilation.GetDiagnostics();

            Directory.CreateDirectory(prefix);

            using (StreamWriter writer = File.CreateText("./" + prefix + "/" + "src.cs"))
            {
                writer.Write(source);
            }

            var generatedSyntaxTrees = compilation.SyntaxTrees.ToList();

            for (int i = 0; i < generatedSyntaxTrees.Count; i++)
            {
                SyntaxTree?tree       = generatedSyntaxTrees[i];
                var        sourceText = tree.GetText();
                using (StreamWriter writer = File.CreateText("./" + prefix + "/" + i + "gen.cs"))
                {
                    sourceText.Write(writer);
                }
            }

            using (StreamWriter writer = File.CreateText("./" + prefix + "/" + "gerr.txt"))
            {
                foreach (var diag in generatorDiags)
                {
                    writer.WriteLine(diag.GetMessage());
                }
            }

            using (StreamWriter writer = File.CreateText("./" + prefix + "/" + "gferr.txt"))
            {
                foreach (var diag in generatorDiags)
                {
                    writer.WriteLine(diag.ToString());
                }
            }

            using (StreamWriter writer = File.CreateText("./" + prefix + "/" + "cerr.txt"))
            {
                foreach (var diag in compDiag)
                {
                    writer.WriteLine(diag.GetMessage());
                }
            }
            using (StreamWriter writer = File.CreateText("./" + prefix + "/" + "cferr.txt"))
            {
                foreach (var diag in compDiag)
                {
                    writer.WriteLine(diag.ToString());
                }
            }
        }
示例#12
0
 internal static IList <TextSpan> GetPossiblyDifferentTextSpans(SyntaxTree?before, SyntaxTree?after)
 {
     if (object.ReferenceEquals(before, after))
     {
         // They're the same, so nothing changed.
         return(SpecializedCollections.EmptyList <TextSpan>());
     }
     else if (before == null)
     {
         // The tree is completely new, everything has changed.
         return(new[] { new TextSpan(0, after !.GetText().Length) });
示例#13
0
        public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree?syntaxTree)
        {
            syntaxTree = null;
            if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
            {
                syntaxTree = treeAndVersion.Tree;
                BindSyntaxTreeToId(syntaxTree, this.Id);
                return(true);
            }

            return(false);
        }
        private void AddDiagnostic(
            ref Dictionary <DocumentId, List <DiagnosticData> >?lazyLocals, SyntaxTree?tree, Diagnostic diagnostic)
        {
            // REVIEW: what is our plan for additional locations?
            switch (diagnostic.Location.Kind)
            {
            case LocationKind.ExternalFile:
                var diagnosticDocumentId = Project.GetDocumentForExternalLocation(diagnostic.Location);
                if (diagnosticDocumentId != null)
                {
                    AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetRequiredTextDocument(diagnosticDocumentId), diagnostic);
                }
                else
                {
                    AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
                }

                break;

            case LocationKind.None:
                AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
                break;

            case LocationKind.SourceFile:
                var diagnosticTree = diagnostic.Location.SourceTree;
                if (tree != null && diagnosticTree == tree)
                {
                    // local diagnostics to a file
                    AddDocumentDiagnostic(ref lazyLocals, Project.GetDocument(diagnosticTree), diagnostic);
                }
                else if (diagnosticTree != null)
                {
                    // non local diagnostics to a file
                    AddDocumentDiagnostic(ref _lazyNonLocals, Project.GetDocument(diagnosticTree), diagnostic);
                }
                else
                {
                    // non local diagnostics without location
                    AddOtherDiagnostic(DiagnosticData.Create(diagnostic, Project));
                }

                break;

            case LocationKind.MetadataFile:
            case LocationKind.XmlFile:
                // ignore
                return;

            default:
                throw ExceptionUtilities.UnexpectedValue(diagnostic.Location.Kind);
            }
        }
示例#15
0
 public SemanticEditInfo(
     SemanticEditKind kind,
     SymbolKey symbol,
     Func <SyntaxNode, SyntaxNode?>?syntaxMap,
     SyntaxTree?syntaxMapTree,
     SymbolKey?partialType)
 {
     Kind          = kind;
     Symbol        = symbol;
     SyntaxMap     = syntaxMap;
     SyntaxMapTree = syntaxMapTree;
     PartialType   = partialType;
 }
示例#16
0
        public bool Equals(SyntaxTree?x, SyntaxTree?y)
        {
            if (x == null)
            {
                return(y == null);
            }
            else if (y == null)
            {
                return(false);
            }

            return(string.Equals(x.FilePath, y.FilePath, StringComparison.OrdinalIgnoreCase) &&
                   SourceTextComparer.Instance.Equals(x.GetText(), y.GetText()));
        }
示例#17
0
        internal static bool AreEquivalent(SyntaxTree?before, SyntaxTree?after, Func <SyntaxKind, bool>?ignoreChildNode, bool topLevel)
        {
            if (before == after)
            {
                return(true);
            }

            if (before == null || after == null)
            {
                return(false);
            }

            return(AreEquivalent(before.GetRoot(), after.GetRoot(), ignoreChildNode, topLevel));
        }
示例#18
0
 public SemanticEditInfo(
     SemanticEditKind kind,
     SymbolKey symbol,
     Func <SyntaxNode, SyntaxNode?>?syntaxMap,
     SyntaxTree?syntaxMapTree,
     SymbolKey?partialType,
     SymbolKey?deletedSymbolContainer = null)
 {
     Kind                   = kind;
     Symbol                 = symbol;
     SyntaxMap              = syntaxMap;
     SyntaxMapTree          = syntaxMapTree;
     PartialType            = partialType;
     DeletedSymbolContainer = deletedSymbolContainer;
 }
        public async Task <IEnumerable <Diagnostic> > GetDiagnosticsAsync()
        {
            if (CurrentDocument != null)
            {
                Document   document   = CurrentDocument;
                SyntaxTree?syntaxTree = await document.GetSyntaxTreeAsync();

                if (syntaxTree != null)
                {
                    return(syntaxTree.GetDiagnostics());
                }
            }

            return(Enumerable.Empty <Diagnostic>());
        }
            private static bool TryGetSemanticModel(
                Compilation compilation, SyntaxTree?syntaxTree,
                [NotNullWhen(true)] out SemanticModel?semanticModel)
            {
                // Ensure that the tree we're looking at is actually in this compilation.  It may not be in the
                // compilation in the case of work done with a speculative model.
                if (syntaxTree != null && Contains(compilation.SyntaxTrees, syntaxTree))
                {
                    semanticModel = compilation.GetSemanticModel(syntaxTree);
                    return(true);
                }

                semanticModel = null;
                return(false);
            }
        private static bool TryGetSyntaxTreeForOption(ISymbol symbol, [NotNullWhen(returnValue: true)] out SyntaxTree?tree)
        {
            switch (symbol.Kind)
            {
            case SymbolKind.Assembly:
            case SymbolKind.Namespace when((INamespaceSymbol)symbol).IsGlobalNamespace:
                tree = null;

                return(false);

            default:
                tree = symbol.Locations[0].SourceTree;
                return(tree != null);
            }
        }
示例#22
0
 internal SyntaxTreeDiagnosticEnumerator(SyntaxTree syntaxTree, GreenNode?node, int position)
 {
     _syntaxTree = null;
     _current    = null;
     _position   = position;
     if (node != null && node.ContainsDiagnostics)
     {
         _syntaxTree = syntaxTree;
         _stack      = new NodeIterationStack(DefaultStackCapacity);
         _stack.PushNodeOrToken(node);
     }
     else
     {
         _stack = new NodeIterationStack();
     }
 }
示例#23
0
        public static void AssertGeneratedFile(this GeneratorDriverRunResult result, string fileName, Action <SyntaxTree>?treeAssertion = null)
        {
            SyntaxTree?foundTree = null;

            foreach (var tree in result.GeneratedTrees)
            {
                if (tree.FilePath == $"TypedIds\\TypedIds.Generator\\{fileName}")
                {
                    foundTree = tree;
                    break;
                }
            }

            Assert.NotNull(foundTree);

            treeAssertion?.Invoke(foundTree !);
        }
示例#24
0
            static void AddDiagnosticsToResult(
                ImmutableArray <Diagnostic> diagnostics,
                ref DiagnosticAnalysisResultBuilder result,
                Compilation compilation,
                SyntaxTree?tree,
                DocumentId?additionalDocumentId,
                TextSpan?span,
                AnalysisKind kind,
                ImmutableArray <string> diagnosticIdsToFilter,
                bool includeSuppressedDiagnostics)
            {
                if (diagnostics.IsEmpty)
                {
                    return;
                }

                diagnostics = diagnostics.Filter(diagnosticIdsToFilter, includeSuppressedDiagnostics, span);
                Debug.Assert(diagnostics.Length == CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).Count());

                switch (kind)
                {
                case AnalysisKind.Syntax:
                    if (tree != null)
                    {
                        Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree));
                        result.AddSyntaxDiagnostics(tree !, diagnostics);
                    }
                    else
                    {
                        RoslynDebug.Assert(additionalDocumentId != null);
                        result.AddExternalSyntaxDiagnostics(additionalDocumentId, diagnostics);
                    }

                    break;

                case AnalysisKind.Semantic:
                    Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree));
                    result.AddSemanticDiagnostics(tree !, diagnostics);
                    break;

                default:
                    result.AddCompilationDiagnostics(diagnostics);
                    break;
                }
            }
示例#25
0
 static void AddAnalyzerDiagnosticsToResult(
     DiagnosticAnalyzer analyzer,
     ImmutableDictionary <DiagnosticAnalyzer, ImmutableArray <Diagnostic> > diagnosticsByAnalyzer,
     ref DiagnosticAnalysisResultBuilder result,
     Compilation compilation,
     SyntaxTree?tree,
     DocumentId?additionalDocumentId,
     TextSpan?span,
     AnalysisKind kind,
     ImmutableArray <string> diagnosticIdsToFilter,
     bool includeSuppressedDiagnostics)
 {
     if (diagnosticsByAnalyzer.TryGetValue(analyzer, out var diagnostics))
     {
         AddDiagnosticsToResult(diagnostics, ref result, compilation,
                                tree, additionalDocumentId, span, kind, diagnosticIdsToFilter, includeSuppressedDiagnostics);
     }
 }
        public async Task <SyntaxNode?> GetSyntaxNodeAsync(TextSpan span)
        {
            if (CurrentDocument != null)
            {
                Document   document   = CurrentDocument;
                SyntaxTree?syntaxTree = await document.GetSyntaxTreeAsync();

                if (syntaxTree != null)
                {
                    SyntaxNode root = await syntaxTree.GetRootAsync();

                    SyntaxNode node = root.FindNode(span);

                    return(node);
                }
            }

            return(null);
        }
示例#27
0
        public virtual SyntaxTree Tokenize(
            SyntaxTree tree,
            string line,
            Match foundMatch,
            int position)
        {
            SyntaxTree?result = null;
            string     substr = GetRemainingTokens(line, foundMatch);

            if (_tokenizers.Count == 0)
            {
                return(TokenizeInternal(tree, substr, foundMatch));
            }

            foreach (var tokenizer in _tokenizers)
            {
                Match match = tokenizer.CanTokenize(substr);
                if (match.Success)
                {
                    result = TokenizeInternal(tree, substr, foundMatch);

                    result = tokenizer.Tokenize(
                        result.Value,
                        substr,
                        match,
                        position + match.Index);

                    break;
                }
            }

            if (result.HasValue)
            {
                return(result.Value);
            }
            else
            {
                throw new SyntaxParseException(
                          $"[{GetType().Name}] Invalid token at col {position + foundMatch.Length}",
                          position + foundMatch.Length);
            }
        }
示例#28
0
        /// <summary>
        /// Tries to find a document given the <see cref="SyntaxTree"/> provided.
        /// </summary>
        /// <param name="sln">The solution to search in.</param>
        /// <param name="tree">The tree to match.</param>
        /// <param name="document">The resulting document.</param>
        /// <returns>Whether the search was successful or not.</returns>
        public static bool TryGetDocument(this Solution sln, SyntaxTree?tree, [MaybeNullWhen(false)] out Document document)
        {
            if (tree is null || sln is null)
            {
                document = null;
                return(false);
            }

            foreach (var project in sln.Projects)
            {
                var doc = project.GetDocument(tree);

                if (doc is not null)
                {
                    document = doc;
                    return(true);
                }
            }

            document = null;
            return(false);
        }
示例#29
0
        public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree?syntaxTree)
        {
            // if we already have cache, use it
            if (_syntaxTreeResultTask != null)
            {
                syntaxTree = _syntaxTreeResultTask.Result;
                return(true);
            }

            if (!DocumentState.TryGetSyntaxTree(out syntaxTree))
            {
                return(false);
            }

            // cache the result if it is not already cached
            if (_syntaxTreeResultTask == null)
            {
                var result = Task.FromResult(syntaxTree);
                Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null);
            }

            return(true);
        }
示例#30
0
        public static string?GetSource(this Diagnostic diagnostic, IOpenApiElementRegistry elementRegistry)
        {
            if (diagnostic == null)
            {
                throw new ArgumentNullException(nameof(diagnostic));
            }
            if (elementRegistry == null)
            {
                throw new ArgumentNullException(nameof(elementRegistry));
            }

            SyntaxTree?syntaxTree = diagnostic.Location.SourceTree;

            if (syntaxTree == null)
            {
                return(null);
            }

            CompilationUnitSyntax compilationUnit = syntaxTree.GetCompilationUnitRoot();

            return(compilationUnit.GetResourceNameAnnotation()
                   ?? compilationUnit.GetElementAnnotations(elementRegistry).FirstOrDefault()?.ToString());
        }