コード例 #1
0
ファイル: RazorErrorExtensions.cs プロジェクト: zt97/Mvc
        public static Diagnostic ToDiagnostics([NotNull] this RazorError error, [NotNull] string filePath)
        {
            var descriptor = new DiagnosticDescriptor(
                id: "Razor",
                title: "Razor parsing error",
                messageFormat: error.Message.Replace("{", "{{").Replace("}", "}}"),
                category: "Razor.Parser",
                defaultSeverity: DiagnosticSeverity.Error,
                isEnabledByDefault: true);

            var location = error.Location;

            if (location.Equals(SourceLocation.Undefined))
            {
                location = SourceLocation.Zero;
            }
            var length = Math.Max(0, error.Length);

            var textSpan          = new TextSpan(location.AbsoluteIndex, length);
            var linePositionStart = new LinePosition(location.LineIndex, location.CharacterIndex);
            var linePositionEnd   = new LinePosition(location.LineIndex, location.CharacterIndex + length);
            var linePositionSpan  = new LinePositionSpan(linePositionStart, linePositionEnd);

            return(Diagnostic.Create(descriptor, Location.Create(filePath, textSpan, linePositionSpan)));
        }
コード例 #2
0
 public override void VisitError(RazorError err)
 {
     if (StrictMode)
     {
         throw new TemplateParsingException(err.Message, err.Location.CharacterIndex, err.Location.LineIndex);
     }
 }
コード例 #3
0
 /// <summary>
 /// Visits an error generated through parsing.
 /// </summary>
 /// <param name="err">The error that was generated.</param>
 public override void VisitError(RazorError err)
 {
     if (StrictMode)
     {
         throw new TemplateParsingException(err);
     }
 }
コード例 #4
0
 public override void VisitError(RazorError err) {
     base.VisitError(err);
     if (_errorList == null) {
         _errorList = new List<RazorError>();
     }
     _errorList.Add(err);
 }
コード例 #5
0
        private void NamespaceImportTest(
            string content,
            string expectedNS,
            AcceptedCharacters acceptedCharacters = AcceptedCharacters.None,
            string errorMessage     = null,
            SourceLocation?location = null
            )
        {
            var errors = new RazorError[0];

            if (!String.IsNullOrEmpty(errorMessage) && location.HasValue)
            {
                errors = new RazorError[] { new RazorError(errorMessage, location.Value) };
            }
            ParseBlockTest(
                content,
                new DirectiveBlock(
                    Factory
                    .Code(content)
                    .AsNamespaceImport(expectedNS, CSharpCodeParser.UsingKeywordLength)
                    .Accepts(acceptedCharacters)
                    ),
                errors
                );
        }
コード例 #6
0
ファイル: ParserContext.cs プロジェクト: lodejard/AllNetCore
        public void OnError(RazorError error)
        {
            EnusreNotTerminated();
            AssertOnOwnerTask();

            _errorSink.OnError(error);
        }
