Beispiel #1
0
        public void AtValidContentKind_ReturnsFalseAtMarkup()
        {
            // Arrange
            var syntaxTree     = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create("<p></p>"));
            var changePosition = 2;

            // Act
            var result = BraceSmartIndenter.AtValidContentKind(changePosition, syntaxTree);

            // Assert
            Assert.False(result);
        }
Beispiel #2
0
        public void AtValidContentKind_ReturnsTrueAtCode()
        {
            // Arrange
            var syntaxTree     = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create("@{}"));
            var changePosition = 2;

            // Act
            var result = BraceSmartIndenter.AtValidContentKind(changePosition, syntaxTree);

            // Assert
            Assert.True(result);
        }
Beispiel #3
0
    public void Parse_CanParseEmptyDocument()
    {
        // Arrange
        var source = TestRazorSourceDocument.Create(string.Empty);

        // Act
        var syntaxTree = RazorSyntaxTree.Parse(source);

        // Assert
        Assert.NotNull(syntaxTree);
        Assert.Empty(syntaxTree.Diagnostics);
    }
        private CompletionList GenerateCompletionList(string documentContent, int queryIndex, TagHelperCompletionProvider componentCompletionProvider)
        {
            var sourceDocument           = RazorSourceDocument.Create(documentContent, RazorSourceDocumentProperties.Default);
            var syntaxTree               = RazorSyntaxTree.Parse(sourceDocument);
            var tagHelperDocumentContext = TagHelperDocumentContext.Create(prefix: string.Empty, DefaultTagHelpers);

            var completionQueryLocation = new SourceSpan(queryIndex, length: 0);
            var razorCompletionItems    = componentCompletionProvider.GetCompletionItems(syntaxTree, tagHelperDocumentContext, completionQueryLocation);
            var completionList          = RazorCompletionEndpoint.CreateLSPCompletionList(razorCompletionItems, new CompletionListCache());

            return(completionList);
        }
Beispiel #5
0
        private static RazorSyntaxTree GetSyntaxTree(string content)
        {
            var syntaxTree = RazorSyntaxTree.Parse(
                TestRazorSourceDocument.Create(content),
                RazorParserOptions.Create(options =>
            {
                options.Directives.Add(FunctionsDirective.Directive);
                options.Directives.Add(SectionDirective.Directive);
            }));

            return(syntaxTree);
        }
Beispiel #6
0
        public void AtApplicableRazorBlock_AtExplicitCodeBlocksCode_ReturnsTrue()
        {
            // Arrange
            var syntaxTree     = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create("@{}"));
            var changePosition = 2;

            // Act
            var result = BraceSmartIndenter.AtApplicableRazorBlock(changePosition, syntaxTree);

            // Assert
            Assert.True(result);
        }
Beispiel #7
0
        private static RazorCodeDocument CreateCodeDocument(string text)
        {
            var codeDocument   = TestRazorCodeDocument.CreateEmpty();
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var syntaxTree     = RazorSyntaxTree.Parse(sourceDocument);

            codeDocument.SetSyntaxTree(syntaxTree);
            var tagHelperDocumentContext = TagHelperDocumentContext.Create(prefix: string.Empty, Enumerable.Empty <TagHelperDescriptor>());

            codeDocument.SetTagHelperContext(tagHelperDocumentContext);
            return(codeDocument);
        }
Beispiel #8
0
        public void AtApplicableRazorBlock_AtMarkup_ReturnsFalse()
        {
            // Arrange
            var syntaxTree     = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create("<p></p>"));
            var changePosition = 2;

            // Act
            var result = BraceSmartIndenter.AtApplicableRazorBlock(changePosition, syntaxTree);

            // Assert
            Assert.False(result);
        }
Beispiel #9
0
        public void AtApplicableRazorBlock_WhenNoOwner_ReturnsFalse()
        {
            // Arrange
            var syntaxTree     = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create("@DateTime.Now"));
            var changePosition = 14; // 1 after the end of the content

            // Act
            var result = BraceSmartIndenter.AtApplicableRazorBlock(changePosition, syntaxTree);

            // Assert
            Assert.False(result);
        }
