Ejemplo n.º 1
0
        internal virtual RazorSyntaxTree ParseDocument(string document, IEnumerable <DirectiveDescriptor> directives, bool designTime = false)
        {
            directives = directives ?? Array.Empty <DirectiveDescriptor>();

            var source = TestRazorSourceDocument.Create(document, filePath: null);

            var options = CreateParserOptions(directives, designTime);
            var context = new ParserContext(source, options);

            var codeParser   = new CSharpCodeParser(directives, context);
            var markupParser = new HtmlMarkupParser(context);

            codeParser.HtmlParser   = markupParser;
            markupParser.CodeParser = codeParser;

            markupParser.ParseDocument();

            var root        = context.Builder.Build();
            var diagnostics = context.ErrorSink.Errors;

            var codeDocument = RazorCodeDocument.Create(source);

            var syntaxTree = RazorSyntaxTree.Create(root, source, diagnostics, options);

            codeDocument.SetSyntaxTree(syntaxTree);

            var defaultDirectivePass = new DefaultDirectiveSyntaxTreePass();

            syntaxTree = defaultDirectivePass.Execute(codeDocument, syntaxTree);

            return(syntaxTree);
        }
Ejemplo n.º 2
0
        internal virtual RazorSyntaxTree ParseDocument(RazorLanguageVersion version, string document, IEnumerable <DirectiveDescriptor> directives, bool designTime = false, RazorParserFeatureFlags featureFlags = null, string fileKind = null)
        {
            directives = directives ?? Array.Empty <DirectiveDescriptor>();

            var source = TestRazorSourceDocument.Create(document, filePath: null, relativePath: null, normalizeNewLines: true);

            var options = CreateParserOptions(version, directives, designTime, featureFlags, fileKind);
            var context = new ParserContext(source, options);

            var codeParser   = new CSharpCodeParser(directives, context);
            var markupParser = new HtmlMarkupParser(context);

            codeParser.HtmlParser   = markupParser;
            markupParser.CodeParser = codeParser;

            var root = markupParser.ParseDocument().CreateRed();

            var diagnostics = context.ErrorSink.Errors;

            var codeDocument = RazorCodeDocument.Create(source);

            var syntaxTree = RazorSyntaxTree.Create(root, source, diagnostics, options);

            codeDocument.SetSyntaxTree(syntaxTree);

            var defaultDirectivePass = new DefaultDirectiveSyntaxTreePass();

            syntaxTree = defaultDirectivePass.Execute(codeDocument, syntaxTree);

            return(syntaxTree);
        }
Ejemplo n.º 3
0
        public void Indexer_ProvidesCharacterAccessToContent(int contentLength)
        {
            // Arrange
            var content = new char[contentLength];

            for (var i = 0; i < contentLength - 1; i++)
            {
                content[i] = 'a';
            }
            content[contentLength - 1] = 'b';
            var contentString = new string(content);

            var stream   = TestRazorSourceDocument.CreateStreamContent(new string(content));
            var reader   = new StreamReader(stream, true);
            var document = new LargeTextSourceDocument(reader, ChunkTestLength, Encoding.UTF8, "file.cshtml");

            // Act
            var output = new char[contentLength];

            for (var i = 0; i < document.Length; i++)
            {
                output[i] = document[i];
            }
            var outputString = new string(output);

            // Assert
            Assert.Equal(contentLength, document.Length);
            Assert.Equal(contentString, outputString);
        }