コード例 #7
0
        public void ParseDocument_WithUnexpectedTransitionsInAttributeValue_Throws()
        {
            // Arrange
            var expected = new MarkupBlock(
                new MarkupTagBlock(
                    Factory.Markup("<span"),
                    new MarkupBlock(
                        new AttributeBlockChunkGenerator("foo", new LocationTagged <string>(" foo='", 5, 0, 5), new LocationTagged <string>("'", 14, 0, 14)),
                        Factory.Markup(" foo='").With(SpanChunkGenerator.Null),
                        new MarkupBlock(
                            new DynamicAttributeBlockChunkGenerator(new LocationTagged <string>(string.Empty, 11, 0, 11), 11, 0, 11),
                            new ExpressionBlock(
                                Factory.CodeTransition(),
                                Factory.EmptyCSharp().AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace))),
                        new MarkupBlock(
                            new DynamicAttributeBlockChunkGenerator(new LocationTagged <string>(" ", 12, 0, 12), 12, 0, 12),
                            Factory.Markup(" ").With(SpanChunkGenerator.Null),
                            new ExpressionBlock(
                                Factory.CodeTransition().Accepts(AcceptedCharacters.None).With(SpanChunkGenerator.Null),
                                Factory.EmptyCSharp().AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace))),
                        Factory.Markup("'").With(SpanChunkGenerator.Null)),
                    Factory.Markup(" />")));
            var expectedErrors = new RazorError[]
            {
                new RazorError(@"A space or line break was encountered after the ""@"" character.  Only valid identifiers, keywords, comments, ""("" and ""{"" are valid at the start of a code block and they must occur immediately following ""@"" with no space in between.", new SourceLocation(12, 0, 12)),
                new RazorError(@"""' />"" is not valid at the start of a code block.  Only identifiers, keywords, comments, ""("" and ""{"" are valid.", new SourceLocation(14, 0, 14)),
            };

            // Act & Assert
            ParseDocumentTest("<span foo='@ @' />", expected, expectedErrors);
        }
コード例 #8
0
        public override void VisitError(RazorError err)
        {
            err.ThrowIfNull("err");

            if (_throwExceptionOnParserError)
            {
                throw new TemplateParsingException(err);
            }
        }
コード例 #9
0
        public override void VisitError(RazorError err)
        {
            err.ThrowIfNull("err");

            if (_throwExceptionOnParserError)
            {
                throw new TemplateParsingException(err);
            }
        }
コード例 #10
0
        internal static RazorDiagnostic Create(RazorError error)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            return(new LegacyRazorDiagnostic(error));
        }
コード例 #11
0
        public RazorPadRazorError(RazorError error)
        {
            if (error == null)
                return;

            Column = error.Location.CharacterIndex;
            Line = error.Location.LineIndex;
            Message = error.Message;
        }
コード例 #12
0
        public RazorPadRazorError(RazorError error)
        {
            if (error == null)
            {
                return;
            }

            Column  = error.Location.CharacterIndex;
            Line    = error.Location.LineIndex;
            Message = error.Message;
        }
コード例 #13
0
        public void LegacyRazorDiagnostic_ToString_FormatProvider()
        {
            // Arrange
            var error      = new RazorError("This is an error", SourceLocation.Zero, 5);
            var diagnostic = new LegacyRazorDiagnostic(new RazorError("This is an error", SourceLocation.Zero, 5));

            // Act
            var result = ((IFormattable)diagnostic).ToString("ignored", CultureInfo.InvariantCulture);

            // Assert
            Assert.Equal("(1,1): Error RZ9999: This is an error", result);
        }
コード例 #14
0
 private DiagnosticMessage CreateDiagnosticMessage(RazorError error, string filePath)
 {
     return(new DiagnosticMessage(
                error.Message,
                $"{error} ({error.Location.LineIndex},{error.Location.CharacterIndex}) {error.Message}",
                filePath,
                DiagnosticMessageSeverity.Error,
                error.Location.LineIndex + 1,
                error.Location.CharacterIndex,
                error.Location.LineIndex + 1,
                error.Location.CharacterIndex + error.Length));
 }
コード例 #15
0
        public void LegacyRazorDiagnostic_ToString()
        {
            // Arrange
            var error      = new RazorError("This is an error", SourceLocation.Zero, 5);
            var diagnostic = new LegacyRazorDiagnostic(error);

            // Act
            var result = diagnostic.ToString();

            // Assert
            Assert.Equal("(1,1): Error RZ9999: This is an error", result);
        }
コード例 #16
0
        public void LegacyRazorDiagnostic_GetMessage_FormatProvider()
        {
            // Arrange
            var error      = new RazorError("This is an error", SourceLocation.Zero, 5);
            var diagnostic = new LegacyRazorDiagnostic(error);

            // Act
            var result = diagnostic.GetMessage(CultureInfo.InvariantCulture);

            // Assert
            Assert.Equal("This is an error", result);
        }
コード例 #17
0
        public void LegacyRazorDiagnostic_GetMessage()
        {
            // Arrange
            var error      = new RazorError("This is an error", SourceLocation.Zero, 5);
            var diagnostic = new LegacyRazorDiagnostic(error);

            // Act
            var result = diagnostic.GetMessage();

            // Assert
            Assert.Equal("This is an error", result);
        }
コード例 #18
0
 private static HttpParseException CreateExceptionFromParserError(
     RazorError error,
     string virtualPath
     )
 {
     return(new HttpParseException(
                error.Message + Environment.NewLine,
                null,
                virtualPath,
                null,
                error.Location.LineIndex + 1
                ));
 }
コード例 #19
0
 private DiagnosticMessage CreateDiagnosticMessage(RazorError error, string filePath)
 {
     return(new DiagnosticMessage(
                errorCode: null,
                message: error.Message,
                formattedMessage: $"{error} ({error.Location.LineIndex},{error.Location.CharacterIndex}) {error.Message}",
                filePath: filePath,
                severity: DiagnosticMessageSeverity.Error,
                startLine: error.Location.LineIndex + 1,
                startColumn: error.Location.CharacterIndex,
                endLine: error.Location.LineIndex + 1,
                endColumn: error.Location.CharacterIndex + error.Length));
 }
コード例 #20
0
 public void ParseBlockMethodParsesNullConditionalOperatorImplicitExpression_Bracket(
     string implicitExpresison,
     string expectedImplicitExpression,
     AcceptedCharacters acceptedCharacters,
     RazorError[] expectedErrors)
 {
     // Act & Assert
     ImplicitExpressionTest(
         implicitExpresison,
         expectedImplicitExpression,
         acceptedCharacters,
         expectedErrors);
 }
コード例 #21
0
        private DiagnosticMessage CreateDiagnosticMessage(RazorError error, string filePath)
        {
            var location = error.Location;

            return(new DiagnosticMessage(
                       message: error.Message,
                       formattedMessage: $"{error} ({location.LineIndex},{location.CharacterIndex}) {error.Message}",
                       filePath: filePath,
                       startLine: error.Location.LineIndex + 1,
                       startColumn: error.Location.CharacterIndex,
                       endLine: error.Location.LineIndex + 1,
                       endColumn: error.Location.CharacterIndex + error.Length));
        }
コード例 #22
0
        public void LegacyRazorDiagnostic_Ctor()
        {
            // Arrange
            var span  = new SourceSpan("test.cs", 15, 1, 8, 5);
            var error = new RazorError("This is an error", new SourceLocation("test.cs", 15, 1, 8), 5);

            // Act
            var diagnostic = new LegacyRazorDiagnostic(error);

            // Assert
            Assert.Equal("RZ9999", diagnostic.Id);
            Assert.Equal(RazorDiagnosticSeverity.Error, diagnostic.Severity);
            Assert.Equal(span, diagnostic.Span);
        }
コード例 #23
0
        public void Create_WithRazorError_CreatesLegacyRazorDiagnostic()
        {
            // Arrange
            var span  = new SourceSpan("test.cs", 15, 1, 8, 5);
            var error = new RazorError("This is an error", new SourceLocation("test.cs", 15, 1, 8), 5);

            // Act
            var diagnostic = RazorDiagnostic.Create(error);

            // Assert
            var legacyDiagnostic = Assert.IsType <LegacyRazorDiagnostic>(diagnostic);

            Assert.Equal("RZ9999", legacyDiagnostic.Id);
            Assert.Equal(RazorDiagnosticSeverity.Error, legacyDiagnostic.Severity);
            Assert.Equal(span, diagnostic.Span);
        }
コード例 #24
0
        /// <summary>
        /// Initializes a <see cref="RazorCompilationMessage"/> with the specified message.
        /// </summary>
        /// <param name="razorError">A <see cref="RazorError"/>.</param>
        /// <param name="sourceFilePath">The path of the Razor source file that was parsed.</param>
        public RazorCompilationMessage(
            [NotNull] RazorError razorError,
            string sourceFilePath)
        {
            SourceFilePath = sourceFilePath;
            Message        = razorError.Message;

            var location = razorError.Location;

            FormattedMessage =
                $"{sourceFilePath} ({location.LineIndex},{location.CharacterIndex}) {razorError.Message}";

            StartColumn = location.CharacterIndex;
            StartLine   = location.LineIndex + 1;
            EndColumn   = location.CharacterIndex + razorError.Length;
            EndLine     = location.LineIndex + 1;
        }
コード例 #25
0
        public void ToDiagnostic_ConvertsRazorErrorLocation_ToSourceLineMappings()
        {
            // Arrange
            var sourceLocation = new SourceLocation(absoluteIndex: 30, lineIndex: 10, characterIndex: 1);
            var error = new RazorError("some message", sourceLocation, length: 5);

            // Act
            var diagnostics = error.ToDiagnostics("/some-path");

            // Assert
            var span = diagnostics.Location.GetMappedLineSpan();
            Assert.Equal("/some-path", span.Path);
            Assert.Equal(10, span.StartLinePosition.Line);
            Assert.Equal(1, span.StartLinePosition.Character);
            Assert.Equal(10, span.EndLinePosition.Line);
            Assert.Equal(6, span.EndLinePosition.Character);
        }
コード例 #26
0
ファイル: RazorErrorTest.cs プロジェクト: billwaddyjr/Razor
        public void RazorError_CanBeSerialized()
        {
            // Arrange
            var error = new RazorError(
                message: "Testing",
                location: new SourceLocation(absoluteIndex: 1, lineIndex: 2, characterIndex: 3),
                length: 456);
            var expectedSerializedError =
                $"{{\"{nameof(RazorError.Message)}\":\"Testing\",\"{nameof(RazorError.Location)}\":{{\"" +
                $"{nameof(SourceLocation.AbsoluteIndex)}\":1,\"{nameof(SourceLocation.LineIndex)}\":2,\"" +
                $"{nameof(SourceLocation.CharacterIndex)}\":3}},\"{nameof(RazorError.Length)}\":456}}";

            // Act
            var serializedError = JsonConvert.SerializeObject(error);

            // Assert
            Assert.Equal(expectedSerializedError, serializedError, StringComparer.Ordinal);
        }
コード例 #27
0
        public static DiagnosticMessage ToDiagnosticMessage(this RazorError error)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            var location = error.Location;

            return(new DiagnosticMessage(
                       message: error.Message,
                       formattedMessage: $"{error} ({location.LineIndex},{location.CharacterIndex}) {error.Message}",
                       filePath: location.FilePath,
                       startLine: location.LineIndex + 1,
                       startColumn: location.CharacterIndex,
                       endLine: location.LineIndex + 1,
                       endColumn: location.CharacterIndex + error.Length));
        }
コード例 #28
0
        public void ToDiagnostic_ConvertsRazorErrorLocation_ToSourceLineMappings()
        {
            // Arrange
            var sourceLocation = new SourceLocation(absoluteIndex: 30, lineIndex: 10, characterIndex: 1);
            var error          = new RazorError("some message", sourceLocation, length: 5);

            // Act
            var diagnostics = error.ToDiagnostics("/some-path");

            // Assert
            var span = diagnostics.Location.GetMappedLineSpan();

            Assert.Equal("/some-path", span.Path);
            Assert.Equal(10, span.StartLinePosition.Line);
            Assert.Equal(1, span.StartLinePosition.Character);
            Assert.Equal(10, span.EndLinePosition.Line);
            Assert.Equal(6, span.EndLinePosition.Character);
        }
コード例 #29
0
        public void ToDiagnostic_SucceedsWhenRazorErrorLocationIsZeroOrUndefined(
            SourceLocation location,
            int length)
        {
            // Arrange
            var error = new RazorError("some message", location, length);

            // Act
            var diagnostics = error.ToDiagnostics("/some-path");

            // Assert
            var span = diagnostics.Location.GetMappedLineSpan();
            Assert.Equal("/some-path", span.Path);
            Assert.Equal(0, span.StartLinePosition.Line);
            Assert.Equal(0, span.StartLinePosition.Character);
            Assert.Equal(0, span.EndLinePosition.Line);
            Assert.Equal(0, span.EndLinePosition.Character);
        }
コード例 #30
0
ファイル: RazorErrorTest.cs プロジェクト: huoxudong125/Razor
        public void RazorError_CanBeDeserialized()
        {
            // Arrange
            var error = new RazorError(
                message: "Testing",
                location: new SourceLocation("somepath", absoluteIndex: 1, lineIndex: 2, characterIndex: 3),
                length: 456);
            var serializedError = JsonConvert.SerializeObject(error);

            // Act
            var deserializedError = JsonConvert.DeserializeObject<RazorError>(serializedError);

            // Assert
            Assert.Equal("Testing", deserializedError.Message, StringComparer.Ordinal);
            Assert.Equal(1, deserializedError.Location.AbsoluteIndex);
            Assert.Equal(2, deserializedError.Location.LineIndex);
            Assert.Equal(3, deserializedError.Location.CharacterIndex);
            Assert.Equal(456, deserializedError.Length);
        }
コード例 #31
0
        public void ToDiagnostic_SucceedsWhenRazorErrorLocationIsZeroOrUndefined(
            SourceLocation location,
            int length)
        {
            // Arrange
            var error = new RazorError("some message", location, length);

            // Act
            var diagnostics = error.ToDiagnostics("/some-path");

            // Assert
            var span = diagnostics.Location.GetMappedLineSpan();

            Assert.Equal("/some-path", span.Path);
            Assert.Equal(0, span.StartLinePosition.Line);
            Assert.Equal(0, span.StartLinePosition.Character);
            Assert.Equal(0, span.EndLinePosition.Line);
            Assert.Equal(0, span.EndLinePosition.Character);
        }
コード例 #32
0
        private bool NotifyOnCodeGenerationComplete(List <RazorRange> newCodeRanges)
        {
            IList <RazorError> parserErrors = _result.ParserErrors;
            int  num  = parserErrors.Count + _runtimeError.Count;
            bool flag = newCodeRanges == null;
            List <CodeGenerationError> list = new List <CodeGenerationError>();

            if (_runtimeError.Count == 1)
            {
                list.Add(new CodeGenerationError(_runtimeError.Message, _runtimeError.Line, _runtimeError.Column, _runtimeError.Length));
            }
            for (int i = _runtimeError.Count; i < num; i++)
            {
                RazorError razorError = parserErrors[i - _runtimeError.Count];
                list.Add(new CodeGenerationError(razorError.Message, razorError.Location.LineIndex + 1, razorError.Location.CharacterIndex, razorError.Length));
            }
            _code = (flag ? string.Empty : GetCodeFromCCU(_result.GeneratedCode));
            if (OnCodeGenerationComplete != null)
            {
                OnCodeGenerationComplete(this, new ContainedCodeGeneratorEventArgs(_code, list));
            }
            return(!flag && SetTextAndMappings(newCodeRanges));
        }
コード例 #33
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
            {
                return(null);
            }

            var diagnostic     = JObject.Load(reader);
            var span           = diagnostic[nameof(RazorDiagnostic.Span)].Value <JObject>();
            var absoluteIndex  = span[nameof(SourceSpan.AbsoluteIndex)].Value <int>();
            var lineIndex      = span[nameof(SourceSpan.LineIndex)].Value <int>();
            var characterIndex = span[nameof(SourceSpan.CharacterIndex)].Value <int>();
            var length         = span[nameof(SourceSpan.Length)].Value <int>();
            var filePath       = span[nameof(SourceSpan.FilePath)].Value <string>();
            var message        = diagnostic[RazorDiagnosticMessageKey].Value <string>();
            var typeName       = diagnostic[RazorDiagnosticTypeNameKey].Value <string>();

            if (string.Equals(typeName, typeof(DefaultRazorDiagnostic).FullName, StringComparison.Ordinal))
            {
                var id       = diagnostic[nameof(RazorDiagnostic.Id)].Value <string>();
                var severity = diagnostic[nameof(RazorDiagnostic.Severity)].Value <int>();

                var descriptor = new RazorDiagnosticDescriptor(id, () => message, (RazorDiagnosticSeverity)severity);
                var sourceSpan = new SourceSpan(filePath, absoluteIndex, lineIndex, characterIndex, length);

                return(RazorDiagnostic.Create(descriptor, sourceSpan));
            }
            else if (string.Equals(typeName, typeof(LegacyRazorDiagnostic).FullName, StringComparison.Ordinal))
            {
                var error = new RazorError(message, absoluteIndex, lineIndex, characterIndex, length);

                return(RazorDiagnostic.Create(error));
            }

            return(null);
        }
コード例 #34
0
 public override void VisitError(RazorError err) {
     Visitor1.VisitError(err);
     Visitor2.VisitError(err);
 }
コード例 #35
0
 /// <summary>
 /// Initialises a new instance of <see cref="TemplateParsingException"/>
 /// </summary>
 internal TemplateParsingException(RazorError error)
     : base(error.Message)
 {
     Column = error.Location.CharacterIndex;
     Line = error.Location.LineIndex;
 }
コード例 #36
0
 private static HttpParseException CreateExceptionFromParserError(RazorError error, string virtualPath)
 {
     return new HttpParseException(error.Message + Environment.NewLine, null, virtualPath, null, error.Location.LineIndex + 1);
 }
コード例 #37
0
        public void Rewrite_UnderstandsPartialRequiredParentTags(
            string documentContent,
            MarkupBlock expectedOutput,
            RazorError[] expectedErrors)
        {
            // Arrange
            var descriptors = new TagHelperDescriptor[]
            {
                new TagHelperDescriptor
                {
                    TagName = "strong",
                    TypeName = "StrongTagHelper",
                    AssemblyName = "SomeAssembly",
                    RequiredParent = "p",
                },
                new TagHelperDescriptor
                {
                    TagName = "strong",
                    TypeName = "StrongTagHelper",
                    AssemblyName = "SomeAssembly",
                    RequiredParent = "div",
                },
                new TagHelperDescriptor
                {
                    TagName = "*",
                    TypeName = "CatchALlTagHelper",
                    AssemblyName = "SomeAssembly",
                    RequiredParent = "p",
                },
                new TagHelperDescriptor
                {
                    TagName = "p",
                    TypeName = "PTagHelper",
                    AssemblyName = "SomeAssembly"
                }
            };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors);
        }
コード例 #38
0
ファイル: ErrorSink.cs プロジェクト: huoxudong125/Razor
 /// <summary>
 /// Tracks the given <paramref name="error"/>.
 /// </summary>
 /// <param name="error">The <see cref="RazorError"/> to track.</param>
 public void OnError(RazorError error)
 {
     _errors.Add(error);
 }
コード例 #39
0
 public override void VisitError(RazorError err)
 {
     base.VisitError(err);
 }
コード例 #40
0
 private void NamespaceImportTest(string content, string expectedNS, AcceptedCharacters acceptedCharacters = AcceptedCharacters.None, string errorMessage = null, SourceLocation? location = null) {
     var errors = new RazorError[0];
     if (!String.IsNullOrEmpty(errorMessage) && location.HasValue) {
         errors = new RazorError[] { 
             new RazorError(errorMessage, location.Value) 
         };
     }
     ParseBlockTest(content,
                     new DirectiveBlock(
                         new NamespaceImportSpan(SpanKind.Code,
                                                 content,
                                                 acceptedCharacters,
                                                 expectedNS,
                                                 CSharpCodeParser.UsingKeywordLength)), errors);
 }
コード例 #41
0
ファイル: ParserVisitor.cs プロジェクト: KennyBu/Razor
 public virtual void VisitError(RazorError err)
 {
     ThrowIfCanceled();
 }
コード例 #42
0
 public void Rewrite_AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock(
     string documentContent,
     MarkupBlock expectedOutput,
     RazorError[] expectedErrors)
 {
     RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "text");
 }
コード例 #43
0
 public void Rewrite_AllowsTagHelperElementOptOutHTML(
     string documentContent,
     MarkupBlock expectedOutput,
     RazorError[] expectedErrors)
 {
     RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p");
 }
コード例 #44
0
        public void Rewrite_CreatesErrorForEmptyTagHelperBoundAttributes(
            string documentContent,
            MarkupBlock expectedOutput,
            RazorError[] expectedErrors)
        {
            // Arrange
            var descriptors = new TagHelperDescriptor[]
                {
                    new TagHelperDescriptor(
                        tagName: "myth",
                        typeName: "mythTagHelper",
                        assemblyName: "SomeAssembly",
                        attributes: new[]
                        {
                            new TagHelperAttributeDescriptor(
                                name: "bound",
                                propertyName: "Bound",
                                typeName: typeof(bool).FullName,
                                isIndexer: false),
                            new TagHelperAttributeDescriptor(
                                name: "name",
                                propertyName: "Name",
                                typeName: typeof(string).FullName,
                                isIndexer: false)
                        })
                };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors);
        }
コード例 #45
0
 /// <summary>
 /// Visits an error generated through parsing.
 /// </summary>
 /// <param name="err">The error that was generated.</param>
 public override void VisitError(RazorError err)
 {
     if (StrictMode)
         throw new TemplateParsingException(err);
 }
コード例 #46
0
        public void Rewrite_UnderstandsAllowedChildren(
            string documentContent,
            IEnumerable<string> allowedChildren,
            MarkupBlock expectedOutput,
            RazorError[] expectedErrors)
        {
            // Arrange
            var descriptors = new TagHelperDescriptor[]
                {
                    new TagHelperDescriptor
                    {
                        TagName = "p",
                        TypeName = "PTagHelper",
                        AssemblyName = "SomeAssembly",
                        AllowedChildren = allowedChildren
                    },
                    new TagHelperDescriptor
                    {
                        TagName = "strong",
                        TypeName = "StrongTagHelper",
                        AssemblyName = "SomeAssembly",
                        AllowedChildren = allowedChildren
                    },
                    new TagHelperDescriptor
                    {
                        TagName = "br",
                        TypeName = "BRTagHelper",
                        AssemblyName = "SomeAssembly",
                        TagStructure = TagStructure.WithoutEndTag
                    }
                };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors);
        }
コード例 #47
0
 private DiagnosticMessage CreateDiagnosticMessage(RazorError error, string filePath)
 {
     return new DiagnosticMessage(
         errorCode: null,
         message: error.Message,
         formattedMessage: $"{error} ({error.Location.LineIndex},{error.Location.CharacterIndex}) {error.Message}",
         filePath: filePath,
         severity: DiagnosticMessageSeverity.Error,
         startLine: error.Location.LineIndex + 1,
         startColumn: error.Location.CharacterIndex,
         endLine: error.Location.LineIndex + 1,
         endColumn: error.Location.CharacterIndex + error.Length);
 }
コード例 #48
0
 /// <summary>
 /// Initialises a new instance of <see cref="TemplateParsingException"/>.
 /// </summary>
 /// <param name="error">The <see cref="RazorError"/> generated by the parser.</param>
 internal TemplateParsingException(RazorError error)
     : base(error.Message)
 {
     Column = error.Location.CharacterIndex;
     Line   = error.Location.LineIndex;
 }
コード例 #49
0
 public void Rewrite_CreatesErrorForMalformedTagHelpersWithAttributes(
     string documentContent,
     MarkupBlock expectedOutput,
     RazorError[] expectedErrors)
 {
     RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p");
 }
コード例 #50
0
        public void Rewrite_UnderstandsMinimizedAttributes(
            string documentContent,
            MarkupBlock expectedOutput,
            RazorError[] expectedErrors)
        {
            // Arrange
            var descriptors = new TagHelperDescriptor[]
                {
                    new TagHelperDescriptor(
                        tagName: "input",
                        typeName: "InputTagHelper1",
                        assemblyName: "SomeAssembly",
                        attributes: new[]
                        {
                            new TagHelperAttributeDescriptor(
                                "bound-required-string",
                                "BoundRequiredString",
                                typeof(string).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null)
                        },
                        requiredAttributes: new[] { "unbound-required" }),
                    new TagHelperDescriptor(
                        tagName: "input",
                        typeName: "InputTagHelper1",
                        assemblyName: "SomeAssembly",
                        attributes: new[]
                        {
                            new TagHelperAttributeDescriptor(
                                "bound-required-string",
                                "BoundRequiredString",
                                typeof(string).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null)
                        },
                        requiredAttributes: new[] { "bound-required-string" }),
                    new TagHelperDescriptor(
                        tagName: "input",
                        typeName: "InputTagHelper2",
                        assemblyName: "SomeAssembly",
                        attributes: new[]
                        {
                            new TagHelperAttributeDescriptor(
                                "bound-required-int",
                                "BoundRequiredInt",
                                typeof(int).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null)
                        },
                        requiredAttributes: new[] { "bound-required-int" }),
                    new TagHelperDescriptor(
                        tagName: "input",
                        typeName: "InputTagHelper3",
                        assemblyName: "SomeAssembly",
                        attributes: new[]
                        {
                            new TagHelperAttributeDescriptor(
                                "int-dictionary",
                                "DictionaryOfIntProperty",
                                typeof(IDictionary<string, int>).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null),
                            new TagHelperAttributeDescriptor(
                                "string-dictionary",
                                "DictionaryOfStringProperty",
                                typeof(IDictionary<string, string>).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null),
                            new TagHelperAttributeDescriptor(
                                "int-prefix-",
                                "DictionaryOfIntProperty",
                                typeof(int).FullName,
                                isIndexer: true,
                                designTimeDescriptor: null),
                            new TagHelperAttributeDescriptor(
                                "string-prefix-",
                                "DictionaryOfStringProperty",
                                typeof(string).FullName,
                                isIndexer: true,
                                designTimeDescriptor: null),
                        },
                        requiredAttributes: Enumerable.Empty<string>()),
                    new TagHelperDescriptor(
                        tagName: "p",
                        typeName: "PTagHelper",
                        assemblyName: "SomeAssembly",
                        attributes: new[]
                        {
                            new TagHelperAttributeDescriptor(
                                "bound-string",
                                "BoundRequiredString",
                                typeof(string).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null),
                            new TagHelperAttributeDescriptor(
                                "bound-int",
                                "BoundRequiredString",
                                typeof(int).FullName,
                                isIndexer: false,
                                designTimeDescriptor: null)
                        },
                        requiredAttributes: Enumerable.Empty<string>()),
                };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors);
        }
コード例 #51
0
 private static HttpParseException CreateExceptionFromParserError(RazorError error, string virtualPath, string sourceCode) =>
 new HttpParseException(error.Message + Environment.NewLine, null, virtualPath, sourceCode, error.Location.LineIndex + 1);
コード例 #52
0
 public void TagHelperParseTreeRewriter_CreatesErrorForIncompleteTagHelper(
     string documentContent,
     MarkupBlock expectedOutput,
     RazorError[] expectedErrors)
 {
     RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p");
 }
コード例 #53
0
ファイル: ParserVisitor.cs プロジェクト: baronhq/IISManager
 public virtual void VisitError(RazorError err)
 {
     ThrowIfCanceled();
 }
コード例 #54
0
        public void Rewrite_RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly(
            string documentContent,
            MarkupBlock expectedOutput,
            RazorError[] expectedErrors)
        {
            // Arrange
            var descriptors = new TagHelperDescriptor[]
                {
                    new TagHelperDescriptor(
                        tagName: "p",
                        typeName: "pTagHelper",
                        assemblyName: "SomeAssembly",
                        attributes: new TagHelperAttributeDescriptor[0],
                        requiredAttributes: new[] { "class" })
                };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors);
        }
コード例 #55
0
 public override void VisitError(RazorError err)
 {
     base.VisitError(err);
     RaiseCallback(SynchronizationContext, err, _errorCallback);
 }
コード例 #56
0
 public void ExceptionFilterErrors(
     string document,
     StatementBlock expectedStatement,
     RazorError[] expectedErrors)
 {
     // Act & Assert
     ParseBlockTest(document, expectedStatement, expectedErrors);
 }
コード例 #57
0
ファイル: HtmlDocumentTest.cs プロジェクト: rohitpoudel/Razor
        public void ParseDocument_WithUnexpectedTransitionsInAttributeValue_Throws()
        {
            // Arrange
            var expected = new MarkupBlock(
                new MarkupTagBlock(
                    Factory.Markup("<span"),
                    new MarkupBlock(
                        new AttributeBlockCodeGenerator("foo", new LocationTagged<string>(" foo='", 5, 0, 5), new LocationTagged<string>("'", 14, 0, 14)),
                        Factory.Markup(" foo='").With(SpanCodeGenerator.Null),
                        new MarkupBlock(
                            new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(string.Empty, 11, 0, 11), 11, 0, 11),
                            new ExpressionBlock(
                                Factory.CodeTransition(),
                                Factory.EmptyCSharp().AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace))),
                        new MarkupBlock(
                            new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(" ", 12, 0, 12), 12, 0, 12),
                            Factory.Markup(" ").With(SpanCodeGenerator.Null),
                            new ExpressionBlock(
                                Factory.CodeTransition().Accepts(AcceptedCharacters.None).With(SpanCodeGenerator.Null),
                                Factory.EmptyCSharp().AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace))),
                        Factory.Markup("'").With(SpanCodeGenerator.Null)),
                    Factory.Markup(" />")));
            var expectedErrors = new RazorError[]
            {
                new RazorError(@"A space or line break was encountered after the ""@"" character.  Only valid identifiers, keywords, comments, ""("" and ""{"" are valid at the start of a code block and they must occur immediately following ""@"" with no space in between.", new SourceLocation(12, 0, 12)),
                new RazorError(@"""' />"" is not valid at the start of a code block.  Only identifiers, keywords, comments, ""("" and ""{"" are valid.", new SourceLocation(14, 0, 14)),
            };

            // Act & Assert
            ParseDocumentTest("<span foo='@ @' />", expected, expectedErrors);
        }
