Esempio n. 1
0
        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);
            }
        }
Esempio n. 2
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>
        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;
        }
Esempio n. 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;
        }
Esempio n. 4
0
        private static void RunParseWithListenerTest(Action<RazorParser, TextReader> parserAction)
        {
            // Arrange
            ParserBase markupParser = new MockMarkupParser();
            ParserBase codeParser = new CSharpCodeParser();
            RazorParser parser = new RazorParser(codeParser, markupParser);
            TextReader expectedReader = new StringReader("foo");

            // Act
            parserAction(parser, expectedReader);

            // Assert
            ParserContext actualContext = markupParser.Context;
            Assert.NotNull(actualContext);
            Assert.Same(markupParser, actualContext.MarkupParser);
            Assert.Same(markupParser, actualContext.ActiveParser);
            Assert.Same(codeParser, actualContext.CodeParser);
        }
Esempio n. 5
0
        public void ParseMethodCallsParseDocumentOnMarkupParserAndReturnsResults()
        {
            var factory = SpanFactory.CreateCsHtml();

            // Arrange
            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            // 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")));
        }
Esempio n. 6
0
        public void ParseMethodUsesProvidedParserListenerIfSpecified()
        {
            var factory = SpanFactory.CreateCsHtml();

            // Arrange
            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            // Act
            ParserResults 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")));
        }
Esempio n. 7
0
        private static Span[] GenerateSpans(string text, SpanKind spanKind, int spanIndex, string spanText)
        {
            Assert.True(spanIndex > 0);

            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            Span[] spans;

            using (var reader = new StringReader(text))
            {
                ParserResults 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;
        }
Esempio n. 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);
        }
Esempio n. 9
0
        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);
        }
Esempio n. 10
0
 public TestableMvcRazorParser(RazorParser parser,
                               IReadOnlyList<CodeTree> codeTrees,
                               IReadOnlyList<Chunk> defaultInheritedChunks)
     : base(parser, codeTrees, defaultInheritedChunks, typeof(ModelExpression).FullName)
 {
 }
Esempio n. 11
0
        public void GetTagHelperDescriptors_ReturnsExpectedDirectiveDescriptors(
            CodeTree[] codeTrees,
            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, codeTrees, 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);
            }
        }
Esempio n. 12
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);
        }
Esempio n. 13
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;
        }
Esempio n. 14
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([NotNull] RazorParser parser)
     : this(parser.CodeParser, parser.MarkupParser, parser.TagHelperDescriptorResolver, parser.Optimizers)
 {
     DesignTimeMode = parser.DesignTimeMode;
 }
Esempio n. 15
0
		public IEnumerable<Invocation> GetInvocations(TextReader reader, string fileName = null)
		{
			var result = new List<Invocation>();

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

			var parserResults = parser.Parse(reader);
			var codeSpans = parserResults.Document.Flatten()
				.Where(s => s.Kind == SpanKind.Code);

			foreach (var codeSpan in codeSpans)
			{
				var symbols = codeSpan.Symbols as IReadOnlyList<ISymbol> ?? codeSpan.Symbols.ToArray();

				for (var i = 0; i < symbols.Count; i++)
				{
					var call = PeekMethodCall(symbols, i, fileName, codeSpan.Start.LineIndex, codeSpan.Start.CharacterIndex);
					if (call == null)
						continue;

					result.Add(call);
				}
			}

			return result;
		}