Exemple #1
0
        /// <summary>
        /// Initializes a new instance of <see cref="MvcRazorParser"/>.
        /// </summary>
        /// <param name="parser">The <see cref="RazorParser"/> to copy properties from.</param>
        /// <param name="inheritedChunkTrees">The <see cref="IReadOnlyList{ChunkTree}"/>s that are inherited
        /// from parsed pages from _ViewImports files.</param>
        /// <param name="defaultInheritedChunks">The <see cref="IReadOnlyList{Chunk}"/> inherited by
        /// default by all Razor pages in the application.</param>
        /// <param name="modelExpressionTypeName">The full name of the model expression <see cref="Type"/>.</param>
        public MvcRazorParser(
            RazorParser parser,
            IReadOnlyList<ChunkTree> inheritedChunkTrees,
            IReadOnlyList<Chunk> defaultInheritedChunks,
            string modelExpressionTypeName)
            : base(parser)
        {
            if (parser == null)
            {
                throw new ArgumentNullException(nameof(parser));
            }

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

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

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

            // Construct tag helper descriptors from @addTagHelper, @removeTagHelper and @tagHelperPrefix chunks
            _viewImportsDirectiveDescriptors = GetTagHelperDirectiveDescriptors(
                inheritedChunkTrees,
                defaultInheritedChunks);

            _modelExpressionTypeName = modelExpressionTypeName;
        }
        public void DecorateRazorParser_DesignTimeRazorPathNormalizer_NormalizesChunkInheritanceUtilityPaths(
            string rootPrefix)
        {
            // Arrange
            var rootedAppPath = $"{rootPrefix}SomeComputer/Location/Project/";
            var rootedFilePath = $"{rootPrefix}SomeComputer/Location/Project/src/file.cshtml";
            var chunkTreeCache = new DefaultChunkTreeCache(new TestFileProvider());
            using (var host = new MvcRazorHost(
                chunkTreeCache,
                pathNormalizer: new DesignTimeRazorPathNormalizer(rootedAppPath)))
            {
                var parser = new RazorParser(
                    host.CodeLanguage.CreateCodeParser(),
                    host.CreateMarkupParser(),
                    tagHelperDescriptorResolver: null);
                var chunkInheritanceUtility = new PathValidatingChunkInheritanceUtility(host, chunkTreeCache);
                host.ChunkInheritanceUtility = chunkInheritanceUtility;

                // Act
                host.DecorateRazorParser(parser, rootedFilePath);

                // Assert
                Assert.Equal("src/file.cshtml", chunkInheritanceUtility.InheritedChunkTreePagePath, StringComparer.Ordinal);
            }
        }
Exemple #3
0
        /// <summary>
        /// Initializes a new instance of <see cref="RazorParser"/> from the specified <paramref name="parser" />.
        /// </summary>
        /// <param name="parser">The <see cref="RazorParser"/> to copy values from.</param>
        public RazorParser(RazorParser parser)
           : this(parser.CodeParser, parser.MarkupParser, parser.TagHelperDescriptorResolver, parser.Optimizers)
        {
            if (parser == null)
            {
                throw new ArgumentNullException(nameof(parser));
            }

            DesignTimeMode = parser.DesignTimeMode;
        }
Exemple #4
0
        public void ParseMethodCallsParseDocumentOnMarkupParserAndReturnsResults()
        {
            var factory = SpanFactory.CreateCsHtml();

            // Arrange
            var parser = new RazorParser(new CSharpCodeParser(),
                                         new HtmlMarkupParser(),
                                         tagHelperDescriptorResolver: null);

            // Act/Assert
            ParserTestBase.EvaluateResults(parser.Parse(new StringReader("foo @bar baz")),
                new MarkupBlock(
                    factory.Markup("foo "),
                    new ExpressionBlock(
                        factory.CodeTransition(),
                        factory.Code("bar")
                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
                               .Accepts(AcceptedCharacters.NonWhiteSpace)),
                    factory.Markup(" baz")));
        }
Exemple #5
0
        public static RazorSyntaxTree Parse(RazorSourceDocument document)
        {
            if (document == null)
            {
                throw new ArgumentException(nameof(document));
            }

            var codeParser   = new PageCodeParser();
            var markupParser = new HtmlMarkupParser();

            var parser = new OldParser.RazorParser(codeParser, markupParser, new NullTagHelperDescriptorResolver());

            ParserResults result;

            using (var reader = document.CreateReader())
            {
                result = parser.Parse(reader);
            }

            return(RazorSyntaxTree.Create(result.Document, result.ParserErrors));
        }
Exemple #6
0
        public void ParseMethodUsesProvidedParserListenerIfSpecified()
        {
            var factory = SpanFactory.CreateCsHtml();

            // Arrange
            var parser = new RazorParser(new CSharpCodeParser(),
                                         new HtmlMarkupParser(),
                                         tagHelperDescriptorResolver: null);

            // Act
            var results = parser.Parse(new StringReader("foo @bar baz"));

            // Assert
            ParserTestBase.EvaluateResults(results,
                new MarkupBlock(
                    factory.Markup("foo "),
                    new ExpressionBlock(
                        factory.CodeTransition(),
                        factory.Code("bar")
                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
                               .Accepts(AcceptedCharacters.NonWhiteSpace)),
                    factory.Markup(" baz")));
        }
        protected internal virtual RazorParser CreateParser(string sourceFileName)
        {
            var codeParser = Host.CodeLanguage.CreateCodeParser();
            var markupParser = Host.CreateMarkupParser();

            var parser = new RazorParser(
                Host.DecorateCodeParser(codeParser),
                Host.DecorateMarkupParser(markupParser),
                Host.TagHelperDescriptorResolver)
            {
                DesignTimeMode = Host.DesignTimeMode
            };

            return Host.DecorateRazorParser(parser, sourceFileName);
        }