コード例 #58
0
ファイル: ParserContext.cs プロジェクト: leloulight/Razor
        public void OnError(RazorError error)
        {
            EnusreNotTerminated();
            AssertOnOwnerTask();

            _errorSink.OnError(error);
        }
コード例 #59
0
        public void Rewrite_CreatesErrorForInconsistentTagStructures()
        {
            // Arrange
            var factory = CreateDefaultSpanFactory();
            var blockFactory = new BlockFactory(factory);
            var expectedError = new RazorError(
                RazorResources.FormatTagHelperParseTreeRewriter_InconsistentTagStructure(
                    "InputTagHelper1",
                    "InputTagHelper2",
                    "input",
                    nameof(TagHelperDescriptor.TagStructure)),
                absoluteIndex: 0,
                lineIndex: 0,
                columnIndex: 0,
                length: 7);
            var documentContent = "<input>";
            var expectedOutput = new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.StartTagOnly));
            var descriptors = new TagHelperDescriptor[]
                {
                    new TagHelperDescriptor
                    {
                        TagName = "input",
                        TypeName = "InputTagHelper1",
                        AssemblyName = "SomeAssembly",
                        TagStructure = TagStructure.WithoutEndTag
                    },
                    new TagHelperDescriptor
                    {
                        TagName = "input",
                        TypeName = "InputTagHelper2",
                        AssemblyName = "SomeAssembly",
                        TagStructure = TagStructure.NormalOrSelfClosing
                    }
                };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new[] { expectedError });
        }
コード例 #60
0
        public void Rewrite_CreatesErrorForWithoutEndTagTagStructureForEndTags()
        {
            // Arrange
            var factory = CreateDefaultSpanFactory();
            var blockFactory = new BlockFactory(factory);
            var expectedError = new RazorError(
                RazorResources.FormatTagHelperParseTreeRewriter_EndTagTagHelperMustNotHaveAnEndTag(
                    "input",
                    "InputTagHelper",
                    TagStructure.WithoutEndTag),
                absoluteIndex: 2,
                lineIndex: 0,
                columnIndex: 2,
                length: 5);
            var documentContent = "</input>";
            var expectedOutput = new MarkupBlock(blockFactory.MarkupTagBlock("</input>"));
            var descriptors = new TagHelperDescriptor[]
                {
                    new TagHelperDescriptor
                    {
                        TagName = "input",
                        TypeName = "InputTagHelper",
                        AssemblyName = "SomeAssembly",
                        TagStructure = TagStructure.WithoutEndTag
                    }
                };
            var descriptorProvider = new TagHelperDescriptorProvider(descriptors);

            // Act & Assert
            EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new[] { expectedError });
        }