Ejemplo n.º 4
0
        internal virtual RazorSyntaxTree ParseCodeBlock(
            string document,
            IEnumerable <DirectiveDescriptor> directives,
            bool designTime)
        {
            directives = directives ?? Array.Empty <DirectiveDescriptor>();

            var source  = TestRazorSourceDocument.Create(document, filePath: null);
            var options = CreateParserOptions(directives, designTime);
            var context = new ParserContext(source, options);

            var parser = new CSharpCodeParser(directives, context);

            parser.HtmlParser = new HtmlMarkupParser(context)
            {
                CodeParser = parser,
            };

            parser.ParseBlock();

            var root        = context.Builder.Build();
            var diagnostics = context.ErrorSink.Errors;

            return(RazorSyntaxTree.Create(root, source, diagnostics, options));
        }
        private static RazorCodeActionContext CreateRazorCodeActionContext(
            CodeActionParams request,
            SourceLocation location,
            string filePath,
            string text,
            SourceSpan componentSourceSpan,
            bool supportsFileCreation      = true,
            bool supportsCodeActionResolve = true)
        {
            var tagHelpers     = Array.Empty <TagHelperDescriptor>();
            var sourceDocument = TestRazorSourceDocument.Create(text, filePath: filePath, relativePath: filePath);
            var projectEngine  = RazorProjectEngine.Create(builder => builder.AddTagHelpers(tagHelpers));
            var codeDocument   = projectEngine.ProcessDesignTime(sourceDocument, FileKinds.Component, Array.Empty <RazorSourceDocument>(), tagHelpers);

            var cSharpDocument               = codeDocument.GetCSharpDocument();
            var diagnosticDescriptor         = new RazorDiagnosticDescriptor("RZ10012", () => "", RazorDiagnosticSeverity.Error);
            var diagnostic                   = RazorDiagnostic.Create(diagnosticDescriptor, componentSourceSpan);
            var cSharpDocumentWithDiagnostic = RazorCSharpDocument.Create(cSharpDocument.GeneratedCode, cSharpDocument.Options, new[] { diagnostic });

            codeDocument.SetCSharpDocument(cSharpDocumentWithDiagnostic);

            var documentSnapshot = Mock.Of <DocumentSnapshot>(document =>
                                                              document.GetGeneratedOutputAsync() == Task.FromResult(codeDocument) &&
                                                              document.GetTextAsync() == Task.FromResult(codeDocument.GetSourceText()) &&
                                                              document.Project.TagHelpers == tagHelpers, MockBehavior.Strict);

            var sourceText = SourceText.From(text);

            var context = new RazorCodeActionContext(request, documentSnapshot, codeDocument, location, sourceText, supportsFileCreation, supportsCodeActionResolve);

            return(context);
        }
Ejemplo n.º 6
0
        private static RazorCodeActionContext CreateRazorCodeActionContext(CodeActionParams request, SourceLocation location, string filePath, string text, SourceSpan componentSourceSpan)
        {
            var shortComponent = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, "Fully.Qualified.Component", "TestAssembly");

            shortComponent.TagMatchingRule(rule => rule.TagName = "Component");
            var fullyQualifiedComponent = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, "Fully.Qualified.Component", "TestAssembly");

            fullyQualifiedComponent.TagMatchingRule(rule => rule.TagName = "Fully.Qualified.Component");

            var tagHelpers = new[] { shortComponent.Build(), fullyQualifiedComponent.Build() };

            var sourceDocument = TestRazorSourceDocument.Create(text, filePath: filePath, relativePath: filePath);
            var projectEngine  = RazorProjectEngine.Create(builder => {
                builder.AddTagHelpers(tagHelpers);
            });
            var codeDocument = projectEngine.ProcessDesignTime(sourceDocument, FileKinds.Component, Array.Empty <RazorSourceDocument>(), tagHelpers);

            var cSharpDocument               = codeDocument.GetCSharpDocument();
            var diagnosticDescriptor         = new RazorDiagnosticDescriptor("RZ10012", () => "", RazorDiagnosticSeverity.Error);
            var diagnostic                   = RazorDiagnostic.Create(diagnosticDescriptor, componentSourceSpan);
            var cSharpDocumentWithDiagnostic = RazorCSharpDocument.Create(cSharpDocument.GeneratedCode, cSharpDocument.Options, new[] { diagnostic });

            codeDocument.SetCSharpDocument(cSharpDocumentWithDiagnostic);

            var documentSnapshot = Mock.Of <DocumentSnapshot>(document =>
                                                              document.GetGeneratedOutputAsync() == Task.FromResult(codeDocument) &&
                                                              document.GetTextAsync() == Task.FromResult(codeDocument.GetSourceText()) &&
                                                              document.Project.TagHelpers == tagHelpers);

            return(new RazorCodeActionContext(request, documentSnapshot, codeDocument, location));
        }