Beispiel #10
0
        public void AtApplicableRazorBlock_AtMetacode_ReturnsTrue()
        {
            // Arrange
            var parseOptions   = RazorParserOptions.Create(options => options.Directives.Add(FunctionsDirective.Directive));
            var syntaxTree     = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create("@functions {}"), parseOptions);
            var changePosition = 12;

            // Act
            var result = BraceSmartIndenter.AtApplicableRazorBlock(changePosition, syntaxTree);

            // Assert
            Assert.True(result);
        }
    public void SetRazorSyntaxTree_SetsSyntaxTree()
    {
        // Arrange
        var codeDocument = TestRazorCodeDocument.CreateEmpty();

        var expected = RazorSyntaxTree.Parse(codeDocument.Source);

        // Act
        codeDocument.SetSyntaxTree(expected);

        // Assert
        Assert.Same(expected, codeDocument.Items[typeof(RazorSyntaxTree)]);
    }
        private static RazorSyntaxTree CreateSyntaxTree(string text, params DirectiveDescriptor[] directives)
        {
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var options        = RazorParserOptions.Create(builder =>
            {
                foreach (var directive in directives)
                {
                    builder.Directives.Add(directive);
                }
            });
            var syntaxTree = RazorSyntaxTree.Parse(sourceDocument, options);

            return(syntaxTree);
        }
Beispiel #13
0
        public async Task SyntaxTreeRequest_Complete_FinishesTask()
        {
            // Arrange
            var syntaxTree = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create());
            var request    = new DefaultVisualStudioRazorParser.SyntaxTreeRequest(StringTextSnapshot.Empty, CancellationToken.None);

            // Act
            request.Complete(syntaxTree);

            // Assert
            Assert.True(request.Task.IsCompleted);
            var resolvedSyntaxTree = await request.Task;

            Assert.Same(syntaxTree, resolvedSyntaxTree);
        }
Beispiel #14
0
        protected override void ExecuteCore(RazorCodeDocument codeDocument)
        {
            var options    = codeDocument.GetParserOptions() ?? _optionsFeature.GetOptions();
            var syntaxTree = RazorSyntaxTree.Parse(codeDocument.Source, options);

            codeDocument.SetSyntaxTree(syntaxTree);

            var importSyntaxTrees = new RazorSyntaxTree[codeDocument.Imports.Count];

            for (var i = 0; i < codeDocument.Imports.Count; i++)
            {
                importSyntaxTrees[i] = RazorSyntaxTree.Parse(codeDocument.Imports[i], options);
            }
            codeDocument.SetImportSyntaxTrees(importSyntaxTrees);
        }
    public void GetAndSetImportSyntaxTrees_ReturnsSyntaxTrees()
    {
        // Arrange
        var codeDocument = TestRazorCodeDocument.CreateEmpty();

        var expected = new[] { RazorSyntaxTree.Parse(codeDocument.Source), };

        codeDocument.SetImportSyntaxTrees(expected);

        // Act
        var actual = codeDocument.GetImportSyntaxTrees();

        // Assert
        Assert.Same(expected, actual);
    }
    public void GetRazorSyntaxTree_ReturnsSyntaxTree()
    {
        // Arrange
        var codeDocument = TestRazorCodeDocument.CreateEmpty();

        var expected = RazorSyntaxTree.Parse(codeDocument.Source);

        codeDocument.Items[typeof(RazorSyntaxTree)] = expected;

        // Act
        var actual = codeDocument.GetSyntaxTree();

        // Assert
        Assert.Same(expected, actual);
    }
Beispiel #17
0
        public void SyntaxTreeRequest_CancelToCompleteNoops()
        {
            // Arrange
            var syntaxTree = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create());
            var request    = new DefaultVisualStudioRazorParser.SyntaxTreeRequest(StringTextSnapshot.Empty, CancellationToken.None);

            // Act - 1
            request.Cancel();

            // Assert - 1
            Assert.True(request.Task.IsCanceled);

            // Act & Assert - 2
            request.Complete(syntaxTree);
        }
Beispiel #18
0
        public void SyntaxTreeGeneration_Runtime_LargeStaticFile()
        {
            var options = RazorParserOptions.Create(o =>
            {
                foreach (var directive in Directives)
                {
                    o.Directives.Add(directive);
                }
            });
            var syntaxTree = RazorSyntaxTree.Parse(MSN, options);

            if (syntaxTree.Diagnostics.Count != 0)
            {
                throw new Exception("Error!" + Environment.NewLine + string.Join(Environment.NewLine, syntaxTree.Diagnostics));
            }
        }