Exemple #8
0
        private static void RunParseWithListenerTest(Action<RazorParser, TextReader> parserAction)
        {
            // Arrange
            var markupParser = new MockMarkupParser();
            var codeParser = new CSharpCodeParser();
            var parser = new RazorParser(codeParser, markupParser, tagHelperDescriptorResolver: null);
            var expectedReader = new StringReader("foo");

            // Act
            parserAction(parser, expectedReader);

            // Assert
            var actualContext = markupParser.Context;
            Assert.NotNull(actualContext);
            Assert.Same(markupParser, actualContext.MarkupParser);
            Assert.Same(markupParser, actualContext.ActiveParser);
            Assert.Same(codeParser, actualContext.CodeParser);
        }
Exemple #9
0
 public TestableMvcRazorParser(
     RazorParser parser,
     IReadOnlyList<ChunkTree> chunkTrees,
     IReadOnlyList<Chunk> defaultInheritedChunks)
     : base(parser, chunkTrees, defaultInheritedChunks, typeof(ModelExpression).FullName)
 {
 }
Exemple #10
0
        public void GetTagHelperDescriptors_ReturnsExpectedDirectiveDescriptors(
            ChunkTree[] chunkTrees,
            TagHelperDirectiveDescriptor[] expectedDirectiveDescriptors)
        {
            // Arrange
            var builder = new BlockBuilder { Type = BlockType.Comment };
            var block = new Block(builder);

            IList<TagHelperDirectiveDescriptor> descriptors = null;
            var resolver = new Mock<ITagHelperDescriptorResolver>();
            resolver.Setup(r => r.Resolve(It.IsAny<TagHelperDescriptorResolutionContext>()))
                    .Callback((TagHelperDescriptorResolutionContext context) =>
                    {
                        descriptors = context.DirectiveDescriptors;
                    })
                    .Returns(Enumerable.Empty<TagHelperDescriptor>())
                    .Verifiable();

            var baseParser = new RazorParser(
                new CSharpCodeParser(),
                new HtmlMarkupParser(),
                tagHelperDescriptorResolver: resolver.Object);
            var parser = new TestableMvcRazorParser(baseParser, chunkTrees, defaultInheritedChunks: new Chunk[0]);

            // Act
            parser.GetTagHelperDescriptorsPublic(block, errorSink: new ErrorSink()).ToArray();

            // Assert
            Assert.NotNull(descriptors);
            Assert.Equal(expectedDirectiveDescriptors.Length, descriptors.Count);

            for (var i = 0; i < expectedDirectiveDescriptors.Length; i++)
            {
                var expected = expectedDirectiveDescriptors[i];
                var actual = descriptors[i];

                Assert.Equal(expected.DirectiveText, actual.DirectiveText, StringComparer.Ordinal);
                Assert.Equal(SourceLocation.Zero, actual.Location);
                Assert.Equal(expected.DirectiveType, actual.DirectiveType);
            }
        }
Exemple #11
0
        /// <summary>
        /// Provides an opportunity for derived types to modify the instance of <see cref="RazorParser"/>
        /// used by the <see cref="RazorTemplateEngine"/> to parse the Razor tree.
        /// </summary>
        /// <param name="incomingRazorParser">The <see cref="RazorParser"/></param>
        /// <param name="sourceFileName">The file name of the Razor file being parsed.</param>
        /// <returns>Either the same code parser, after modifications, or a different code parser.</returns>
        public virtual RazorParser DecorateRazorParser(
            RazorParser incomingRazorParser,
            string sourceFileName)
        {
            if (incomingRazorParser == null)
            {
                throw new ArgumentNullException(nameof(incomingRazorParser));
            }

            return incomingRazorParser;
        }
        private static Span[] GenerateSpans(string text, SpanKind spanKind, int spanIndex, string spanText)
        {
            Assert.True(spanIndex > 0);

            var parser = new RazorParser(new CSharpCodeParser(),
                                         new HtmlMarkupParser(),
                                         tagHelperDescriptorResolver: null);

            Span[] spans;

            using (var reader = new StringReader(text))
            {
                var results = parser.Parse(reader);
                spans = results.Document.Flatten().ToArray();
            }

            Assert.True(spans.Length > spanIndex);
            Assert.Equal(spanKind, spans[spanIndex].Kind);
            Assert.Equal(spanText, spans[spanIndex].Content);

            return spans;
        }
Exemple #13
0
        /// <inheritdoc />
        public override RazorParser DecorateRazorParser(RazorParser razorParser, string sourceFileName)
        {
            if (razorParser == null)
            {
                throw new ArgumentNullException(nameof(razorParser));
            }

            var inheritedChunkTrees = GetInheritedChunkTrees(sourceFileName);
            return new MvcRazorParser(razorParser, inheritedChunkTrees, DefaultInheritedChunks, ModelExpressionType);
        }