Ejemplo n.º 7
0
        public void OnDocumentStructureChanged_FiresForLatestTextBufferEdit()
        {
            // Arrange
            var documentTracker = CreateDocumentTracker();

            using (var parser = new DefaultVisualStudioRazorParser(
                       Dispatcher,
                       documentTracker,
                       Mock.Of <RazorTemplateEngineFactoryService>(),
                       new DefaultErrorReporter(),
                       Mock.Of <VisualStudioCompletionBroker>()))
            {
                var called = false;
                parser.DocumentStructureChanged += (sender, e) => called = true;
                var latestChange   = new SourceChange(0, 0, string.Empty);
                var latestSnapshot = documentTracker.TextBuffer.CurrentSnapshot;
                parser._latestChangeReference = new DefaultVisualStudioRazorParser.ChangeReference(latestChange, latestSnapshot);
                var codeDocument = TestRazorCodeDocument.CreateEmpty();
                codeDocument.SetSyntaxTree(RazorSyntaxTree.Parse(TestRazorSourceDocument.Create()));
                var args = new DocumentStructureChangedEventArgs(
                    latestChange,
                    latestSnapshot,
                    codeDocument);

                // Act
                parser.OnDocumentStructureChanged(args);

                // Assert
                Assert.True(called);
            }
        }
Ejemplo n.º 8
0
        internal virtual RazorSyntaxTree ParseCodeBlock(
            RazorLanguageVersion version,
            string document,
            IEnumerable <DirectiveDescriptor> directives,
            bool designTime)
        {
            directives = directives ?? Array.Empty <DirectiveDescriptor>();

            var source = TestRazorSourceDocument.Create(document, filePath: null, relativePath: null, normalizeNewLines: true);

            var options = CreateParserOptions(version, directives, designTime);
            var context = new ParserContext(source, options);

            var codeParser   = new CSharpCodeParser(directives, context);
            var markupParser = new HtmlMarkupParser(context);

            codeParser.HtmlParser   = markupParser;
            markupParser.CodeParser = codeParser;

            var root = codeParser.ParseBlock().CreateRed();

            var diagnostics = context.ErrorSink.Errors;

            var syntaxTree = RazorSyntaxTree.Create(root, source, diagnostics, options);

            return(syntaxTree);
        }
    public void Execute_ParsesImports()
    {
        // Arrange
        var phase  = new DefaultRazorParsingPhase();
        var engine = RazorProjectEngine.CreateEmpty((builder) =>
        {
            builder.Phases.Add(phase);
            builder.Features.Add(new DefaultRazorParserOptionsFeature(designTime: false, version: RazorLanguageVersion.Latest, fileKind: null));
            builder.Features.Add(new MyParserOptionsFeature());
        });

        var imports = new[]
        {
            TestRazorSourceDocument.Create(),
            TestRazorSourceDocument.Create(),
        };

        var codeDocument = TestRazorCodeDocument.Create(TestRazorSourceDocument.Create(), imports);

        // Act
        phase.Execute(codeDocument);

        // Assert
        Assert.Collection(
            codeDocument.GetImportSyntaxTrees(),
            t => { Assert.Same(t.Source, imports[0]); Assert.Equal("test", Assert.Single(t.Options.Directives).Directive); },
            t => { Assert.Same(t.Source, imports[1]); Assert.Equal("test", Assert.Single(t.Options.Directives).Directive); });
    }