Beispiel #19
0
        public void TryCreateIndentationContext_ReturnsFalseIfNoFocusedTextView()
        {
            // Arrange
            var         snapshot        = new StringTextSnapshot(Environment.NewLine + "Hello World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(snapshot.Content));
            ITextBuffer textBuffer      = null;
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView: null);

            textBuffer = CreateTextBuffer(snapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(0, Environment.NewLine.Length, Environment.NewLine, syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Beispiel #20
0
        public void Parse_UseDirectiveTokenizer_ParsesUntilFirstDirective()
        {
            // Arrange
            var source  = TestRazorSourceDocument.Create("\r\n  \r\n    @*SomeComment*@ \r\n  @tagHelperPrefix \"SomePrefix\"\r\n<html>\r\n@if (true) {\r\n @if(false) { <div>@something.</div> } \r\n}");
            var options = RazorParserOptions.Create(builder => builder.ParseLeadingDirectives = true);

            // Act
            var syntaxTree = RazorSyntaxTree.Parse(source, options);

            // Assert
            Assert.NotNull(syntaxTree);
            Assert.Equal(6, syntaxTree.Root.Children.Count);
            var block = Assert.IsType <Block>(syntaxTree.Root.Children[4]);

            Assert.Equal(BlockKindInternal.Directive, block.Type);
            Assert.Empty(syntaxTree.Diagnostics);
        }
    public void Execute_ThrowsForMissingDependency_IRDocument()
    {
        // Arrange
        var phase = new DefaultRazorCSharpLoweringPhase();

        var engine = RazorProjectEngine.CreateEmpty(b => b.Phases.Add(phase));

        var codeDocument = TestRazorCodeDocument.CreateEmpty();

        codeDocument.SetSyntaxTree(RazorSyntaxTree.Parse(codeDocument.Source));

        // Act & Assert
        ExceptionAssert.Throws <InvalidOperationException>(
            () => phase.Execute(codeDocument),
            $"The '{nameof(DefaultRazorCSharpLoweringPhase)}' phase requires a '{nameof(DocumentIntermediateNode)}' " +
            $"provided by the '{nameof(RazorCodeDocument)}'.");
    }
Beispiel #22
0
        public void Parse_NodesReturnCorrectFilePath()
        {
            // Arrange
            var filePath = "test.cshtml";
            var source   = TestRazorSourceDocument.Create("@if (true) { @if(false) { <div>@something.</div> } }", filePath: filePath);

            // Act
            var syntaxTree = RazorSyntaxTree.Parse(source);

            // Assert
            Assert.Empty(syntaxTree.Diagnostics);
            Assert.NotNull(syntaxTree);

            var children = syntaxTree.Root.DescendantNodes();

            Assert.All(children, node => Assert.Equal(filePath, node.GetSourceLocation(source).FilePath));
        }
Beispiel #23
0
        public void GetDirectiveCompletionItems_AllProvidersCompletionItems()
        {
            // Arrange
            var syntaxTree = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create());
            var tagHelperDocumentContext = TagHelperDocumentContext.Create(prefix: null, Enumerable.Empty <TagHelperDescriptor>());
            var completionItem1          = new RazorCompletionItem("displayText1", "insertText1", RazorCompletionItemKind.Directive);
            var provider1              = Mock.Of <RazorCompletionItemProvider>(p => p.GetCompletionItems(syntaxTree, tagHelperDocumentContext, default) == new[] { completionItem1 }, MockBehavior.Strict);
            var completionItem2        = new RazorCompletionItem("displayText2", "insertText2", RazorCompletionItemKind.Directive);
            var provider2              = Mock.Of <RazorCompletionItemProvider>(p => p.GetCompletionItems(syntaxTree, tagHelperDocumentContext, default) == new[] { completionItem2 }, MockBehavior.Strict);
            var completionFactsService = new DefaultRazorCompletionFactsService(new[] { provider1, provider2 });

            // Act
            var completionItems = completionFactsService.GetCompletionItems(syntaxTree, tagHelperDocumentContext, default);

            // Assert
            Assert.Equal(new[] { completionItem1, completionItem2 }, completionItems);
        }
Beispiel #24
0
        public void Parse_UseDirectiveTokenizer_ParsesUntilFirstDirective()
        {
            // Arrange
            var source  = TestRazorSourceDocument.Create("\r\n  \r\n    @*SomeComment*@ \r\n  @tagHelperPrefix \"SomePrefix\"\r\n<html>\r\n@if (true) {\r\n @if(false) { <div>@something.</div> } \r\n}");
            var options = RazorParserOptions.Create(builder => builder.ParseLeadingDirectives = true);

            // Act
            var syntaxTree = RazorSyntaxTree.Parse(source, options);

            // Assert
            var root = syntaxTree.Root;

            Assert.NotNull(syntaxTree);
            Assert.Equal(61, root.EndPosition);
            Assert.Single(root.DescendantNodes().Where(n => n is RazorDirectiveBodySyntax body && body.Keyword.GetContent() == "tagHelperPrefix"));
            Assert.Empty(root.DescendantNodes().Where(n => n is MarkupTagBlockSyntax));
            Assert.Empty(syntaxTree.Diagnostics);
        }
Beispiel #25
0
        public void TryCreateIndentationContext_ReturnsFalseIfTextChangeIsNotNewline()
        {
            // Arrange
            var         snapshot        = new StringTextSnapshot("This Hello World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(snapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(snapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(0, 5, "This ", syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Beispiel #26
0
        public void TryCreateIndentationContext_ReturnsFalseIfNewLineIsNotPrecededByOpenBrace_MidFile()
        {
            // Arrange
            var         initialSnapshot = new StringTextSnapshot("Hello\u0085World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(initialSnapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(5, 1, "\u0085", syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Beispiel #27
0
        public void TryCreateIndentationContext_ReturnsFalseIfNewLineIsNotFollowedByCloseBrace()
        {
            // Arrange
            var         initialSnapshot = new StringTextSnapshot("@{ " + Environment.NewLine + "World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(initialSnapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(3, Environment.NewLine.Length, Environment.NewLine, syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
    public void TryComputeNamespace_OverrideImportsNamespaceDirective()
    {
        // Arrange
        var sourceDocument = TestRazorSourceDocument.Create(
            content: "@namespace My.Custom.OverrideNS",
            filePath: "C:\\Hello\\Components\\Test.cshtml",
            relativePath: "\\Components\\Test.cshtml");
        var codeDocument = TestRazorCodeDocument.Create(sourceDocument, Array.Empty <RazorSourceDocument>());

        codeDocument.SetFileKind(FileKinds.Component);
        codeDocument.SetSyntaxTree(RazorSyntaxTree.Parse(sourceDocument, RazorParserOptions.Create(options =>
        {
            options.Directives.Add(NamespaceDirective.Directive);
        })));

        var importSourceDocument = TestRazorSourceDocument.Create(
            content: "@namespace My.Custom.NS",
            filePath: "C:\\Hello\\_Imports.razor",
            relativePath: "\\_Imports.razor");

        codeDocument.SetImportSyntaxTrees(new[]
        {
            RazorSyntaxTree.Parse(importSourceDocument, RazorParserOptions.Create(options =>
            {
                options.Directives.Add(NamespaceDirective.Directive);
            }))
        });

        var documentNode = new DocumentIntermediateNode()
        {
            Options = RazorCodeGenerationOptions.Create(c =>
            {
                c.RootNamespace = "Hello.World";
            })
        };

        codeDocument.SetDocumentIntermediateNode(documentNode);

        // Act
        codeDocument.TryComputeNamespace(fallbackToRootNamespace: true, out var @namespace);

        // Assert
        Assert.Equal("My.Custom.OverrideNS", @namespace);
    }
Beispiel #29
0
        public void TagHelperPrefixDirective_DuplicatesCauseError()
        {
            // Arrange
            var expectedDiagnostic = RazorDiagnosticFactory.CreateParsing_DuplicateDirective(
                new SourceSpan(null, 22 + Environment.NewLine.Length, 1, 0, 16), "tagHelperPrefix");
            var source = TestRazorSourceDocument.Create(
                @"@tagHelperPrefix ""th:""
@tagHelperPrefix ""th""",
                filePath: null);

            // Act
            var document = RazorSyntaxTree.Parse(source);

            // Assert
            var erroredNode    = document.Root.DescendantNodes().Last(n => n.GetSpanContext()?.ChunkGenerator is TagHelperPrefixDirectiveChunkGenerator);
            var chunkGenerator = Assert.IsType <TagHelperPrefixDirectiveChunkGenerator>(erroredNode.GetSpanContext().ChunkGenerator);
            var diagnostic     = Assert.Single(chunkGenerator.Diagnostics);

            Assert.Equal(expectedDiagnostic, diagnostic);
        }
        private static Lazy <RazorCodeDocumentProvider> CreateCodeDocumentProvider(string text, IEnumerable <DirectiveDescriptor> directives)
        {
            var codeDocumentProvider = new Mock <RazorCodeDocumentProvider>();
            var codeDocument         = TestRazorCodeDocument.CreateEmpty();
            var sourceDocument       = TestRazorSourceDocument.Create(text);
            var options = RazorParserOptions.Create(builder =>
            {
                foreach (var directive in directives)
                {
                    builder.Directives.Add(directive);
                }
            });
            var syntaxTree = RazorSyntaxTree.Parse(sourceDocument, options);

            codeDocument.SetSyntaxTree(syntaxTree);
            codeDocumentProvider.Setup(provider => provider.TryGetFromDocument(It.IsAny <TextDocument>(), out codeDocument))
            .Returns(true);

            return(new Lazy <RazorCodeDocumentProvider>(() => codeDocumentProvider.Object));
        }