Ejemplo n.º 10
0
        public void WriteCSharpCodeAttributeValue_WithExpression_RendersCorrectly()
        {
            var writer         = new DesignTimeNodeWriter();
            var content        = "<input checked=\"hello-world @if(@true){ @false }\" />";
            var sourceDocument = TestRazorSourceDocument.Create(content);
            var codeDocument   = RazorCodeDocument.Create(sourceDocument);
            var documentNode   = Lower(codeDocument);
            var node           = documentNode.Children.OfType <HtmlAttributeIntermediateNode>().Single().Children[1] as CSharpCodeAttributeValueIntermediateNode;

            var context = TestCodeRenderingContext.CreateDesignTime(source: sourceDocument);

            // Act
            writer.WriteCSharpCodeAttributeValue(context, node);

            // Assert
            var csharp = context.CodeWriter.GenerateCode();

            Assert.Equal(
                @"#line 1 ""test.cshtml""
                             if(@true){ 

#line default
#line hidden
Render Children
#line 1 ""test.cshtml""
                                               }

#line default
#line hidden
",
                csharp,
                ignoreLineEndingDifferences: true);
        }
Ejemplo n.º 11
0
        public void WriteUsingDirective_WithSource_WritesContentWithLinePragmaAndMapping()
        {
            // Arrange
            var writer         = new DesignTimeNodeWriter();
            var sourceDocument = TestRazorSourceDocument.Create("@using System;");
            var context        = TestCodeRenderingContext.CreateDesignTime();

            var originalSpan          = new SourceSpan("test.cshtml", 0, 0, 0, 6);
            var generatedSpan         = new SourceSpan(null, 21 + Environment.NewLine.Length, 1, 0, 6);
            var expectedSourceMapping = new SourceMapping(originalSpan, generatedSpan);
            var node = new UsingDirectiveIntermediateNode()
            {
                Content = "System",
                Source  = originalSpan,
            };

            // Act
            writer.WriteUsingDirective(context, node);

            // Assert
            var mapping = Assert.Single(((DefaultCodeRenderingContext)context).SourceMappings);

            Assert.Equal(expectedSourceMapping, mapping);
            var csharp = context.CodeWriter.GenerateCode();

            Assert.Equal(
                @"#line 1 ""test.cshtml""
using System;

#line default
#line hidden
",
                csharp,
                ignoreLineEndingDifferences: true);
        }
    public void Lower_WithMultipleImports_SingleLineFileScopedSinglyOccurring()
    {
        // Arrange
        var source  = TestRazorSourceDocument.Create("<p>Hi!</p>");
        var imports = new[]
        {
            TestRazorSourceDocument.Create("@test value1"),
            TestRazorSourceDocument.Create("@test value2"),
        };

        var codeDocument = TestRazorCodeDocument.Create(source, imports);

        // Act
        var documentNode = Lower(codeDocument, b =>
        {
            b.AddDirective(DirectiveDescriptor.CreateDirective(
                               "test",
                               DirectiveKind.SingleLine,
                               builder =>
            {
                builder.AddMemberToken();
                builder.Usage = DirectiveUsage.FileScopedSinglyOccurring;
            }));
        });

        // Assert
        Children(
            documentNode,
            n => Directive("test", n, c => DirectiveToken(DirectiveTokenKind.Member, "value2", c)),
            n => Html("<p>Hi!</p>", n));
    }
Ejemplo n.º 13
0
        public void Parse_Persists_FilePath()
        {
            // Arrange
            var filePath = "test.cshtml";
            var source   = TestRazorSourceDocument.Create("@if (true) { @if(false) { <div>@something.</div> } }", fileName: filePath);

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

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

            var spans = new List <SyntaxTreeNode>();

            GetChildren(syntaxTree.Root);
            Assert.All(spans, node => Assert.Equal(filePath, node.Start.FilePath));

            void GetChildren(SyntaxTreeNode node)
            {
                if (node is Block block)
                {
                    foreach (var child in block.Children)
                    {
                        GetChildren(child);
                    }
                }
                else
                {
                    spans.Add(node);
                }
            }
        }
Ejemplo n.º 14
0
        public void CanParseStuff()
        {
            var parser         = new RazorParser();
            var sourceDocument = TestRazorSourceDocument.CreateResource("TestFiles/Source/BasicMarkup.cshtml", GetType());
            var output         = parser.Parse(sourceDocument);

            Assert.NotNull(output);
        }
        private static RazorCodeDocument CreateCodeDocument(string text)
        {
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var projectEngine  = RazorProjectEngine.Create(builder => { });
            var codeDocument   = projectEngine.ProcessDesignTime(sourceDocument, FileKinds.Legacy, Array.Empty <RazorSourceDocument>(), Array.Empty <TagHelperDescriptor>());

            return(codeDocument);
        }
Ejemplo n.º 16
0
        public void Execute_HasRequiredInfo_AddsItemAndSourceChecksum()
        {
            // Arrange
            var engine = CreateEngine();
            var pass   = new MetadataAttributePass()
            {
                Engine = engine,
            };

            var sourceDocument = TestRazorSourceDocument.Create("", new RazorSourceDocumentProperties(null, "Foo\\Bar.cshtml"));
            var codeDocument   = RazorCodeDocument.Create(sourceDocument);

            var irDocument = new DocumentIntermediateNode()
            {
                DocumentKind = "test",
                Options      = RazorCodeGenerationOptions.Create((o) => { }),
            };
            var builder    = IntermediateNodeBuilder.Create(irDocument);
            var @namespace = new NamespaceDeclarationIntermediateNode
            {
                Annotations =
                {
                    [CommonAnnotations.PrimaryNamespace] = CommonAnnotations.PrimaryNamespace,
                },
                Content = "Some.Namespace"
            };

            builder.Push(@namespace);
            var @class = new ClassDeclarationIntermediateNode
            {
                Annotations =
                {
                    [CommonAnnotations.PrimaryClass] = CommonAnnotations.PrimaryClass,
                },
                ClassName = "Test",
            };

            builder.Add(@class);

            // Act
            pass.Execute(codeDocument, irDocument);

            // Assert
            Assert.Equal(2, irDocument.Children.Count);

            var item = Assert.IsType <RazorCompiledItemAttributeIntermediateNode>(irDocument.Children[0]);

            Assert.Equal("/Foo/Bar.cshtml", item.Identifier);
            Assert.Equal("test", item.Kind);
            Assert.Equal("Some.Namespace.Test", item.TypeName);

            Assert.Equal(2, @namespace.Children.Count);
            var checksum = Assert.IsType <RazorSourceChecksumAttributeIntermediateNode>(@namespace.Children[0]);

            Assert.NotNull(checksum.Checksum); // Not verifying the checksum here
            Assert.Equal("SHA1", checksum.ChecksumAlgorithm);
            Assert.Equal("/Foo/Bar.cshtml", checksum.Identifier);
        }
        private static RazorCodeDocument CreateComponentDocument(string text, params TagHelperDescriptor[] tagHelpers)
        {
            tagHelpers ??= Array.Empty <TagHelperDescriptor>();
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var projectEngine  = RazorProjectEngine.Create(builder => { });
            var codeDocument   = projectEngine.ProcessDesignTime(sourceDocument, FileKinds.Component, Array.Empty <RazorSourceDocument>(), tagHelpers);

            return(codeDocument);
        }
Ejemplo n.º 18
0
        private static RazorCodeDocument CreateCodeDocument(string text)
        {
            var codeDocument   = TestRazorCodeDocument.CreateEmpty();
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var syntaxTree     = RazorSyntaxTree.Parse(sourceDocument);

            codeDocument.SetSyntaxTree(syntaxTree);
            return(codeDocument);
        }
Ejemplo n.º 19
0
        private static RazorCodeDocument CreateCodeDocument(string text, IReadOnlyList <TagHelperDescriptor> tagHelpers = null)
        {
            tagHelpers ??= Array.Empty <TagHelperDescriptor>();
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var projectEngine  = RazorProjectEngine.Create(builder => { });
            var codeDocument   = projectEngine.ProcessDesignTime(sourceDocument, "mvc", Array.Empty <RazorSourceDocument>(), tagHelpers);

            return(codeDocument);
        }
Ejemplo n.º 20
0
        public void Execute_SuppressMetadataSourceChecksumAttributes_DoesNotGenerateSourceChecksumAttributes()
        {
            // Arrange
            var engine = CreateEngine();
            var pass   = new MetadataAttributePass()
            {
                Engine = engine,
            };

            var sourceDocument = TestRazorSourceDocument.Create("", new RazorSourceDocumentProperties(null, "Foo\\Bar.cshtml"));
            var import         = TestRazorSourceDocument.Create("@using System", new RazorSourceDocumentProperties(null, "Foo\\Import.cshtml"));
            var codeDocument   = RazorCodeDocument.Create(sourceDocument, new[] { import, });

            var irDocument = new DocumentIntermediateNode()
            {
                DocumentKind = "test",
                Options      = RazorCodeGenerationOptions.Create(o => o.SuppressMetadataSourceChecksumAttributes = true),
            };
            var builder    = IntermediateNodeBuilder.Create(irDocument);
            var @namespace = new NamespaceDeclarationIntermediateNode
            {
                Annotations =
                {
                    [CommonAnnotations.PrimaryNamespace] = CommonAnnotations.PrimaryNamespace,
                },
                Content = "Some.Namespace"
            };

            builder.Push(@namespace);
            var @class = new ClassDeclarationIntermediateNode
            {
                Annotations =
                {
                    [CommonAnnotations.PrimaryClass] = CommonAnnotations.PrimaryClass,
                },
                ClassName = "Test",
            };

            builder.Add(@class);

            // Act
            pass.Execute(codeDocument, irDocument);

            // Assert
            Assert.Equal(2, irDocument.Children.Count);

            var item = Assert.IsType <RazorCompiledItemAttributeIntermediateNode>(irDocument.Children[0]);

            Assert.Equal("/Foo/Bar.cshtml", item.Identifier);
            Assert.Equal("test", item.Kind);
            Assert.Equal("Some.Namespace.Test", item.TypeName);

            var child = Assert.Single(@namespace.Children);

            Assert.IsType <ClassDeclarationIntermediateNode>(child);
        }
        private static RazorSyntaxTree GetSyntaxTree(string text, string fileKind = null)
        {
            fileKind ??= FileKinds.Component;
            var sourceDocument = TestRazorSourceDocument.Create(text);
            var projectEngine  = RazorProjectEngine.Create(builder => { });
            var codeDocument   = projectEngine.ProcessDesignTime(sourceDocument, fileKind, Array.Empty <RazorSourceDocument>(), Array.Empty <TagHelperDescriptor>());
            var syntaxTree     = codeDocument.GetSyntaxTree();

            return(syntaxTree);
        }
Ejemplo n.º 22
0
        private static TestTokenizerBackedParser CreateContentTokenizer(string content)
        {
            var source  = TestRazorSourceDocument.Create(content);
            var options = RazorParserOptions.CreateDefault();
            var context = new ParserContext(source, options);

            var tokenizer = new TestTokenizerBackedParser(HtmlLanguageCharacteristics.Instance, context);

            return(tokenizer);
        }
        internal static RazorCodeDocument CreateCodeDocument(string text, string filePath, params TagHelperDescriptor[] tagHelpers)
        {
            tagHelpers ??= Array.Empty <TagHelperDescriptor>();
            var sourceDocument = TestRazorSourceDocument.Create(text, filePath: filePath, relativePath: filePath);
            var projectEngine  = RazorProjectEngine.Create(builder => { });
            var fileKind       = filePath.EndsWith(".razor", StringComparison.Ordinal) ? FileKinds.Component : FileKinds.Legacy;
            var codeDocument   = projectEngine.ProcessDesignTime(sourceDocument, fileKind, Array.Empty <RazorSourceDocument>(), tagHelpers);

            return(codeDocument);
        }
 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;
 }
        public void CodeDocumentRequest_Complete_CanBeCalledMultipleTimes()
        {
            // Arrange
            var codeDocument = RazorCodeDocument.Create(TestRazorSourceDocument.Create());
            var request      = new DefaultVisualStudioRazorParser.CodeDocumentRequest(StringTextSnapshot.Empty, CancellationToken.None);

            // Act & Assert
            request.Complete(codeDocument);
            request.Complete(codeDocument);
            request.Complete(codeDocument);
        }
Ejemplo n.º 26
0
        internal static IReadOnlyList <ClassifiedSpanInternal> GetClassifiedSpans(Block root, string filePath)
        {
            // We don't care about the options and diagnostic here.
            var syntaxTree = RazorSyntaxTree.Create(
                root,
                TestRazorSourceDocument.Create(filePath: filePath),
                Array.Empty <RazorDiagnostic>(),
                RazorParserOptions.CreateDefault());

            return(syntaxTree.GetClassifiedSpans());
        }
Ejemplo n.º 27
0
        public void GetLineLength_Bigger()
        {
            // Arrange
            var content    = @"@addTagHelper, * Stuff
@* A comment *@";
            var document   = TestRazorSourceDocument.Create(content);
            var collection = new DefaultRazorSourceLineCollection(document);

            // Act & Assert
            Assert.Throws <IndexOutOfRangeException>(() => collection.GetLineLength(40));
        }
        private static TextBufferCodeDocumentProvider CreateCodeDocumentProvider(string content)
        {
            var sourceDocument = TestRazorSourceDocument.Create(content);
            var syntaxTree     = RazorSyntaxTree.Parse(sourceDocument, RazorParserOptions.Create(opt => opt.Directives.Add(FunctionsDirective.Directive)));
            var codeDocument   = TestRazorCodeDocument.Create(content);

            codeDocument.SetSyntaxTree(syntaxTree);
            var codeDocumentProvider = Mock.Of <TextBufferCodeDocumentProvider>(provider => provider.TryGetFromBuffer(It.IsAny <ITextBuffer>(), out codeDocument), MockBehavior.Strict);

            return(codeDocumentProvider);
        }
Ejemplo n.º 29
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);
        }
        public void Execute_EscapesViewPathAndRouteWhenAddingAttributeToPage()
        {
            // Arrange
            var expectedAttribute = "[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@\"/test/\"\"Index.cshtml\", typeof(SomeNamespace.SomeName))]";
            var irDocument        = new DocumentIntermediateNode
            {
                DocumentKind = MvcViewDocumentClassifierPass.MvcViewDocumentKind,
                Options      = RazorCodeGenerationOptions.CreateDefault(),
            };
            var builder    = IntermediateNodeBuilder.Create(irDocument);
            var @namespace = new NamespaceDeclarationIntermediateNode
            {
                Content     = "SomeNamespace",
                Annotations =
                {
                    [CommonAnnotations.PrimaryNamespace] = CommonAnnotations.PrimaryNamespace
                },
            };

            builder.Push(@namespace);
            var @class = new ClassDeclarationIntermediateNode
            {
                ClassName   = "SomeName",
                Annotations =
                {
                    [CommonAnnotations.PrimaryClass] = CommonAnnotations.PrimaryClass,
                },
            };

            builder.Add(@class);

            var pass = new AssemblyAttributeInjectionPass
            {
                Engine = RazorProjectEngine.Create().Engine,
            };

            var source   = TestRazorSourceDocument.Create("test", new RazorSourceDocumentProperties(filePath: null, relativePath: "test\\\"Index.cshtml"));
            var document = RazorCodeDocument.Create(source);

            // Act
            pass.Execute(document, irDocument);

            // Assert
            Assert.Collection(irDocument.Children,
                              node =>
            {
                var csharpCode = Assert.IsType <CSharpCodeIntermediateNode>(node);
                var token      = Assert.IsType <IntermediateToken>(Assert.Single(csharpCode.Children));
                Assert.Equal(TokenKind.CSharp, token.Kind);
                Assert.Equal(expectedAttribute, token.Content);
            },
                              node => Assert.Same(@namespace, node));
        }