From a7eb30ddca7872498696f2bb14c286105b0ae57c Mon Sep 17 00:00:00 2001 From: Ryan Brandenburg Date: Thu, 16 Mar 2017 15:54:15 -0700 Subject: [PATCH] Remove old razor --- Razor.sln | 13 +- ...nsitiveBoundAttributeDescriptorComparer.cs | 57 - ...tiveRequiredAttributeDescriptorComparer.cs | 43 - ...aseSensitiveTagHelperDescriptorComparer.cs | 96 - ...erAttributeDesignTimeDescriptorComparer.cs | 48 - .../TagHelperDesignTimeDescriptorComparer.cs | 48 - .../Microsoft.AspNetCore.Razor.Runtime.csproj | 4 - .../Resources.resx | 90 - .../Runtime/TagHelpers/Constants.cs | 12 - .../TagHelpers/ITagHelperDescriptorFactory.cs | 28 - .../TagHelpers/ITagHelperTypeResolver.cs | 28 - .../TagHelpers/TagHelperConventions.cs | 30 - .../TagHelpers/TagHelperDescriptorFactory.cs | 1054 ---- .../TagHelpers/TagHelperDescriptorResolver.cs | 299 -- .../TagHelperDesignTimeDescriptorFactory.cs | 240 - .../TagHelpers/TagHelperTypeResolver.cs | 93 - .../TagHelpers/XmlDocumentationProvider.cs | 127 - .../TagHelpers/DefaultTagHelperContent.cs | 7 +- .../TagHelpers/HtmlTargetElementAttribute.cs | 3 +- .../CSharpRazorCodeLanguage.cs | 50 - .../Chunks/AddTagHelperChunk.cs | 16 - .../Chunks/Chunk.cs | 13 - .../Chunks/ChunkTree.cs | 9 - .../Chunks/ChunkTreeBuilder.cs | 194 - .../Chunks/CodeAttributeChunk.cs | 14 - .../Chunks/DynamicCodeAttributeChunk.cs | 12 - .../Chunks/ExpressionBlockChunk.cs | 9 - .../Chunks/ExpressionChunk.cs | 15 - .../Generators/AddImportChunkGenerator.cs | 48 - .../Generators/AddTagHelperChunkGenerator.cs | 62 - .../AttributeBlockChunkGenerator.cs | 65 - .../Generators/ChunkGeneratorContext.cs | 44 - .../DynamicAttributeBlockChunkGenerator.cs | 56 - .../Generators/ExpressionChunkGenerator.cs | 43 - .../Generators/IParentChunkGenerator.cs | 13 - .../Chunks/Generators/ISpanChunkGenerator.cs | 12 - .../LiteralAttributeChunkGenerator.cs | 83 - .../Chunks/Generators/MarkupChunkGenerator.cs | 20 - .../Chunks/Generators/ParentChunkGenerator.cs | 49 - .../Chunks/Generators/RazorChunkGenerator.cs | 93 - .../Generators/RazorCommentChunkGenerator.cs | 10 - .../RemoveTagHelperChunkGenerator.cs | 62 - .../Generators/SectionChunkGenerator.cs | 47 - .../Generators/SetBaseTypeChunkGenerator.cs | 40 - .../Chunks/Generators/SpanChunkGenerator.cs | 41 - .../Generators/StatementChunkGenerator.cs | 20 - .../Generators/TagHelperChunkGenerator.cs | 112 - .../TagHelperPrefixDirectiveChunkGenerator.cs | 63 - .../Generators/TemplateBlockChunkGenerator.cs | 20 - .../Generators/TypeMemberChunkGenerator.cs | 20 - .../Chunks/LiteralChunk.cs | 15 - .../Chunks/LiteralCodeAttributeChunk.cs | 15 - .../Chunks/ParentChunk.cs | 17 - .../Chunks/ParentLiteralChunk.cs | 21 - .../PreallocatedTagHelperAttributeChunk.cs | 16 - .../Chunks/RemoveTagHelperChunk.cs | 18 - .../Chunks/SectionChunk.cs | 10 - .../Chunks/SetBaseTypeChunk.cs | 10 - .../Chunks/StatementChunk.cs | 15 - .../Chunks/TagHelperAttributeChunk.cs | 23 - .../Chunks/TagHelperChunk.cs | 56 - .../Chunks/TagHelperPrefixDirectiveChunk.cs | 17 - .../Chunks/TemplateChunk.cs | 9 - .../Chunks/TypeMemberChunk.cs | 10 - .../Chunks/UsingChunk.cs | 10 - .../CodeGenerators/CSharpCodeGenerator.cs | 188 - .../CodeGenerators/CSharpCodeWriter.cs | 579 --- .../CodeGenerators/CSharpCodeWritingScope.cs | 71 - .../CSharpDisableWarningScope.cs | 29 - .../CodeGenerators/CSharpLineMappingWriter.cs | 137 - .../CodeGenerators/CSharpPaddingBuilder.cs | 180 - .../CSharpTagHelperCodeRenderer.cs | 833 --- .../CodeGenerators/CodeGenerator.cs | 22 - .../CodeGenerators/CodeGeneratorContext.cs | 75 - .../CodeGenerators/CodeGeneratorResult.cs | 19 - .../CodeGenerators/CodeWriter.cs | 203 - .../CodeGenerators/ExpressionRenderingMode.cs | 29 - .../CodeGenerators/GeneratedClassContext.cs | 219 - .../GeneratedTagHelperContext.cs | 239 - .../CodeGenerators/GeneratorResults.cs | 111 - .../CodeGenerators/LineMapping.cs | 79 - .../CodeGenerators/LineMappingManager.cs | 22 - .../CodeGenerators/MappingLocation.cs | 105 - .../TagHelperAttributeValueCodeRenderer.cs | 62 - .../Visitors/CSharpBaseTypeVisitor.cs | 32 - .../Visitors/CSharpCodeVisitor.cs | 623 --- .../Visitors/CSharpDesignTimeCodeVisitor.cs | 124 - .../CSharpTagHelperAttributeValueVisitor.cs | 167 - .../CSharpTagHelperFieldDeclarationVisitor.cs | 315 -- ...pTagHelperPropertyInitializationVisitor.cs | 93 - .../Visitors/CSharpTypeMemberVisitor.cs | 44 - .../Visitors/CSharpUsingVisitor.cs | 86 - .../CodeGenerators/Visitors/ChunkVisitor.cs | 145 - .../CodeGenerators/Visitors/CodeVisitor.cs | 81 - .../CodeGenerators/Visitors/IChunkVisitor.cs | 14 - .../CommonResources.resx | 144 - .../ITagHelperDescriptorResolver.cs | 23 - .../TagHelperAttributeDescriptor.cs | 156 - .../TagHelperAttributeDesignTimeDescriptor.cs | 21 - .../TagHelpers/TagHelperDescriptor.cs | 252 - .../TagHelpers/TagHelperDescriptorComparer.cs | 110 - .../TagHelpers/TagHelperDescriptorProvider.cs | 133 - .../TagHelperDescriptorResolutionContext.cs | 54 - .../TagHelperDesignTimeDescriptor.cs | 29 - .../TagHelperDirectiveDescriptor.cs | 45 - .../TagHelpers/TagHelperDirectiveType.cs | 26 - .../TagHelperRequiredAttributeDescriptor.cs | 82 - ...lperRequiredAttributeDescriptorComparer.cs | 58 - ...agHelperRequiredAttributeNameComparison.cs | 21 - ...gHelperRequiredAttributeValueComparison.cs | 31 - .../TypeBasedTagHelperDescriptorComparer.cs | 64 - .../DocumentParseCompleteEventArgs.cs | 30 - .../Editor/AutoCompleteEditHandler.cs | 73 - .../Editor/BackgroundParser.cs | 487 -- .../Editor/EditResult.cs | 19 - .../Editor/EditorHints.cs | 28 - .../Editor/ImplicitExpressionEditHandler.cs | 383 -- .../Editor/RazorEditorTrace.cs | 53 - .../Editor/SingleLineMarkupEditHandler.cs | 23 - .../Editor/SpanEditHandler.cs | 185 - src/Microsoft.AspNetCore.Razor/ErrorSink.cs | 54 - .../Microsoft.AspNetCore.Razor.csproj | 9 - .../Parser/BalancingModes.cs | 16 - .../Parser/CSharpCodeParser.Directives.cs | 369 -- .../Parser/CSharpCodeParser.Expressions.cs | 40 - .../Parser/CSharpCodeParser.Statements.cs | 760 --- .../Parser/CSharpCodeParser.cs | 675 --- .../Parser/CSharpLanguageCharacteristics.cs | 191 - .../Parser/ConditionalAttributeCollapser.cs | 76 - .../Parser/DisposableAction.cs | 32 - .../Parser/ISyntaxTreeRewriter.cs | 21 - .../Parser/Internal/CallbackVisitor.cs | 97 - .../Internal/HtmlLanguageCharacteristics.cs | 137 - .../Parser/Internal/HtmlMarkupParser.Block.cs | 1191 ----- .../Internal/HtmlMarkupParser.Document.cs | 168 - .../Internal/HtmlMarkupParser.Section.cs | 198 - .../Parser/Internal/HtmlMarkupParser.cs | 257 - .../Parser/LanguageCharacteristics.cs | 112 - .../Parser/MarkupCollapser.cs | 39 - .../Parser/MarkupRewriter.cs | 106 - .../Parser/ParserBase.cs | 50 - .../Parser/ParserContext.cs | 348 -- .../Parser/ParserHelpers.cs | 147 - .../Parser/ParserVisitor.cs | 59 - .../Parser/ParserVisitorExtensions.cs | 30 - .../Parser/RazorParser.cs | 258 - .../Parser/RewritingContext.cs | 34 - .../Parser/SyntaxConstants.cs | 31 - .../Parser/SyntaxTree/AcceptedCharacters.cs | 22 - .../Parser/SyntaxTree/Block.cs | 234 - .../Parser/SyntaxTree/BlockBuilder.cs | 39 - .../Parser/SyntaxTree/BlockType.cs | 24 - .../Parser/SyntaxTree/EquivalenceComparer.cs | 31 - .../Parser/SyntaxTree/Span.cs | 172 - .../Parser/SyntaxTree/SpanBuilder.cs | 101 - .../Parser/SyntaxTree/SpanKind.cs | 14 - .../Parser/SyntaxTree/SyntaxTreeNode.cs | 51 - .../Internal/TagHelperBlockRewriter.cs | 742 --- .../Internal/TagHelperParseTreeRewriter.cs | 874 ---- .../TagHelpers/TagHelperAttributeNode.cs | 30 - .../Parser/TagHelpers/TagHelperBlock.cs | 202 - .../TagHelpers/TagHelperBlockBuilder.cs | 138 - .../TagHelperDirectiveSpanVisitor.cs | 132 - .../Parser/TextReaderExtensions.cs | 167 - .../Parser/TokenizerBackedParser.Helpers.cs | 563 -- .../Parser/TokenizerBackedParser.cs | 124 - .../Parser/WhitespaceRewriter.cs | 52 - .../ParserResults.cs | 120 - .../PartialParseResult.cs | 59 - .../Properties/CommonResources.Designer.cs | 158 - .../Properties/RazorResources.Designer.cs | 1598 ------ .../RazorCodeLanguage.cs | 64 - .../RazorEditorParser.cs | 310 -- .../RazorEngineHost.cs | 263 - src/Microsoft.AspNetCore.Razor/RazorError.cs | 82 - .../RazorResources.resx | 434 -- .../RazorTemplateEngine.cs | 463 -- .../SourceLocation.cs | 254 - .../Text/ITextBuffer.cs | 13 - .../Text/ITextDocument.cs | 10 - .../Text/LineTrackingStringBuffer.cs | 179 - .../Text/LocationTagged.cs | 104 - .../Text/LookaheadTextReader.cs | 15 - .../Text/LookaheadToken.cs | 36 - .../Text/SeekableTextReader.cs | 109 - .../Text/SourceLocationTracker.cs | 102 - .../Text/TextChange.cs | 253 - .../Text/TextDocumentReader.cs | 43 - .../Text/TextExtensions.cs | 42 - .../Tokenizer/CSharpKeywordDetector.cs | 105 - .../Tokenizer/ITokenizer.cs | 12 - .../Tokenizer/Internal/CSharpHelpers.cs | 46 - .../Tokenizer/Internal/CSharpTokenizer.cs | 515 -- .../Tokenizer/Internal/HtmlTokenizer.cs | 263 - .../Tokenizer/Symbols/CSharpKeyword.cs | 88 - .../Tokenizer/Symbols/CSharpSymbol.cs | 74 - .../Tokenizer/Symbols/CSharpSymbolType.cs | 75 - .../Tokenizer/Symbols/ISymbol.cs | 14 - .../Tokenizer/Symbols/Internal/HtmlSymbol.cs | 59 - .../Symbols/Internal/HtmlSymbolType.cs | 32 - .../Tokenizer/Symbols/KnownSymbolType.cs | 18 - .../Tokenizer/Symbols/SymbolBase.cs | 73 - .../Tokenizer/Symbols/SymbolExtensions.cs | 62 - .../Tokenizer/Tokenizer.cs | 441 -- .../Tokenizer/TokenizerView.cs | 54 - .../TagHelperDescriptorFactoryTest.cs | 2541 ---------- .../TagHelperDescriptorResolverTest.cs | 1462 ------ ...agHelperDesignTimeDescriptorFactoryTest.cs | 567 --- .../TagHelpers/TagHelperTypeResolverTest.cs | 231 - .../XmlDocumentationProviderTest.cs | 164 - .../CSharpRazorCodeLanguageTest.cs | 67 - .../Chunks/ChunkTreeBuilderTest.cs | 162 - .../Chunks/ChunkVisitorTests.cs | 46 - .../Generators/AddImportChunkGeneratorTest.cs | 104 - .../AttributeBlockChunkGeneratorTest.cs | 157 - .../RazorCommentChunkGeneratorTest.cs | 92 - .../CodeGenerators/CSharpCodeGeneratorTest.cs | 219 - .../CodeGenerators/CSharpCodeWriterTest.cs | 47 - .../CSharpLineMappingWriterTest.cs | 90 - .../CSharpPaddingBuilderTests.cs | 243 - .../CSharpRazorCodeGeneratorTest.cs | 636 --- .../CSharpTagHelperRenderingTest.cs | 2100 -------- .../CSharpTagHelperRenderingUnitTest.cs | 302 -- .../CodeGenTestCodeGenerator.cs | 30 - .../CodeGenerators/CodeGenTestHost.cs | 27 - .../CodeGenerators/CodeWriterTest.cs | 265 - ...DynamicAttributeBlockChunkGeneratorTest.cs | 166 - .../CodeGenerators/LineMappingTest.cs | 124 - .../CodeGenerators/RazorChunkGeneratorTest.cs | 314 -- .../CodeGenerators/TabTest.cs | 15 - ...TagHelperAttributeValueCodeRendererTest.cs | 123 - .../CodeGenerators/TagHelperTestBase.cs | 129 - .../CodeGenerators/TestSpan.cs | 61 - .../TagHelperDescriptorProviderTest.cs | 499 -- .../TagHelpers/TagHelperDescriptorTest.cs | 558 -- ...agHelperRequiredAttributeDescriptorTest.cs | 173 - .../Editor/AutoCompleteEditHandlerTest.cs | 222 - .../ImplicitExpressionEditHandlerTest.cs | 297 -- .../Editor/SpanEditHandlerTest.cs | 167 - .../Framework/BlockExtensions.cs | 30 - .../Framework/BlockFactory.cs | 83 - .../Framework/BlockTypes.cs | 269 - .../Framework/CodeParserTestBase.cs | 77 - .../Framework/CsHtmlCodeParserTestBase.cs | 37 - .../Framework/CsHtmlMarkupParserTestBase.cs | 37 - .../Framework/ErrorCollector.cs | 58 - .../Framework/MarkupParserTestBase.cs | 22 - .../Framework/ParserTestBase.cs | 543 -- .../Framework/RawTextSymbol.cs | 66 - .../Framework/TestSpanBuilder.cs | 452 -- .../Microsoft.AspNetCore.Razor.Test.csproj | 35 - .../Parser/CSharpAutoCompleteTest.cs | 143 - .../Parser/CSharpBlockTest.cs | 1284 ----- .../Parser/CSharpDirectivesTest.cs | 429 -- .../Parser/CSharpErrorTest.cs | 698 --- .../Parser/CSharpExplicitExpressionTest.cs | 141 - .../Parser/CSharpImplicitExpressionTest.cs | 304 -- .../CSharpLanguageCharacteristicsTest.cs | 21 - .../Parser/CSharpNestedStatementsTest.cs | 106 - .../Parser/CSharpRazorCommentsTest.cs | 428 -- .../Parser/CSharpReservedWordsTest.cs | 44 - .../Parser/CSharpSectionTest.cs | 602 --- .../Parser/CSharpSpecialBlockTest.cs | 219 - .../Parser/CSharpStatementTest.cs | 421 -- .../Parser/CSharpTemplateTest.cs | 327 -- .../Parser/CSharpToMarkupSwitchTest.cs | 697 --- .../Parser/CSharpVerbatimBlockTest.cs | 140 - .../Parser/CSharpWhitespaceHandlingTest.cs | 38 - .../Parser/DisposableActionTest.cs | 25 - .../Parser/HtmlToCodeSwitchTest.cs | 441 -- .../Parser/Internal/CallbackVisitorTest.cs | 168 - .../Parser/Internal/HtmlAttributeTest.cs | 649 --- .../Parser/Internal/HtmlBlockTest.cs | 661 --- .../Parser/Internal/HtmlDocumentTest.cs | 831 --- .../Parser/Internal/HtmlErrorTest.cs | 128 - .../Parser/Internal/HtmlParserTestUtils.cs | 46 - .../Parser/Internal/HtmlTagsTest.cs | 210 - .../Parser/ParserContextTest.cs | 239 - .../Parser/ParserVisitorExtensionsTest.cs | 77 - .../Parser/RazorParserTest.cs | 157 - .../Parser/SyntaxTree/BlockTest.cs | 106 - .../Internal/TagHelperBlockRewriterTest.cs | 4046 --------------- .../TagHelperParseTreeRewriterTest.cs | 4513 ----------------- .../Internal/TagHelperRewritingTestBase.cs | 94 - .../Parser/TagHelpers/TagHelperBlockTest.cs | 108 - .../TagHelperDirectiveSpanVisitorTest.cs | 426 -- .../Parser/TextReaderExtensionsTest.cs | 113 - .../Parser/WhitespaceRewriterTest.cs | 46 - .../PartialParsingTestBase.cs | 136 - .../RazorCodeLanguageTest.cs | 49 - .../RazorEditorParserTest.cs | 1390 ----- .../RazorEngineHostTest.cs | 98 - .../RazorErrorTest.cs | 75 - .../RazorTemplateEngineTest.cs | 409 -- .../SourceLocationTest.cs | 301 -- .../StringTextBuffer.cs | 53 - .../Output/AddTagHelperDirective.cs | 27 - ...AttributeTargetingTagHelpers.DesignTime.cs | 53 - .../Output/AttributeTargetingTagHelpers.cs | 129 - .../CodeGenerator/Output/Await.DesignTime.cs | 121 - .../TestFiles/CodeGenerator/Output/Await.cs | 167 - ...TagHelpers.CustomAttributeCodeGenerator.cs | 127 - .../Output/BasicTagHelpers.DesignTime.cs | 51 - .../BasicTagHelpers.Prefixed.DesignTime.cs | 42 - .../Output/BasicTagHelpers.Prefixed.cs | 82 - .../Output/BasicTagHelpers.RemoveTagHelper.cs | 23 - .../CodeGenerator/Output/BasicTagHelpers.cs | 128 - .../TestFiles/CodeGenerator/Output/Blocks.cs | 197 - .../AddGenerateChunkTest.cs | 27 - .../BuildAfterExecuteContentTest.cs | 27 - .../ChunkTreeWithUsings.cs | 30 - .../ClearGenerateChunkTest.cs | 18 - .../DefaultGenerateChunkTest.cs | 26 - .../CodeGenerator/Output/CodeBlock.cs | 29 - .../CodeGenerator/Output/CodeBlockAtEOF.cs | 31 - .../Output/CodeBlockWithTextElement.cs | 53 - .../Output/ComplexTagHelpers.DesignTime.cs | 215 - .../CodeGenerator/Output/ComplexTagHelpers.cs | 535 -- .../ConditionalAttributes.DesignTime.cs | 162 - .../Output/ConditionalAttributes.cs | 136 - .../Output/CssSelectorTagHelperAttributes.cs | 276 - .../CodeGenerator/Output/DesignTime.cs | 70 - ...DuplicateAttributeTagHelpers.DesignTime.cs | 59 - .../Output/DuplicateAttributeTagHelpers.cs | 142 - .../Output/DuplicateTargetTagHelper.cs | 57 - .../DynamicAttributeTagHelpers.DesignTime.cs | 199 - .../Output/DynamicAttributeTagHelpers.cs | 321 -- .../EmptyAttributeTagHelpers.DesignTime.cs | 55 - .../Output/EmptyAttributeTagHelpers.cs | 113 - .../CodeGenerator/Output/EmptyCodeBlock.cs | 31 - .../Output/EmptyExplicitExpression.cs | 30 - .../Output/EmptyImplicitExpression.cs | 30 - .../EmptyImplicitExpressionInCode.Tabs.cs | 43 - .../Output/EmptyImplicitExpressionInCode.cs | 43 - .../Output/EnumTagHelpers.DesignTime.cs | 82 - .../CodeGenerator/Output/EnumTagHelpers.cs | 162 - .../Output/EscapedTagHelpers.DesignTime.cs | 49 - .../CodeGenerator/Output/EscapedTagHelpers.cs | 75 - .../Output/ExplicitExpression.cs | 30 - .../Output/ExplicitExpressionAtEOF.cs | 30 - ...ExplicitExpressionWithMarkup.DesignTime.cs | 33 - .../Output/ExplicitExpressionWithMarkup.cs | 36 - .../CodeGenerator/Output/ExpressionsInCode.cs | 88 - .../Output/FunctionsBlock.DesignTime.Tabs.cs | 45 - .../Output/FunctionsBlock.DesignTime.cs | 45 - .../CodeGenerator/Output/FunctionsBlock.cs | 48 - .../FunctionsBlockMinimal.DesignTime.Tabs.cs | 33 - .../Output/FunctionsBlock_Tabs.cs | 48 - .../CodeGenerator/Output/HiddenSpansInCode.cs | 38 - .../Output/HtmlCommentWithQuote_Double.cs | 23 - .../Output/HtmlCommentWithQuote_Single.cs | 23 - .../Output/ImplicitExpression.cs | 45 - .../Output/ImplicitExpressionAtEOF.cs | 30 - .../Output/Imports.DesignTime.cs | 70 - .../TestFiles/CodeGenerator/Output/Imports.cs | 81 - .../Output/IncompleteTagHelper.cs | 45 - .../Output/Inherits.Designtime.cs | 35 - .../CodeGenerator/Output/Inherits.Runtime.cs | 30 - .../CodeGenerator/Output/InlineBlocks.cs | 62 - .../CodeGenerator/Output/Instrumented.cs | 208 - .../CodeGenerator/Output/MarkupInCodeBlock.cs | 46 - .../Output/MinimizedTagHelpers.DesignTime.cs | 42 - .../Output/MinimizedTagHelpers.cs | 139 - .../Output/NestedCSharp.DesignTime.cs | 58 - .../CodeGenerator/Output/NestedCSharp.cs | 59 - .../CodeGenerator/Output/NestedCodeBlocks.cs | 41 - .../NestedScriptTagTagHelpers.DesignTime.cs | 64 - .../Output/NestedScriptTagTagHelpers.cs | 118 - .../CodeGenerator/Output/NoLinePragmas.cs | 204 - .../NullConditionalExpressions.DesignTime.cs | 99 - .../Output/NullConditionalExpressions.cs | 122 - .../Output/OpenedIf.DesignTime.Tabs.cs | 43 - .../Output/OpenedIf.DesignTime.cs | 43 - .../CodeGenerator/Output/ParserError.cs | 35 - .../PrefixedAttributeTagHelpers.DesignTime.cs | 120 - .../PrefixedAttributeTagHelpers.Reversed.cs | 247 - .../Output/PrefixedAttributeTagHelpers.cs | 247 - .../Output/RazorComments.DesignTime.cs | 64 - .../CodeGenerator/Output/RazorComments.cs | 78 - .../Output/RemoveTagHelperDirective.cs | 27 - .../CodeGenerator/Output/Sections.cs | 99 - .../SimpleUnspacedIf.DesignTime.Tabs.cs | 40 - .../Output/SingleTagHelper.DesignTime.cs | 35 - .../CodeGenerator/Output/SingleTagHelper.cs | 58 - ...gleTagHelperWithNewlineBeforeAttributes.cs | 58 - .../CodeGenerator/Output/StringLiterals.cs | 279 - .../SymbolBoundAttributes.DesignTime.cs | 58 - .../Output/SymbolBoundAttributes.cs | 194 - .../Output/TagHelpersInSection.cs | 116 - .../TagHelpersWithWeirdlySpacedAttributes.cs | 131 - .../CodeGenerator/Output/Templates.cs | 229 - ...sitionsInTagHelperAttributes.DesignTime.cs | 83 - .../TransitionsInTagHelperAttributes.cs | 186 - .../Output/UnfinishedExpressionInCode.Tabs.cs | 42 - .../Output/UnfinishedExpressionInCode.cs | 42 - .../Source/AddTagHelperDirective.cshtml | 1 - .../AttributeTargetingTagHelpers.cshtml | 8 - .../CodeGenerator/Source/Await.cshtml | 26 - .../Source/BasicTagHelpers.Prefixed.cshtml | 10 - .../BasicTagHelpers.RemoveTagHelper.cshtml | 10 - .../Source/BasicTagHelpers.cshtml | 9 - .../CodeGenerator/Source/Blocks.cshtml | 37 - .../CodeGenerator/Source/CodeBlock.cshtml | 5 - .../Source/CodeBlockAtEOF.cshtml | 1 - .../Source/CodeBlockWithTextElement.cshtml | 4 - .../Source/ComplexTagHelpers.cshtml | 36 - .../Source/ConditionalAttributes.cshtml | 15 - .../CssSelectorTagHelperAttributes.cshtml | 13 - .../CodeGenerator/Source/DesignTime.cshtml | 15 - .../DuplicateAttributeTagHelpers.cshtml | 7 - .../Source/DuplicateTargetTagHelper.cshtml | 3 - .../Source/DynamicAttributeTagHelpers.cshtml | 14 - .../Source/EmptyAttributeTagHelpers.cshtml | 8 - .../Source/EmptyCodeBlock.cshtml | 3 - .../Source/EmptyExplicitExpression.cshtml | 3 - .../Source/EmptyImplicitExpression.cshtml | 3 - .../EmptyImplicitExpressionInCode.cshtml | 3 - .../Source/EnumTagHelpers.cshtml | 11 - .../Source/EscapedTagHelpers.cshtml | 8 - .../Source/ExplicitExpression.cshtml | 1 - .../Source/ExplicitExpressionAtEOF.cshtml | 3 - .../ExplicitExpressionWithMarkup.cshtml | 1 - .../Source/ExpressionsInCode.cshtml | 16 - .../Source/FunctionsBlock.cshtml | 12 - .../Source/FunctionsBlockMinimal.cshtml | 7 - .../Source/FunctionsBlock_Tabs.cshtml | 12 - .../Source/HiddenSpansInCode.cshtml | 3 - .../Source/HtmlCommentWithQuote_Double.cshtml | 2 - .../Source/HtmlCommentWithQuote_Single.cshtml | 2 - .../Source/ImplicitExpression.cshtml | 3 - .../Source/ImplicitExpressionAtEOF.cshtml | 3 - .../CodeGenerator/Source/Imports.cshtml | 10 - .../Source/IncompleteTagHelper.cshtml | 3 - .../CodeGenerator/Source/Inherits.cshtml | 3 - .../CodeGenerator/Source/InlineBlocks.cshtml | 3 - .../CodeGenerator/Source/Instrumented.cshtml | 38 - .../Source/MarkupInCodeBlock.cshtml | 5 - .../Source/MinimizedTagHelpers.cshtml | 18 - .../CodeGenerator/Source/NestedCSharp.cshtml | 8 - .../Source/NestedCodeBlocks.cshtml | 4 - .../Source/NestedScriptTagTagHelpers.cshtml | 16 - .../CodeGenerator/Source/NoLinePragmas.cshtml | 38 - .../Source/NullConditionalExpressions.cshtml | 11 - .../CodeGenerator/Source/OpenedIf.cshtml | 5 - .../CodeGenerator/Source/ParserError.cshtml | 5 - .../Source/PrefixedAttributeTagHelpers.cshtml | 23 - .../CodeGenerator/Source/RazorComments.cshtml | 15 - .../Source/RemoveTagHelperDirective.cshtml | 1 - .../CodeGenerator/Source/Sections.cshtml | 17 - .../Source/SimpleUnspacedIf.cshtml | 4 - .../Source/SingleTagHelper.cshtml | 3 - ...agHelperWithNewlineBeforeAttributes.cshtml | 4 - .../Source/StringLiterals.cshtml | 237 - .../Source/SymbolBoundAttributes.cshtml | 19 - .../Source/TagHelpersInSection.cshtml | 14 - ...gHelpersWithWeirdlySpacedAttributes.cshtml | 15 - .../CodeGenerator/Source/Templates.cshtml | 48 - .../TransitionsInTagHelperAttributes.cshtml | 12 - .../Source/UnfinishedExpressionInCode.cshtml | 3 - .../TestFiles/DesignTime/Simple.cshtml | 16 - .../TestFiles/DesignTime/Simple.txt | 53 - .../TestFiles/nested-1000.html | 2002 -------- .../Text/LineTrackingStringBufferTest.cs | 27 - .../Text/LookaheadTextReaderTestBase.cs | 255 - .../Text/SourceLocationTrackerTest.cs | 196 - .../Text/TextChangeTest.cs | 319 -- .../Internal/CSharpTokenizerCommentTest.cs | 91 - .../Internal/CSharpTokenizerIdentifierTest.cs | 172 - .../Internal/CSharpTokenizerLiteralTest.cs | 287 -- .../Internal/CSharpTokenizerOperatorsTest.cs | 298 -- .../Tokenizer/Internal/CSharpTokenizerTest.cs | 98 - .../Internal/CSharpTokenizerTestBase.cs | 30 - .../Tokenizer/Internal/HtmlTokenizerTest.cs | 162 - .../Internal/HtmlTokenizerTestBase.cs | 30 - .../Internal/TokenizerLookaheadTest.cs | 153 - .../Tokenizer/TokenizerTestBase.cs | 79 - .../Utils/BaselineWriter.cs | 46 - .../Utils/ExceptionHelpers.cs | 16 - .../Utils/MiscUtils.cs | 33 - .../Utils/TestFile.cs | 95 - 480 files changed, 3 insertions(+), 77298 deletions(-) delete mode 100644 shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveBoundAttributeDescriptorComparer.cs delete mode 100644 shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveRequiredAttributeDescriptorComparer.cs delete mode 100644 shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveTagHelperDescriptorComparer.cs delete mode 100644 shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperAttributeDesignTimeDescriptorComparer.cs delete mode 100644 shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperDesignTimeDescriptorComparer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/Constants.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperDescriptorFactory.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperTypeResolver.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperConventions.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorFactory.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorResolver.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactory.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperTypeResolver.cs delete mode 100644 src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/XmlDocumentationProvider.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CSharpRazorCodeLanguage.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/AddTagHelperChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Chunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/ChunkTree.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/ChunkTreeBuilder.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/CodeAttributeChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/DynamicCodeAttributeChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/ExpressionBlockChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/ExpressionChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddImportChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddTagHelperChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/AttributeBlockChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/ChunkGeneratorContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/DynamicAttributeBlockChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/ExpressionChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/IParentChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/ISpanChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/LiteralAttributeChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/MarkupChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/ParentChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorCommentChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/RemoveTagHelperChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/SectionChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/SetBaseTypeChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/SpanChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/StatementChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperPrefixDirectiveChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/TemplateBlockChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/Generators/TypeMemberChunkGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/LiteralChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/LiteralCodeAttributeChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/ParentChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/ParentLiteralChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/PreallocatedTagHelperAttributeChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/RemoveTagHelperChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/SectionChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/SetBaseTypeChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/StatementChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/TagHelperAttributeChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/TagHelperChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/TagHelperPrefixDirectiveChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/TemplateChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/TypeMemberChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Chunks/UsingChunk.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWritingScope.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpDisableWarningScope.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpLineMappingWriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpPaddingBuilder.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpTagHelperCodeRenderer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGenerator.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorResult.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeWriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/ExpressionRenderingMode.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedClassContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedTagHelperContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratorResults.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMapping.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMappingManager.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/MappingLocation.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/TagHelperAttributeValueCodeRenderer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpBaseTypeVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpCodeVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpDesignTimeCodeVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperAttributeValueVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperFieldDeclarationVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperPropertyInitializationVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTypeMemberVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpUsingVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/ChunkVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CodeVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/IChunkVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/CommonResources.resx delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/ITagHelperDescriptorResolver.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDescriptor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDesignTimeDescriptor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorComparer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorProvider.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorResolutionContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDesignTimeDescriptor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveDescriptor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveType.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorComparer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeNameComparison.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeValueComparison.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TypeBasedTagHelperDescriptorComparer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/DocumentParseCompleteEventArgs.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/AutoCompleteEditHandler.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/BackgroundParser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/EditResult.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/EditorHints.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/ImplicitExpressionEditHandler.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/RazorEditorTrace.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/SingleLineMarkupEditHandler.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Editor/SpanEditHandler.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/ErrorSink.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/BalancingModes.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Directives.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Expressions.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Statements.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/CSharpLanguageCharacteristics.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ConditionalAttributeCollapser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/DisposableAction.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ISyntaxTreeRewriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/Internal/CallbackVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlLanguageCharacteristics.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.Block.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.Document.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.Section.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/LanguageCharacteristics.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/MarkupCollapser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/MarkupRewriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ParserBase.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ParserContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ParserHelpers.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ParserVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/ParserVisitorExtensions.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/RazorParser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/RewritingContext.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxConstants.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/AcceptedCharacters.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/Block.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/BlockBuilder.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/BlockType.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/EquivalenceComparer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/Span.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/SpanBuilder.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/SpanKind.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/SyntaxTree/SyntaxTreeNode.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TagHelpers/Internal/TagHelperBlockRewriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TagHelpers/Internal/TagHelperParseTreeRewriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TagHelpers/TagHelperAttributeNode.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TagHelpers/TagHelperBlock.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TagHelpers/TagHelperBlockBuilder.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TagHelpers/TagHelperDirectiveSpanVisitor.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TextReaderExtensions.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TokenizerBackedParser.Helpers.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/TokenizerBackedParser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Parser/WhitespaceRewriter.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/ParserResults.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/PartialParseResult.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Properties/CommonResources.Designer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Properties/RazorResources.Designer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/RazorCodeLanguage.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/RazorEditorParser.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/RazorEngineHost.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/RazorError.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/RazorResources.resx delete mode 100644 src/Microsoft.AspNetCore.Razor/RazorTemplateEngine.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/SourceLocation.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/ITextBuffer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/ITextDocument.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/LineTrackingStringBuffer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/LocationTagged.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/LookaheadTextReader.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/LookaheadToken.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/SeekableTextReader.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/SourceLocationTracker.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/TextChange.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/TextDocumentReader.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Text/TextExtensions.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/CSharpKeywordDetector.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/ITokenizer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpHelpers.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpTokenizer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/HtmlTokenizer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpKeyword.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbol.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbolType.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/ISymbol.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbol.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbolType.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/KnownSymbolType.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolBase.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolExtensions.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/Tokenizer.cs delete mode 100644 src/Microsoft.AspNetCore.Razor/Tokenizer/TokenizerView.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorFactoryTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorResolverTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactoryTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperTypeResolverTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/XmlDocumentationProviderTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CSharpRazorCodeLanguageTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkTreeBuilderTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkVisitorTests.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AddImportChunkGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AttributeBlockChunkGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/RazorCommentChunkGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeWriterTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpLineMappingWriterTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpPaddingBuilderTests.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpRazorCodeGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingUnitTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestCodeGenerator.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestHost.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeWriterTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/DynamicAttributeBlockChunkGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/LineMappingTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/RazorChunkGeneratorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TabTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperAttributeValueCodeRendererTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TestSpan.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorProviderTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Editor/AutoCompleteEditHandlerTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Editor/ImplicitExpressionEditHandlerTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Editor/SpanEditHandlerTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/BlockExtensions.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/BlockFactory.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/BlockTypes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/CodeParserTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlCodeParserTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlMarkupParserTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/ErrorCollector.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/MarkupParserTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/ParserTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/RawTextSymbol.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Framework/TestSpanBuilder.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Microsoft.AspNetCore.Razor.Test.csproj delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpAutoCompleteTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpBlockTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpDirectivesTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpErrorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpExplicitExpressionTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpImplicitExpressionTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpLanguageCharacteristicsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpNestedStatementsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpRazorCommentsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpReservedWordsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSectionTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSpecialBlockTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpStatementTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpTemplateTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpToMarkupSwitchTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpVerbatimBlockTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpWhitespaceHandlingTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/DisposableActionTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/HtmlToCodeSwitchTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/CallbackVisitorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlAttributeTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlBlockTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlDocumentTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlErrorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlParserTestUtils.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlTagsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/ParserContextTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/ParserVisitorExtensionsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/RazorParserTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/SyntaxTree/BlockTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperBlockRewriterTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperParseTreeRewriterTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperRewritingTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperBlockTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperDirectiveSpanVisitorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/TextReaderExtensionsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Parser/WhitespaceRewriterTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/PartialParsingTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/RazorCodeLanguageTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/RazorEditorParserTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/RazorEngineHostTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/RazorErrorTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/RazorTemplateEngineTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/SourceLocationTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/StringTextBuffer.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AddTagHelperDirective.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.CustomAttributeCodeGenerator.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.RemoveTagHelper.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Blocks.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/AddGenerateChunkTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/BuildAfterExecuteContentTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ChunkTreeWithUsings.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ClearGenerateChunkTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/DefaultGenerateChunkTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlock.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockAtEOF.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockWithTextElement.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CssSelectorTagHelperAttributes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateTargetTagHelper.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyCodeBlock.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyExplicitExpression.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpression.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpression.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionAtEOF.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExpressionsInCode.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlockMinimal.DesignTime.Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock_Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HiddenSpansInCode.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Double.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Single.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpression.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpressionAtEOF.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/IncompleteTagHelper.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Designtime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Runtime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/InlineBlocks.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Instrumented.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MarkupInCodeBlock.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCodeBlocks.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NoLinePragmas.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ParserError.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.Reversed.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RemoveTagHelperDirective.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Sections.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SimpleUnspacedIf.DesignTime.Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelperWithNewlineBeforeAttributes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/StringLiterals.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersInSection.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersWithWeirdlySpacedAttributes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Templates.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.DesignTime.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.Tabs.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AddTagHelperDirective.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AttributeTargetingTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Await.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.Prefixed.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.RemoveTagHelper.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Blocks.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlock.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockAtEOF.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockWithTextElement.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ComplexTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ConditionalAttributes.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CssSelectorTagHelperAttributes.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DesignTime.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateAttributeTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateTargetTagHelper.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DynamicAttributeTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyAttributeTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyCodeBlock.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyExplicitExpression.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpression.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpressionInCode.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EnumTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EscapedTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpression.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionAtEOF.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionWithMarkup.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExpressionsInCode.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlockMinimal.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock_Tabs.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HiddenSpansInCode.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Double.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Single.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpression.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpressionAtEOF.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Imports.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/IncompleteTagHelper.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Inherits.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/InlineBlocks.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Instrumented.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MarkupInCodeBlock.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MinimizedTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCSharp.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCodeBlocks.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedScriptTagTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NoLinePragmas.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NullConditionalExpressions.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/OpenedIf.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ParserError.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/PrefixedAttributeTagHelpers.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RazorComments.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RemoveTagHelperDirective.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Sections.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SimpleUnspacedIf.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelper.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelperWithNewlineBeforeAttributes.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/StringLiterals.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SymbolBoundAttributes.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersInSection.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersWithWeirdlySpacedAttributes.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Templates.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TransitionsInTagHelperAttributes.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/UnfinishedExpressionInCode.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.cshtml delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.txt delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/TestFiles/nested-1000.html delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Text/LineTrackingStringBufferTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Text/LookaheadTextReaderTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Text/SourceLocationTrackerTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Text/TextChangeTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerCommentTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerIdentifierTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerLiteralTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerOperatorsTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/TokenizerLookaheadTest.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Tokenizer/TokenizerTestBase.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Utils/BaselineWriter.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Utils/ExceptionHelpers.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Utils/MiscUtils.cs delete mode 100644 test/Microsoft.AspNetCore.Razor.Test/Utils/TestFile.cs diff --git a/Razor.sln b/Razor.sln index 00bd82cfbf..136a526e59 100644 --- a/Razor.sln +++ b/Razor.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26228.0 +VisualStudioVersion = 15.0.26228.9 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{3C0D6505-79B3-49D0-B4C3-176F0F1836ED}" EndProject @@ -8,8 +8,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{92463391-8 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor", "src\Microsoft.AspNetCore.Razor\Microsoft.AspNetCore.Razor.csproj", "{EDA30434-C567-44DC-B8B6-2566A7F77163}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Test", "test\Microsoft.AspNetCore.Razor.Test\Microsoft.AspNetCore.Razor.Test.csproj", "{87C7338B-0C06-4C7B-BE75-A2368AE26797}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Runtime", "src\Microsoft.AspNetCore.Razor.Runtime\Microsoft.AspNetCore.Razor.Runtime.csproj", "{D0196096-1B01-4133-AACE-1A10A0F7247C}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F8C12DD6-659D-405A-AA27-FB22AD92A010}" @@ -61,14 +59,6 @@ Global {EDA30434-C567-44DC-B8B6-2566A7F77163}.Release|Any CPU.Build.0 = Release|Any CPU {EDA30434-C567-44DC-B8B6-2566A7F77163}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU {EDA30434-C567-44DC-B8B6-2566A7F77163}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.Debug|Any CPU.Build.0 = Debug|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.DebugNoVSIX|Any CPU.Build.0 = Debug|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.Release|Any CPU.ActiveCfg = Release|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.Release|Any CPU.Build.0 = Release|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU - {87C7338B-0C06-4C7B-BE75-A2368AE26797}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU {D0196096-1B01-4133-AACE-1A10A0F7247C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D0196096-1B01-4133-AACE-1A10A0F7247C}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0196096-1B01-4133-AACE-1A10A0F7247C}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU @@ -177,7 +167,6 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {EDA30434-C567-44DC-B8B6-2566A7F77163} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} - {87C7338B-0C06-4C7B-BE75-A2368AE26797} = {92463391-81BE-462B-AC3C-78C6C760741F} {D0196096-1B01-4133-AACE-1A10A0F7247C} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} {7BE58880-36AD-4CD5-9E16-2A5AFEA790EF} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} {932F3C9C-A6C0-40D3-BA50-9309886242FC} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} diff --git a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveBoundAttributeDescriptorComparer.cs b/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveBoundAttributeDescriptorComparer.cs deleted file mode 100644 index 65f40c37e0..0000000000 --- a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveBoundAttributeDescriptorComparer.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.Extensions.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.TagHelpers.Testing -{ - internal class TagHelperAttributeDescriptorComparer : IEqualityComparer - { - public static readonly TagHelperAttributeDescriptorComparer Default = - new TagHelperAttributeDescriptorComparer(); - - private TagHelperAttributeDescriptorComparer() - { - } - - public bool Equals(TagHelperAttributeDescriptor descriptorX, TagHelperAttributeDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - Assert.NotNull(descriptorX); - Assert.NotNull(descriptorY); - Assert.Equal(descriptorX.IsIndexer, descriptorY.IsIndexer); - Assert.Equal(descriptorX.Name, descriptorY.Name, StringComparer.Ordinal); - Assert.Equal(descriptorX.PropertyName, descriptorY.PropertyName, StringComparer.Ordinal); - Assert.Equal(descriptorX.TypeName, descriptorY.TypeName, StringComparer.Ordinal); - Assert.Equal(descriptorX.IsEnum, descriptorY.IsEnum); - Assert.Equal(descriptorX.IsStringProperty, descriptorY.IsStringProperty); - - return TagHelperAttributeDesignTimeDescriptorComparer.Default.Equals( - descriptorX.DesignTimeDescriptor, - descriptorY.DesignTimeDescriptor); - } - - public int GetHashCode(TagHelperAttributeDescriptor descriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(descriptor.IsIndexer); - hashCodeCombiner.Add(descriptor.Name, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.PropertyName, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.TypeName, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.IsEnum); - hashCodeCombiner.Add(descriptor.IsStringProperty); - hashCodeCombiner.Add(TagHelperAttributeDesignTimeDescriptorComparer.Default.GetHashCode( - descriptor.DesignTimeDescriptor)); - - return hashCodeCombiner; - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveRequiredAttributeDescriptorComparer.cs b/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveRequiredAttributeDescriptorComparer.cs deleted file mode 100644 index 71d75ec6fd..0000000000 --- a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveRequiredAttributeDescriptorComparer.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.Extensions.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.TagHelpers.Testing -{ - internal class CaseSensitiveTagHelperRequiredAttributeDescriptorComparer : TagHelperRequiredAttributeDescriptorComparer - { - public new static readonly CaseSensitiveTagHelperRequiredAttributeDescriptorComparer Default = - new CaseSensitiveTagHelperRequiredAttributeDescriptorComparer(); - - private CaseSensitiveTagHelperRequiredAttributeDescriptorComparer() - : base() - { - } - - public override bool Equals(TagHelperRequiredAttributeDescriptor descriptorX, TagHelperRequiredAttributeDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - Assert.True(base.Equals(descriptorX, descriptorY)); - Assert.Equal(descriptorX.Name, descriptorY.Name, StringComparer.Ordinal); - - return true; - } - - public override int GetHashCode(TagHelperRequiredAttributeDescriptor descriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(base.GetHashCode(descriptor)); - hashCodeCombiner.Add(descriptor.Name, StringComparer.Ordinal); - - return hashCodeCombiner.CombinedHash; - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveTagHelperDescriptorComparer.cs b/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveTagHelperDescriptorComparer.cs deleted file mode 100644 index eefd9e4c3f..0000000000 --- a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/CaseSensitiveTagHelperDescriptorComparer.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.Extensions.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.TagHelpers.Testing -{ - internal class CaseSensitiveTagHelperDescriptorComparer : TagHelperDescriptorComparer - { - public new static readonly CaseSensitiveTagHelperDescriptorComparer Default = - new CaseSensitiveTagHelperDescriptorComparer(); - - private CaseSensitiveTagHelperDescriptorComparer() - : base() - { - } - - public override bool Equals(TagHelperDescriptor descriptorX, TagHelperDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - Assert.True(base.Equals(descriptorX, descriptorY)); - - // Normal comparer doesn't care about the case, required attribute order, allowed children order, - // attributes or prefixes. In tests we do. - Assert.Equal(descriptorX.TagName, descriptorY.TagName, StringComparer.Ordinal); - Assert.Equal(descriptorX.Prefix, descriptorY.Prefix, StringComparer.Ordinal); - Assert.Equal( - descriptorX.RequiredAttributes, - descriptorY.RequiredAttributes, - CaseSensitiveTagHelperRequiredAttributeDescriptorComparer.Default); - Assert.Equal(descriptorX.RequiredParent, descriptorY.RequiredParent, StringComparer.Ordinal); - - if (descriptorX.AllowedChildren != descriptorY.AllowedChildren) - { - Assert.Equal(descriptorX.AllowedChildren, descriptorY.AllowedChildren, StringComparer.Ordinal); - } - - Assert.Equal( - descriptorX.Attributes, - descriptorY.Attributes, - TagHelperAttributeDescriptorComparer.Default); - Assert.Equal( - descriptorX.DesignTimeDescriptor, - descriptorY.DesignTimeDescriptor, - TagHelperDesignTimeDescriptorComparer.Default); - - return true; - } - - public override int GetHashCode(TagHelperDescriptor descriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(base.GetHashCode(descriptor)); - hashCodeCombiner.Add(descriptor.TagName, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.Prefix, StringComparer.Ordinal); - - if (descriptor.DesignTimeDescriptor != null) - { - hashCodeCombiner.Add( - TagHelperDesignTimeDescriptorComparer.Default.GetHashCode(descriptor.DesignTimeDescriptor)); - } - - foreach (var requiredAttribute in descriptor.RequiredAttributes.OrderBy(attribute => attribute.Name)) - { - hashCodeCombiner.Add( - CaseSensitiveTagHelperRequiredAttributeDescriptorComparer.Default.GetHashCode(requiredAttribute)); - } - - if (descriptor.AllowedChildren != null) - { - foreach (var child in descriptor.AllowedChildren.OrderBy(child => child)) - { - hashCodeCombiner.Add(child, StringComparer.Ordinal); - } - } - - var orderedAttributeHashCodes = descriptor.Attributes - .Select(attribute => TagHelperAttributeDescriptorComparer.Default.GetHashCode(attribute)) - .OrderBy(hashcode => hashcode); - foreach (var attributeHashCode in orderedAttributeHashCodes) - { - hashCodeCombiner.Add(attributeHashCode); - } - - return hashCodeCombiner.CombinedHash; - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperAttributeDesignTimeDescriptorComparer.cs b/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperAttributeDesignTimeDescriptorComparer.cs deleted file mode 100644 index 9293dd2ef8..0000000000 --- a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperAttributeDesignTimeDescriptorComparer.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.Extensions.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.TagHelpers.Testing -{ - internal class TagHelperAttributeDesignTimeDescriptorComparer : - IEqualityComparer - { - public static readonly TagHelperAttributeDesignTimeDescriptorComparer Default = - new TagHelperAttributeDesignTimeDescriptorComparer(); - - private TagHelperAttributeDesignTimeDescriptorComparer() - { - } - - public bool Equals( - TagHelperAttributeDesignTimeDescriptor descriptorX, - TagHelperAttributeDesignTimeDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - Assert.NotNull(descriptorX); - Assert.NotNull(descriptorY); - Assert.Equal(descriptorX.Summary, descriptorY.Summary, StringComparer.Ordinal); - Assert.Equal(descriptorX.Remarks, descriptorY.Remarks, StringComparer.Ordinal); - - return true; - } - - public int GetHashCode(TagHelperAttributeDesignTimeDescriptor descriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(descriptor.Summary, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.Remarks, StringComparer.Ordinal); - - return hashCodeCombiner; - } - } -} diff --git a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperDesignTimeDescriptorComparer.cs b/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperDesignTimeDescriptorComparer.cs deleted file mode 100644 index 290d399fce..0000000000 --- a/shared/Microsoft.AspNetCore.Razor.TagHelpers.Testing.Sources/TagHelperDesignTimeDescriptorComparer.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.Extensions.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.TagHelpers.Testing -{ - internal class TagHelperDesignTimeDescriptorComparer : IEqualityComparer - { - public static readonly TagHelperDesignTimeDescriptorComparer Default = - new TagHelperDesignTimeDescriptorComparer(); - - private TagHelperDesignTimeDescriptorComparer() - { - } - - public bool Equals(TagHelperDesignTimeDescriptor descriptorX, TagHelperDesignTimeDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - Assert.NotNull(descriptorX); - Assert.NotNull(descriptorY); - Assert.Equal(descriptorX.Summary, descriptorY.Summary, StringComparer.Ordinal); - Assert.Equal(descriptorX.Remarks, descriptorY.Remarks, StringComparer.Ordinal); - Assert.Equal(descriptorX.OutputElementHint, descriptorY.OutputElementHint, StringComparer.Ordinal); - - return true; - } - - public int GetHashCode(TagHelperDesignTimeDescriptor descriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - - hashCodeCombiner.Add(descriptor.Summary, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.Remarks, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.OutputElementHint, StringComparer.Ordinal); - - return hashCodeCombiner; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Microsoft.AspNetCore.Razor.Runtime.csproj b/src/Microsoft.AspNetCore.Razor.Runtime/Microsoft.AspNetCore.Razor.Runtime.csproj index 2632cea07a..d826a00e31 100644 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Microsoft.AspNetCore.Razor.Runtime.csproj +++ b/src/Microsoft.AspNetCore.Razor.Runtime/Microsoft.AspNetCore.Razor.Runtime.csproj @@ -17,12 +17,8 @@ Microsoft.AspNetCore.Razor.TagHelpers.ITagHelper - - - - diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Resources.resx b/src/Microsoft.AspNetCore.Razor.Runtime/Resources.resx index c175059d9a..9c2750778a 100644 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Resources.resx +++ b/src/Microsoft.AspNetCore.Razor.Runtime/Resources.resx @@ -117,97 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Invalid tag helper directive look up text '{0}'. The correct look up text format is: "typeName, assemblyName". - - - Cannot resolve TagHelper containing assembly '{0}'. Error: {1} - - - Tag helper directive assembly name cannot be null or empty. - Must call '{2}.{1}' before calling '{2}.{0}'. - - {0} name cannot be null or whitespace. - - - The value cannot be null or empty. - - - Encountered an unexpected error when attempting to resolve tag helper directive '{0}' with value '{1}'. Error: {2} - - - Tag helpers cannot target {0} name '{1}' because it contains a '{2}' character. - - - Invalid tag helper directive '{0}'. Cannot have multiple '{0}' directives on a page. - - - Invalid tag helper directive '{0}' value. '{1}' is not allowed in prefix '{2}'. - - - Attribute - - - name - - - prefix - - - Tag - - - Invalid tag helper bound property '{0}.{1}'. An '{2}' must not be associated with a property with no public setter unless its type implements '{3}'. - - - Invalid tag helper bound property '{0}.{1}'. Tag helpers cannot bind to HTML attributes with {2} '{3}' because {2} contains a '{4}' character. - - - Invalid tag helper bound property '{0}.{1}'. Tag helpers cannot bind to HTML attributes with {2} '{3}' because {2} starts with '{4}'. - - - Invalid tag helper bound property '{0}.{1}'. Tag helpers cannot bind to HTML attributes with a whitespace {2}. - - - Invalid tag helper bound property '{0}.{1}'. Tag helpers cannot bind to HTML attributes with a null or empty name. - - - Invalid tag helper bound property '{0}.{1}'. '{2}.{3}' must be null or empty if property has no public setter. - - - Invalid tag helper bound property '{0}.{1}'. '{2}.{3}' must not be null if property has no public setter and its type implements '{4}'. - - - Invalid tag helper bound property '{0}.{1}'. '{2}.{3}' must be null unless property type implements '{4}'. - - - Invalid '{0}' tag name '{1}' for tag helper '{2}'. Tag helpers cannot restrict child elements that contain a '{3}' character. - - - Invalid '{0}' tag name for tag helper '{1}'. Name cannot be null or whitespace. - - - Parent Tag - - - Argument must be an instance of '{0}'. - - - Could not find matching ']' for required attribute '{0}'. - - - Invalid required attribute character '{0}' in required attribute '{1}'. Separate required attributes with commas. - - - Required attribute '{0}' has mismatched quotes '{1}' around value. - - - Required attribute '{0}' has a partial CSS operator. '{1}' must be followed by an equals. - - - Invalid character '{0}' in required attribute '{1}'. Expected supported CSS operator or ']'. - \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/Constants.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/Constants.cs deleted file mode 100644 index 3004c2d729..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/Constants.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - internal static class Constants - { - public static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(10); - } -} diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperDescriptorFactory.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperDescriptorFactory.cs deleted file mode 100644 index c7d9c597d3..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperDescriptorFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Factory for instances. - /// - public interface ITagHelperDescriptorFactory - { - /// - /// Creates a from the given . - /// - /// The assembly name that contains . - /// The to create a from. - /// - /// The used to collect s encountered - /// when creating s for the given . - /// - /// A collection of s that describe the given . - /// - IEnumerable CreateDescriptors(string assemblyName, Type type, ErrorSink errorSink); - } -} diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperTypeResolver.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperTypeResolver.cs deleted file mode 100644 index c2770dffe7..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/ITagHelperTypeResolver.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Locates valid s within an assembly. - /// - public interface ITagHelperTypeResolver - { - /// - /// Locates valid types from the named . - /// - /// The name of an to search. - /// The of the associated - /// responsible for the current call. - /// - /// The used to record errors found when resolving - /// types. - /// An of valid types. - IEnumerable Resolve(string name, SourceLocation documentLocation, ErrorSink errorSink); - } -} diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperConventions.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperConventions.cs deleted file mode 100644 index 94bf4a69d5..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperConventions.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Reflection; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Default convention for determining if a type is a tag helper. - /// - public static class TagHelperConventions - { - private static readonly TypeInfo ITagHelperTypeInfo = typeof(ITagHelper).GetTypeInfo(); - - /// - /// Indicates whether or not the is a tag helper. - /// - /// The . - /// true if is a tag helper; false otherwise. - public static bool IsTagHelper(TypeInfo typeInfo) - { - return !typeInfo.IsNested && - typeInfo.IsPublic && - !typeInfo.IsAbstract && - !typeInfo.IsGenericType && - ITagHelperTypeInfo.IsAssignableFrom(typeInfo); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorFactory.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorFactory.cs deleted file mode 100644 index d032003c77..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorFactory.cs +++ /dev/null @@ -1,1054 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Factory for s from s. - /// - public class TagHelperDescriptorFactory : ITagHelperDescriptorFactory - { - private const string DataDashPrefix = "data-"; - private const string TagHelperNameEnding = "TagHelper"; - private const string HtmlCaseRegexReplacement = "-$1$2"; - private const char RequiredAttributeWildcardSuffix = '*'; - - // This matches the following AFTER the start of the input string (MATCH). - // Any letter/number followed by an uppercase letter then lowercase letter: 1(Aa), a(Aa), A(Aa) - // Any lowercase letter followed by an uppercase letter: a(A) - // Each match is then prefixed by a "-" via the ToHtmlCase method. - private static readonly Regex HtmlCaseRegex = - new Regex( - "(? InvalidNonWhitespaceNameCharacters { get; } = new HashSet( - new[] { '@', '!', '<', '/', '?', '[', '>', ']', '=', '"', '\'', '*' }); - - /// - /// Instantiates a new . - /// - /// - /// Indicates if s should be created for design time. - /// - public TagHelperDescriptorFactory(bool designTime) - { - if (designTime) - { - _designTimeDescriptorFactory = new TagHelperDesignTimeDescriptorFactory(); - } - - _designTime = designTime; - } - - /// - public virtual IEnumerable CreateDescriptors( - string assemblyName, - Type type, - ErrorSink errorSink) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (errorSink == null) - { - throw new ArgumentNullException(nameof(errorSink)); - } - - if (ShouldSkipDescriptorCreation(type.GetTypeInfo())) - { - return Enumerable.Empty(); - } - - var attributeDescriptors = GetAttributeDescriptors(type, errorSink); - var targetElementAttributes = GetValidHtmlTargetElementAttributes(type, errorSink); - var allowedChildren = GetAllowedChildren(type, errorSink); - - var tagHelperDescriptors = - BuildTagHelperDescriptors( - type, - assemblyName, - attributeDescriptors, - targetElementAttributes, - allowedChildren); - - return tagHelperDescriptors.Distinct(TagHelperDescriptorComparer.Default); - } - - private static IEnumerable GetValidHtmlTargetElementAttributes( - Type type, - ErrorSink errorSink) - { - var targetElementAttributes = type - .GetTypeInfo() - .GetCustomAttributes(inherit: false); - return targetElementAttributes.Where( - attribute => ValidHtmlTargetElementAttributeNames(attribute, errorSink)); - } - - private IEnumerable BuildTagHelperDescriptors( - Type type, - string assemblyName, - IEnumerable attributeDescriptors, - IEnumerable targetElementAttributes, - IEnumerable allowedChildren) - { - TagHelperDesignTimeDescriptor typeDesignTimeDescriptor = null; - - if (_designTime) - { - typeDesignTimeDescriptor = _designTimeDescriptorFactory.CreateDescriptor(type); - } - - var typeName = type.FullName; - - // If there isn't an attribute specifying the tag name derive it from the name - if (!targetElementAttributes.Any()) - { - var name = type.Name; - - if (name.EndsWith(TagHelperNameEnding, StringComparison.OrdinalIgnoreCase)) - { - name = name.Substring(0, name.Length - TagHelperNameEnding.Length); - } - - return new[] - { - BuildTagHelperDescriptor( - ToHtmlCase(name), - typeName, - assemblyName, - attributeDescriptors, - requiredAttributeDescriptors: Enumerable.Empty(), - allowedChildren: allowedChildren, - tagStructure: default(TagStructure), - parentTag: null, - designTimeDescriptor: typeDesignTimeDescriptor) - }; - } - - return targetElementAttributes.Select( - attribute => - BuildTagHelperDescriptor( - typeName, - assemblyName, - attributeDescriptors, - attribute, - allowedChildren, - typeDesignTimeDescriptor)); - } - - private static IEnumerable GetAllowedChildren(Type type, ErrorSink errorSink) - { - var restrictChildrenAttribute = type.GetTypeInfo().GetCustomAttribute(inherit: false); - if (restrictChildrenAttribute == null) - { - return null; - } - - var allowedChildren = restrictChildrenAttribute.ChildTags; - var validAllowedChildren = GetValidAllowedChildren(allowedChildren, type.FullName, errorSink); - - if (validAllowedChildren.Any()) - { - return validAllowedChildren; - } - else - { - // All allowed children were invalid, return null to indicate that any child is acceptable. - return null; - } - } - - // Internal for unit testing - internal static IEnumerable GetValidAllowedChildren( - IEnumerable allowedChildren, - string tagHelperName, - ErrorSink errorSink) - { - var validAllowedChildren = new List(); - - foreach (var name in allowedChildren) - { - if (string.IsNullOrWhiteSpace(name)) - { - var whitespaceError = Resources.FormatTagHelperDescriptorFactory_InvalidRestrictChildrenAttributeNameNullWhitespace( - nameof(RestrictChildrenAttribute), - tagHelperName); - errorSink.OnError(SourceLocation.Zero, whitespaceError, length: 0); - } - else if (TryValidateName( - name, - invalidCharacter => Resources.FormatTagHelperDescriptorFactory_InvalidRestrictChildrenAttributeName( - nameof(RestrictChildrenAttribute), - name, - tagHelperName, - invalidCharacter), - errorSink)) - { - validAllowedChildren.Add(name); - } - } - - return validAllowedChildren; - } - - private static TagHelperDescriptor BuildTagHelperDescriptor( - string typeName, - string assemblyName, - IEnumerable attributeDescriptors, - HtmlTargetElementAttribute targetElementAttribute, - IEnumerable allowedChildren, - TagHelperDesignTimeDescriptor designTimeDescriptor) - { - IEnumerable requiredAttributeDescriptors; - TryGetRequiredAttributeDescriptors(targetElementAttribute.Attributes, errorSink: null, descriptors: out requiredAttributeDescriptors); - - return BuildTagHelperDescriptor( - targetElementAttribute.Tag, - typeName, - assemblyName, - attributeDescriptors, - requiredAttributeDescriptors, - allowedChildren, - targetElementAttribute.ParentTag, - targetElementAttribute.TagStructure, - designTimeDescriptor); - } - - private static TagHelperDescriptor BuildTagHelperDescriptor( - string tagName, - string typeName, - string assemblyName, - IEnumerable attributeDescriptors, - IEnumerable requiredAttributeDescriptors, - IEnumerable allowedChildren, - string parentTag, - TagStructure tagStructure, - TagHelperDesignTimeDescriptor designTimeDescriptor) - { - return new TagHelperDescriptor - { - TagName = tagName, - TypeName = typeName, - AssemblyName = assemblyName, - Attributes = attributeDescriptors, - RequiredAttributes = requiredAttributeDescriptors, - AllowedChildren = allowedChildren, - RequiredParent = parentTag, - TagStructure = tagStructure, - DesignTimeDescriptor = designTimeDescriptor - }; - } - - /// - /// Internal for testing. - /// - internal static bool ValidHtmlTargetElementAttributeNames( - HtmlTargetElementAttribute attribute, - ErrorSink errorSink) - { - var validTagName = ValidateName(attribute.Tag, targetingAttributes: false, errorSink: errorSink); - IEnumerable requiredAttributeDescriptors; - var validRequiredAttributes = TryGetRequiredAttributeDescriptors(attribute.Attributes, errorSink, out requiredAttributeDescriptors); - var validParentTagName = ValidateParentTagName(attribute.ParentTag, errorSink); - - return validTagName && validRequiredAttributes && validParentTagName; - } - - /// - /// Internal for unit testing. - /// - internal static bool ValidateParentTagName(string parentTag, ErrorSink errorSink) - { - if (parentTag == null) - { - return true; - } - else if (string.IsNullOrWhiteSpace(parentTag)) - { - var error = Resources.FormatHtmlTargetElementAttribute_NameCannotBeNullOrWhitespace( - Resources.TagHelperDescriptorFactory_ParentTag); - errorSink.OnError(SourceLocation.Zero, error, length: 0); - return false; - } - else if (!TryValidateName( - parentTag, - invalidCharacter => Resources.FormatHtmlTargetElementAttribute_InvalidName( - Resources.TagHelperDescriptorFactory_ParentTag.ToLower(), - parentTag, - invalidCharacter), - errorSink)) - { - return false; - } - - return true; - } - - private static bool TryGetRequiredAttributeDescriptors( - string requiredAttributes, - ErrorSink errorSink, - out IEnumerable descriptors) - { - var parser = new RequiredAttributeParser(requiredAttributes); - - return parser.TryParse(errorSink, out descriptors); - } - - private static bool ValidateName(string name, bool targetingAttributes, ErrorSink errorSink) - { - if (!targetingAttributes && - string.Equals( - name, - TagHelperDescriptorProvider.ElementCatchAllTarget, - StringComparison.OrdinalIgnoreCase)) - { - // '*' as the entire name is OK in the HtmlTargetElement catch-all case. - return true; - } - - var targetName = targetingAttributes ? - Resources.TagHelperDescriptorFactory_Attribute : - Resources.TagHelperDescriptorFactory_Tag; - - if (string.IsNullOrWhiteSpace(name)) - { - var error = Resources.FormatHtmlTargetElementAttribute_NameCannotBeNullOrWhitespace(targetName); - errorSink.OnError(SourceLocation.Zero, error, length: 0); - return false; - } - else if (!TryValidateName( - name, - invalidCharacter => Resources.FormatHtmlTargetElementAttribute_InvalidName( - targetName.ToLower(), - name, - invalidCharacter), - errorSink)) - { - return false; - } - - return true; - } - - private static bool TryValidateName( - string name, - Func characterErrorBuilder, - ErrorSink errorSink) - { - var validName = true; - - foreach (var character in name) - { - if (char.IsWhiteSpace(character) || - InvalidNonWhitespaceNameCharacters.Contains(character)) - { - var error = characterErrorBuilder(character); - errorSink.OnError(SourceLocation.Zero, error, length: 0); - - validName = false; - } - } - - return validName; - } - - private IEnumerable GetAttributeDescriptors(Type type, ErrorSink errorSink) - { - var attributeDescriptors = new List(); - - // Keep indexer descriptors separate to avoid sorting the combined list later. - var indexerDescriptors = new List(); - - var accessibleProperties = type.GetRuntimeProperties().Where(IsAccessibleProperty); - foreach (var property in accessibleProperties) - { - if (ShouldSkipDescriptorCreation(property)) - { - continue; - } - - var attributeNameAttribute = property - .GetCustomAttributes(inherit: false) - .FirstOrDefault(); - var hasExplicitName = - attributeNameAttribute != null && !string.IsNullOrEmpty(attributeNameAttribute.Name); - var attributeName = hasExplicitName ? attributeNameAttribute.Name : ToHtmlCase(property.Name); - - TagHelperAttributeDescriptor mainDescriptor = null; - if (property.SetMethod != null && property.SetMethod.IsPublic) - { - mainDescriptor = ToAttributeDescriptor(property, attributeName); - if (!ValidateTagHelperAttributeDescriptor(mainDescriptor, type, errorSink)) - { - // HtmlAttributeNameAttribute.Name is invalid. Ignore this property completely. - continue; - } - } - else if (hasExplicitName) - { - // Specified HtmlAttributeNameAttribute.Name though property has no public setter. - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributeNameNotNullOrEmpty( - type.FullName, - property.Name, - typeof(HtmlAttributeNameAttribute).FullName, - nameof(HtmlAttributeNameAttribute.Name)), - length: 0); - continue; - } - - bool isInvalid; - var indexerDescriptor = ToIndexerAttributeDescriptor( - property, - attributeNameAttribute, - parentType: type, - errorSink: errorSink, - defaultPrefix: attributeName + "-", - isInvalid: out isInvalid); - if (indexerDescriptor != null && - !ValidateTagHelperAttributeDescriptor(indexerDescriptor, type, errorSink)) - { - isInvalid = true; - } - - if (isInvalid) - { - // The property type or HtmlAttributeNameAttribute.DictionaryAttributePrefix (or perhaps the - // HTML-casing of the property name) is invalid. Ignore this property completely. - continue; - } - - if (mainDescriptor != null) - { - attributeDescriptors.Add(mainDescriptor); - } - - if (indexerDescriptor != null) - { - indexerDescriptors.Add(indexerDescriptor); - } - } - - attributeDescriptors.AddRange(indexerDescriptors); - - return attributeDescriptors; - } - - // Internal for testing. - internal static bool ValidateTagHelperAttributeDescriptor( - TagHelperAttributeDescriptor attributeDescriptor, - Type parentType, - ErrorSink errorSink) - { - string nameOrPrefix; - if (attributeDescriptor.IsIndexer) - { - nameOrPrefix = Resources.TagHelperDescriptorFactory_Prefix; - } - else if (string.IsNullOrEmpty(attributeDescriptor.Name)) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributeNameNullOrEmpty( - parentType.FullName, - attributeDescriptor.PropertyName), - length: 0); - - return false; - } - else - { - nameOrPrefix = Resources.TagHelperDescriptorFactory_Name; - } - - return ValidateTagHelperAttributeNameOrPrefix( - attributeDescriptor.Name, - parentType, - attributeDescriptor.PropertyName, - errorSink, - nameOrPrefix); - } - - private bool ShouldSkipDescriptorCreation(MemberInfo memberInfo) - { - if (_designTime) - { - var editorBrowsableAttribute = memberInfo.GetCustomAttribute(inherit: false); - - return editorBrowsableAttribute != null && - editorBrowsableAttribute.State == EditorBrowsableState.Never; - } - - return false; - } - - private static bool ValidateTagHelperAttributeNameOrPrefix( - string attributeNameOrPrefix, - Type parentType, - string propertyName, - ErrorSink errorSink, - string nameOrPrefix) - { - if (string.IsNullOrEmpty(attributeNameOrPrefix)) - { - // ValidateTagHelperAttributeDescriptor validates Name is non-null and non-empty. The empty string is - // valid for DictionaryAttributePrefix and null is impossible at this point because it means "don't - // create a descriptor". (Empty DictionaryAttributePrefix is a corner case which would bind every - // attribute of a target element. Likely not particularly useful but unclear what minimum length - // should be required and what scenarios a minimum length would break.) - return true; - } - - if (string.IsNullOrWhiteSpace(attributeNameOrPrefix)) - { - // Provide a single error if the entire name is whitespace, not an error per character. - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributeNameOrPrefixWhitespace( - parentType.FullName, - propertyName, - nameOrPrefix), - length: 0); - - return false; - } - - // data-* attributes are explicitly not implemented by user agents and are not intended for use on - // the server; therefore it's invalid for TagHelpers to bind to them. - if (attributeNameOrPrefix.StartsWith(DataDashPrefix, StringComparison.OrdinalIgnoreCase)) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributeNameOrPrefixStart( - parentType.FullName, - propertyName, - nameOrPrefix, - attributeNameOrPrefix, - DataDashPrefix), - length: 0); - - return false; - } - - var isValid = true; - foreach (var character in attributeNameOrPrefix) - { - if (char.IsWhiteSpace(character) || InvalidNonWhitespaceNameCharacters.Contains(character)) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributeNameOrPrefixCharacter( - parentType.FullName, - propertyName, - nameOrPrefix, - attributeNameOrPrefix, - character), - length: 0); - - isValid = false; - } - } - - return isValid; - } - - private TagHelperAttributeDescriptor ToAttributeDescriptor(PropertyInfo property, string attributeName) - { - return ToAttributeDescriptor( - property, - attributeName, - property.PropertyType.FullName, - isIndexer: false, - isStringProperty: typeof(string) == property.PropertyType); - } - - private TagHelperAttributeDescriptor ToIndexerAttributeDescriptor( - PropertyInfo property, - HtmlAttributeNameAttribute attributeNameAttribute, - Type parentType, - ErrorSink errorSink, - string defaultPrefix, - out bool isInvalid) - { - isInvalid = false; - var hasPublicSetter = property.SetMethod != null && property.SetMethod.IsPublic; - var dictionaryTypeArguments = ClosedGenericMatcher.ExtractGenericInterface( - property.PropertyType, - typeof(IDictionary<,>)) - ?.GenericTypeArguments - .Select(type => type.IsGenericParameter ? null : type) - .ToArray(); - if (dictionaryTypeArguments?[0] != typeof(string)) - { - if (attributeNameAttribute?.DictionaryAttributePrefix != null) - { - // DictionaryAttributePrefix is not supported unless associated with an - // IDictionary property. - isInvalid = true; - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributePrefixNotNull( - parentType.FullName, - property.Name, - nameof(HtmlAttributeNameAttribute), - nameof(HtmlAttributeNameAttribute.DictionaryAttributePrefix), - "IDictionary"), - length: 0); - } - else if (attributeNameAttribute != null && !hasPublicSetter) - { - // Associated an HtmlAttributeNameAttribute with a non-dictionary property that lacks a public - // setter. - isInvalid = true; - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributeNameAttribute( - parentType.FullName, - property.Name, - nameof(HtmlAttributeNameAttribute), - "IDictionary"), - length: 0); - } - - return null; - } - else if (!hasPublicSetter && - attributeNameAttribute != null && - !attributeNameAttribute.DictionaryAttributePrefixSet) - { - // Must set DictionaryAttributePrefix when using HtmlAttributeNameAttribute with a dictionary property - // that lacks a public setter. - isInvalid = true; - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidAttributePrefixNull( - parentType.FullName, - property.Name, - nameof(HtmlAttributeNameAttribute), - nameof(HtmlAttributeNameAttribute.DictionaryAttributePrefix), - "IDictionary"), - length: 0); - - return null; - } - - // Potential prefix case. Use default prefix (based on name)? - var useDefault = attributeNameAttribute == null || !attributeNameAttribute.DictionaryAttributePrefixSet; - - var prefix = useDefault ? defaultPrefix : attributeNameAttribute.DictionaryAttributePrefix; - if (prefix == null) - { - // DictionaryAttributePrefix explicitly set to null. Ignore. - return null; - } - - return ToAttributeDescriptor( - property, - attributeName: prefix, - typeName: dictionaryTypeArguments[1].FullName, - isIndexer: true, - isStringProperty: typeof(string) == dictionaryTypeArguments[1]); - } - - private TagHelperAttributeDescriptor ToAttributeDescriptor( - PropertyInfo property, - string attributeName, - string typeName, - bool isIndexer, - bool isStringProperty) - { - TagHelperAttributeDesignTimeDescriptor propertyDesignTimeDescriptor = null; - - if (_designTime) - { - propertyDesignTimeDescriptor = _designTimeDescriptorFactory.CreateAttributeDescriptor(property); - } - - return new TagHelperAttributeDescriptor - { - Name = attributeName, - PropertyName = property.Name, - IsEnum = property.PropertyType.GetTypeInfo().IsEnum, - TypeName = typeName, - IsStringProperty = isStringProperty, - IsIndexer = isIndexer, - DesignTimeDescriptor = propertyDesignTimeDescriptor - }; - } - - private static bool IsAccessibleProperty(PropertyInfo property) - { - // Accessible properties are those with public getters and without [HtmlAttributeNotBound]. - return property.GetIndexParameters().Length == 0 && - property.GetMethod != null && - property.GetMethod.IsPublic && - !property.IsDefined(typeof(HtmlAttributeNotBoundAttribute), inherit: false); - } - - /// - /// Converts from pascal/camel case to lower kebab-case. - /// - /// - /// - /// SomeThing => some-thing - /// capsONInside => caps-on-inside - /// CAPSOnOUTSIDE => caps-on-outside - /// ALLCAPS => allcaps - /// One1Two2Three3 => one1-two2-three3 - /// ONE1TWO2THREE3 => one1two2three3 - /// First_Second_ThirdHi => first_second_third-hi - /// - /// - public static string ToHtmlCase(string name) - { - return HtmlCaseRegex.Replace(name, HtmlCaseRegexReplacement).ToLowerInvariant(); - } - - // Internal for testing - internal class RequiredAttributeParser - { - private static readonly IReadOnlyDictionary CssValueComparisons = - new Dictionary - { - { '=', TagHelperRequiredAttributeValueComparison.FullMatch }, - { '^', TagHelperRequiredAttributeValueComparison.PrefixMatch }, - { '$', TagHelperRequiredAttributeValueComparison.SuffixMatch } - }; - private static readonly char[] InvalidPlainAttributeNameCharacters = { ' ', '\t', ',', RequiredAttributeWildcardSuffix }; - private static readonly char[] InvalidCssAttributeNameCharacters = (new[] { ' ', '\t', ',', ']' }) - .Concat(CssValueComparisons.Keys) - .ToArray(); - private static readonly char[] InvalidCssQuotelessValueCharacters = { ' ', '\t', ']' }; - - private int _index; - private string _requiredAttributes; - - public RequiredAttributeParser(string requiredAttributes) - { - _requiredAttributes = requiredAttributes; - } - - private char Current => _requiredAttributes[_index]; - - private bool AtEnd => _index >= _requiredAttributes.Length; - - public bool TryParse( - ErrorSink errorSink, - out IEnumerable requiredAttributeDescriptors) - { - if (string.IsNullOrEmpty(_requiredAttributes)) - { - requiredAttributeDescriptors = Enumerable.Empty(); - return true; - } - - requiredAttributeDescriptors = null; - var descriptors = new List(); - - PassOptionalWhitespace(); - - do - { - TagHelperRequiredAttributeDescriptor descriptor; - if (At('[')) - { - descriptor = ParseCssSelector(errorSink); - } - else - { - descriptor = ParsePlainSelector(errorSink); - } - - if (descriptor == null) - { - // Failed to create the descriptor due to an invalid required attribute. - return false; - } - else - { - descriptors.Add(descriptor); - } - - PassOptionalWhitespace(); - - if (At(',')) - { - _index++; - - if (!EnsureNotAtEnd(errorSink)) - { - return false; - } - } - else if (!AtEnd) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeCharacter(Current, _requiredAttributes), - length: 0); - return false; - } - - PassOptionalWhitespace(); - } - while (!AtEnd); - - requiredAttributeDescriptors = descriptors; - return true; - } - - private TagHelperRequiredAttributeDescriptor ParsePlainSelector(ErrorSink errorSink) - { - var nameEndIndex = _requiredAttributes.IndexOfAny(InvalidPlainAttributeNameCharacters, _index); - string attributeName; - - var nameComparison = TagHelperRequiredAttributeNameComparison.FullMatch; - if (nameEndIndex == -1) - { - attributeName = _requiredAttributes.Substring(_index); - _index = _requiredAttributes.Length; - } - else - { - attributeName = _requiredAttributes.Substring(_index, nameEndIndex - _index); - _index = nameEndIndex; - - if (_requiredAttributes[nameEndIndex] == RequiredAttributeWildcardSuffix) - { - nameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch; - - // Move past wild card - _index++; - } - } - - TagHelperRequiredAttributeDescriptor descriptor = null; - if (ValidateName(attributeName, targetingAttributes: true, errorSink: errorSink)) - { - descriptor = new TagHelperRequiredAttributeDescriptor - { - Name = attributeName, - NameComparison = nameComparison - }; - } - - return descriptor; - } - - private string ParseCssAttributeName(ErrorSink errorSink) - { - var nameStartIndex = _index; - var nameEndIndex = _requiredAttributes.IndexOfAny(InvalidCssAttributeNameCharacters, _index); - nameEndIndex = nameEndIndex == -1 ? _requiredAttributes.Length : nameEndIndex; - _index = nameEndIndex; - - var attributeName = _requiredAttributes.Substring(nameStartIndex, nameEndIndex - nameStartIndex); - - return attributeName; - } - - private TagHelperRequiredAttributeValueComparison? ParseCssValueComparison(ErrorSink errorSink) - { - Debug.Assert(!AtEnd); - TagHelperRequiredAttributeValueComparison valueComparison; - - if (CssValueComparisons.TryGetValue(Current, out valueComparison)) - { - var op = Current; - _index++; - - if (op != '=' && At('=')) - { - // Two length operator (ex: ^=). Move past the second piece - _index++; - } - else if (op != '=') // We're at an incomplete operator (ex: [foo^] - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_PartialRequiredAttributeOperator(_requiredAttributes, op), - length: 0); - return null; - } - } - else if (!At(']')) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeOperator(Current, _requiredAttributes), - length: 0); - return null; - } - - return valueComparison; - } - - private string ParseCssValue(ErrorSink errorSink) - { - int valueStart; - int valueEnd; - if (At('\'') || At('"')) - { - var quote = Current; - - // Move past the quote - _index++; - - valueStart = _index; - valueEnd = _requiredAttributes.IndexOf(quote, _index); - if (valueEnd == -1) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeMismatchedQuotes( - _requiredAttributes, - quote), - length: 0); - return null; - } - _index = valueEnd + 1; - } - else - { - valueStart = _index; - var valueEndIndex = _requiredAttributes.IndexOfAny(InvalidCssQuotelessValueCharacters, _index); - valueEnd = valueEndIndex == -1 ? _requiredAttributes.Length : valueEndIndex; - _index = valueEnd; - } - - var value = _requiredAttributes.Substring(valueStart, valueEnd - valueStart); - - return value; - } - - private TagHelperRequiredAttributeDescriptor ParseCssSelector(ErrorSink errorSink) - { - Debug.Assert(At('[')); - - // Move past '['. - _index++; - PassOptionalWhitespace(); - - var attributeName = ParseCssAttributeName(errorSink); - - PassOptionalWhitespace(); - - if (!EnsureNotAtEnd(errorSink)) - { - return null; - } - - if (!ValidateName(attributeName, targetingAttributes: true, errorSink: errorSink)) - { - // Couldn't parse a valid attribute name. - return null; - } - - var valueComparison = ParseCssValueComparison(errorSink); - - if (!valueComparison.HasValue) - { - return null; - } - - PassOptionalWhitespace(); - - if (!EnsureNotAtEnd(errorSink)) - { - return null; - } - - var value = ParseCssValue(errorSink); - - if (value == null) - { - // Couldn't parse value - return null; - } - - PassOptionalWhitespace(); - - if (At(']')) - { - // Move past the ending bracket. - _index++; - } - else if (AtEnd) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace(_requiredAttributes), - length: 0); - return null; - } - else - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeCharacter(Current, _requiredAttributes), - length: 0); - return null; - } - - return new TagHelperRequiredAttributeDescriptor - { - Name = attributeName, - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = value, - ValueComparison = valueComparison.Value, - }; - } - - private bool EnsureNotAtEnd(ErrorSink errorSink) - { - if (AtEnd) - { - errorSink.OnError( - SourceLocation.Zero, - Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace(_requiredAttributes), - length: 0); - - return false; - } - - return true; - } - - private bool At(char c) - { - return !AtEnd && Current == c; - } - - private void PassOptionalWhitespace() - { - while (!AtEnd && (Current == ' ' || Current == '\t')) - { - _index++; - } - } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorResolver.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorResolver.cs deleted file mode 100644 index 9f8dd9312b..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDescriptorResolver.cs +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Used to resolve s. - /// - public class TagHelperDescriptorResolver : ITagHelperDescriptorResolver - { - private static readonly IReadOnlyDictionary _directiveNames = - new Dictionary - { - { TagHelperDirectiveType.AddTagHelper, SyntaxConstants.CSharp.AddTagHelperKeyword }, - { TagHelperDirectiveType.RemoveTagHelper, SyntaxConstants.CSharp.RemoveTagHelperKeyword }, - { TagHelperDirectiveType.TagHelperPrefix, SyntaxConstants.CSharp.TagHelperPrefixKeyword }, - }; - - private readonly ITagHelperTypeResolver _typeResolver; - private readonly ITagHelperDescriptorFactory _descriptorFactory; - - /// - /// Instantiates a new instance of the class. - /// - /// Indicates whether resolved s should include - /// design time specific information. - public TagHelperDescriptorResolver(bool designTime) - : this(new TagHelperTypeResolver(), new TagHelperDescriptorFactory(designTime)) - { - } - - /// - /// Instantiates a new instance of class with the - /// specified . - /// - /// The . - /// The . - public TagHelperDescriptorResolver( - ITagHelperTypeResolver typeResolver, - ITagHelperDescriptorFactory descriptorFactory) - { - _typeResolver = typeResolver; - _descriptorFactory = descriptorFactory; - } - - /// - public IEnumerable Resolve(TagHelperDescriptorResolutionContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - var resolvedDescriptors = new HashSet(TagHelperDescriptorComparer.Default); - - // tagHelperPrefix directives do not affect which TagHelperDescriptors are added or removed from the final - // list, need to remove them. - var actionableDirectiveDescriptors = context.DirectiveDescriptors.Where( - directive => directive.DirectiveType != TagHelperDirectiveType.TagHelperPrefix); - - foreach (var directiveDescriptor in actionableDirectiveDescriptors) - { - try - { - var lookupInfo = GetLookupInfo(directiveDescriptor, context.ErrorSink); - - // Could not resolve the lookup info. - if (lookupInfo == null) - { - return Enumerable.Empty(); - } - - if (directiveDescriptor.DirectiveType == TagHelperDirectiveType.RemoveTagHelper) - { - resolvedDescriptors.RemoveWhere(descriptor => MatchesLookupInfo(descriptor, lookupInfo)); - } - else if (directiveDescriptor.DirectiveType == TagHelperDirectiveType.AddTagHelper) - { - var descriptors = ResolveDescriptorsInAssembly( - lookupInfo.AssemblyName, - lookupInfo.AssemblyNameLocation, - context.ErrorSink); - - // Only use descriptors that match our lookup info - descriptors = descriptors.Where(descriptor => MatchesLookupInfo(descriptor, lookupInfo)); - - resolvedDescriptors.UnionWith(descriptors); - } - } - catch (Exception ex) - { - string directiveName; - _directiveNames.TryGetValue(directiveDescriptor.DirectiveType, out directiveName); - Debug.Assert(!string.IsNullOrEmpty(directiveName)); - - context.ErrorSink.OnError( - directiveDescriptor.Location, - Resources.FormatTagHelperDescriptorResolver_EncounteredUnexpectedError( - "@" + directiveName, - directiveDescriptor.DirectiveText, - ex.Message), - GetErrorLength(directiveDescriptor.DirectiveText)); - } - } - - var prefixedDescriptors = PrefixDescriptors(context, resolvedDescriptors); - - return prefixedDescriptors; - } - - /// - /// Resolves all s for s from the - /// given . - /// - /// - /// The name of the assembly to resolve s from. - /// - /// The of the directive. - /// Used to record errors found when resolving s - /// within the given . - /// s for s from the given - /// . - // This is meant to be overridden by tooling to enable assembly level caching. - protected virtual IEnumerable ResolveDescriptorsInAssembly( - string assemblyName, - SourceLocation documentLocation, - ErrorSink errorSink) - { - // Resolve valid tag helper types from the assembly. - var tagHelperTypes = _typeResolver.Resolve(assemblyName, documentLocation, errorSink); - - // Convert types to TagHelperDescriptors - var descriptors = tagHelperTypes.SelectMany( - type => _descriptorFactory.CreateDescriptors(assemblyName, type, errorSink)); - - return descriptors; - } - - private static IEnumerable PrefixDescriptors( - TagHelperDescriptorResolutionContext context, - IEnumerable descriptors) - { - var tagHelperPrefix = ResolveTagHelperPrefix(context); - - if (!string.IsNullOrEmpty(tagHelperPrefix)) - { - return descriptors.Select(descriptor => new TagHelperDescriptor(descriptor) - { - Prefix = tagHelperPrefix - }); - } - - return descriptors; - } - - private static string ResolveTagHelperPrefix(TagHelperDescriptorResolutionContext context) - { - var prefixDirectiveDescriptors = context.DirectiveDescriptors.Where( - descriptor => descriptor.DirectiveType == TagHelperDirectiveType.TagHelperPrefix); - - TagHelperDirectiveDescriptor prefixDirective = null; - - foreach (var directive in prefixDirectiveDescriptors) - { - if (prefixDirective == null) - { - prefixDirective = directive; - } - else - { - // For each invalid @tagHelperPrefix we need to create an error. - context.ErrorSink.OnError( - directive.Location, - Resources.FormatTagHelperDescriptorResolver_InvalidTagHelperDirective( - SyntaxConstants.CSharp.TagHelperPrefixKeyword), - GetErrorLength(directive.DirectiveText)); - } - } - - var prefix = prefixDirective?.DirectiveText; - - if (prefix != null && !EnsureValidPrefix(prefix, prefixDirective.Location, context.ErrorSink)) - { - prefix = null; - } - - return prefix; - } - - private static bool EnsureValidPrefix( - string prefix, - SourceLocation directiveLocation, - ErrorSink errorSink) - { - foreach (var character in prefix) - { - // Prefixes are correlated with tag names, tag names cannot have whitespace. - if (char.IsWhiteSpace(character) || - TagHelperDescriptorFactory.InvalidNonWhitespaceNameCharacters.Contains(character)) - { - errorSink.OnError( - directiveLocation, - Resources.FormatTagHelperDescriptorResolver_InvalidTagHelperPrefixValue( - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - character, - prefix), - prefix.Length); - - return false; - } - } - - return true; - } - - private static bool MatchesLookupInfo(TagHelperDescriptor descriptor, LookupInfo lookupInfo) - { - if (!string.Equals(descriptor.AssemblyName, lookupInfo.AssemblyName, StringComparison.Ordinal)) - { - return false; - } - - if (lookupInfo.TypePattern.EndsWith("*", StringComparison.Ordinal)) - { - if (lookupInfo.TypePattern.Length == 1) - { - // TypePattern is "*". - return true; - } - - var lookupTypeName = lookupInfo.TypePattern.Substring(0, lookupInfo.TypePattern.Length - 1); - - return descriptor.TypeName.StartsWith(lookupTypeName, StringComparison.Ordinal); - } - - return string.Equals(descriptor.TypeName, lookupInfo.TypePattern, StringComparison.Ordinal); - } - - private static LookupInfo GetLookupInfo( - TagHelperDirectiveDescriptor directiveDescriptor, - ErrorSink errorSink) - { - var lookupText = directiveDescriptor.DirectiveText; - var lookupStrings = lookupText?.Split(new[] { ',' }); - - // Ensure that we have valid lookupStrings to work with. The valid format is "typeName, assemblyName" - if (lookupStrings == null || - lookupStrings.Any(string.IsNullOrWhiteSpace) || - lookupStrings.Length != 2) - { - errorSink.OnError( - directiveDescriptor.Location, - Resources.FormatTagHelperDescriptorResolver_InvalidTagHelperLookupText(lookupText), - GetErrorLength(lookupText)); - - return null; - } - - var trimmedAssemblyName = lookupStrings[1].Trim(); - - // + 1 is for the comma separator in the lookup text. - var assemblyNameIndex = - lookupStrings[0].Length + 1 + lookupStrings[1].IndexOf(trimmedAssemblyName, StringComparison.Ordinal); - var assemblyNamePrefix = directiveDescriptor.DirectiveText.Substring(0, assemblyNameIndex); - var assemblyNameLocation = SourceLocation.Advance(directiveDescriptor.Location, assemblyNamePrefix); - - return new LookupInfo - { - TypePattern = lookupStrings[0].Trim(), - AssemblyName = trimmedAssemblyName, - AssemblyNameLocation = assemblyNameLocation, - }; - } - - private static int GetErrorLength(string directiveText) - { - var nonNullLength = directiveText == null ? 1 : directiveText.Length; - var normalizeEmptyStringLength = Math.Max(nonNullLength, 1); - - return normalizeEmptyStringLength; - } - - private class LookupInfo - { - public string AssemblyName { get; set; } - - public string TypePattern { get; set; } - - public SourceLocation AssemblyNameLocation { get; set; } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactory.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactory.cs deleted file mode 100644 index d1f3cb51a0..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactory.cs +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Factory for providing s from s and - /// s from s. - /// - public class TagHelperDesignTimeDescriptorFactory - { - private readonly ConcurrentDictionary _documentationProviderCache = - new ConcurrentDictionary(); - - /// - /// Creates a from the given . - /// - /// - /// The to create a from. - /// - /// A that describes design time specific information - /// for the given . - public TagHelperDesignTimeDescriptor CreateDescriptor(Type type) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - var id = XmlDocumentationProvider.GetId(type); - var documentationDescriptor = CreateDocumentationDescriptor(type.GetTypeInfo().Assembly, id); - - var outputElementHintAttribute = type - .GetTypeInfo() - .GetCustomAttributes(inherit: false) - ?.OfType() - .FirstOrDefault(); - var outputElementHint = outputElementHintAttribute?.OutputElement; - - if (documentationDescriptor != null || outputElementHint != null) - { - return new TagHelperDesignTimeDescriptor - { - Summary = documentationDescriptor?.Summary, - Remarks = documentationDescriptor?.Remarks, - OutputElementHint = outputElementHint - }; - } - - return null; - } - - /// - /// Creates a from the given - /// . - /// - /// - /// The to create a from. - /// - /// A that describes design time specific - /// information for the given . - public TagHelperAttributeDesignTimeDescriptor CreateAttributeDescriptor(PropertyInfo propertyInfo) - { - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - - var id = XmlDocumentationProvider.GetId(propertyInfo); - var declaringAssembly = propertyInfo.DeclaringType.GetTypeInfo().Assembly; - var documentationDescriptor = CreateDocumentationDescriptor(declaringAssembly, id); - if (documentationDescriptor != null) - { - return new TagHelperAttributeDesignTimeDescriptor - { - Summary = documentationDescriptor.Summary, - Remarks = documentationDescriptor.Remarks - }; - } - - return null; - } - - /// - /// Retrieves 's location on disk. - /// - /// The assembly. - /// The path to the given . - public virtual string GetAssemblyLocation(Assembly assembly) - { - var assemblyLocation = assembly.Location; - - return assemblyLocation; - } - - private XmlDocumentationProvider GetXmlDocumentationProvider(Assembly assembly) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(assembly); - hashCodeCombiner.Add(CultureInfo.CurrentCulture); - var cacheKey = hashCodeCombiner.CombinedHash; - - var documentationProvider = _documentationProviderCache.GetOrAdd(cacheKey, valueFactory: _ => - { - var assemblyLocation = GetAssemblyLocation(assembly); - - // Couldn't resolve a valid assemblyLocation. - if (string.IsNullOrEmpty(assemblyLocation)) - { - return null; - } - - var xmlDocumentationFile = GetXmlDocumentationFile(assemblyLocation); - - // Only want to process the file if it exists. - if (xmlDocumentationFile != null) - { - return new XmlDocumentationProvider(xmlDocumentationFile.FullName); - } - - return null; - }); - - return documentationProvider; - } - - private DocumentationDescriptor CreateDocumentationDescriptor(Assembly assembly, string id) - { - var documentationProvider = GetXmlDocumentationProvider(assembly); - - if (documentationProvider != null) - { - var summary = documentationProvider.GetSummary(id); - var remarks = documentationProvider.GetRemarks(id); - - if (!string.IsNullOrEmpty(summary) || !string.IsNullOrEmpty(remarks)) - { - return new DocumentationDescriptor - { - Summary = summary, - Remarks = remarks - }; - } - } - - return null; - } - - private static FileInfo GetXmlDocumentationFile(string assemblyLocation) - { - try - { - var assemblyDirectory = Path.GetDirectoryName(assemblyLocation); - var assemblyName = Path.GetFileName(assemblyLocation); - var assemblyXmlDocumentationName = Path.ChangeExtension(assemblyName, ".xml"); - - // Check for a localized XML file for the current culture. - var xmlDocumentationFile = GetLocalizedXmlDocumentationFile( - CultureInfo.CurrentCulture, - assemblyDirectory, - assemblyXmlDocumentationName); - - if (xmlDocumentationFile == null) - { - // Check for a culture-neutral XML file next to the assembly - xmlDocumentationFile = new FileInfo( - Path.Combine(assemblyDirectory, assemblyXmlDocumentationName)); - - if (!xmlDocumentationFile.Exists) - { - xmlDocumentationFile = null; - } - } - - return xmlDocumentationFile; - } - catch (ArgumentException) - { - // Could not resolve XML file. - return null; - } - } - - private static IEnumerable ExpandPaths( - CultureInfo culture, - string assemblyDirectory, - string assemblyXmlDocumentationName) - { - // Following the fall-back process defined by: - // https://msdn.microsoft.com/en-us/library/sb6a8618.aspx#cpconpackagingdeployingresourcesanchor1 - do - { - var cultureName = culture.Name; - var cultureSpecificFileName = - Path.ChangeExtension(assemblyXmlDocumentationName, cultureName + ".xml"); - - // Look for a culture specific XML file next to the assembly. - yield return Path.Combine(assemblyDirectory, cultureSpecificFileName); - - // Look for an XML file with the same name as the assembly in a culture specific directory. - yield return Path.Combine(assemblyDirectory, cultureName, assemblyXmlDocumentationName); - - // Look for a culture specific XML file in a culture specific directory. - yield return Path.Combine(assemblyDirectory, cultureName, cultureSpecificFileName); - - culture = culture.Parent; - } while (culture != null && culture != CultureInfo.InvariantCulture); - } - - private static FileInfo GetLocalizedXmlDocumentationFile( - CultureInfo culture, - string assemblyDirectory, - string assemblyXmlDocumentationName) - { - var localizedXmlPaths = ExpandPaths(culture, assemblyDirectory, assemblyXmlDocumentationName); - var xmlDocumentationFile = localizedXmlPaths - .Select(path => new FileInfo(path)) - .FirstOrDefault(file => file.Exists); - - return xmlDocumentationFile; - } - - private class DocumentationDescriptor - { - public string Summary { get; set; } - public string Remarks { get; set; } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperTypeResolver.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperTypeResolver.cs deleted file mode 100644 index c4c4c0843c..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/TagHelperTypeResolver.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Class that locates valid s within an assembly. - /// - public class TagHelperTypeResolver : ITagHelperTypeResolver - { - private static readonly TypeInfo ITagHelperTypeInfo = typeof(ITagHelper).GetTypeInfo(); - - /// - public IEnumerable Resolve( - string name, - SourceLocation documentLocation, - ErrorSink errorSink) - { - if (errorSink == null) - { - throw new ArgumentNullException(nameof(errorSink)); - } - - if (string.IsNullOrEmpty(name)) - { - var errorLength = name == null ? 1 : Math.Max(name.Length, 1); - errorSink.OnError( - documentLocation, - Resources.TagHelperTypeResolver_TagHelperAssemblyNameCannotBeEmptyOrNull, - errorLength); - - return Type.EmptyTypes; - } - - var assemblyName = new AssemblyName(name); - - IEnumerable libraryTypes; - try - { - libraryTypes = GetExportedTypes(assemblyName); - } - catch (Exception ex) - { - errorSink.OnError( - documentLocation, - Resources.FormatTagHelperTypeResolver_CannotResolveTagHelperAssembly( - assemblyName.Name, - ex.Message), - name.Length); - - return Type.EmptyTypes; - } - - return libraryTypes.Where(IsTagHelper).Select(t => t.AsType()); - } - - /// - /// Returns all exported types from the given - /// - /// The to get s from. - /// - /// An of types exported from the given . - /// - protected virtual IEnumerable GetExportedTypes(AssemblyName assemblyName) - { - var assembly = Assembly.Load(assemblyName); - - return assembly.ExportedTypes.Select(type => type.GetTypeInfo()); - } - - /// - /// Indicates if a should be treated as a tag helper. - /// - /// The to inspect. - /// true if should be treated as a tag helper; - /// false otherwise - protected virtual bool IsTagHelper(TypeInfo typeInfo) - { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } - - return TagHelperConventions.IsTagHelper(typeInfo); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/XmlDocumentationProvider.cs b/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/XmlDocumentationProvider.cs deleted file mode 100644 index 5003b80965..0000000000 --- a/src/Microsoft.AspNetCore.Razor.Runtime/Runtime/TagHelpers/XmlDocumentationProvider.cs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Xml.Linq; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - /// - /// Extracts summary and remarks XML documentation from an XML documentation file. - /// - public class XmlDocumentationProvider - { - private readonly IEnumerable _members; - - /// - /// Instantiates a new instance of the . - /// - /// Path to the XML documentation file to read. - public XmlDocumentationProvider(string xmlFileLocation) - { - // XML file processing is defined by: https://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx - var xmlDocumentation = XDocument.Load(xmlFileLocation); - var documentationRootMembers = xmlDocumentation.Root.Element("members"); - _members = documentationRootMembers.Elements("member"); - } - - /// - /// Retrieves the <summary> documentation for the given . - /// - /// The id to lookup. - /// <summary> documentation for the given . - public string GetSummary(string id) - { - var associatedMemeber = GetMember(id); - var summaryElement = associatedMemeber?.Element("summary"); - - if (summaryElement != null) - { - var summaryValue = GetElementValue(summaryElement); - - return summaryValue; - } - - return null; - } - - /// - /// Retrieves the <remarks> documentation for the given . - /// - /// The id to lookup. - /// <remarks> documentation for the given . - public string GetRemarks(string id) - { - var associatedMemeber = GetMember(id); - var remarksElement = associatedMemeber?.Element("remarks"); - - if (remarksElement != null) - { - var remarksValue = GetElementValue(remarksElement); - - return remarksValue; - } - - return null; - } - - /// - /// Generates the identifier for the given . - /// - /// The to get the identifier for. - /// The identifier for the given . - public static string GetId(Type type) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - return $"T:{type.FullName}"; - } - - /// - /// Generates the identifier for the given . - /// - /// The to get the identifier for. - /// The identifier for the given . - public static string GetId(PropertyInfo propertyInfo) - { - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - - var declaringTypeInfo = propertyInfo.DeclaringType; - return $"P:{declaringTypeInfo.FullName}.{propertyInfo.Name}"; - } - - private XElement GetMember(string id) - { - var associatedMemeber = _members - .FirstOrDefault(element => - string.Equals(element.Attribute("name").Value, id, StringComparison.Ordinal)); - - return associatedMemeber; - } - - private static string GetElementValue(XElement element) - { - var stringBuilder = new StringBuilder(); - var node = element.FirstNode; - - while (node != null) - { - stringBuilder.Append(node.ToString(SaveOptions.DisableFormatting)); - - node = node.NextNode; - } - - return stringBuilder.ToString().Trim(); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/DefaultTagHelperContent.cs b/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/DefaultTagHelperContent.cs index 018d88f81a..b8609a051a 100644 --- a/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/DefaultTagHelperContent.cs +++ b/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/DefaultTagHelperContent.cs @@ -324,12 +324,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers return this; } - - private string DebuggerToString() - { - return GetContent(); - } - + // Overrides Write(string) to find if the content written is empty/whitespace. private class EmptyOrWhiteSpaceWriter : TextWriter { diff --git a/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/HtmlTargetElementAttribute.cs b/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/HtmlTargetElementAttribute.cs index fe8d3c221a..857d6a0e5d 100644 --- a/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/HtmlTargetElementAttribute.cs +++ b/src/Microsoft.AspNetCore.Razor.Runtime/TagHelpers/HtmlTargetElementAttribute.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; namespace Microsoft.AspNetCore.Razor.TagHelpers { @@ -12,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public sealed class HtmlTargetElementAttribute : Attribute { - public const string ElementCatchAllTarget = TagHelperDescriptorProvider.ElementCatchAllTarget; + public const string ElementCatchAllTarget = "*"; /// /// Instantiates a new instance of the class that targets all HTML diff --git a/src/Microsoft.AspNetCore.Razor/CSharpRazorCodeLanguage.cs b/src/Microsoft.AspNetCore.Razor/CSharpRazorCodeLanguage.cs deleted file mode 100644 index 3d128a6f8f..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CSharpRazorCodeLanguage.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Parser; - -namespace Microsoft.AspNetCore.Razor -{ - /// - /// Defines the C# Code Language for Razor - /// - public class CSharpRazorCodeLanguage : RazorCodeLanguage - { - private const string CSharpLanguageName = "csharp"; - - /// - /// Returns the name of the language: "csharp" - /// - public override string LanguageName - { - get { return CSharpLanguageName; } - } - - /// - /// Constructs a new instance of the code parser for this language - /// - public override ParserBase CreateCodeParser() - { - return new CSharpCodeParser(); - } - - /// - /// Constructs a new instance of the chunk generator for this language with the specified settings - /// - public override RazorChunkGenerator CreateChunkGenerator( - string className, - string rootNamespaceName, - string sourceFileName, - RazorEngineHost host) - { - return new RazorChunkGenerator(className, rootNamespaceName, sourceFileName, host); - } - - public override CodeGenerator CreateCodeGenerator(CodeGeneratorContext chunkGeneratorContext) - { - return new CSharpCodeGenerator(chunkGeneratorContext); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/AddTagHelperChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/AddTagHelperChunk.cs deleted file mode 100644 index 86f9bbed8f..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/AddTagHelperChunk.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - /// - /// A used to look up s. - /// - public class AddTagHelperChunk : Chunk - { - /// - /// Text used to look up s. - /// - public string LookupText { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Chunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Chunk.cs deleted file mode 100644 index 8d6840328b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Chunk.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class Chunk - { - public SourceLocation Start { get; set; } - public SyntaxTreeNode Association { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/ChunkTree.cs b/src/Microsoft.AspNetCore.Razor/Chunks/ChunkTree.cs deleted file mode 100644 index d7aa853afc..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/ChunkTree.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ChunkTree : ParentChunk - { - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/ChunkTreeBuilder.cs b/src/Microsoft.AspNetCore.Razor/Chunks/ChunkTreeBuilder.cs deleted file mode 100644 index bdcbe142a4..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/ChunkTreeBuilder.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ChunkTreeBuilder - { - private readonly Stack _parentStack; - private Chunk _lastChunk; - - public ChunkTreeBuilder() - { - Root = new ChunkTree(); - _parentStack = new Stack(); - _parentStack.Push(Root); - } - - public ParentChunk Current => _parentStack.Peek(); - - public ChunkTree Root { get; } - - public void AddChunk(Chunk chunk, SyntaxTreeNode association, bool topLevel = false) - { - _lastChunk = chunk; - - chunk.Start = association.Start; - chunk.Association = association; - - // If we're not in the middle of a parent chunk - if (topLevel) - { - Root.Children.Add(chunk); - } - else - { - Current.Children.Add(chunk); - } - } - - public void AddTagHelperPrefixDirectiveChunk(string prefix, SyntaxTreeNode association) - { - AddChunk( - new TagHelperPrefixDirectiveChunk - { - Prefix = prefix - }, - association, - topLevel: true); - } - - public void AddAddTagHelperChunk(string lookupText, SyntaxTreeNode association) - { - AddChunk(new AddTagHelperChunk - { - LookupText = lookupText - }, association, topLevel: true); - } - - public void AddRemoveTagHelperChunk(string lookupText, SyntaxTreeNode association) - { - AddChunk(new RemoveTagHelperChunk - { - LookupText = lookupText - }, association, topLevel: true); - } - - public void AddLiteralChunk(string literal, SyntaxTreeNode association) - { - ParentLiteralChunk parentLiteralChunk; - - // We try to join literal chunks where possible, so that we have fewer 'writes' in the generated code. - // - // Possible cases here: - // - We just added a LiteralChunk and we need to add another - so merge them into ParentLiteralChunk. - // - We have a ParentLiteralChunk - merge the new chunk into it. - // - We just added something - just add the LiteralChunk like normal. - if (_lastChunk is LiteralChunk) - { - parentLiteralChunk = new ParentLiteralChunk() - { - Start = _lastChunk.Start, - }; - - parentLiteralChunk.Children.Add(_lastChunk); - parentLiteralChunk.Children.Add(new LiteralChunk - { - Association = association, - Start = association.Start, - Text = literal, - }); - - Debug.Assert(Current.Children[Current.Children.Count - 1] == _lastChunk); - Current.Children.RemoveAt(Current.Children.Count - 1); - Current.Children.Add(parentLiteralChunk); - _lastChunk = parentLiteralChunk; - } - else if ((parentLiteralChunk = _lastChunk as ParentLiteralChunk) != null) - { - parentLiteralChunk.Children.Add(new LiteralChunk - { - Association = association, - Start = association.Start, - Text = literal, - }); - _lastChunk = parentLiteralChunk; - } - else - { - AddChunk(new LiteralChunk - { - Text = literal, - }, association); - } - } - - public void AddExpressionChunk(string expression, SyntaxTreeNode association) - { - AddChunk(new ExpressionChunk - { - Code = expression - }, association); - } - - public void AddStatementChunk(string code, SyntaxTreeNode association) - { - AddChunk(new StatementChunk - { - Code = code, - }, association); - } - - public void AddUsingChunk(string usingNamespace, SyntaxTreeNode association) - { - AddChunk(new UsingChunk - { - Namespace = usingNamespace, - }, association, topLevel: true); - } - - public void AddTypeMemberChunk(string code, SyntaxTreeNode association) - { - AddChunk(new TypeMemberChunk - { - Code = code, - }, association, topLevel: true); - } - - public void AddLiteralCodeAttributeChunk(string code, SyntaxTreeNode association) - { - AddChunk(new LiteralCodeAttributeChunk - { - Code = code, - }, association); - } - - public void AddSetBaseTypeChunk(string typeName, SyntaxTreeNode association) - { - AddChunk(new SetBaseTypeChunk - { - TypeName = typeName.Trim() - }, association, topLevel: true); - } - - public T StartParentChunk(SyntaxTreeNode association) where T : ParentChunk, new() - { - return StartParentChunk(association, topLevel: false); - } - - public T StartParentChunk(SyntaxTreeNode association, bool topLevel) where T : ParentChunk, new() - { - var parentChunk = new T(); - - return StartParentChunk(parentChunk, association, topLevel); - } - - public T StartParentChunk(T parentChunk, SyntaxTreeNode association, bool topLevel) where T : ParentChunk - { - AddChunk(parentChunk, association, topLevel); - - _parentStack.Push(parentChunk); - - return parentChunk; - } - - public void EndParentChunk() - { - _lastChunk = _parentStack.Pop(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/CodeAttributeChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/CodeAttributeChunk.cs deleted file mode 100644 index ba31b234a3..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/CodeAttributeChunk.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class CodeAttributeChunk : ParentChunk - { - public string Attribute { get; set; } - public LocationTagged Prefix { get; set; } - public LocationTagged Suffix { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/DynamicCodeAttributeChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/DynamicCodeAttributeChunk.cs deleted file mode 100644 index 97833d746a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/DynamicCodeAttributeChunk.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class DynamicCodeAttributeChunk : ParentChunk - { - public LocationTagged Prefix { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/ExpressionBlockChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/ExpressionBlockChunk.cs deleted file mode 100644 index 2ef28150b5..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/ExpressionBlockChunk.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ExpressionBlockChunk : ParentChunk - { - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/ExpressionChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/ExpressionChunk.cs deleted file mode 100644 index 93cb225ac7..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/ExpressionChunk.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ExpressionChunk : Chunk - { - public string Code { get; set; } - - public override string ToString() - { - return Start + " = " + Code; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddImportChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddImportChunkGenerator.cs deleted file mode 100644 index a9e028d562..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddImportChunkGenerator.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class AddImportChunkGenerator : SpanChunkGenerator - { - public AddImportChunkGenerator(string ns) - { - Namespace = ns; - } - - public string Namespace { get; } - - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - var ns = Namespace; - - if (!string.IsNullOrEmpty(ns) && char.IsWhiteSpace(ns[0])) - { - ns = ns.Substring(1); - } - - context.ChunkTreeBuilder.AddUsingChunk(ns, target); - } - - public override string ToString() - { - return "Import:" + Namespace + ";"; - } - - public override bool Equals(object obj) - { - var other = obj as AddImportChunkGenerator; - return other != null && - string.Equals(Namespace, other.Namespace, StringComparison.Ordinal); - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties. - return Namespace == null ? 0 : StringComparer.Ordinal.GetHashCode(Namespace); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddTagHelperChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddTagHelperChunkGenerator.cs deleted file mode 100644 index 17bac2b7b5..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AddTagHelperChunkGenerator.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - /// - /// A responsible for generating s. - /// - public class AddTagHelperChunkGenerator : SpanChunkGenerator - { - /// - /// Initializes a new instance of . - /// - /// - /// Text used to look up s that should be added. - /// - public AddTagHelperChunkGenerator(string lookupText) - { - LookupText = lookupText; - } - - /// - /// Gets the text used to look up s that should be added. - /// - public string LookupText { get; } - - /// - /// Generates s. - /// - /// - /// The responsible for this . - /// - /// A instance that contains information about - /// the current chunk generation process. - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddAddTagHelperChunk(LookupText, target); - } - - /// - public override bool Equals(object obj) - { - var other = obj as AddTagHelperChunkGenerator; - return base.Equals(other) && - string.Equals(LookupText, other.LookupText, StringComparison.Ordinal); - } - - /// - public override int GetHashCode() - { - var combiner = HashCodeCombiner.Start(); - combiner.Add(base.GetHashCode()); - combiner.Add(LookupText, StringComparer.Ordinal); - - return combiner.CombinedHash; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AttributeBlockChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AttributeBlockChunkGenerator.cs deleted file mode 100644 index 4971a66406..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/AttributeBlockChunkGenerator.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class AttributeBlockChunkGenerator : ParentChunkGenerator - { - public AttributeBlockChunkGenerator(string name, LocationTagged prefix, LocationTagged suffix) - { - Name = name; - Prefix = prefix; - Suffix = suffix; - } - - public string Name { get; } - - public LocationTagged Prefix { get; } - - public LocationTagged Suffix { get; } - - public override void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - var chunk = context.ChunkTreeBuilder.StartParentChunk(target); - - chunk.Attribute = Name; - chunk.Prefix = Prefix; - chunk.Suffix = Suffix; - } - - public override void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.EndParentChunk(); - } - - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "Attr:{0},{1:F},{2:F}", Name, Prefix, Suffix); - } - - public override bool Equals(object obj) - { - var other = obj as AttributeBlockChunkGenerator; - return other != null && - string.Equals(other.Name, Name, StringComparison.Ordinal) && - Equals(other.Prefix, Prefix) && - Equals(other.Suffix, Suffix); - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(Name, StringComparer.Ordinal); - hashCodeCombiner.Add(Prefix); - hashCodeCombiner.Add(Suffix); - - return hashCodeCombiner; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ChunkGeneratorContext.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ChunkGeneratorContext.cs deleted file mode 100644 index 2adf230986..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ChunkGeneratorContext.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class ChunkGeneratorContext - { - protected ChunkGeneratorContext(ChunkGeneratorContext context) - : this( - context.Host, - context.ClassName, - context.RootNamespace, - context.SourceFile, - // True because we're pulling from the provided context's source file. - shouldGenerateLinePragmas: true) - { - ChunkTreeBuilder = context.ChunkTreeBuilder; - } - - public ChunkGeneratorContext( - RazorEngineHost host, - string className, - string rootNamespace, - string sourceFile, - bool shouldGenerateLinePragmas) - { - ChunkTreeBuilder = new ChunkTreeBuilder(); - Host = host; - SourceFile = shouldGenerateLinePragmas ? sourceFile : null; - RootNamespace = rootNamespace; - ClassName = className; - } - - public string SourceFile { get; internal set; } - - public string RootNamespace { get; } - - public string ClassName { get; } - - public RazorEngineHost Host { get; } - - public ChunkTreeBuilder ChunkTreeBuilder { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/DynamicAttributeBlockChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/DynamicAttributeBlockChunkGenerator.cs deleted file mode 100644 index 6056c96674..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/DynamicAttributeBlockChunkGenerator.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Globalization; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class DynamicAttributeBlockChunkGenerator : ParentChunkGenerator - { - public DynamicAttributeBlockChunkGenerator(LocationTagged prefix, int offset, int line, int col) - : this(prefix, new SourceLocation(offset, line, col)) - { - } - - public DynamicAttributeBlockChunkGenerator(LocationTagged prefix, SourceLocation valueStart) - { - Prefix = prefix; - ValueStart = valueStart; - } - - public LocationTagged Prefix { get; } - - public SourceLocation ValueStart { get; } - - public override void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - var chunk = context.ChunkTreeBuilder.StartParentChunk(target); - chunk.Start = ValueStart; - chunk.Prefix = Prefix; - } - - public override void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.EndParentChunk(); - } - - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "DynAttr:{0:F}", Prefix); - } - - public override bool Equals(object obj) - { - var other = obj as DynamicAttributeBlockChunkGenerator; - return other != null && - Equals(other.Prefix, Prefix); - } - - public override int GetHashCode() - { - return Prefix == null ? 0 : Prefix.GetHashCode(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ExpressionChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ExpressionChunkGenerator.cs deleted file mode 100644 index 809fcdb10a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ExpressionChunkGenerator.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class ExpressionChunkGenerator : ISpanChunkGenerator, IParentChunkGenerator - { - private static readonly int TypeHashCode = typeof(ExpressionChunkGenerator).GetHashCode(); - - public void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.StartParentChunk(target); - } - - public void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddExpressionChunk(target.Content, target); - } - - public void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.EndParentChunk(); - } - - public override string ToString() - { - return "Expr"; - } - - public override bool Equals(object obj) - { - return obj != null && - GetType() == obj.GetType(); - } - - public override int GetHashCode() - { - return TypeHashCode; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/IParentChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/IParentChunkGenerator.cs deleted file mode 100644 index f5ae9c9aa8..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/IParentChunkGenerator.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public interface IParentChunkGenerator - { - void GenerateStartParentChunk(Block target, ChunkGeneratorContext context); - void GenerateEndParentChunk(Block target, ChunkGeneratorContext context); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ISpanChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ISpanChunkGenerator.cs deleted file mode 100644 index ab7dcde8d3..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ISpanChunkGenerator.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public interface ISpanChunkGenerator - { - void GenerateChunk(Span target, ChunkGeneratorContext context); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/LiteralAttributeChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/LiteralAttributeChunkGenerator.cs deleted file mode 100644 index a9a03fff12..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/LiteralAttributeChunkGenerator.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Globalization; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class LiteralAttributeChunkGenerator : SpanChunkGenerator - { - public LiteralAttributeChunkGenerator( - LocationTagged prefix, - LocationTagged valueGenerator) - { - Prefix = prefix; - ValueGenerator = valueGenerator; - } - - public LiteralAttributeChunkGenerator(LocationTagged prefix, LocationTagged value) - { - Prefix = prefix; - Value = value; - } - - public LocationTagged Prefix { get; } - - public LocationTagged Value { get; } - - public LocationTagged ValueGenerator { get; } - - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - var chunk = context.ChunkTreeBuilder.StartParentChunk(target); - chunk.Prefix = Prefix; - chunk.Value = Value; - - if (ValueGenerator != null) - { - chunk.ValueLocation = ValueGenerator.Location; - - ValueGenerator.Value.GenerateChunk(target, context); - - chunk.ValueLocation = ValueGenerator.Location; - } - - context.ChunkTreeBuilder.EndParentChunk(); - } - - public override string ToString() - { - if (ValueGenerator == null) - { - return string.Format(CultureInfo.CurrentCulture, "LitAttr:{0:F},{1:F}", Prefix, Value); - } - else - { - return string.Format(CultureInfo.CurrentCulture, "LitAttr:{0:F},", Prefix, ValueGenerator); - } - } - - public override bool Equals(object obj) - { - var other = obj as LiteralAttributeChunkGenerator; - return other != null && - Equals(other.Prefix, Prefix) && - Equals(other.Value, Value) && - Equals(other.ValueGenerator, ValueGenerator); - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - - hashCodeCombiner.Add(Prefix); - hashCodeCombiner.Add(Value); - hashCodeCombiner.Add(ValueGenerator); - - return hashCodeCombiner; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/MarkupChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/MarkupChunkGenerator.cs deleted file mode 100644 index 48d897dd32..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/MarkupChunkGenerator.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class MarkupChunkGenerator : SpanChunkGenerator - { - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddLiteralChunk(target.Content, target); - } - - public override string ToString() - { - return "Markup"; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ParentChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ParentChunkGenerator.cs deleted file mode 100644 index e05ff9d1a6..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/ParentChunkGenerator.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public abstract class ParentChunkGenerator : IParentChunkGenerator - { - private static readonly int TypeHashCode = typeof(ParentChunkGenerator).GetHashCode(); - - public static readonly IParentChunkGenerator Null = new NullParentChunkGenerator(); - - public virtual void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - } - - public virtual void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - } - - public override bool Equals(object obj) - { - return obj != null && - GetType() == obj.GetType(); - } - - public override int GetHashCode() - { - return TypeHashCode; - } - - private class NullParentChunkGenerator : IParentChunkGenerator - { - public void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - } - - public void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - } - - public override string ToString() - { - return "None"; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorChunkGenerator.cs deleted file mode 100644 index eeff2a4307..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorChunkGenerator.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class RazorChunkGenerator : ParserVisitor - { - private ChunkGeneratorContext _context; - - public RazorChunkGenerator( - string className, - string rootNamespaceName, - string sourceFileName, - RazorEngineHost host) - { - if (rootNamespaceName == null) - { - throw new ArgumentNullException(nameof(rootNamespaceName)); - } - - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } - - if (string.IsNullOrEmpty(className)) - { - throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(className)); - } - - ClassName = className; - RootNamespaceName = rootNamespaceName; - SourceFileName = sourceFileName; - GenerateLinePragmas = !string.IsNullOrEmpty(SourceFileName); - Host = host; - } - - // Data pulled from constructor - public string ClassName { get; private set; } - public string RootNamespaceName { get; private set; } - public string SourceFileName { get; private set; } - public RazorEngineHost Host { get; private set; } - - // Generation settings - public bool GenerateLinePragmas { get; set; } - public bool DesignTimeMode { get; set; } - - public ChunkGeneratorContext Context - { - get - { - EnsureContextInitialized(); - return _context; - } - } - - public override void VisitStartBlock(Block block) - { - block.ChunkGenerator.GenerateStartParentChunk(block, Context); - } - - public override void VisitEndBlock(Block block) - { - block.ChunkGenerator.GenerateEndParentChunk(block, Context); - } - - public override void VisitSpan(Span span) - { - span.ChunkGenerator.GenerateChunk(span, Context); - } - - private void EnsureContextInitialized() - { - if (_context == null) - { - _context = new ChunkGeneratorContext(Host, - ClassName, - RootNamespaceName, - SourceFileName, - GenerateLinePragmas); - Initialize(_context); - } - } - - protected virtual void Initialize(ChunkGeneratorContext context) - { - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorCommentChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorCommentChunkGenerator.cs deleted file mode 100644 index 4b12955a11..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RazorCommentChunkGenerator.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class RazorCommentChunkGenerator : ParentChunkGenerator - { - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RemoveTagHelperChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RemoveTagHelperChunkGenerator.cs deleted file mode 100644 index 1c57cc6cb0..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/RemoveTagHelperChunkGenerator.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - /// - /// A responsible for generating s. - /// - public class RemoveTagHelperChunkGenerator : SpanChunkGenerator - { - /// - /// Initializes a new instance of . - /// - /// - /// Text used to look up s that should be removed. - /// - public RemoveTagHelperChunkGenerator(string lookupText) - { - LookupText = lookupText; - } - - /// - /// Text used to look up s that should be removed. - /// - public string LookupText { get; } - - /// - /// Generates s. - /// - /// - /// The responsible for this . - /// - /// A instance that contains information about - /// the current chunk generation process. - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddRemoveTagHelperChunk(LookupText, target); - } - - /// - public override bool Equals(object obj) - { - var other = obj as RemoveTagHelperChunkGenerator; - return base.Equals(other) && - string.Equals(LookupText, other.LookupText, StringComparison.Ordinal); - } - - /// - public override int GetHashCode() - { - var combiner = HashCodeCombiner.Start(); - combiner.Add(base.GetHashCode()); - combiner.Add(LookupText, StringComparer.Ordinal); - - return combiner.CombinedHash; - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SectionChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SectionChunkGenerator.cs deleted file mode 100644 index 917ba33b1e..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SectionChunkGenerator.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class SectionChunkGenerator : ParentChunkGenerator - { - public SectionChunkGenerator(string sectionName) - { - SectionName = sectionName; - } - - public string SectionName { get; } - - public override void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - var chunk = context.ChunkTreeBuilder.StartParentChunk(target); - - chunk.Name = SectionName; - } - - public override void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.EndParentChunk(); - } - - public override bool Equals(object obj) - { - var other = obj as SectionChunkGenerator; - return base.Equals(other) && - string.Equals(SectionName, other.SectionName, StringComparison.Ordinal); - } - - public override int GetHashCode() - { - return SectionName == null ? 0 : StringComparer.Ordinal.GetHashCode(SectionName); - } - - public override string ToString() - { - return "Section:" + SectionName; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SetBaseTypeChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SetBaseTypeChunkGenerator.cs deleted file mode 100644 index b0d0648ab8..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SetBaseTypeChunkGenerator.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class SetBaseTypeChunkGenerator : SpanChunkGenerator - { - public SetBaseTypeChunkGenerator(string baseType) - { - BaseType = baseType; - } - - public string BaseType { get; } - - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddSetBaseTypeChunk(BaseType, target); - } - - public override string ToString() - { - return "Base:" + BaseType; - } - - public override bool Equals(object obj) - { - var other = obj as SetBaseTypeChunkGenerator; - return other != null && - string.Equals(BaseType, other.BaseType, StringComparison.Ordinal); - } - - public override int GetHashCode() - { - return BaseType.GetHashCode(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SpanChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SpanChunkGenerator.cs deleted file mode 100644 index 75870a8104..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/SpanChunkGenerator.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public abstract class SpanChunkGenerator : ISpanChunkGenerator - { - private static readonly int TypeHashCode = typeof(SpanChunkGenerator).GetHashCode(); - - public static readonly ISpanChunkGenerator Null = new NullSpanChunkGenerator(); - - public virtual void GenerateChunk(Span target, ChunkGeneratorContext context) - { - } - - public override bool Equals(object obj) - { - return obj != null && - GetType() == obj.GetType(); - } - - public override int GetHashCode() - { - return TypeHashCode; - } - - private class NullSpanChunkGenerator : ISpanChunkGenerator - { - public void GenerateChunk(Span target, ChunkGeneratorContext context) - { - } - - public override string ToString() - { - return "None"; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/StatementChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/StatementChunkGenerator.cs deleted file mode 100644 index fe17f5d566..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/StatementChunkGenerator.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class StatementChunkGenerator : SpanChunkGenerator - { - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddStatementChunk(target.Content, target); - } - - public override string ToString() - { - return "Stmt"; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperChunkGenerator.cs deleted file mode 100644 index 87b8d1789d..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperChunkGenerator.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - /// - /// A that is responsible for generating valid s. - /// - public class TagHelperChunkGenerator : ParentChunkGenerator - { - private IEnumerable _tagHelperDescriptors; - - /// - /// Instantiates a new . - /// - /// - /// s associated with the current HTML tag. - /// - public TagHelperChunkGenerator(IEnumerable tagHelperDescriptors) - { - _tagHelperDescriptors = tagHelperDescriptors; - } - - /// - /// Starts the generation of a . - /// - /// - /// The responsible for this . - /// - /// A instance that contains information about - /// the current chunk generation process. - public override void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - var tagHelperBlock = target as TagHelperBlock; - - Debug.Assert( - tagHelperBlock != null, - $"A {nameof(TagHelperChunkGenerator)} must only be used with {nameof(TagHelperBlock)}s."); - - var attributes = new List(); - - // We need to create a chunk generator to create chunks for each of the attributes. - var chunkGenerator = context.Host.CreateChunkGenerator( - context.ClassName, - context.RootNamespace, - context.SourceFile); - - foreach (var attribute in tagHelperBlock.Attributes) - { - ParentChunk attributeChunkValue = null; - - if (attribute.Value != null) - { - // Populates the chunk tree with chunks associated with attributes - attribute.Value.Accept(chunkGenerator); - - var chunks = chunkGenerator.Context.ChunkTreeBuilder.Root.Children; - var first = chunks.FirstOrDefault(); - - attributeChunkValue = new ParentChunk - { - Association = first?.Association, - Children = chunks, - Start = first == null ? SourceLocation.Zero : first.Start - }; - } - - var attributeChunk = new TagHelperAttributeTracker( - attribute.Name, - attributeChunkValue, - attribute.ValueStyle); - - attributes.Add(attributeChunk); - - // Reset the chunk tree builder so we can build a new one for the next attribute - chunkGenerator.Context.ChunkTreeBuilder = new ChunkTreeBuilder(); - } - - var unprefixedTagName = tagHelperBlock.TagName.Substring(_tagHelperDescriptors.First().Prefix.Length); - - context.ChunkTreeBuilder.StartParentChunk( - new TagHelperChunk( - unprefixedTagName, - tagHelperBlock.TagMode, - attributes, - _tagHelperDescriptors), - target, - topLevel: false); - } - - /// - /// Ends the generation of a capturing all previously visited children - /// since the method was called. - /// - /// - /// The responsible for this . - /// - /// A instance that contains information about - /// the current chunk generation process. - public override void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.EndParentChunk(); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperPrefixDirectiveChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperPrefixDirectiveChunkGenerator.cs deleted file mode 100644 index d9fc198f6d..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TagHelperPrefixDirectiveChunkGenerator.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - /// - /// A responsible for generating - /// s. - /// - public class TagHelperPrefixDirectiveChunkGenerator : SpanChunkGenerator - { - /// - /// Initializes a new instance of . - /// - /// - /// Text used as a required prefix when matching HTML. - /// - public TagHelperPrefixDirectiveChunkGenerator(string prefix) - { - Prefix = prefix; - } - - /// - /// Text used as a required prefix when matching HTML. - /// - public string Prefix { get; } - - /// - /// Generates s. - /// - /// - /// The responsible for this . - /// - /// A instance that contains information about - /// the current chunk generation process. - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddTagHelperPrefixDirectiveChunk(Prefix, target); - } - - /// - public override bool Equals(object obj) - { - var other = obj as TagHelperPrefixDirectiveChunkGenerator; - return base.Equals(other) && - string.Equals(Prefix, other.Prefix, StringComparison.Ordinal); - } - - /// - public override int GetHashCode() - { - var combiner = HashCodeCombiner.Start(); - combiner.Add(base.GetHashCode()); - combiner.Add(Prefix, StringComparer.Ordinal); - - return combiner.CombinedHash; - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TemplateBlockChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TemplateBlockChunkGenerator.cs deleted file mode 100644 index d52e7c0d44..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TemplateBlockChunkGenerator.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class TemplateBlockChunkGenerator : ParentChunkGenerator - { - public override void GenerateStartParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.StartParentChunk(target); - } - - public override void GenerateEndParentChunk(Block target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.EndParentChunk(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TypeMemberChunkGenerator.cs b/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TypeMemberChunkGenerator.cs deleted file mode 100644 index 2a2cd1359e..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/Generators/TypeMemberChunkGenerator.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class TypeMemberChunkGenerator : SpanChunkGenerator - { - public override void GenerateChunk(Span target, ChunkGeneratorContext context) - { - context.ChunkTreeBuilder.AddTypeMemberChunk(target.Content, target); - } - - public override string ToString() - { - return "TypeMember"; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/LiteralChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/LiteralChunk.cs deleted file mode 100644 index 769de11adc..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/LiteralChunk.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class LiteralChunk : Chunk - { - public string Text { get; set; } - - public override string ToString() - { - return Start + " = " + Text; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/LiteralCodeAttributeChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/LiteralCodeAttributeChunk.cs deleted file mode 100644 index 4915745a88..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/LiteralCodeAttributeChunk.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class LiteralCodeAttributeChunk : ParentChunk - { - public string Code { get; set; } - public LocationTagged Prefix { get; set; } - public LocationTagged Value { get; set; } - public SourceLocation ValueLocation { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/ParentChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/ParentChunk.cs deleted file mode 100644 index 6230a62482..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/ParentChunk.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ParentChunk : Chunk - { - public ParentChunk() - { - Children = new List(); - } - - public IList Children { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/ParentLiteralChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/ParentLiteralChunk.cs deleted file mode 100644 index fe9fabcf3d..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/ParentLiteralChunk.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ParentLiteralChunk : ParentChunk - { - public string GetText() - { - var builder = new StringBuilder(); - for (var i = 0; i < Children.Count; i++) - { - builder.Append(((LiteralChunk)Children[i]).Text); - } - - return builder.ToString(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/PreallocatedTagHelperAttributeChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/PreallocatedTagHelperAttributeChunk.cs deleted file mode 100644 index 751680e6b8..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/PreallocatedTagHelperAttributeChunk.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - /// - /// A that represents a pre-allocated tag helper attribute. - /// - public class PreallocatedTagHelperAttributeChunk : Chunk - { - /// - /// The variable holding the pre-allocated attribute. - /// - public string AttributeVariableAccessor { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/RemoveTagHelperChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/RemoveTagHelperChunk.cs deleted file mode 100644 index f924f9c2ab..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/RemoveTagHelperChunk.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - /// - /// A used to look up s that should be ignored - /// within the Razor page. - /// - public class RemoveTagHelperChunk : Chunk - { - /// - /// Text used to look up s that should be ignored within the Razor - /// page. - /// - public string LookupText { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/SectionChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/SectionChunk.cs deleted file mode 100644 index c266bdd940..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/SectionChunk.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class SectionChunk : ParentChunk - { - public string Name { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/SetBaseTypeChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/SetBaseTypeChunk.cs deleted file mode 100644 index c33e75e228..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/SetBaseTypeChunk.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class SetBaseTypeChunk : Chunk - { - public string TypeName { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/StatementChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/StatementChunk.cs deleted file mode 100644 index 0f1a47f704..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/StatementChunk.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class StatementChunk : Chunk - { - public string Code { get; set; } - - public override string ToString() - { - return Start + " = " + Code; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperAttributeChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperAttributeChunk.cs deleted file mode 100644 index a19d61f252..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperAttributeChunk.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public struct TagHelperAttributeTracker - { - public TagHelperAttributeTracker(string name, Chunk value, HtmlAttributeValueStyle valueStyle) - { - Name = name; - Value = value; - ValueStyle = valueStyle; - } - - public string Name { get; } - - public Chunk Value { get; } - - public HtmlAttributeValueStyle ValueStyle { get; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperChunk.cs deleted file mode 100644 index 1cb4c69033..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperChunk.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - /// - /// A that represents a special HTML tag. - /// - public class TagHelperChunk : ParentChunk - { - /// - /// Instantiates a new . - /// - /// The tag name associated with the tag helpers HTML element. - /// HTML syntax of the element in the Razor source. - /// The attributes associated with the tag helpers HTML element. - /// - /// The s associated with this tag helpers HTML element. - /// - public TagHelperChunk( - string tagName, - TagMode tagMode, - IList attributes, - IEnumerable descriptors) - { - TagName = tagName; - TagMode = tagMode; - Attributes = attributes; - Descriptors = descriptors; - } - - /// - /// The HTML attributes. - /// - public IList Attributes { get; set; } - - /// - /// The s that are associated with the tag helpers HTML element. - /// - public IEnumerable Descriptors { get; set; } - - /// - /// The HTML tag name. - /// - public string TagName { get; set; } - - /// - /// Gets the HTML syntax of the element in the Razor source. - /// - public TagMode TagMode { get; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperPrefixDirectiveChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperPrefixDirectiveChunk.cs deleted file mode 100644 index 43e8230582..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/TagHelperPrefixDirectiveChunk.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - /// - /// A for the @tagHelperPrefix directive. - /// - public class TagHelperPrefixDirectiveChunk : Chunk - { - /// - /// Text used as a required prefix when matching HTML start and end tags in the Razor source to available - /// tag helpers. - /// - public string Prefix { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/TemplateChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/TemplateChunk.cs deleted file mode 100644 index 68a8336964..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/TemplateChunk.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class TemplateChunk : ParentChunk - { - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/TypeMemberChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/TypeMemberChunk.cs deleted file mode 100644 index b89e5ea8b1..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/TypeMemberChunk.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class TypeMemberChunk : Chunk - { - public string Code { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Chunks/UsingChunk.cs b/src/Microsoft.AspNetCore.Razor/Chunks/UsingChunk.cs deleted file mode 100644 index 9a95091c7a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Chunks/UsingChunk.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class UsingChunk : Chunk - { - public string Namespace { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeGenerator.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeGenerator.cs deleted file mode 100644 index 17141eb07e..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeGenerator.cs +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpCodeGenerator : CodeGenerator - { - // See http://msdn.microsoft.com/en-us/library/system.codedom.codechecksumpragma.checksumalgorithmid.aspx - private const string Sha1AlgorithmId = "{ff1816ec-aa5e-4d10-87f7-6f4963833460}"; - private const int DisableAsyncWarning = 1998; - - public CSharpCodeGenerator(CodeGeneratorContext context) - : base(context) - { - } - - protected ChunkTree Tree { get { return Context.ChunkTreeBuilder.Root; } } - public RazorEngineHost Host { get { return Context.Host; } } - - /// - /// Protected for testing. - /// - /// A new instance of . - protected virtual CSharpCodeWriter CreateCodeWriter() - { - return new CSharpCodeWriter(); - } - - public override CodeGeneratorResult Generate() - { - var writer = CreateCodeWriter(); - - if (!Host.DesignTimeMode && !string.IsNullOrEmpty(Context.Checksum)) - { - writer.Write("#pragma checksum \"") - .Write(Context.SourceFile) - .Write("\" \"") - .Write(Sha1AlgorithmId) - .Write("\" \"") - .Write(Context.Checksum) - .WriteLine("\""); - } - - using (writer.BuildNamespace(Context.RootNamespace)) - { - // Write out using directives - AddImports(Tree, writer, Host.NamespaceImports); - // Separate the usings and the class - writer.WriteLine(); - - using (BuildClassDeclaration(writer)) - { - if (Host.DesignTimeMode) - { - writer.WriteLine("private static object @__o;"); - } - - var csharpCodeVisitor = CreateCSharpCodeVisitor(writer, Context); - - new CSharpTypeMemberVisitor(csharpCodeVisitor, writer, Context).Accept(Tree.Children); - CreateCSharpDesignTimeCodeVisitor(csharpCodeVisitor, writer, Context) - .AcceptTree(Tree); - new CSharpTagHelperFieldDeclarationVisitor(writer, Context).Accept(Tree.Children); - - BuildConstructor(writer); - - // Add space in-between constructor and method body - writer.WriteLine(); - - using (writer.BuildDisableWarningScope(DisableAsyncWarning)) - { - using (writer.BuildMethodDeclaration("public override async", "Task", Host.GeneratedClassContext.ExecuteMethodName)) - { - new CSharpTagHelperPropertyInitializationVisitor(writer, Context).Accept(Tree.Children); - csharpCodeVisitor.Accept(Tree.Children); - } - } - - BuildAfterExecuteContent(writer, Tree.Children); - } - } - - return new CodeGeneratorResult(writer.GenerateCode(), writer.LineMappingManager.Mappings); - } - - /// - /// Provides an entry point to append code (after execute content) to a generated Razor class. - /// - /// The to receive the additional content. - /// The list of s for the generated program. - protected virtual void BuildAfterExecuteContent(CSharpCodeWriter writer, IList chunks) - { - } - - protected virtual CSharpCodeVisitor CreateCSharpCodeVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - return new CSharpCodeVisitor(writer, context); - } - - protected virtual CSharpDesignTimeCodeVisitor CreateCSharpDesignTimeCodeVisitor( - CSharpCodeVisitor csharpCodeVisitor, - CSharpCodeWriter writer, - CodeGeneratorContext context) - { - if (csharpCodeVisitor == null) - { - throw new ArgumentNullException(nameof(csharpCodeVisitor)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - return new CSharpDesignTimeCodeVisitor(csharpCodeVisitor, writer, context); - } - - protected virtual CSharpCodeWritingScope BuildClassDeclaration(CSharpCodeWriter writer) - { - var baseTypeVisitor = new CSharpBaseTypeVisitor(writer, Context); - baseTypeVisitor.Accept(Tree.Children); - - var baseType = baseTypeVisitor.CurrentBaseType ?? Host.DefaultBaseClass; - - var baseTypes = string.IsNullOrEmpty(baseType) ? Enumerable.Empty() : new string[] { baseType }; - - return writer.BuildClassDeclaration("public", Context.ClassName, baseTypes); - } - - protected virtual void BuildConstructor(CSharpCodeWriter writer) - { - writer.WriteLineHiddenDirective(); - using (writer.BuildConstructor(Context.ClassName)) - { - // Any constructor based logic that we need to add? - } - } - - private void AddImports(ChunkTree chunkTree, CSharpCodeWriter writer, IEnumerable defaultImports) - { - // Write out using directives - var usingVisitor = new CSharpUsingVisitor(writer, Context); - foreach (var chunk in Tree.Children) - { - usingVisitor.Accept(chunk); - } - - defaultImports = defaultImports.Except(usingVisitor.ImportedUsings); - - foreach (string import in defaultImports) - { - writer.WriteUsing(import); - } - - var taskNamespace = typeof(Task).Namespace; - - // We need to add the task namespace but ONLY if it hasn't been added by the default imports or using imports yet. - if (!defaultImports.Contains(taskNamespace) && !usingVisitor.ImportedUsings.Contains(taskNamespace)) - { - writer.WriteUsing(taskNamespace); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWriter.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWriter.cs deleted file mode 100644 index c53ff2fc62..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWriter.cs +++ /dev/null @@ -1,579 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpCodeWriter : CodeWriter - { - private const string InstanceMethodFormat = "{0}.{1}"; - - private static readonly char[] CStyleStringLiteralEscapeChars = { - '\r', - '\t', - '\"', - '\'', - '\\', - '\0', - '\n', - '\u2028', - '\u2029', - }; - - public CSharpCodeWriter() - { - LineMappingManager = new LineMappingManager(); - } - - public LineMappingManager LineMappingManager { get; private set; } - - public new CSharpCodeWriter Write(string data) - { - return (CSharpCodeWriter)base.Write(data); - } - - public new CSharpCodeWriter Indent(int size) - { - return (CSharpCodeWriter)base.Indent(size); - } - - public new CSharpCodeWriter ResetIndent() - { - return (CSharpCodeWriter)base.ResetIndent(); - } - - public new CSharpCodeWriter SetIndent(int size) - { - return (CSharpCodeWriter)base.SetIndent(size); - } - - public new CSharpCodeWriter IncreaseIndent(int size) - { - return (CSharpCodeWriter)base.IncreaseIndent(size); - } - - public new CSharpCodeWriter DecreaseIndent(int size) - { - return (CSharpCodeWriter)base.DecreaseIndent(size); - } - - public new CSharpCodeWriter WriteLine(string data) - { - return (CSharpCodeWriter)base.WriteLine(data); - } - - public new CSharpCodeWriter WriteLine() - { - return (CSharpCodeWriter)base.WriteLine(); - } - - public CSharpCodeWriter WriteVariableDeclaration(string type, string name, string value) - { - Write(type).Write(" ").Write(name); - if (!string.IsNullOrEmpty(value)) - { - Write(" = ").Write(value); - } - else - { - Write(" = null"); - } - - WriteLine(";"); - - return this; - } - - public CSharpCodeWriter WriteComment(string comment) - { - return Write("// ").WriteLine(comment); - } - - public CSharpCodeWriter WriteBooleanLiteral(bool value) - { - return Write(value.ToString().ToLowerInvariant()); - } - - public CSharpCodeWriter WriteStartAssignment(string name) - { - return Write(name).Write(" = "); - } - - public CSharpCodeWriter WriteParameterSeparator() - { - return Write(", "); - } - - public CSharpCodeWriter WriteStartNewObject(string typeName) - { - return Write("new ").Write(typeName).Write("("); - } - - public CSharpCodeWriter WriteLocationTaggedString(LocationTagged value) - { - WriteStringLiteral(value.Value); - WriteParameterSeparator(); - Write(value.Location.AbsoluteIndex.ToString(CultureInfo.InvariantCulture)); - - return this; - } - - public CSharpCodeWriter WriteStringLiteral(string literal) - { - if (literal.Length >= 256 && literal.Length <= 1500 && literal.IndexOf('\0') == -1) - { - WriteVerbatimStringLiteral(literal); - } - else - { - WriteCStyleStringLiteral(literal); - } - - return this; - } - - public CSharpCodeWriter WriteLineHiddenDirective() - { - return WriteLine("#line hidden"); - } - - public CSharpCodeWriter WritePragma(string value) - { - return Write("#pragma ").WriteLine(value); - } - - public CSharpCodeWriter WriteUsing(string name) - { - return WriteUsing(name, endLine: true); - } - - public CSharpCodeWriter WriteUsing(string name, bool endLine) - { - Write("using "); - Write(name); - - if (endLine) - { - WriteLine(";"); - } - - return this; - } - - public CSharpCodeWriter WriteLineDefaultDirective() - { - return WriteLine("#line default"); - } - - public CSharpCodeWriter WriteStartReturn() - { - return Write("return "); - } - - public CSharpCodeWriter WriteReturn(string value) - { - return WriteReturn(value, endLine: true); - } - - public CSharpCodeWriter WriteReturn(string value, bool endLine) - { - Write("return ").Write(value); - - if (endLine) - { - Write(";"); - } - - return WriteLine(); - } - - /// - /// Writes a #line pragma directive for the line number at the specified . - /// - /// The location to generate the line pragma for. - /// The file to generate the line pragma for. - /// The current instance of . - public CSharpCodeWriter WriteLineNumberDirective(SourceLocation location, string file) - { - if (location.FilePath != null) - { - file = location.FilePath; - } - - if (Builder.Length >= NewLine.Length && !IsAfterNewLine) - { - WriteLine(); - } - - var lineNumberAsString = (location.LineIndex + 1).ToString(CultureInfo.InvariantCulture); - return Write("#line ").Write(lineNumberAsString).Write(" \"").Write(file).WriteLine("\""); - } - - public CSharpCodeWriter WriteStartMethodInvocation(string methodName) - { - return WriteStartMethodInvocation(methodName, new string[0]); - } - - public CSharpCodeWriter WriteStartMethodInvocation(string methodName, params string[] genericArguments) - { - Write(methodName); - - if (genericArguments.Length > 0) - { - Write("<").Write(string.Join(", ", genericArguments)).Write(">"); - } - - return Write("("); - } - - public CSharpCodeWriter WriteEndMethodInvocation() - { - return WriteEndMethodInvocation(endLine: true); - } - - public CSharpCodeWriter WriteEndMethodInvocation(bool endLine) - { - Write(")"); - if (endLine) - { - WriteLine(";"); - } - - return this; - } - - // Writes a method invocation for the given instance name. - public CSharpCodeWriter WriteInstanceMethodInvocation(string instanceName, - string methodName, - params string[] parameters) - { - if (instanceName == null) - { - throw new ArgumentNullException(nameof(instanceName)); - } - - if (methodName == null) - { - throw new ArgumentNullException(nameof(methodName)); - } - - return WriteInstanceMethodInvocation(instanceName, methodName, endLine: true, parameters: parameters); - } - - // Writes a method invocation for the given instance name. - public CSharpCodeWriter WriteInstanceMethodInvocation(string instanceName, - string methodName, - bool endLine, - params string[] parameters) - { - if (instanceName == null) - { - throw new ArgumentNullException(nameof(instanceName)); - } - - if (methodName == null) - { - throw new ArgumentNullException(nameof(methodName)); - } - - return WriteMethodInvocation( - string.Format(CultureInfo.InvariantCulture, InstanceMethodFormat, instanceName, methodName), - endLine, - parameters); - } - - public CSharpCodeWriter WriteStartInstanceMethodInvocation(string instanceName, - string methodName) - { - if (instanceName == null) - { - throw new ArgumentNullException(nameof(instanceName)); - } - - if (methodName == null) - { - throw new ArgumentNullException(nameof(methodName)); - } - - return WriteStartMethodInvocation( - string.Format(CultureInfo.InvariantCulture, InstanceMethodFormat, instanceName, methodName)); - } - - public CSharpCodeWriter WriteMethodInvocation(string methodName, params string[] parameters) - { - return WriteMethodInvocation(methodName, endLine: true, parameters: parameters); - } - - public CSharpCodeWriter WriteMethodInvocation(string methodName, bool endLine, params string[] parameters) - { - return WriteStartMethodInvocation(methodName) - .Write(string.Join(", ", parameters)) - .WriteEndMethodInvocation(endLine); - } - - public CSharpCodeWriter WriteAutoPropertyDeclaration(string accessibility, string typeName, string name) - { - return Write(accessibility) - .Write(" ") - .Write(typeName) - .Write(" ") - .Write(name) - .Write(" { get; set; }") - .WriteLine(); - } - - public CSharpDisableWarningScope BuildDisableWarningScope(int warning) - { - return new CSharpDisableWarningScope(this, warning); - } - - public CSharpCodeWritingScope BuildScope() - { - return new CSharpCodeWritingScope(this); - } - - public CSharpCodeWritingScope BuildLambda(bool endLine, params string[] parameterNames) - { - return BuildLambda(endLine, async: false, parameterNames: parameterNames); - } - - public CSharpCodeWritingScope BuildAsyncLambda(bool endLine, params string[] parameterNames) - { - return BuildLambda(endLine, async: true, parameterNames: parameterNames); - } - - private CSharpCodeWritingScope BuildLambda(bool endLine, bool async, string[] parameterNames) - { - if (async) - { - Write("async"); - } - - Write("(").Write(string.Join(", ", parameterNames)).Write(") => "); - - var scope = new CSharpCodeWritingScope(this); - - if (endLine) - { - // End the lambda with a semicolon - scope.OnClose += () => - { - WriteLine(";"); - }; - } - - return scope; - } - - public CSharpCodeWritingScope BuildNamespace(string name) - { - Write("namespace ").WriteLine(name); - - return new CSharpCodeWritingScope(this); - } - - public CSharpCodeWritingScope BuildClassDeclaration(string accessibility, string name) - { - return BuildClassDeclaration(accessibility, name, Enumerable.Empty()); - } - - public CSharpCodeWritingScope BuildClassDeclaration(string accessibility, string name, string baseType) - { - return BuildClassDeclaration(accessibility, name, new string[] { baseType }); - } - - public CSharpCodeWritingScope BuildClassDeclaration( - string accessibility, - string name, - IEnumerable baseTypes) - { - Write(accessibility).Write(" class ").Write(name); - - if (baseTypes.Count() > 0) - { - Write(" : "); - Write(string.Join(", ", baseTypes)); - } - - WriteLine(); - - return new CSharpCodeWritingScope(this); - } - - public CSharpCodeWritingScope BuildConstructor(string name) - { - return BuildConstructor("public", name); - } - - public CSharpCodeWritingScope BuildConstructor(string accessibility, string name) - { - return BuildConstructor(accessibility, name, Enumerable.Empty>()); - } - - public CSharpCodeWritingScope BuildConstructor( - string accessibility, - string name, - IEnumerable> parameters) - { - Write(accessibility) - .Write(" ") - .Write(name) - .Write("(") - .Write(string.Join(", ", parameters.Select(p => p.Key + " " + p.Value))) - .WriteLine(")"); - - return new CSharpCodeWritingScope(this); - } - - public CSharpCodeWritingScope BuildMethodDeclaration(string accessibility, string returnType, string name) - { - return BuildMethodDeclaration(accessibility, returnType, name, Enumerable.Empty>()); - } - - public CSharpCodeWritingScope BuildMethodDeclaration( - string accessibility, - string returnType, - string name, - IEnumerable> parameters) - { - Write(accessibility) - .Write(" ") - .Write(returnType) - .Write(" ") - .Write(name) - .Write("(") - .Write(string.Join(", ", parameters.Select(p => p.Key + " " + p.Value))) - .WriteLine(")"); - - return new CSharpCodeWritingScope(this); - } - - public CSharpLineMappingWriter BuildLineMapping( - SourceLocation documentLocation, - int contentLength, - string sourceFilename) - { - return new CSharpLineMappingWriter(this, documentLocation, contentLength, sourceFilename); - } - - private void WriteVerbatimStringLiteral(string literal) - { - Write("@\""); - - // We need to find the index of each '"' (double-quote) to escape it. - var start = 0; - int end; - while ((end = literal.IndexOf('\"', start)) > -1) - { - Write(literal, start, end - start); - - Write("\"\""); - - start = end + 1; - } - - Debug.Assert(end == -1); // We've hit all of the double-quotes. - - // Write the remainder after the last double-quote. - Write(literal, start, literal.Length - start); - - Write("\""); - } - - private void WriteCStyleStringLiteral(string literal) - { - // From CSharpCodeGenerator.QuoteSnippetStringCStyle in CodeDOM - Write("\""); - - // We need to find the index of each escapable character to escape it. - var start = 0; - int end; - while ((end = literal.IndexOfAny(CStyleStringLiteralEscapeChars, start)) > -1) - { - Write(literal, start, end - start); - - switch (literal[end]) - { - case '\r': - Write("\\r"); - break; - case '\t': - Write("\\t"); - break; - case '\"': - Write("\\\""); - break; - case '\'': - Write("\\\'"); - break; - case '\\': - Write("\\\\"); - break; - case '\0': - Write("\\\0"); - break; - case '\n': - Write("\\n"); - break; - case '\u2028': - case '\u2029': - Write("\\u"); - Write(((int)literal[end]).ToString("X4", CultureInfo.InvariantCulture)); - break; - default: - Debug.Assert(false, "Unknown escape character."); - break; - } - - start = end + 1; - } - - Debug.Assert(end == -1); // We've hit all of chars that need escaping. - - // Write the remainder after the last escaped char. - Write(literal, start, literal.Length - start); - - Write("\""); - } - - public CSharpCodeWriter WriteStartInstrumentationContext( - ChunkGeneratorContext context, - SyntaxTreeNode syntaxNode, - bool isLiteral) - { - return WriteStartInstrumentationContext( - context, - syntaxNode.Start.AbsoluteIndex, - syntaxNode.Length, - isLiteral); - } - - public CSharpCodeWriter WriteStartInstrumentationContext( - ChunkGeneratorContext context, - int absoluteIndex, - int length, - bool isLiteral) - { - WriteStartMethodInvocation(context.Host.GeneratedClassContext.BeginContextMethodName); - Write(absoluteIndex.ToString(CultureInfo.InvariantCulture)); - WriteParameterSeparator(); - Write(length.ToString(CultureInfo.InvariantCulture)); - WriteParameterSeparator(); - Write(isLiteral ? "true" : "false"); - return WriteEndMethodInvocation(); - } - - public CSharpCodeWriter WriteEndInstrumentationContext(ChunkGeneratorContext context) - { - return WriteMethodInvocation(context.Host.GeneratedClassContext.EndContextMethodName); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWritingScope.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWritingScope.cs deleted file mode 100644 index 9b6ec1342a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpCodeWritingScope.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public struct CSharpCodeWritingScope : IDisposable - { - private CodeWriter _writer; - private bool _autoSpace; - private int _tabSize; - private int _startIndent; - - public CSharpCodeWritingScope(CodeWriter writer) : this(writer, true) { } - public CSharpCodeWritingScope(CodeWriter writer, int tabSize) : this(writer, tabSize, true) { } - // TODO: Make indents (tabs) environment specific - public CSharpCodeWritingScope(CodeWriter writer, bool autoSpace) : this(writer, 4, autoSpace) { } - public CSharpCodeWritingScope(CodeWriter writer, int tabSize, bool autoSpace) - { - _writer = writer; - _autoSpace = true; - _tabSize = tabSize; - _startIndent = -1; // Set in WriteStartScope - - OnClose = () => { }; - - WriteStartScope(); - } - - public Action OnClose; - - public void Dispose() - { - WriteEndScope(); - OnClose(); - } - - private void WriteStartScope() - { - TryAutoSpace(" "); - - _writer.WriteLine("{").IncreaseIndent(_tabSize); - _startIndent = _writer.CurrentIndent; - } - - private void WriteEndScope() - { - TryAutoSpace(_writer.NewLine); - - // Ensure the scope hasn't been modified - if (_writer.CurrentIndent == _startIndent) - { - _writer.DecreaseIndent(_tabSize); - } - - _writer.WriteLine("}"); - } - - private void TryAutoSpace(string spaceCharacter) - { - if (_autoSpace && - _writer.Builder.Length > 0 && - !char.IsWhiteSpace(_writer.Builder[_writer.Builder.Length - 1])) - { - _writer.Write(spaceCharacter); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpDisableWarningScope.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpDisableWarningScope.cs deleted file mode 100644 index 9215af74d6..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpDisableWarningScope.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public struct CSharpDisableWarningScope : IDisposable - { - private CSharpCodeWriter _writer; - int _warningNumber; - - public CSharpDisableWarningScope(CSharpCodeWriter writer) : this(writer, 219) - { } - - public CSharpDisableWarningScope(CSharpCodeWriter writer, int warningNumber) - { - _writer = writer; - _warningNumber = warningNumber; - - _writer.WritePragma("warning disable " + _warningNumber); - } - - public void Dispose() - { - _writer.WritePragma("warning restore " + _warningNumber); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpLineMappingWriter.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpLineMappingWriter.cs deleted file mode 100644 index 9b703b8e05..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpLineMappingWriter.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpLineMappingWriter : IDisposable - { - private readonly CSharpCodeWriter _writer; - private readonly MappingLocation _documentMapping; - private readonly int _startIndent; - private readonly bool _writePragmas; - private readonly bool _addLineMapping; - - private SourceLocation _generatedLocation; - private int _generatedContentLength; - - private CSharpLineMappingWriter(CSharpCodeWriter writer, bool addLineMappings) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - _writer = writer; - _addLineMapping = addLineMappings; - _startIndent = _writer.CurrentIndent; - _writer.ResetIndent(); - } - - public CSharpLineMappingWriter(CSharpCodeWriter writer, SourceLocation documentLocation, int contentLength) - : this(writer, addLineMappings: true) - { - _documentMapping = new MappingLocation(documentLocation, contentLength); - _generatedLocation = _writer.GetCurrentSourceLocation(); - } - - public CSharpLineMappingWriter( - CSharpCodeWriter writer, - SourceLocation documentLocation, - int contentLength, - string sourceFilename) - : this(writer, documentLocation, contentLength) - { - _writePragmas = true; - - _writer.WriteLineNumberDirective(documentLocation, sourceFilename); - _generatedLocation = _writer.GetCurrentSourceLocation(); - } - - /// - /// Initializes a new instance of used for generation of runtime - /// line mappings. The constructed instance of does not track - /// mappings between the Razor content and the generated content. - /// - /// The to write output to. - /// The of the Razor content being mapping. - /// The input file path. - public CSharpLineMappingWriter( - CSharpCodeWriter writer, - SourceLocation documentLocation, - string sourceFileName) - : this(writer, addLineMappings: false) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - _writePragmas = true; - _writer.WriteLineNumberDirective(documentLocation, sourceFileName); - } - - public void MarkLineMappingStart() - { - _generatedLocation = _writer.GetCurrentSourceLocation(); - } - - public void MarkLineMappingEnd() - { - _generatedContentLength = _writer.Builder.Length - _generatedLocation.AbsoluteIndex; - } - - public void Dispose() - { - if (_addLineMapping) - { - // Verify that the generated length has not already been calculated - if (_generatedContentLength == 0) - { - _generatedContentLength = _writer.Builder.Length - _generatedLocation.AbsoluteIndex; - } - - var generatedLocation = new MappingLocation(_generatedLocation, _generatedContentLength); - var documentMapping = _documentMapping; - if (documentMapping.ContentLength == -1) - { - documentMapping = new MappingLocation( - location: new SourceLocation( - _documentMapping.FilePath, - _documentMapping.AbsoluteIndex, - _documentMapping.LineIndex, - _documentMapping.CharacterIndex), - contentLength: _generatedContentLength); - } - - _writer.LineMappingManager.AddMapping( - documentLocation: documentMapping, - generatedLocation: generatedLocation); - } - - if (_writePragmas) - { - // Need to add an additional line at the end IF there wasn't one already written. - // This is needed to work with the C# editor's handling of #line ... - var builder = _writer.Builder; - var endsWithNewline = builder.Length > 0 && builder[builder.Length - 1] == '\n'; - - // Always write at least 1 empty line to potentially separate code from pragmas. - _writer.WriteLine(); - - // Check if the previous empty line wasn't enough to separate code from pragmas. - if (!endsWithNewline) - { - _writer.WriteLine(); - } - - _writer.WriteLineDefaultDirective() - .WriteLineHiddenDirective(); - } - - // Reset indent back to when it was started - _writer.SetIndent(_startIndent); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpPaddingBuilder.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpPaddingBuilder.cs deleted file mode 100644 index a13071f18e..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpPaddingBuilder.cs +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpPaddingBuilder - { - private static readonly char[] _newLineChars = { '\r', '\n' }; - - private readonly RazorEngineHost _host; - - public CSharpPaddingBuilder(RazorEngineHost host) - { - _host = host; - } - - // Special case for statement padding to account for brace positioning in the editor. - public string BuildStatementPadding(Span target) - { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - var padding = CalculatePadding(target, generatedStart: 0); - - // We treat statement padding specially so for brace positioning, so that in the following example: - // @if (foo > 0) - // { - // } - // - // the braces shows up under the @ rather than under the if. - if (_host.DesignTimeMode && - padding > 0 && - target.Previous.Kind == SpanKind.Transition && // target.Previous is guaranteed to not be null if you have padding. - string.Equals(target.Previous.Content, SyntaxConstants.TransitionString, StringComparison.Ordinal)) - { - padding--; - } - - var generatedCode = BuildPaddingInternal(padding); - - return generatedCode; - } - - public string BuildExpressionPadding(Span target) - { - return BuildExpressionPadding(target, generatedStart: 0); - } - - public string BuildExpressionPadding(Span target, int generatedStart) - { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - var padding = CalculatePadding(target, generatedStart); - - return BuildPaddingInternal(padding); - } - - internal int CalculatePadding(Span target, int generatedStart) - { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - int padding; - - padding = CollectSpacesAndTabs(target, _host.TabSize) - generatedStart; - - // if we add generated text that is longer than the padding we wanted to insert we have no recourse and we have to skip padding - // example: - // Razor code at column zero: @somecode() - // Generated code will be: - // In design time: __o = somecode(); - // In Run time: Write(somecode()); - // - // In both cases the padding would have been 1 space to remote the space the @ symbol takes, which will be smaller than the 6 - // chars the hidden generated code takes. - if (padding < 0) - { - padding = 0; - } - - return padding; - } - - private string BuildPaddingInternal(int padding) - { - if (_host.DesignTimeMode && _host.IsIndentingWithTabs) - { - var spaces = padding % _host.TabSize; - var tabs = padding / _host.TabSize; - - return new string('\t', tabs) + new string(' ', spaces); - } - else - { - return new string(' ', padding); - } - } - - private static int CollectSpacesAndTabs(Span target, int tabSize) - { - var firstSpanInLine = target; - - string currentContent = null; - - while (firstSpanInLine.Previous != null) - { - // When scanning previous spans we need to be break down the spans with spaces. The parser combines - // whitespace into existing spans so you'll see tabs, newlines etc. within spans. We only care about - // the \t in existing spans. - var previousContent = firstSpanInLine.Previous.Content ?? string.Empty; - - var lastNewLineIndex = previousContent.LastIndexOfAny(_newLineChars); - - if (lastNewLineIndex < 0) - { - firstSpanInLine = firstSpanInLine.Previous; - } - else - { - if (lastNewLineIndex != previousContent.Length - 1) - { - firstSpanInLine = firstSpanInLine.Previous; - currentContent = previousContent.Substring(lastNewLineIndex + 1); - } - - break; - } - } - - // We need to walk from the beginning of the line, because space + tab(tabSize) = tabSize columns, but tab(tabSize) + space = tabSize+1 columns. - var currentSpanInLine = firstSpanInLine; - - if (currentContent == null) - { - currentContent = currentSpanInLine.Content; - } - - var padding = 0; - while (currentSpanInLine != target) - { - if (currentContent != null) - { - for (int i = 0; i < currentContent.Length; i++) - { - if (currentContent[i] == '\t') - { - // Example: - // : - // iter 1) 1 - // iter 2) 2 - // iter 3) 4 = 2 + (4 - 2) - // iter 4) 8 = 4 + (4 - 0) - padding = padding + (tabSize - (padding % tabSize)); - } - else - { - padding++; - } - } - } - - currentSpanInLine = currentSpanInLine.Next; - currentContent = currentSpanInLine.Content; - } - - return padding; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpTagHelperCodeRenderer.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpTagHelperCodeRenderer.cs deleted file mode 100644 index b04d7c5a9d..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CSharpTagHelperCodeRenderer.cs +++ /dev/null @@ -1,833 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - /// - /// Renders tag helper rendering code. - /// - public class CSharpTagHelperCodeRenderer - { - internal static readonly string ExecutionContextVariableName = "__tagHelperExecutionContext"; - internal static readonly string StringValueBufferVariableName = "__tagHelperStringValueBuffer"; - internal static readonly string ScopeManagerVariableName = "__tagHelperScopeManager"; - internal static readonly string RunnerVariableName = "__tagHelperRunner"; - - private readonly CSharpCodeWriter _writer; - private readonly CodeGeneratorContext _context; - private readonly IChunkVisitor _bodyVisitor; - private readonly IChunkVisitor _literalBodyVisitor; - private readonly TagHelperAttributeCodeVisitor _attributeCodeVisitor; - private readonly GeneratedTagHelperContext _tagHelperContext; - private readonly bool _designTimeMode; - - /// - /// Instantiates a new . - /// - /// The used to render chunks found in the body. - /// The used to write code. - /// A instance that contains information about - /// the current code generation process. - public CSharpTagHelperCodeRenderer( - IChunkVisitor bodyVisitor, - CSharpCodeWriter writer, - CodeGeneratorContext context) - { - if (bodyVisitor == null) - { - throw new ArgumentNullException(nameof(bodyVisitor)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _bodyVisitor = bodyVisitor; - _writer = writer; - _context = context; - _tagHelperContext = context.Host.GeneratedClassContext.GeneratedTagHelperContext; - _designTimeMode = context.Host.DesignTimeMode; - - _literalBodyVisitor = new CSharpLiteralCodeVisitor(this, writer, context); - _attributeCodeVisitor = new TagHelperAttributeCodeVisitor(writer, context); - AttributeValueCodeRenderer = new TagHelperAttributeValueCodeRenderer(); - } - - public TagHelperAttributeValueCodeRenderer AttributeValueCodeRenderer { get; set; } - - /// - /// Renders the code for the given . - /// - /// A to render. - public void RenderTagHelper(TagHelperChunk chunk) - { - // Remove any duplicate TagHelperDescriptors that reference the same type name. Duplicates can occur when - // multiple HtmlTargetElement attributes are on a TagHelper type and matches overlap for an HTML element. - // Having more than one descriptor with the same TagHelper type results in generated code that runs - // the same TagHelper X many times (instead of once) over a single HTML element. - var tagHelperDescriptors = chunk.Descriptors.Distinct(TypeBasedTagHelperDescriptorComparer.Default); - - RenderBeginTagHelperScope(chunk.TagName, chunk.TagMode, chunk.Children); - - RenderTagHelpersCreation(chunk, tagHelperDescriptors); - - RenderAttributes(chunk.Attributes, tagHelperDescriptors); - - // No need to run anything in design time mode. - if (!_designTimeMode) - { - RenderRunTagHelpers(); - RenderTagHelperOutput(chunk); - RenderEndTagHelpersScope(); - } - } - - public static bool TryGetPlainTextValue(Chunk chunk, out string plainText) - { - var parentChunk = chunk as ParentChunk; - - plainText = null; - - if (parentChunk == null || parentChunk.Children.Count != 1) - { - return false; - } - - LiteralChunk literalChildChunk; - if ((literalChildChunk = parentChunk.Children[0] as LiteralChunk) != null) - { - plainText = literalChildChunk.Text; - return true; - } - - ParentLiteralChunk parentLiteralChunk; - if ((parentLiteralChunk = parentChunk.Children[0] as ParentLiteralChunk) != null) - { - plainText = parentLiteralChunk.GetText(); - return true; - } - - return false; - } - - internal static string GetVariableName(TagHelperDescriptor descriptor) - { - return "__" + descriptor.TypeName.Replace('.', '_'); - } - - private void RenderBeginTagHelperScope(string tagName, TagMode tagMode, IList children) - { - // Scopes/execution contexts are a runtime feature. - if (_designTimeMode) - { - // Render all of the tag helper children inline for IntelliSense. - _bodyVisitor.Accept(children); - return; - } - - // Call into the tag helper scope manager to start a new tag helper scope. - // Also capture the value as the current execution context. - _writer - .WriteStartAssignment(ExecutionContextVariableName) - .WriteStartInstanceMethodInvocation( - ScopeManagerVariableName, - _tagHelperContext.ScopeManagerBeginMethodName); - - // Assign a unique ID for this instance of the source HTML tag. This must be unique - // per call site, e.g. if the tag is on the view twice, there should be two IDs. - _writer.WriteStringLiteral(tagName) - .WriteParameterSeparator() - .Write("global::") - .Write(typeof(TagMode).FullName) - .Write(".") - .Write(tagMode.ToString()) - .WriteParameterSeparator() - .WriteStringLiteral(GenerateUniqueId()) - .WriteParameterSeparator(); - - // We remove the target writer so TagHelper authors can retrieve content. - var oldWriter = _context.TargetWriterName; - _context.TargetWriterName = null; - - using (_writer.BuildAsyncLambda(endLine: false)) - { - // Render all of the tag helper children. - _bodyVisitor.Accept(children); - } - - _context.TargetWriterName = oldWriter; - - _writer.WriteEndMethodInvocation(); - } - - /// - /// Generates a unique ID for an HTML element. - /// - /// - /// A globally unique ID. - /// - protected virtual string GenerateUniqueId() - { - return Guid.NewGuid().ToString("N"); - } - - private void RenderTagHelpersCreation( - TagHelperChunk chunk, - IEnumerable tagHelperDescriptors) - { - // This is to maintain value accessors for attributes when creating the TagHelpers. - // Ultimately it enables us to do scenarios like this: - // myTagHelper1.Foo = DateTime.Now; - // myTagHelper2.Foo = myTagHelper1.Foo; - var htmlAttributeValues = new Dictionary(StringComparer.OrdinalIgnoreCase); - - foreach (var tagHelperDescriptor in tagHelperDescriptors) - { - var tagHelperVariableName = GetVariableName(tagHelperDescriptor); - - // Create the tag helper - _writer.WriteStartAssignment(tagHelperVariableName) - .WriteStartMethodInvocation( - _tagHelperContext.CreateTagHelperMethodName, - "global::" + tagHelperDescriptor.TypeName) - .WriteEndMethodInvocation(); - - // Execution contexts and throwing errors for null dictionary properties are a runtime feature. - if (_designTimeMode) - { - continue; - } - - _writer.WriteInstanceMethodInvocation( - ExecutionContextVariableName, - _tagHelperContext.ExecutionContextAddMethodName, - tagHelperVariableName); - - // Track dictionary properties we have confirmed are non-null. - var confirmedDictionaries = new HashSet(StringComparer.Ordinal); - - // Ensure that all created TagHelpers have initialized dictionary bound properties which are used - // via TagHelper indexers. - foreach (var chunkAttribute in chunk.Attributes) - { - var associatedAttributeDescriptor = tagHelperDescriptor.Attributes.FirstOrDefault( - attributeDescriptor => attributeDescriptor.IsNameMatch(chunkAttribute.Name)); - - if (associatedAttributeDescriptor != null && - associatedAttributeDescriptor.IsIndexer && - confirmedDictionaries.Add(associatedAttributeDescriptor.PropertyName)) - { - // Throw a reasonable Exception at runtime if the dictionary property is null. - _writer - .Write("if (") - .Write(tagHelperVariableName) - .Write(".") - .Write(associatedAttributeDescriptor.PropertyName) - .WriteLine(" == null)"); - using (_writer.BuildScope()) - { - // System is in Host.NamespaceImports for all MVC scenarios. No need to generate FullName - // of InvalidOperationException type. - _writer - .Write("throw ") - .WriteStartNewObject(nameof(InvalidOperationException)) - .WriteStartMethodInvocation(_tagHelperContext.FormatInvalidIndexerAssignmentMethodName) - .WriteStringLiteral(chunkAttribute.Name) - .WriteParameterSeparator() - .WriteStringLiteral(tagHelperDescriptor.TypeName) - .WriteParameterSeparator() - .WriteStringLiteral(associatedAttributeDescriptor.PropertyName) - .WriteEndMethodInvocation(endLine: false) // End of method call - .WriteEndMethodInvocation(endLine: true); // End of new expression / throw statement - } - } - } - } - } - - private void RenderAttributes( - IList chunkAttributes, - IEnumerable tagHelperDescriptors) - { - var renderedBoundAttributeNames = new HashSet(StringComparer.OrdinalIgnoreCase); - - // Go through the HTML attributes in source order, assigning to properties or indexers or adding to - // TagHelperExecutionContext.HtmlAttributes' as we go. - foreach (var attribute in chunkAttributes) - { - var attributeValueChunk = attribute.Value; - var associatedDescriptors = tagHelperDescriptors.Where(descriptor => - descriptor.Attributes.Any(attributeDescriptor => attributeDescriptor.IsNameMatch(attribute.Name))); - - // Bound attributes have associated descriptors. First attribute value wins if there are duplicates; - // later values of duplicate bound attributes are treated as if they were unbound. - if (associatedDescriptors.Any() && renderedBoundAttributeNames.Add(attribute.Name)) - { - if (attributeValueChunk == null) - { - // Minimized attributes are not valid for bound attributes. TagHelperBlockRewriter has already - // logged an error if it was a bound attribute; so we can skip. - continue; - } - - // We need to capture the tag helper's property value accessor so we can retrieve it later - // if there are more tag helpers that need the value. - string valueAccessor = null; - - foreach (var associatedDescriptor in associatedDescriptors) - { - var associatedAttributeDescriptor = associatedDescriptor.Attributes.First( - attributeDescriptor => attributeDescriptor.IsNameMatch(attribute.Name)); - var tagHelperVariableName = GetVariableName(associatedDescriptor); - - valueAccessor = RenderBoundAttribute( - attribute, - tagHelperVariableName, - valueAccessor, - associatedAttributeDescriptor); - } - } - else - { - RenderUnboundAttribute(attribute); - } - } - } - - private string RenderBoundAttribute( - TagHelperAttributeTracker attribute, - string tagHelperVariableName, - string previousValueAccessor, - TagHelperAttributeDescriptor attributeDescriptor) - { - var currentValueAccessor = string.Format( - CultureInfo.InvariantCulture, - "{0}.{1}", - tagHelperVariableName, - attributeDescriptor.PropertyName); - - if (attributeDescriptor.IsIndexer) - { - var dictionaryKey = attribute.Name.Substring(attributeDescriptor.Name.Length); - currentValueAccessor += $"[\"{dictionaryKey}\"]"; - } - - // If this attribute value has not been seen before, need to record its value. - if (previousValueAccessor == null) - { - var preallocatedAttributeValueChunk = attribute.Value as PreallocatedTagHelperAttributeChunk; - - if (preallocatedAttributeValueChunk != null) - { - RenderBoundPreAllocatedAttribute(preallocatedAttributeValueChunk, currentValueAccessor); - - return currentValueAccessor; - } - - // Bufferable attributes are attributes that can have Razor code inside of them. Such - // attributes have string values and may be calculated using a temporary TextWriter or other - // buffer. - var bufferableAttribute = attributeDescriptor.IsStringProperty; - - RenderNewAttributeValueAssignment( - attributeDescriptor, - bufferableAttribute, - attribute.Value, - currentValueAccessor); - - if (_designTimeMode) - { - // Execution contexts are a runtime feature. - return currentValueAccessor; - } - - // We need to inform the context of the attribute value. - _writer - .WriteStartInstanceMethodInvocation( - ExecutionContextVariableName, - _tagHelperContext.ExecutionContextAddTagHelperAttributeMethodName) - .WriteStringLiteral(attribute.Name) - .WriteParameterSeparator() - .Write(currentValueAccessor) - .WriteParameterSeparator() - .Write($"global::{typeof(HtmlAttributeValueStyle).FullName}.{attribute.ValueStyle}") - .WriteEndMethodInvocation(); - - return currentValueAccessor; - } - else - { - // The attribute value has already been determined and accessor was passed to us as - // previousValueAccessor, we don't want to evaluate the value twice so lets just use the - // previousValueLocation. - _writer - .WriteStartAssignment(currentValueAccessor) - .Write(previousValueAccessor) - .WriteLine(";"); - - return previousValueAccessor; - } - } - - // Render bound attributes that are of string type and are preallocated. - private void RenderBoundPreAllocatedAttribute( - PreallocatedTagHelperAttributeChunk preallocatedAttributeValueChunk, - string valueAccessor) - { - var attributeValueAccessor = string.Format( - CultureInfo.InvariantCulture, - "{0}.{1}", - preallocatedAttributeValueChunk.AttributeVariableAccessor, - _tagHelperContext.TagHelperAttributeValuePropertyName); - - _writer - .WriteStartAssignment(valueAccessor) - .Write("(string)") - .Write(attributeValueAccessor) - .WriteLine(";"); - - if (_designTimeMode) - { - // Execution contexts are a runtime feature. - return; - } - - _writer - .WriteStartInstanceMethodInvocation( - ExecutionContextVariableName, - _tagHelperContext.ExecutionContextAddTagHelperAttributeMethodName) - .Write(preallocatedAttributeValueChunk.AttributeVariableAccessor) - .WriteEndMethodInvocation(); - } - - // Render assignment of attribute value to the value accessor. - private void RenderNewAttributeValueAssignment( - TagHelperAttributeDescriptor attributeDescriptor, - bool bufferableAttribute, - Chunk attributeValueChunk, - string valueAccessor) - { - // Plain text values are non Razor code (@DateTime.Now) values. If an attribute is bufferable it - // may be more than just a plain text value, it may also contain Razor code which is why we attempt - // to retrieve a plain text value here. - string textValue; - var isPlainTextValue = TryGetPlainTextValue(attributeValueChunk, out textValue); - - if (bufferableAttribute) - { - if (!isPlainTextValue) - { - // If we haven't recorded a value and we need to buffer an attribute value and the value is not - // plain text then we need to prepare the value prior to setting it below. - BuildBufferedWritingScope(attributeValueChunk, htmlEncodeValues: false); - } - - _writer.WriteStartAssignment(valueAccessor); - - if (isPlainTextValue) - { - // If the attribute is bufferable but has a plain text value that means the value - // is a string which needs to be surrounded in quotes. - RenderQuotedAttributeValue(textValue, attributeDescriptor); - } - else - { - // The value contains more than plain text e.g. stringAttribute ="Time: @DateTime.Now". - RenderBufferedAttributeValue(attributeDescriptor); - } - - _writer.WriteLine(";"); - } - else - { - // Write out simple assignment for non-string property value. Try to keep the whole - // statement together and the #line pragma correct to make debugging possible. - using (var lineMapper = new CSharpLineMappingWriter( - _writer, - attributeValueChunk.Start, - _context.SourceFile)) - { - // Place the assignment LHS to align RHS with original attribute value's indentation. - // Unfortunately originalIndent is incorrect if original line contains tabs. Unable to - // use a CSharpPaddingBuilder because the Association has no Previous node; lost the - // original Span sequence when the parse tree was rewritten. - var originalIndent = attributeValueChunk.Start.CharacterIndex; - var generatedLength = valueAccessor.Length + " = ".Length; - var newIndent = originalIndent - generatedLength; - if (newIndent > 0) - { - _writer.Indent(newIndent); - } - - _writer.WriteStartAssignment(valueAccessor); - lineMapper.MarkLineMappingStart(); - - // Write out code expression for this attribute value. Property is not a string. - // So quoting or buffering are not helpful. - RenderCodeAttributeValue(attributeValueChunk, attributeDescriptor, isPlainTextValue); - - // End the assignment to the attribute. - lineMapper.MarkLineMappingEnd(); - _writer.WriteLine(";"); - } - } - } - - private void RenderUnboundAttribute(TagHelperAttributeTracker attribute) - { - // Render children to provide IntelliSense at design time. No need for the execution context logic, it's - // a runtime feature. - if (_designTimeMode) - { - if (attribute.Value != null) - { - _bodyVisitor.Accept(attribute.Value); - } - - return; - } - - Debug.Assert(attribute.Value != null); - - var attributeValueStyleParameter = $"global::{typeof(HtmlAttributeValueStyle).FullName}.{attribute.ValueStyle}"; - - // All simple text and minimized attributes will be pre-allocated. - var preallocatedValue = attribute.Value as PreallocatedTagHelperAttributeChunk; - if (preallocatedValue != null) - { - _writer - .WriteStartInstanceMethodInvocation( - ExecutionContextVariableName, - _tagHelperContext.ExecutionContextAddHtmlAttributeMethodName) - .Write(preallocatedValue.AttributeVariableAccessor) - .WriteEndMethodInvocation(); - } - else if (IsDynamicAttributeValue(attribute.Value)) - { - // Dynamic attribute value should be run through the conditional attribute removal system. It's - // unbound and contains C#. - - // TagHelper attribute rendering is buffered by default. We do not want to write to the current - // writer. - var currentTargetWriter = _context.TargetWriterName; - var currentWriteAttributeMethodName = _context.Host.GeneratedClassContext.WriteAttributeValueMethodName; - _context.TargetWriterName = null; - - Debug.Assert(attribute.Value is ParentChunk); - var children = ((ParentChunk)attribute.Value).Children; - var attributeCount = children.Count(c => c is DynamicCodeAttributeChunk || c is LiteralCodeAttributeChunk); - - _writer - .WriteStartMethodInvocation(_tagHelperContext.BeginAddHtmlAttributeValuesMethodName) - .Write(ExecutionContextVariableName) - .WriteParameterSeparator() - .WriteStringLiteral(attribute.Name) - .WriteParameterSeparator() - .Write(attributeCount.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .Write(attributeValueStyleParameter) - .WriteEndMethodInvocation(); - - _attributeCodeVisitor.Accept(attribute.Value); - - _writer.WriteMethodInvocation( - _tagHelperContext.EndAddHtmlAttributeValuesMethodName, - ExecutionContextVariableName); - - _context.TargetWriterName = currentTargetWriter; - } - else - { - // This is a data-* attribute which includes C#. Do not perform the conditional attribute removal or - // other special cases used when IsDynamicAttributeValue(). But the attribute must still be buffered to - // determine its final value. - - // Attribute value is not plain text, must be buffered to determine its final value. - BuildBufferedWritingScope(attribute.Value, htmlEncodeValues: true); - - _writer - .WriteStartInstanceMethodInvocation( - ExecutionContextVariableName, - _tagHelperContext.ExecutionContextAddHtmlAttributeMethodName) - .WriteStringLiteral(attribute.Name) - .WriteParameterSeparator() - .WriteStartMethodInvocation(_tagHelperContext.MarkAsHtmlEncodedMethodName); - - RenderBufferedAttributeValueAccessor(_writer); - - _writer - .WriteEndMethodInvocation(endLine: false) - .WriteParameterSeparator() - .Write(attributeValueStyleParameter) - .WriteEndMethodInvocation(); - } - } - - private void RenderEndTagHelpersScope() - { - _writer.WriteStartAssignment(ExecutionContextVariableName) - .WriteInstanceMethodInvocation(ScopeManagerVariableName, - _tagHelperContext.ScopeManagerEndMethodName); - } - - private void RenderTagHelperOutput(TagHelperChunk chunk) - { - var tagHelperOutputAccessor = - $"{ExecutionContextVariableName}.{_tagHelperContext.ExecutionContextOutputPropertyName}"; - - if (ContainsChildContent(chunk.Children)) - { - _writer - .Write("if (!") - .Write(tagHelperOutputAccessor) - .Write(".") - .Write(_tagHelperContext.TagHelperOutputIsContentModifiedPropertyName) - .WriteLine(")"); - - using (_writer.BuildScope()) - { - _writer - .Write("await ") - .WriteInstanceMethodInvocation( - ExecutionContextVariableName, - _tagHelperContext.ExecutionContextSetOutputContentAsyncMethodName); - } - } - - _writer - .WriteStartInstrumentationContext(_context, chunk.Association, isLiteral: false); - - if (!string.IsNullOrEmpty(_context.TargetWriterName)) - { - _writer - .WriteStartMethodInvocation(_context.Host.GeneratedClassContext.WriteToMethodName) - .Write(_context.TargetWriterName) - .WriteParameterSeparator(); - } - else - { - _writer.WriteStartMethodInvocation(_context.Host.GeneratedClassContext.WriteMethodName); - } - - _writer - .Write(tagHelperOutputAccessor) - .WriteEndMethodInvocation() - .WriteEndInstrumentationContext(_context); - } - - private void RenderRunTagHelpers() - { - _writer - .Write("await ") - .WriteStartInstanceMethodInvocation(RunnerVariableName, _tagHelperContext.RunnerRunAsyncMethodName) - .Write(ExecutionContextVariableName) - .WriteEndMethodInvocation(); - } - - private void RenderBufferedAttributeValue(TagHelperAttributeDescriptor attributeDescriptor) - { - // Pass complexValue: false because variable.ToString() replaces any original complexity in the expression. - RenderAttributeValue( - attributeDescriptor, - valueRenderer: (writer) => - { - RenderBufferedAttributeValueAccessor(writer); - }, - complexValue: false); - } - - private void RenderCodeAttributeValue( - Chunk attributeValueChunk, - TagHelperAttributeDescriptor attributeDescriptor, - bool isPlainTextValue) - { - RenderAttributeValue( - attributeDescriptor, - valueRenderer: (writer) => - { - if (attributeDescriptor.IsEnum && isPlainTextValue) - { - writer - .Write("global::") - .Write(attributeDescriptor.TypeName) - .Write("."); - } - - var visitor = - new CSharpTagHelperAttributeValueVisitor(writer, _context, attributeDescriptor.TypeName); - visitor.Accept(attributeValueChunk); - }, - complexValue: !isPlainTextValue); - } - - private void RenderQuotedAttributeValue(string value, TagHelperAttributeDescriptor attributeDescriptor) - { - RenderAttributeValue( - attributeDescriptor, - valueRenderer: (writer) => - { - writer.WriteStringLiteral(value); - }, - complexValue: false); - } - - // Render a buffered writing scope for the HTML attribute value. - private void BuildBufferedWritingScope(Chunk htmlAttributeChunk, bool htmlEncodeValues) - { - // We're building a writing scope around the provided chunks which captures everything written from the - // page. Therefore, we do not want to write to any other buffer since we're using the pages buffer to - // ensure we capture all content that's written, directly or indirectly. - var oldWriter = _context.TargetWriterName; - _context.TargetWriterName = null; - - // Need to disable instrumentation inside of writing scopes, the instrumentation will not detect - // content written inside writing scopes. - var oldInstrumentation = _context.Host.EnableInstrumentation; - - try - { - _context.Host.EnableInstrumentation = false; - - // Scopes are a runtime feature. - if (!_designTimeMode) - { - _writer.WriteMethodInvocation(_tagHelperContext.BeginWriteTagHelperAttributeMethodName); - } - - var visitor = htmlEncodeValues ? _bodyVisitor : _literalBodyVisitor; - visitor.Accept(htmlAttributeChunk); - - // Scopes are a runtime feature. - if (!_designTimeMode) - { - _writer - .WriteStartAssignment(StringValueBufferVariableName) - .WriteMethodInvocation(_tagHelperContext.EndWriteTagHelperAttributeMethodName); - } - } - finally - { - // Reset instrumentation back to what it was, leaving the writing scope. - _context.Host.EnableInstrumentation = oldInstrumentation; - - // Reset the writer/buffer back to what it was, leaving the writing scope. - _context.TargetWriterName = oldWriter; - } - } - - private void RenderAttributeValue(TagHelperAttributeDescriptor attributeDescriptor, - Action valueRenderer, - bool complexValue) - { - AttributeValueCodeRenderer.RenderAttributeValue( - attributeDescriptor, - _writer, - _context, - valueRenderer, - complexValue); - } - - private void RenderBufferedAttributeValueAccessor(CSharpCodeWriter writer) - { - if (_designTimeMode) - { - // There is no value buffer in design time mode but we still want to write out a value. We write a - // value to ensure the tag helper's property type is string. - writer.Write("string.Empty"); - } - else - { - writer.Write(StringValueBufferVariableName); - } - } - - private static bool ContainsChildContent(IList children) - { - // False will be returned if there are no children or if there are only non-TagHelper ParentChunk leaf - // nodes. - foreach (var child in children) - { - var parentChunk = child as ParentChunk; - if (parentChunk == null || - parentChunk is TagHelperChunk || - ContainsChildContent(parentChunk.Children)) - { - return true; - } - } - - return false; - } - - public static bool IsDynamicAttributeValue(Chunk attributeValueChunk) - { - var parentChunk = attributeValueChunk as ParentChunk; - if (parentChunk != null) - { - return parentChunk.Children.Any(child => child is DynamicCodeAttributeChunk); - } - - return false; - } - - // A CSharpCodeVisitor which does not HTML encode values. Used when rendering bound string attribute values. - private class CSharpLiteralCodeVisitor : CSharpCodeVisitor - { - public CSharpLiteralCodeVisitor( - CSharpTagHelperCodeRenderer tagHelperRenderer, - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(writer, context) - { - // Ensure that no matter how this class is used, we don't create numerous CSharpTagHelperCodeRenderer - // instances. - TagHelperRenderer = tagHelperRenderer; - } - - protected override string WriteMethodName - { - get - { - return Context.Host.GeneratedClassContext.WriteLiteralMethodName; - } - } - - protected override string WriteToMethodName - { - get - { - return Context.Host.GeneratedClassContext.WriteLiteralToMethodName; - } - } - } - - private class TagHelperAttributeCodeVisitor : CSharpCodeVisitor - { - public TagHelperAttributeCodeVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(writer, context) - { - } - - protected override string WriteAttributeValueMethodName => - Context.Host.GeneratedClassContext.GeneratedTagHelperContext.AddHtmlAttributeValueMethodName; - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGenerator.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGenerator.cs deleted file mode 100644 index fba661d227..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGenerator.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public abstract class CodeGenerator - { - private readonly CodeGeneratorContext _context; - - public CodeGenerator(CodeGeneratorContext context) - { - _context = context; - } - - protected CodeGeneratorContext Context - { - get { return _context; } - } - - public abstract CodeGeneratorResult Generate(); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorContext.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorContext.cs deleted file mode 100644 index ff8f38ddda..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorContext.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Chunks.Generators; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - /// - /// Context object with information used to generate a Razor page. - /// - public class CodeGeneratorContext : ChunkGeneratorContext - { - /// - /// Instantiates a new instance of the object. - /// - /// A to copy information from. - /// - /// The used to collect s encountered - /// when parsing the current Razor document. - /// - public CodeGeneratorContext(ChunkGeneratorContext generatorContext, ErrorSink errorSink) - : base(generatorContext) - { - ErrorSink = errorSink; - ExpressionRenderingMode = ExpressionRenderingMode.WriteToOutput; - } - - // Internal for testing. - internal CodeGeneratorContext( - RazorEngineHost host, - string className, - string rootNamespace, - string sourceFile, - bool shouldGenerateLinePragmas, - ErrorSink errorSink) - : base(host, className, rootNamespace, sourceFile, shouldGenerateLinePragmas) - { - ErrorSink = errorSink; - ExpressionRenderingMode = ExpressionRenderingMode.WriteToOutput; - } - - /// - /// The current C# rendering mode. - /// - /// - /// forces C# generation to write - /// s to the output page, i.e. WriteLiteral("Hello World"). - /// writes values in their - /// rawest form, i.g. "Hello World". - /// - public ExpressionRenderingMode ExpressionRenderingMode { get; set; } - - /// - /// The C# writer to write information to. - /// - /// - /// If is null values will be written using a default write method - /// i.e. WriteLiteral("Hello World"). - /// If is not null values will be written to the given - /// , i.e. WriteLiteralTo(myWriter, "Hello World"). - /// - public string TargetWriterName { get; set; } - - /// - /// Gets or sets the SHA1 based checksum for the file whose location is defined by - /// . - /// - public string Checksum { get; set; } - - /// - /// Used to aggregate s. - /// - public ErrorSink ErrorSink { get; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorResult.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorResult.cs deleted file mode 100644 index 8e03030791..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeGeneratorResult.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CodeGeneratorResult - { - public CodeGeneratorResult(string code, IList designTimeLineMappings) - { - Code = code; - DesignTimeLineMappings = designTimeLineMappings; - } - - public string Code { get; private set; } - public IList DesignTimeLineMappings { get; private set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeWriter.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeWriter.cs deleted file mode 100644 index c74889e07a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/CodeWriter.cs +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Text; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CodeWriter : IDisposable - { - private static readonly char[] NewLineCharacters = { '\r', '\n' }; - - private string _cache = string.Empty; - private bool _dirty; - - private int _absoluteIndex; - private int _currentLineIndex; - private int _currentLineCharacterIndex; - - public StringBuilder Builder { get; } = new StringBuilder(); - - public int CurrentIndent { get; private set; } - - public bool IsAfterNewLine { get; private set; } - - public string NewLine { get; set; } = Environment.NewLine; - - public CodeWriter ResetIndent() - { - return SetIndent(0); - } - - public CodeWriter IncreaseIndent(int size) - { - CurrentIndent += size; - - return this; - } - - public CodeWriter DecreaseIndent(int size) - { - CurrentIndent -= size; - - return this; - } - - public CodeWriter SetIndent(int size) - { - CurrentIndent = size; - - return this; - } - - public CodeWriter Indent(int size) - { - if (IsAfterNewLine) - { - Builder.Append(' ', size); - - _currentLineCharacterIndex += size; - _absoluteIndex += size; - - _dirty = true; - IsAfterNewLine = false; - } - - return this; - } - - public CodeWriter Write(string data) - { - if (data == null) - { - return this; - } - - return Write(data, 0, data.Length); - } - - public CodeWriter Write(string data, int index, int count) - { - if (data == null || count == 0) - { - return this; - } - - Indent(CurrentIndent); - - Builder.Append(data, index, count); - - _dirty = true; - IsAfterNewLine = false; - - _absoluteIndex += count; - - // The data string might contain a partial newline where the previously - // written string has part of the newline. - var i = index; - int? trailingPartStart = null; - - if ( - // Check the last character of the previous write operation. - Builder.Length - count - 1 >= 0 && - Builder[Builder.Length - count - 1] == '\r' && - - // Check the first character of the current write operation. - Builder[Builder.Length - count] == '\n') - { - // This is newline that's spread across two writes. Skip the first character of the - // current write operation. - // - // We don't need to increment our newline counter because we already did that when we - // saw the \r. - i += 1; - trailingPartStart = 1; - } - - // Iterate the string, stopping at each occurrence of a newline character. This lets us count the - // newline occurrences and keep the index of the last one. - while ((i = data.IndexOfAny(NewLineCharacters, i)) >= 0) - { - // Newline found. - _currentLineIndex++; - _currentLineCharacterIndex = 0; - - i++; - - // We might have stopped at a \r, so check if it's followed by \n and then advance the index to - // start the next search after it. - if (count > i && - data[i - 1] == '\r' && - data[i] == '\n') - { - i++; - } - - // The 'suffix' of the current line starts after this newline token. - trailingPartStart = i; - } - - if (trailingPartStart == null) - { - // No newlines, just add the length of the data buffer - _currentLineCharacterIndex += count; - } - else - { - // Newlines found, add the trailing part of 'data' - _currentLineCharacterIndex += (count - trailingPartStart.Value); - } - - return this; - } - - public CodeWriter WriteLine() - { - Builder.Append(NewLine); - - _currentLineIndex++; - _currentLineCharacterIndex = 0; - _absoluteIndex += NewLine.Length; - - _dirty = true; - IsAfterNewLine = true; - - return this; - } - - public CodeWriter WriteLine(string data) - { - return Write(data).WriteLine(); - } - - public string GenerateCode() - { - if (_dirty) - { - _cache = Builder.ToString(); - _dirty = false; - } - - return _cache; - } - - public SourceLocation GetCurrentSourceLocation() - { - return new SourceLocation(_absoluteIndex, _currentLineIndex, _currentLineCharacterIndex); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - Builder.Clear(); - } - } - - public void Dispose() - { - Dispose(disposing: true); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/ExpressionRenderingMode.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/ExpressionRenderingMode.cs deleted file mode 100644 index 6793a23429..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/ExpressionRenderingMode.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public enum ExpressionRenderingMode - { - /// - /// Indicates that expressions should be written to the output stream - /// - /// - /// If @foo is rendered with WriteToOutput, the code generator would output the following code: - /// - /// Write(foo); - /// - WriteToOutput, - - /// - /// Indicates that expressions should simply be placed as-is in the code, and the context in which - /// the code exists will be used to render it - /// - /// - /// If @foo is rendered with InjectCode, the code generator would output the following code: - /// - /// foo - /// - InjectCode - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedClassContext.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedClassContext.cs deleted file mode 100644 index 2705597fad..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedClassContext.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public struct GeneratedClassContext - { - public static readonly string DefaultWriteMethodName = "Write"; - public static readonly string DefaultWriteLiteralMethodName = "WriteLiteral"; - public static readonly string DefaultExecuteMethodName = "ExecuteAsync"; - public static readonly string DefaultBeginWriteAttributeMethodName = "BeginWriteAttribute"; - public static readonly string DefaultBeginWriteAttributeToMethodName = "BeginWriteAttributeTo"; - public static readonly string DefaultEndWriteAttributeMethodName = "EndWriteAttribute"; - public static readonly string DefaultEndWriteAttributeToMethodName = "EndWriteAttributeTo"; - public static readonly string DefaultWriteAttributeValueMethodName = "WriteAttributeValue"; - public static readonly string DefaultWriteAttributeValueToMethodName = "WriteAttributeValueTo"; - - public static readonly GeneratedClassContext Default = - new GeneratedClassContext( - DefaultExecuteMethodName, - DefaultWriteMethodName, - DefaultWriteLiteralMethodName, - new GeneratedTagHelperContext()); - - public GeneratedClassContext( - string executeMethodName, - string writeMethodName, - string writeLiteralMethodName, - GeneratedTagHelperContext generatedTagHelperContext) - : this() - { - if (generatedTagHelperContext == null) - { - throw new ArgumentNullException(nameof(generatedTagHelperContext)); - } - - if (string.IsNullOrEmpty(executeMethodName)) - { - throw new ArgumentException( - CommonResources.Argument_Cannot_Be_Null_Or_Empty, - nameof(executeMethodName)); - } - if (string.IsNullOrEmpty(writeMethodName)) - { - throw new ArgumentException( - CommonResources.Argument_Cannot_Be_Null_Or_Empty, - nameof(writeMethodName)); - } - if (string.IsNullOrEmpty(writeLiteralMethodName)) - { - throw new ArgumentException( - CommonResources.Argument_Cannot_Be_Null_Or_Empty, - nameof(writeLiteralMethodName)); - } - - GeneratedTagHelperContext = generatedTagHelperContext; - - WriteMethodName = writeMethodName; - WriteLiteralMethodName = writeLiteralMethodName; - ExecuteMethodName = executeMethodName; - - WriteToMethodName = null; - WriteLiteralToMethodName = null; - TemplateTypeName = null; - DefineSectionMethodName = null; - - BeginWriteAttributeMethodName = DefaultBeginWriteAttributeMethodName; - BeginWriteAttributeToMethodName = DefaultBeginWriteAttributeToMethodName; - EndWriteAttributeMethodName = DefaultEndWriteAttributeMethodName; - EndWriteAttributeToMethodName = DefaultEndWriteAttributeToMethodName; - WriteAttributeValueMethodName = DefaultWriteAttributeValueMethodName; - WriteAttributeValueToMethodName = DefaultWriteAttributeValueToMethodName; - } - - public GeneratedClassContext( - string executeMethodName, - string writeMethodName, - string writeLiteralMethodName, - string writeToMethodName, - string writeLiteralToMethodName, - string templateTypeName, - GeneratedTagHelperContext generatedTagHelperContext) - : this(executeMethodName, - writeMethodName, - writeLiteralMethodName, - generatedTagHelperContext) - { - WriteToMethodName = writeToMethodName; - WriteLiteralToMethodName = writeLiteralToMethodName; - TemplateTypeName = templateTypeName; - } - - public GeneratedClassContext( - string executeMethodName, - string writeMethodName, - string writeLiteralMethodName, - string writeToMethodName, - string writeLiteralToMethodName, - string templateTypeName, - string defineSectionMethodName, - GeneratedTagHelperContext generatedTagHelperContext) - : this(executeMethodName, - writeMethodName, - writeLiteralMethodName, - writeToMethodName, - writeLiteralToMethodName, - templateTypeName, - generatedTagHelperContext) - { - DefineSectionMethodName = defineSectionMethodName; - } - - public GeneratedClassContext( - string executeMethodName, - string writeMethodName, - string writeLiteralMethodName, - string writeToMethodName, - string writeLiteralToMethodName, - string templateTypeName, - string defineSectionMethodName, - string beginContextMethodName, - string endContextMethodName, - GeneratedTagHelperContext generatedTagHelperContext) - : this(executeMethodName, - writeMethodName, - writeLiteralMethodName, - writeToMethodName, - writeLiteralToMethodName, - templateTypeName, - defineSectionMethodName, - generatedTagHelperContext) - { - BeginContextMethodName = beginContextMethodName; - EndContextMethodName = endContextMethodName; - } - - // Required Items - public string WriteMethodName { get; } - public string WriteLiteralMethodName { get; } - public string WriteToMethodName { get; } - public string WriteLiteralToMethodName { get; } - public string ExecuteMethodName { get; } - public GeneratedTagHelperContext GeneratedTagHelperContext { get; } - - // Optional Items - public string BeginContextMethodName { get; set; } - public string EndContextMethodName { get; set; } - public string DefineSectionMethodName { get; set; } - public string TemplateTypeName { get; set; } - - public string BeginWriteAttributeMethodName { get; set; } - public string BeginWriteAttributeToMethodName { get; set; } - public string EndWriteAttributeMethodName { get; set; } - public string EndWriteAttributeToMethodName { get; set; } - public string WriteAttributeValueMethodName { get; set; } - public string WriteAttributeValueToMethodName { get; set; } - - public bool AllowSections - { - get { return !string.IsNullOrEmpty(DefineSectionMethodName); } - } - - public bool AllowTemplates - { - get { return !string.IsNullOrEmpty(TemplateTypeName); } - } - - public bool SupportsInstrumentation - { - get { return !string.IsNullOrEmpty(BeginContextMethodName) && !string.IsNullOrEmpty(EndContextMethodName); } - } - - public override bool Equals(object obj) - { - if (!(obj is GeneratedClassContext)) - { - return false; - } - - var other = (GeneratedClassContext)obj; - return string.Equals(DefineSectionMethodName, other.DefineSectionMethodName, StringComparison.Ordinal) && - string.Equals(WriteMethodName, other.WriteMethodName, StringComparison.Ordinal) && - string.Equals(WriteLiteralMethodName, other.WriteLiteralMethodName, StringComparison.Ordinal) && - string.Equals(WriteToMethodName, other.WriteToMethodName, StringComparison.Ordinal) && - string.Equals(WriteLiteralToMethodName, other.WriteLiteralToMethodName, StringComparison.Ordinal) && - string.Equals(ExecuteMethodName, other.ExecuteMethodName, StringComparison.Ordinal) && - string.Equals(TemplateTypeName, other.TemplateTypeName, StringComparison.Ordinal) && - string.Equals(BeginContextMethodName, other.BeginContextMethodName, StringComparison.Ordinal) && - string.Equals(EndContextMethodName, other.EndContextMethodName, StringComparison.Ordinal); - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties. - var hashCodeCombiner = HashCodeCombiner.Start(); - - hashCodeCombiner.Add(WriteMethodName, StringComparer.Ordinal); - hashCodeCombiner.Add(WriteLiteralMethodName, StringComparer.Ordinal); - hashCodeCombiner.Add(WriteToMethodName, StringComparer.Ordinal); - hashCodeCombiner.Add(WriteLiteralToMethodName, StringComparer.Ordinal); - hashCodeCombiner.Add(ExecuteMethodName, StringComparer.Ordinal); - - return hashCodeCombiner; - } - - public static bool operator ==(GeneratedClassContext left, GeneratedClassContext right) - { - return left.Equals(right); - } - - public static bool operator !=(GeneratedClassContext left, GeneratedClassContext right) - { - return !left.Equals(right); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedTagHelperContext.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedTagHelperContext.cs deleted file mode 100644 index b1fe26f76c..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratedTagHelperContext.cs +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - /// - /// Contains necessary information for the tag helper code generation process. - /// - public class GeneratedTagHelperContext - { - /// - /// Instantiates a new instance of the with default values. - /// - public GeneratedTagHelperContext() - { - BeginAddHtmlAttributeValuesMethodName = "BeginAddHtmlAttributeValues"; - EndAddHtmlAttributeValuesMethodName = "EndAddHtmlAttributeValues"; - AddHtmlAttributeValueMethodName = "AddHtmlAttributeValue"; - CreateTagHelperMethodName = "CreateTagHelper"; - RunnerRunAsyncMethodName = "RunAsync"; - ScopeManagerBeginMethodName = "Begin"; - ScopeManagerEndMethodName = "End"; - ExecutionContextAddMethodName = "Add"; - ExecutionContextAddTagHelperAttributeMethodName = "AddTagHelperAttribute"; - ExecutionContextAddHtmlAttributeMethodName = "AddHtmlAttribute"; - ExecutionContextOutputPropertyName = "Output"; - FormatInvalidIndexerAssignmentMethodName = "FormatInvalidIndexerAssignment"; - MarkAsHtmlEncodedMethodName = "Html.Raw"; - StartTagHelperWritingScopeMethodName = "StartTagHelperWritingScope"; - EndTagHelperWritingScopeMethodName = "EndTagHelperWritingScope"; - BeginWriteTagHelperAttributeMethodName = "BeginWriteTagHelperAttribute"; - EndWriteTagHelperAttributeMethodName = "EndWriteTagHelperAttribute"; - RunnerTypeName = "Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner"; - ScopeManagerTypeName = "Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager"; - ExecutionContextTypeName = "Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext"; - TagHelperContentTypeName = "Microsoft.AspNetCore.Razor.TagHelperContent"; - TagHelperContentGetContentMethodName = "GetContent"; - HtmlEncoderPropertyName = "HtmlEncoder"; - TagHelperOutputIsContentModifiedPropertyName = "IsContentModified"; - TagHelperOutputContentPropertyName = "Content"; - ExecutionContextSetOutputContentAsyncMethodName = "SetOutputContentAsync"; - TagHelperAttributeTypeName = "Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute"; - EncodedHtmlStringTypeName = "Microsoft.AspNetCore.Html.HtmlString"; - TagHelperAttributeValuePropertyName = "Value"; - } - - /// - /// The name of the method used to begin the addition of unbound, complex tag helper attributes to - /// TagHelperExecutionContexts. - /// - /// - /// Method signature should be - /// - /// public void BeginAddHtmlAttributeValues( - /// TagHelperExecutionContext executionContext, - /// string attributeName) - /// - /// - public string BeginAddHtmlAttributeValuesMethodName { get; set; } - - /// - /// Method name used to end addition of unbound, complex tag helper attributes to TagHelperExecutionContexts. - /// - /// - /// Method signature should be - /// - /// public void EndAddHtmlAttributeValues( - /// TagHelperExecutionContext executionContext) - /// - /// - public string EndAddHtmlAttributeValuesMethodName { get; set; } - - /// - /// Method name used to add individual components of an unbound, complex tag helper attribute to - /// TagHelperExecutionContexts. - /// - /// - /// Method signature: - /// - /// public void AddHtmlAttributeValues( - /// string prefix, - /// int prefixOffset, - /// string value, - /// int valueOffset, - /// int valueLength, - /// bool isLiteral) - /// - /// - public string AddHtmlAttributeValueMethodName { get; set; } - - /// - /// The name of the method used to create a tag helper. - /// - public string CreateTagHelperMethodName { get; set; } - - /// - /// The name of the method used to run tag helpers. - /// - public string RunnerRunAsyncMethodName { get; set; } - - /// - /// The name of the method used to start a scope. - /// - public string ScopeManagerBeginMethodName { get; set; } - - /// - /// The name of the method used to end a scope. - /// - public string ScopeManagerEndMethodName { get; set; } - - /// - /// The name of the method used to add tag helper attributes. - /// - public string ExecutionContextAddTagHelperAttributeMethodName { get; set; } - - /// - /// The name of the method used to add HTML attributes. - /// - public string ExecutionContextAddHtmlAttributeMethodName { get; set; } - - /// - /// The name of the method used to add tag helpers. - /// - public string ExecutionContextAddMethodName { get; set; } - - /// - /// The property name for the tag helper's output. - /// - public string ExecutionContextOutputPropertyName { get; set; } - - /// - /// The name of the method used to format an error message about using an indexer when the tag helper property - /// is null. - /// - /// - /// Method signature should be - /// - /// public string FormatInvalidIndexerAssignment( - /// string attributeName, // Name of the HTML attribute associated with the indexer. - /// string tagHelperTypeName, // Full name of the tag helper type. - /// string propertyName) // Dictionary property in the tag helper. - /// - /// - public string FormatInvalidIndexerAssignmentMethodName { get; set; } - - /// - /// The name of the method used to wrap a value and mark it as HTML-encoded. - /// - /// Used together with . - public string MarkAsHtmlEncodedMethodName { get; set; } - - /// - /// The name of the method used to start a new writing scope. - /// - public string StartTagHelperWritingScopeMethodName { get; set; } - - /// - /// The name of the method used to end a writing scope. - /// - public string EndTagHelperWritingScopeMethodName { get; set; } - - /// - /// The name of the method used to begin an attribute writing scope. - /// - public string BeginWriteTagHelperAttributeMethodName { get; set; } - - /// - /// The name of the method used to end an attribute writing scope. - /// - public string EndWriteTagHelperAttributeMethodName { get; set; } - - /// - /// The name of the type used to run tag helpers. - /// - public string RunnerTypeName { get; set; } - - /// - /// The name of the type used to create scoped instances. - /// - public string ScopeManagerTypeName { get; set; } - - /// - /// The name of the type describing a specific tag helper scope. - /// - /// - /// Contains information about in-scope tag helpers, HTML attributes, and the tag helpers' output. - /// - public string ExecutionContextTypeName { get; set; } - - /// - /// The name of the type containing tag helper content. - /// - /// - /// Contains the data returned by EndTagHelperWriteScope(). - /// - public string TagHelperContentTypeName { get; set; } - - /// - /// The name of the property containing the HtmlEncoder. - /// - public string HtmlEncoderPropertyName { get; set; } - - /// - /// The name of the method used to convert a TagHelperContent into a . - /// - public string TagHelperContentGetContentMethodName { get; set; } - - /// - /// The name of the property used to indicate the tag helper's content has been modified. - /// - public string TagHelperOutputIsContentModifiedPropertyName { get; set; } - - /// - /// The name of the property for the tag helper's output content. - /// - public string TagHelperOutputContentPropertyName { get; set; } - - /// - /// The name of the method on the property used to execute - /// child content and set the rendered results on its property. - /// - public string ExecutionContextSetOutputContentAsyncMethodName { get; set; } - - /// - /// The name of the type used to represent tag helper attributes. - /// - public string TagHelperAttributeTypeName { get; set; } - - /// - /// The name of the type used to represent encoded content. - /// - public string EncodedHtmlStringTypeName { get; set; } - - /// - /// The name of the Value property of TagHelperAttribute. - /// - public string TagHelperAttributeValuePropertyName { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratorResults.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratorResults.cs deleted file mode 100644 index 053b78c630..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/GeneratorResults.cs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - /// - /// The results of parsing and generating code for a Razor document. - /// - public class GeneratorResults : ParserResults - { - /// - /// Instantiates a new instance. - /// - /// The results of parsing a document. - /// The results of generating code for the document. - /// A for the document. - public GeneratorResults(ParserResults parserResults, - CodeGeneratorResult codeGeneratorResult, - ChunkTree chunkTree) - : this(parserResults.Document, - parserResults.TagHelperDescriptors, - parserResults.ErrorSink, - codeGeneratorResult, - chunkTree) - { - if (parserResults == null) - { - throw new ArgumentNullException(nameof(parserResults)); - } - if (codeGeneratorResult == null) - { - throw new ArgumentNullException(nameof(codeGeneratorResult)); - } - if (chunkTree == null) - { - throw new ArgumentNullException(nameof(chunkTree)); - } - } - - /// - /// Instantiates a new instance. - /// - /// The for the syntax tree. - /// - /// The s that apply to the current Razor document. - /// - /// - /// The used to collect s encountered when parsing the - /// current Razor document. - /// - /// The results of generating code for the document. - /// A for the document. - public GeneratorResults(Block document, - IEnumerable tagHelperDescriptors, - ErrorSink errorSink, - CodeGeneratorResult codeGeneratorResult, - ChunkTree chunkTree) - : base(document, tagHelperDescriptors, errorSink) - { - if (document == null) - { - throw new ArgumentNullException(nameof(document)); - } - - if (tagHelperDescriptors == null) - { - throw new ArgumentNullException(nameof(tagHelperDescriptors)); - } - - if (errorSink == null) - { - throw new ArgumentNullException(nameof(errorSink)); - } - - if (codeGeneratorResult == null) - { - throw new ArgumentNullException(nameof(codeGeneratorResult)); - } - - if (chunkTree == null) - { - throw new ArgumentNullException(nameof(chunkTree)); - } - - GeneratedCode = codeGeneratorResult.Code; - DesignTimeLineMappings = codeGeneratorResult.DesignTimeLineMappings; - ChunkTree = chunkTree; - } - - /// - /// The generated code for the document. - /// - public string GeneratedCode { get; } - - /// - /// s used to project code from a file during design time. - /// - public IList DesignTimeLineMappings { get; } - - /// - /// A for the document. - /// - public ChunkTree ChunkTree { get; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMapping.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMapping.cs deleted file mode 100644 index 337c04d45c..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMapping.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Globalization; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class LineMapping - { - public LineMapping(MappingLocation documentLocation, MappingLocation generatedLocation) - { - DocumentLocation = documentLocation; - GeneratedLocation = generatedLocation; - } - - public MappingLocation DocumentLocation { get; } - - public MappingLocation GeneratedLocation { get; } - - public override bool Equals(object obj) - { - var other = obj as LineMapping; - if (ReferenceEquals(other, null)) - { - return false; - } - - return DocumentLocation.Equals(other.DocumentLocation) && - GeneratedLocation.Equals(other.GeneratedLocation); - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(DocumentLocation); - hashCodeCombiner.Add(GeneratedLocation); - - return hashCodeCombiner; - } - - public static bool operator ==(LineMapping left, LineMapping right) - { - if (ReferenceEquals(left, right)) - { - // Exact equality e.g. both objects are null. - return true; - } - - if (ReferenceEquals(left, null)) - { - return false; - } - - return left.Equals(right); - } - - public static bool operator !=(LineMapping left, LineMapping right) - { - if (ReferenceEquals(left, right)) - { - // Exact equality e.g. both objects are null. - return false; - } - - if (ReferenceEquals(left, null)) - { - return true; - } - - return !left.Equals(right); - } - - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "{0} -> {1}", DocumentLocation, GeneratedLocation); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMappingManager.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMappingManager.cs deleted file mode 100644 index ff8c920b4b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/LineMappingManager.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class LineMappingManager - { - public LineMappingManager() - { - Mappings = new List(); - } - - public List Mappings { get; } - - public void AddMapping(MappingLocation documentLocation, MappingLocation generatedLocation) - { - Mappings.Add(new LineMapping(documentLocation, generatedLocation)); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/MappingLocation.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/MappingLocation.cs deleted file mode 100644 index 03af0e5f13..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/MappingLocation.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class MappingLocation - { - public MappingLocation() - { - } - - public MappingLocation(SourceLocation location, int contentLength) - { - ContentLength = contentLength; - AbsoluteIndex = location.AbsoluteIndex; - LineIndex = location.LineIndex; - CharacterIndex = location.CharacterIndex; - FilePath = location.FilePath; - } - - public int ContentLength { get; } - - public int AbsoluteIndex { get; } - - public int LineIndex { get; } - - public int CharacterIndex { get; } - - public string FilePath { get; } - - public override bool Equals(object obj) - { - var other = obj as MappingLocation; - if (ReferenceEquals(other, null)) - { - return false; - } - - return string.Equals(FilePath, other.FilePath, StringComparison.Ordinal) && - AbsoluteIndex == other.AbsoluteIndex && - ContentLength == other.ContentLength && - LineIndex == other.LineIndex && - CharacterIndex == other.CharacterIndex; - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(FilePath, StringComparer.Ordinal); - hashCodeCombiner.Add(AbsoluteIndex); - hashCodeCombiner.Add(ContentLength); - hashCodeCombiner.Add(LineIndex); - hashCodeCombiner.Add(CharacterIndex); - - return hashCodeCombiner; - } - - public override string ToString() - { - return string.Format( - CultureInfo.CurrentCulture, "({0}:{1},{2} [{3}] {4})", - AbsoluteIndex, - LineIndex, - CharacterIndex, - ContentLength, - FilePath); - } - - public static bool operator ==(MappingLocation left, MappingLocation right) - { - if (ReferenceEquals(left, right)) - { - // Exact equality e.g. both objects are null. - return true; - } - - if (ReferenceEquals(left, null)) - { - return false; - } - - return left.Equals(right); - } - - public static bool operator !=(MappingLocation left, MappingLocation right) - { - if (ReferenceEquals(left, right)) - { - // Exact equality e.g. both objects are null. - return false; - } - - if (ReferenceEquals(left, null)) - { - return true; - } - - return !left.Equals(right); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/TagHelperAttributeValueCodeRenderer.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/TagHelperAttributeValueCodeRenderer.cs deleted file mode 100644 index c16bb0eb57..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/TagHelperAttributeValueCodeRenderer.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - /// - /// Renders code for tag helper property initialization. - /// - public class TagHelperAttributeValueCodeRenderer - { - /// - /// Called during Razor's code generation process to generate code that instantiates the value of the tag - /// helper's property. Last value written should not be or end with a semicolon. - /// - /// - /// The to generate code for. - /// - /// The that's used to write code. - /// A instance that contains - /// information about the current code generation process. - /// - /// that renders the raw value of the HTML attribute. - /// - /// - /// Indicates whether or not the source attribute value contains more than simple text. false for plain - /// C# expressions e.g. "PropertyName". true if the attribute value contain at least one in-line - /// Razor construct e.g. "@(@readonly)". - /// - public virtual void RenderAttributeValue( - TagHelperAttributeDescriptor attributeDescriptor, - CSharpCodeWriter writer, - CodeGeneratorContext context, - Action renderAttributeValue, - bool complexValue) - { - if (attributeDescriptor == null) - { - throw new ArgumentNullException(nameof(attributeDescriptor)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (renderAttributeValue == null) - { - throw new ArgumentNullException(nameof(renderAttributeValue)); - } - - renderAttributeValue(writer); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpBaseTypeVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpBaseTypeVisitor.cs deleted file mode 100644 index 1d5c2b6853..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpBaseTypeVisitor.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CSharpBaseTypeVisitor : CodeVisitor - { - public CSharpBaseTypeVisitor(CSharpCodeWriter writer, CodeGeneratorContext context) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - } - - public string CurrentBaseType { get; set; } - - protected override void Visit(SetBaseTypeChunk chunk) - { - CurrentBaseType = chunk.TypeName; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpCodeVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpCodeVisitor.cs deleted file mode 100644 index 48af0cfb09..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpCodeVisitor.cs +++ /dev/null @@ -1,623 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Globalization; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CSharpCodeVisitor : CodeVisitor - { - private const string ItemParameterName = "item"; - private const string ValueWriterName = "__razor_attribute_value_writer"; - private const string TemplateWriterName = "__razor_template_writer"; - private const string SectionWriterName = "__razor_section_writer"; - private const int MaxStringLiteralLength = 1024; - - private CSharpPaddingBuilder _paddingBuilder; - private CSharpTagHelperCodeRenderer _tagHelperCodeRenderer; - - public CSharpCodeVisitor(CSharpCodeWriter writer, CodeGeneratorContext context) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _paddingBuilder = new CSharpPaddingBuilder(context.Host); - } - - public CSharpTagHelperCodeRenderer TagHelperRenderer - { - get - { - if (_tagHelperCodeRenderer == null) - { - _tagHelperCodeRenderer = new CSharpTagHelperCodeRenderer(this, Writer, Context); - } - - return _tagHelperCodeRenderer; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _tagHelperCodeRenderer = value; - } - } - - /// - /// Method used to write an to the current output. - /// - /// Default is to HTML encode all but a few types. - protected virtual string WriteMethodName - { - get - { - return Context.Host.GeneratedClassContext.WriteMethodName; - } - } - - /// - /// Method used to write an to a specified . - /// - /// Default is to HTML encode all but a few types. - protected virtual string WriteToMethodName - { - get - { - return Context.Host.GeneratedClassContext.WriteToMethodName; - } - } - - /// - /// Gets the method name used to generate WriteAttribute invocations in the rendered page. - /// - /// Defaults to - protected virtual string WriteAttributeValueMethodName => - Context.Host.GeneratedClassContext.WriteAttributeValueMethodName; - - protected override void Visit(TagHelperChunk chunk) - { - TagHelperRenderer.RenderTagHelper(chunk); - } - - protected override void Visit(ParentChunk chunk) - { - Accept(chunk.Children); - } - - protected override void Visit(TemplateChunk chunk) - { - Writer.Write(ItemParameterName).Write(" => ") - .WriteStartNewObject(Context.Host.GeneratedClassContext.TemplateTypeName); - - var currentTargetWriterName = Context.TargetWriterName; - Context.TargetWriterName = TemplateWriterName; - - using (Writer.BuildAsyncLambda(endLine: false, parameterNames: TemplateWriterName)) - { - Accept(chunk.Children); - } - - Context.TargetWriterName = currentTargetWriterName; - - Writer.WriteEndMethodInvocation(false).WriteLine(); - } - - protected override void Visit(ParentLiteralChunk chunk) - { - Debug.Assert(chunk.Children.Count > 1); - - if (Context.Host.DesignTimeMode) - { - // Skip generating the chunk if we're in design time or if the chunk is empty. - return; - } - - var text = chunk.GetText(); - - if (Context.Host.EnableInstrumentation) - { - var start = chunk.Start.AbsoluteIndex; - Writer.WriteStartInstrumentationContext(Context, start, text.Length, isLiteral: true); - } - - RenderStartWriteLiteral(text); - - if (Context.Host.EnableInstrumentation) - { - Writer.WriteEndInstrumentationContext(Context); - } - } - - protected override void Visit(LiteralChunk chunk) - { - if (Context.Host.DesignTimeMode || string.IsNullOrEmpty(chunk.Text)) - { - // Skip generating the chunk if we're in design time or if the chunk is empty. - return; - } - - if (Context.Host.EnableInstrumentation) - { - Writer.WriteStartInstrumentationContext(Context, chunk.Association, isLiteral: true); - } - - RenderStartWriteLiteral(chunk.Text); - - if (Context.Host.EnableInstrumentation) - { - Writer.WriteEndInstrumentationContext(Context); - } - } - - protected override void Visit(ExpressionBlockChunk chunk) - { - if (Context.Host.DesignTimeMode) - { - RenderDesignTimeExpressionBlockChunk(chunk); - } - else - { - RenderRuntimeExpressionBlockChunk(chunk); - } - } - - protected override void Visit(ExpressionChunk chunk) - { - Writer.Write(chunk.Code); - } - - protected override void Visit(StatementChunk chunk) - { - CreateStatementCodeMapping(chunk.Code, chunk); - Writer.WriteLine(); - } - - protected override void Visit(DynamicCodeAttributeChunk chunk) - { - if (Context.Host.DesignTimeMode) - { - // Render the children as is without wrapping them in calls to WriteAttribute - Accept(chunk.Children); - return; - } - - var currentRenderingMode = Context.ExpressionRenderingMode; - var currentTargetWriterName = Context.TargetWriterName; - - CSharpLineMappingWriter lineMappingWriter = null; - var code = chunk.Children.FirstOrDefault(); - if (code is ExpressionChunk || code is ExpressionBlockChunk) - { - // We only want to render the #line pragma if the attribute value will be in-lined. - // Ex: WriteAttributeValue("", 0, DateTime.Now, 0, 0, false) - // For non-inlined scenarios: WriteAttributeValue("", 0, (_) => ..., 0, 0, false) - // the line pragma will be generated inside the lambda. - lineMappingWriter = new CSharpLineMappingWriter(Writer, chunk.Start, Context.SourceFile); - } - - if (!string.IsNullOrEmpty(currentTargetWriterName)) - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.WriteAttributeValueToMethodName) - .Write(currentTargetWriterName) - .WriteParameterSeparator(); - } - else - { - Writer.WriteStartMethodInvocation(WriteAttributeValueMethodName); - } - - Context.TargetWriterName = ValueWriterName; - - if (code is ExpressionChunk || code is ExpressionBlockChunk) - { - Debug.Assert(lineMappingWriter != null); - - Writer - .WriteLocationTaggedString(chunk.Prefix) - .WriteParameterSeparator(); - - Context.ExpressionRenderingMode = ExpressionRenderingMode.InjectCode; - - Accept(code); - - Writer - .WriteParameterSeparator() - .Write(chunk.Start.AbsoluteIndex.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .Write(chunk.Association.Length.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .WriteBooleanLiteral(value: false) - .WriteEndMethodInvocation(); - - lineMappingWriter.Dispose(); - } - else - { - Writer - .WriteLocationTaggedString(chunk.Prefix) - .WriteParameterSeparator() - .WriteStartNewObject(Context.Host.GeneratedClassContext.TemplateTypeName); - - using (Writer.BuildAsyncLambda(endLine: false, parameterNames: ValueWriterName)) - { - Accept(chunk.Children); - } - - Writer - .WriteEndMethodInvocation(false) - .WriteParameterSeparator() - .Write(chunk.Start.AbsoluteIndex.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .Write(chunk.Association.Length.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .WriteBooleanLiteral(false) - .WriteEndMethodInvocation(); - } - - Context.TargetWriterName = currentTargetWriterName; - Context.ExpressionRenderingMode = currentRenderingMode; - } - - protected override void Visit(LiteralCodeAttributeChunk chunk) - { - var visitChildren = chunk.Value == null; - - if (Context.Host.DesignTimeMode) - { - // Render the attribute without wrapping it in a call to WriteAttribute - if (visitChildren) - { - Accept(chunk.Children); - } - - return; - } - - if (!string.IsNullOrEmpty(Context.TargetWriterName)) - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.WriteAttributeValueToMethodName) - .Write(Context.TargetWriterName) - .WriteParameterSeparator(); - } - else - { - Writer.WriteStartMethodInvocation(WriteAttributeValueMethodName); - } - - Writer - .WriteLocationTaggedString(chunk.Prefix) - .WriteParameterSeparator(); - - if (visitChildren) - { - var currentRenderingMode = Context.ExpressionRenderingMode; - Context.ExpressionRenderingMode = ExpressionRenderingMode.InjectCode; - - Accept(chunk.Children); - - Context.ExpressionRenderingMode = currentRenderingMode; - - Writer - .WriteParameterSeparator() - .Write(chunk.ValueLocation.AbsoluteIndex.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .Write(chunk.Association.Length.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .WriteBooleanLiteral(false) - .WriteEndMethodInvocation(); - } - else - { - Writer - .WriteLocationTaggedString(chunk.Value) - .WriteParameterSeparator() - .Write(chunk.Association.Length.ToString(CultureInfo.InvariantCulture)) - .WriteParameterSeparator() - .WriteBooleanLiteral(true) - .WriteEndMethodInvocation(); - } - } - - protected override void Visit(CodeAttributeChunk chunk) - { - if (Context.Host.DesignTimeMode) - { - // Render the attribute without wrapping it in a "WriteAttribute" invocation - Accept(chunk.Children); - - return; - } - - if (!string.IsNullOrEmpty(Context.TargetWriterName)) - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.BeginWriteAttributeToMethodName) - .Write(Context.TargetWriterName) - .WriteParameterSeparator(); - } - else - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.BeginWriteAttributeMethodName); - } - - var attributeCount = chunk.Children.Count(c => c is LiteralCodeAttributeChunk || c is DynamicCodeAttributeChunk); - - Writer.WriteStringLiteral(chunk.Attribute) - .WriteParameterSeparator() - .WriteLocationTaggedString(chunk.Prefix) - .WriteParameterSeparator() - .WriteLocationTaggedString(chunk.Suffix) - .WriteParameterSeparator() - .Write(attributeCount.ToString(CultureInfo.InvariantCulture)) - .WriteEndMethodInvocation(); - - Accept(chunk.Children); - - if (!string.IsNullOrEmpty(Context.TargetWriterName)) - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.EndWriteAttributeToMethodName) - .Write(Context.TargetWriterName) - .WriteEndMethodInvocation(); - } - else - { - Writer.WriteMethodInvocation(Context.Host.GeneratedClassContext.EndWriteAttributeMethodName); - } - } - - protected override void Visit(SectionChunk chunk) - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.DefineSectionMethodName) - .WriteStringLiteral(chunk.Name) - .WriteParameterSeparator(); - - var currentTargetWriterName = Context.TargetWriterName; - Context.TargetWriterName = SectionWriterName; - - using (Writer.BuildAsyncLambda(endLine: false, parameterNames: SectionWriterName)) - { - Accept(chunk.Children); - } - Context.TargetWriterName = currentTargetWriterName; - Writer.WriteEndMethodInvocation(); - } - - public void RenderDesignTimeExpressionBlockChunk(ExpressionBlockChunk chunk) - { - var firstChild = chunk.Children.FirstOrDefault(); - if (firstChild == null) - { - return; - } - - var currentIndent = Writer.CurrentIndent; - Writer.ResetIndent(); - - var documentLocation = firstChild.Association.Start; - - // This is only here to enable accurate formatting by the C# editor. - Writer.WriteLineNumberDirective(documentLocation, Context.SourceFile); - - var designTimeAssignment = "__o = "; - var firstChildExpressionChunk = firstChild as ExpressionChunk; - if (firstChildExpressionChunk != null) - { - // We build the padding with an offset of the design time assignment statement. - Writer.Write(_paddingBuilder.BuildExpressionPadding((Span)firstChildExpressionChunk.Association, designTimeAssignment.Length)) - .Write(designTimeAssignment); - - // We map the first line of code but do not write the line pragmas associated with it. - CreateRawCodeMapping(firstChildExpressionChunk.Code, documentLocation); - - // Render all but the first child. - // The reason why we render the other children differently is because when formatting the C# code - // the formatter expects the start line to have the assignment statement on it. - Accept(chunk.Children.Skip(1).ToList()); - } - else - { - // First child is not an expression chunk - Accept(chunk.Children); - } - - Writer.WriteLine(";") - .WriteLine() - .WriteLineDefaultDirective() - .WriteLineHiddenDirective() - .SetIndent(currentIndent); - } - - public void RenderRuntimeExpressionBlockChunk(ExpressionBlockChunk chunk) - { - // For expression chunks, such as @value, @(value) etc, pick the first Code or Markup span - // from the expression (in this case "value") and use that to calculate the length. This works - // accurately for most parts. The scenarios that don't work are - // (a) Expressions with inline comments (e.g. @(a @* comment *@ b)) - these have multiple code spans - // (b) Expressions with inline templates (e.g. @Foo(@

Hello world

)). - // Tracked via https://github.com/aspnet/Razor/issues/153 - - var block = (Block)chunk.Association; - var contentSpan = block.Children - .OfType() - .FirstOrDefault(s => s.Kind == SpanKind.Code || s.Kind == SpanKind.Markup); - - if (Context.ExpressionRenderingMode == ExpressionRenderingMode.InjectCode) - { - Accept(chunk.Children); - } - else if (Context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput) - { - if (contentSpan != null) - { - RenderRuntimeExpressionBlockChunkWithContentSpan(chunk, contentSpan); - } - else - { - if (!string.IsNullOrEmpty(Context.TargetWriterName)) - { - Writer - .WriteStartMethodInvocation(WriteToMethodName) - .Write(Context.TargetWriterName) - .WriteParameterSeparator(); - } - else - { - Writer.WriteStartMethodInvocation(WriteMethodName); - } - - Accept(chunk.Children); - - Writer.WriteEndMethodInvocation() - .WriteLine(); - } - } - } - - private void RenderRuntimeExpressionBlockChunkWithContentSpan(ExpressionBlockChunk chunk, Span contentSpan) - { - var generateInstrumentation = ShouldGenerateInstrumentationForExpressions(); - - if (generateInstrumentation) - { - Writer.WriteStartInstrumentationContext(Context, contentSpan, isLiteral: false); - } - - using (var mappingWriter = new CSharpLineMappingWriter(Writer, chunk.Start, Context.SourceFile)) - { - if (!string.IsNullOrEmpty(Context.TargetWriterName)) - { - var generatedStart = - WriteToMethodName.Length + - Context.TargetWriterName.Length + - 3; // 1 for the opening '(' and 2 for ', ' - - var padding = _paddingBuilder.BuildExpressionPadding(contentSpan, generatedStart); - - Writer - .Write(padding) - .WriteStartMethodInvocation(WriteToMethodName) - .Write(Context.TargetWriterName) - .WriteParameterSeparator(); - } - else - { - var generatedStart = - WriteMethodName.Length + - 1; // for the opening '(' - - var padding = _paddingBuilder.BuildExpressionPadding(contentSpan, generatedStart); - - Writer - .Write(padding) - .WriteStartMethodInvocation(WriteMethodName); - } - - Accept(chunk.Children); - - Writer.WriteEndMethodInvocation(); - } - - if (generateInstrumentation) - { - Writer.WriteEndInstrumentationContext(Context); - } - } - - public void CreateStatementCodeMapping(string code, Chunk chunk) - { - CreateCodeMapping(_paddingBuilder.BuildStatementPadding((Span)chunk.Association), code, chunk); - } - - public void CreateExpressionCodeMapping(string code, Chunk chunk) - { - CreateCodeMapping(_paddingBuilder.BuildExpressionPadding((Span)chunk.Association), code, chunk); - } - - public void CreateCodeMapping(string padding, string code, Chunk chunk) - { - using (CSharpLineMappingWriter mappingWriter = Writer.BuildLineMapping(chunk.Start, code.Length, Context.SourceFile)) - { - Writer.Write(padding); - - mappingWriter.MarkLineMappingStart(); - Writer.Write(code); - mappingWriter.MarkLineMappingEnd(); - } - } - - // Raw CodeMapping's do not write out line pragmas, they just map code. - public void CreateRawCodeMapping(string code, SourceLocation documentLocation) - { - using (new CSharpLineMappingWriter(Writer, documentLocation, code.Length)) - { - Writer.Write(code); - } - } - - private bool ShouldGenerateInstrumentationForExpressions() - { - // Only generate instrumentation for expression blocks if instrumentation is enabled and we're generating a - // "Write()" statement. - return Context.Host.EnableInstrumentation && - Context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput; - } - - private void RenderStartWriteLiteral(string text) - { - var charactersRendered = 0; - - // Render the string in pieces to avoid Roslyn OOM exceptions at compile time: - // https://github.com/aspnet/External/issues/54 - while (charactersRendered < text.Length) - { - if (Context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput) - { - if (!string.IsNullOrEmpty(Context.TargetWriterName)) - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.WriteLiteralToMethodName) - .Write(Context.TargetWriterName) - .WriteParameterSeparator(); - } - else - { - Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.WriteLiteralMethodName); - } - } - - string textToRender; - if (text.Length <= MaxStringLiteralLength) - { - textToRender = text; - } - else - { - var charactersToSubstring = Math.Min(MaxStringLiteralLength, text.Length - charactersRendered); - textToRender = text.Substring(charactersRendered, charactersToSubstring); - } - - Writer.WriteStringLiteral(textToRender); - charactersRendered += textToRender.Length; - - if (Context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput) - { - Writer.WriteEndMethodInvocation(); - } - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpDesignTimeCodeVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpDesignTimeCodeVisitor.cs deleted file mode 100644 index f9d050dbb2..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpDesignTimeCodeVisitor.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Globalization; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CSharpDesignTimeCodeVisitor : CodeVisitor - { - private const string InheritsHelper = "__inheritsHelper"; - private const string DesignTimeHelperMethodName = "__RazorDesignTimeHelpers__"; - private const string TagHelperDirectiveSyntaxHelper = "__tagHelperDirectiveSyntaxHelper"; - private const int DisableVariableNamingWarnings = 219; - - private bool _initializedTagHelperDirectiveSyntaxHelper; - - public CSharpDesignTimeCodeVisitor( - CSharpCodeVisitor csharpCodeVisitor, - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(writer, context) - { - if (csharpCodeVisitor == null) - { - throw new ArgumentNullException(nameof(csharpCodeVisitor)); - } - - CSharpCodeVisitor = csharpCodeVisitor; - } - - public CSharpCodeVisitor CSharpCodeVisitor { get; } - - public void AcceptTree(ChunkTree tree) - { - if (Context.Host.DesignTimeMode) - { - using (Writer.BuildMethodDeclaration("private", "void", "@" + DesignTimeHelperMethodName)) - { - using (Writer.BuildDisableWarningScope(DisableVariableNamingWarnings)) - { - AcceptTreeCore(tree); - } - } - } - } - - protected virtual void AcceptTreeCore(ChunkTree tree) - { - Accept(tree.Children); - } - - protected override void Visit(SetBaseTypeChunk chunk) - { - Debug.Assert(Context.Host.DesignTimeMode); - - if (chunk.Start != SourceLocation.Undefined) - { - using (var lineMappingWriter = - Writer.BuildLineMapping(chunk.Start, chunk.TypeName.Length, Context.SourceFile)) - { - Writer.Indent(chunk.Start.CharacterIndex); - - lineMappingWriter.MarkLineMappingStart(); - Writer.Write(chunk.TypeName); - lineMappingWriter.MarkLineMappingEnd(); - - Writer.Write(" ").Write(InheritsHelper).Write(" = null;"); - } - } - } - - protected override void Visit(TagHelperPrefixDirectiveChunk chunk) - { - VisitTagHelperDirectiveChunk(chunk); - } - - protected override void Visit(AddTagHelperChunk chunk) - { - VisitTagHelperDirectiveChunk(chunk); - } - - protected override void Visit(RemoveTagHelperChunk chunk) - { - VisitTagHelperDirectiveChunk(chunk); - } - - private void VisitTagHelperDirectiveChunk(Chunk chunk) - { - // We should always be in design time mode because of the calling AcceptTree method verification. - Debug.Assert(Context.Host.DesignTimeMode); - - if (!_initializedTagHelperDirectiveSyntaxHelper) - { - _initializedTagHelperDirectiveSyntaxHelper = true; - Writer.WriteVariableDeclaration("string", TagHelperDirectiveSyntaxHelper, "null"); - } - - var text = ((Span)chunk.Association).Content.Trim(); - - Writer.WriteStartAssignment(TagHelperDirectiveSyntaxHelper); - - if (!text.StartsWith("\"", StringComparison.Ordinal)) - { - Writer.Write("\""); - } - - using (new CSharpLineMappingWriter(Writer, chunk.Start, text.Length)) - { - Writer.Write(text); - } - - if (!text.EndsWith("\"", StringComparison.Ordinal)) - { - Writer.Write("\""); - } - - Writer.WriteLine(";"); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperAttributeValueVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperAttributeValueVisitor.cs deleted file mode 100644 index 7af7c51b26..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperAttributeValueVisitor.cs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - /// - /// that writes code for a non- tag helper - /// bound attribute value. - /// - /// - /// Since attribute value is not written out as HTML, does not emit instrumentation. Further this - /// writes identical code at design- and runtime. - /// - public class CSharpTagHelperAttributeValueVisitor : CodeVisitor - { - private string _attributeTypeName; - private bool _firstChild; - - /// - /// Initializes a new instance of the class. - /// - /// The used to write code. - /// - /// A instance that contains information about the current code generation - /// process. - /// - /// - /// Full name of the property for which this - /// is writing the value. - /// - public CSharpTagHelperAttributeValueVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context, - string attributeTypeName) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _attributeTypeName = attributeTypeName; - } - - /// - /// Writes code for the given . - /// - /// The to render. - /// - /// Tracks code mappings for all children while writing. - /// - protected override void Visit(ParentChunk chunk) - { - // Line mappings are captured in RenderCode(), not this method. - _firstChild = true; - Accept(chunk.Children); - - if (_firstChild) - { - // Attribute value was empty. - Context.ErrorSink.OnError( - chunk.Association.Start, - RazorResources.TagHelpers_AttributeExpressionRequired, - chunk.Association.Length); - } - } - - /// - /// Writes code for the given . - /// - /// The to render. - protected override void Visit(ExpressionBlockChunk chunk) - { - Accept(chunk.Children); - } - - /// - /// Writes code for the given . - /// - /// The to render. - protected override void Visit(ExpressionChunk chunk) - { - RenderCode(chunk.Code, chunk.Start); - } - - /// - /// Writes code for the given . - /// - /// The to render. - protected override void Visit(LiteralChunk chunk) - { - RenderCode(chunk.Text, chunk.Start); - } - - protected override void Visit(ParentLiteralChunk chunk) - { - RenderCode(chunk.GetText(), chunk.Start); - } - - /// - /// Writes code for the given . - /// - /// The to render. - /// - /// Unconditionally adds a to inform user of unexpected @section directive. - /// - protected override void Visit(SectionChunk chunk) - { - Context.ErrorSink.OnError( - chunk.Association.Start, - RazorResources.FormatTagHelpers_Directives_NotSupported_InAttributes( - SyntaxConstants.CSharp.SectionKeyword), - chunk.Association.Length); - } - - /// - /// Writes code for the given . - /// - /// The to render. - /// - /// Unconditionally adds a to inform user of unexpected code block. - /// - protected override void Visit(StatementChunk chunk) - { - Context.ErrorSink.OnError( - chunk.Association.Start, - RazorResources.TagHelpers_CodeBlocks_NotSupported_InAttributes, - chunk.Association.Length); - } - - /// - /// Writes code for the given . - /// - /// The to render. - /// - /// Unconditionally adds a to inform user of unexpected template e.g. - /// @<p>paragraph@</p>. - /// - protected override void Visit(TemplateChunk chunk) - { - Context.ErrorSink.OnError( - chunk.Association.Start, - RazorResources.FormatTagHelpers_InlineMarkupBlocks_NotSupported_InAttributes(_attributeTypeName), - chunk.Association.Length); - } - - // Tracks the code mapping and writes code for a leaf node in the attribute value Chunk tree. - private void RenderCode(string code, SourceLocation start) - { - _firstChild = false; - using (new CSharpLineMappingWriter(Writer, start, code.Length)) - { - Writer.Write(code); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperFieldDeclarationVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperFieldDeclarationVisitor.cs deleted file mode 100644 index 64851406ff..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperFieldDeclarationVisitor.cs +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CSharpTagHelperFieldDeclarationVisitor : CodeVisitor - { - private const string _preAllocatedAttributeVariablePrefix = "__tagHelperAttribute_"; - private readonly HashSet _declaredTagHelpers; - private readonly Dictionary _preAllocatedAttributes; - private readonly GeneratedTagHelperContext _tagHelperContext; - private bool _foundTagHelpers; - - public CSharpTagHelperFieldDeclarationVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _declaredTagHelpers = new HashSet(StringComparer.Ordinal); - _tagHelperContext = Context.Host.GeneratedClassContext.GeneratedTagHelperContext; - _preAllocatedAttributes = new Dictionary(); - } - - protected override void Visit(TagHelperChunk chunk) - { - // We only want to setup tag helper manager fields if there are tag helpers, and only once - if (!_foundTagHelpers) - { - _foundTagHelpers = true; - - // We want to hide declared TagHelper fields so they cannot be stepped over via a debugger. - Writer.WriteLineHiddenDirective(); - - // Runtime fields aren't useful during design time. - if (!Context.Host.DesignTimeMode) - { - // Need to disable the warning "X is assigned to but never used." for the value buffer since - // whether it's used depends on how a TagHelper is used. - Writer.WritePragma("warning disable 0414"); - Writer - .Write("private ") - .WriteVariableDeclaration( - "string", - CSharpTagHelperCodeRenderer.StringValueBufferVariableName, - value: null); - Writer.WritePragma("warning restore 0414"); - - WritePrivateField( - _tagHelperContext.ExecutionContextTypeName, - CSharpTagHelperCodeRenderer.ExecutionContextVariableName, - value: null); - - WritePrivateField( - _tagHelperContext.RunnerTypeName, - CSharpTagHelperCodeRenderer.RunnerVariableName, - value: null); - - WritePrivateField( - _tagHelperContext.ScopeManagerTypeName, - CSharpTagHelperCodeRenderer.ScopeManagerVariableName, - value: null); - } - } - - foreach (var descriptor in chunk.Descriptors) - { - if (!_declaredTagHelpers.Contains(descriptor.TypeName)) - { - _declaredTagHelpers.Add(descriptor.TypeName); - - WritePrivateField( - descriptor.TypeName, - CSharpTagHelperCodeRenderer.GetVariableName(descriptor), - value: null); - } - } - - if (!Context.Host.DesignTimeMode) - { - PreAllocateTagHelperAttributes(chunk); - } - - // We need to dive deeper to ensure we pick up any nested tag helpers. - Accept(chunk.Children); - } - - private void PreAllocateTagHelperAttributes(TagHelperChunk chunk) - { - var boundAttributes = new HashSet(StringComparer.OrdinalIgnoreCase); - for (var i = 0; i < chunk.Attributes.Count; i++) - { - var attribute = chunk.Attributes[i]; - var associatedAttributeDescriptors = chunk.Descriptors.SelectMany(descriptor => descriptor.Attributes) - .Where(attributeDescriptor => attributeDescriptor.IsNameMatch(attribute.Name)); - - // If there's no descriptors associated or is a repeated attribute with same name as a bound attribute, - // it is considered as an unbound attribute. - var isUnBoundAttribute = !associatedAttributeDescriptors.Any() || !boundAttributes.Add(attribute.Name); - - // Perf: We will preallocate TagHelperAttribute for unbound attributes and simple bound string valued attributes. - if (isUnBoundAttribute || CanPreallocateBoundAttribute(associatedAttributeDescriptors, attribute)) - { - string preAllocatedAttributeVariableName = null; - - if (attribute.ValueStyle == HtmlAttributeValueStyle.Minimized) - { - Debug.Assert(attribute.Value == null); - - var preAllocatedAttributeKey = new TagHelperAttributeKey( - attribute.Name, - value: null, - unBoundAttribute: isUnBoundAttribute, - valueStyle: attribute.ValueStyle); - if (TryCachePreallocatedVariableName(preAllocatedAttributeKey, out preAllocatedAttributeVariableName)) - { - Writer - .Write("private static readonly global::") - .Write(_tagHelperContext.TagHelperAttributeTypeName) - .Write(" ") - .Write(preAllocatedAttributeVariableName) - .Write(" = ") - .WriteStartNewObject("global::" + _tagHelperContext.TagHelperAttributeTypeName) - .WriteStringLiteral(attribute.Name) - .WriteEndMethodInvocation(); - } - } - else - { - Debug.Assert(attribute.Value != null); - - string plainText; - if (CSharpTagHelperCodeRenderer.TryGetPlainTextValue(attribute.Value, out plainText)) - { - var preAllocatedAttributeKey = new TagHelperAttributeKey(attribute.Name, plainText, isUnBoundAttribute, attribute.ValueStyle); - if (TryCachePreallocatedVariableName(preAllocatedAttributeKey, out preAllocatedAttributeVariableName)) - { - Writer - .Write("private static readonly global::") - .Write(_tagHelperContext.TagHelperAttributeTypeName) - .Write(" ") - .Write(preAllocatedAttributeVariableName) - .Write(" = ") - .WriteStartNewObject("global::" + _tagHelperContext.TagHelperAttributeTypeName) - .WriteStringLiteral(attribute.Name) - .WriteParameterSeparator(); - - if (isUnBoundAttribute) - { - // For unbound attributes, we need to create HtmlString. - Writer - .WriteStartNewObject("global::" + _tagHelperContext.EncodedHtmlStringTypeName) - .WriteStringLiteral(plainText) - .WriteEndMethodInvocation(endLine: false); - } - else - { - Writer.WriteStringLiteral(plainText); - - } - - Writer - .WriteParameterSeparator() - .Write($"global::{typeof(HtmlAttributeValueStyle).FullName}.{attribute.ValueStyle}") - .WriteEndMethodInvocation(); - } - } - } - - if (preAllocatedAttributeVariableName != null) - { - chunk.Attributes[i] = new TagHelperAttributeTracker( - attribute.Name, - new PreallocatedTagHelperAttributeChunk - { - AttributeVariableAccessor = preAllocatedAttributeVariableName - }, - attribute.ValueStyle); - } - } - } - } - - private static bool CanPreallocateBoundAttribute( - IEnumerable associatedAttributeDescriptors, - TagHelperAttributeTracker attribute) - { - // If the attribute value is a Dynamic value, it cannot be preallocated. - if (CSharpTagHelperCodeRenderer.IsDynamicAttributeValue(attribute.Value)) - { - return false; - } - - // Only attributes that are associated with string typed properties can be preallocated. - var attributeName = attribute.Name; - var allStringProperties = associatedAttributeDescriptors - .All(attributeDescriptor => attributeDescriptor.IsStringProperty); - - return allStringProperties; - } - - public override void Accept(Chunk chunk) - { - if (chunk == null) - { - throw new ArgumentNullException(nameof(chunk)); - } - - var parentChunk = chunk as ParentChunk; - - // If we're any ParentChunk other than TagHelperChunk then we want to dive into its Children - // to search for more TagHelperChunk chunks. This if-statement enables us to not override - // each of the special ParentChunk types and then dive into their children. - if (parentChunk != null && !(parentChunk is TagHelperChunk)) - { - Accept(parentChunk.Children); - } - else - { - // If we're a TagHelperChunk or any other non ParentChunk we ".Accept" it. This ensures - // that our overridden Visit(TagHelperChunk) method gets called and is not skipped over. - // If we're a non ParentChunk or a TagHelperChunk then we want to just invoke the Visit - // method for that given chunk (base.Accept indirectly calls the Visit method). - base.Accept(chunk); - } - } - - private bool TryCachePreallocatedVariableName(TagHelperAttributeKey key, out string preAllocatedAttributeVariableName) - { - if (!_preAllocatedAttributes.TryGetValue(key, out preAllocatedAttributeVariableName)) - { - preAllocatedAttributeVariableName = _preAllocatedAttributeVariablePrefix + _preAllocatedAttributes.Count; - _preAllocatedAttributes[key] = preAllocatedAttributeVariableName; - return true; - } - - return false; - } - - private void WritePrivateField(string type, string name, string value) - { - Writer - .Write("private global::") - .WriteVariableDeclaration(type, name, value); - } - - private struct TagHelperAttributeKey : IEquatable - { - public TagHelperAttributeKey(string name, string value, bool unBoundAttribute, HtmlAttributeValueStyle valueStyle) - { - Name = name; - Value = value; - UnBoundAttribute = unBoundAttribute; - ValueStyle = valueStyle; - } - - public string Name { get; } - - public string Value { get; } - - public bool UnBoundAttribute { get; } - - public HtmlAttributeValueStyle ValueStyle { get; } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(Name, StringComparer.Ordinal); - hashCodeCombiner.Add(Value, StringComparer.Ordinal); - hashCodeCombiner.Add(UnBoundAttribute); - hashCodeCombiner.Add(ValueStyle); - - return hashCodeCombiner.CombinedHash; - } - - public override bool Equals(object obj) - { - var other = obj as TagHelperAttributeKey?; - - if (other != null) - { - return Equals(other.Value); - } - - return false; - } - - public bool Equals(TagHelperAttributeKey other) - { - return string.Equals(Name, other.Name, StringComparison.Ordinal) && - string.Equals(Value, other.Value, StringComparison.Ordinal) && - UnBoundAttribute == other.UnBoundAttribute && - ValueStyle == other.ValueStyle; - } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperPropertyInitializationVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperPropertyInitializationVisitor.cs deleted file mode 100644 index 4408443f1a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTagHelperPropertyInitializationVisitor.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - /// - /// The that generates the code to initialize the TagHelperRunner. - /// - public class CSharpTagHelperPropertyInitializationVisitor : CodeVisitor - { - private readonly GeneratedTagHelperContext _tagHelperContext; - private bool _foundTagHelpers; - - /// - /// Creates a new instance of . - /// - /// The used to generate code. - /// The . - public CSharpTagHelperPropertyInitializationVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _tagHelperContext = Context.Host.GeneratedClassContext.GeneratedTagHelperContext; - } - - /// - public override void Accept(Chunk chunk) - { - if (chunk == null) - { - throw new ArgumentNullException(nameof(chunk)); - } - - // If at any ParentChunk other than a TagHelperChunk, then dive into its Children to search for more - // TagHelperChunk nodes. This method avoids overriding each of the ParentChunk-specific Visit() methods to - // dive into Children. - var parentChunk = chunk as ParentChunk; - if (parentChunk != null && !(parentChunk is TagHelperChunk)) - { - Accept(parentChunk.Children); - } - else - { - // If at a TagHelperChunk or any non-ParentChunk, "Accept()" it. This ensures the Visit(TagHelperChunk) - // method below is called. - base.Accept(chunk); - } - } - - /// - /// Writes the TagHelperRunner initialization code to the Writer. - /// - /// The . - protected override void Visit(TagHelperChunk chunk) - { - if (!_foundTagHelpers && !Context.Host.DesignTimeMode) - { - _foundTagHelpers = true; - - Writer - .WriteStartAssignment(CSharpTagHelperCodeRenderer.RunnerVariableName) - .Write(CSharpTagHelperCodeRenderer.RunnerVariableName) - .Write(" ?? ") - .WriteStartNewObject("global::" + _tagHelperContext.RunnerTypeName) - .WriteEndMethodInvocation(); - - Writer - .WriteStartAssignment(CSharpTagHelperCodeRenderer.ScopeManagerVariableName) - .Write(CSharpTagHelperCodeRenderer.ScopeManagerVariableName) - .Write(" ?? ") - .WriteStartNewObject("global::" + _tagHelperContext.ScopeManagerTypeName) - .Write(_tagHelperContext.StartTagHelperWritingScopeMethodName) - .WriteParameterSeparator() - .Write(_tagHelperContext.EndTagHelperWritingScopeMethodName) - .WriteEndMethodInvocation(); - } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTypeMemberVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTypeMemberVisitor.cs deleted file mode 100644 index 386e4b3289..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpTypeMemberVisitor.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CSharpTypeMemberVisitor : CodeVisitor - { - private CSharpCodeVisitor _csharpCodeVisitor; - - public CSharpTypeMemberVisitor(CSharpCodeVisitor csharpCodeVisitor, - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(writer, context) - { - if (csharpCodeVisitor == null) - { - throw new ArgumentNullException(nameof(csharpCodeVisitor)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - _csharpCodeVisitor = csharpCodeVisitor; - } - - protected override void Visit(TypeMemberChunk chunk) - { - if (!string.IsNullOrEmpty(chunk.Code)) - { - _csharpCodeVisitor.CreateCodeMapping(string.Empty, chunk.Code, chunk); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpUsingVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpUsingVisitor.cs deleted file mode 100644 index d1bc7db4c0..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CSharpUsingVisitor.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CSharpUsingVisitor : CodeVisitor - { - public CSharpUsingVisitor(CSharpCodeWriter writer, CodeGeneratorContext context) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - ImportedUsings = new HashSet(StringComparer.Ordinal); - } - - public HashSet ImportedUsings { get; set; } - - /// - public override void Accept(Chunk chunk) - { - if (chunk == null) - { - throw new ArgumentNullException(nameof(chunk)); - } - - // If at any ParentChunk other than a TagHelperChunk, then dive into its Children to search for more - // TagHelperChunk or UsingChunk nodes. This method avoids overriding each of the ParentChunk-specific - // Visit() methods to dive into Children. - var parentChunk = chunk as ParentChunk; - if (parentChunk != null && !(parentChunk is TagHelperChunk)) - { - Accept(parentChunk.Children); - } - else - { - // If at a TagHelperChunk or any non-ParentChunk (e.g. UsingChunk), "Accept()" it. This ensures the - // Visit(UsingChunk) and Visit(TagHelperChunk) methods below are called. - base.Accept(chunk); - } - } - - protected override void Visit(UsingChunk chunk) - { - var documentContent = ((Span)chunk.Association).Content.Trim(); - var mapSemicolon = false; - - if (documentContent.LastOrDefault() == ';') - { - mapSemicolon = true; - } - - ImportedUsings.Add(chunk.Namespace); - - // Depending on if the user has a semicolon in their @using statement we have to conditionally decide - // to include the semicolon in the line mapping. - using (Writer.BuildLineMapping(chunk.Start, documentContent.Length, Context.SourceFile)) - { - Writer.WriteUsing(chunk.Namespace, endLine: false); - - if (mapSemicolon) - { - Writer.Write(";"); - } - } - - if (!mapSemicolon) - { - Writer.WriteLine(";"); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/ChunkVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/ChunkVisitor.cs deleted file mode 100644 index 30d919e69b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/ChunkVisitor.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Chunks; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public abstract class ChunkVisitor : IChunkVisitor - where TWriter : CodeWriter - { - public ChunkVisitor(TWriter writer, CodeGeneratorContext context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - Writer = writer; - Context = context; - } - - protected TWriter Writer { get; private set; } - protected CodeGeneratorContext Context { get; private set; } - - public void Accept(IList chunks) - { - if (chunks == null) - { - throw new ArgumentNullException(nameof(chunks)); - } - - foreach (Chunk chunk in chunks) - { - Accept(chunk); - } - } - - public virtual void Accept(Chunk chunk) - { - if (chunk == null) - { - throw new ArgumentNullException(nameof(chunk)); - } - - if (chunk is LiteralChunk) - { - Visit((LiteralChunk)chunk); - } - else if (chunk is ParentLiteralChunk) - { - Visit((ParentLiteralChunk)chunk); - } - else if (chunk is ExpressionBlockChunk) - { - Visit((ExpressionBlockChunk)chunk); - } - else if (chunk is ExpressionChunk) - { - Visit((ExpressionChunk)chunk); - } - else if (chunk is StatementChunk) - { - Visit((StatementChunk)chunk); - } - else if (chunk is TagHelperChunk) - { - Visit((TagHelperChunk)chunk); - } - else if (chunk is TagHelperPrefixDirectiveChunk) - { - Visit((TagHelperPrefixDirectiveChunk)chunk); - } - else if (chunk is AddTagHelperChunk) - { - Visit((AddTagHelperChunk)chunk); - } - else if (chunk is RemoveTagHelperChunk) - { - Visit((RemoveTagHelperChunk)chunk); - } - else if (chunk is TypeMemberChunk) - { - Visit((TypeMemberChunk)chunk); - } - else if (chunk is UsingChunk) - { - Visit((UsingChunk)chunk); - } - else if (chunk is SetBaseTypeChunk) - { - Visit((SetBaseTypeChunk)chunk); - } - else if (chunk is DynamicCodeAttributeChunk) - { - Visit((DynamicCodeAttributeChunk)chunk); - } - else if (chunk is LiteralCodeAttributeChunk) - { - Visit((LiteralCodeAttributeChunk)chunk); - } - else if (chunk is CodeAttributeChunk) - { - Visit((CodeAttributeChunk)chunk); - } - else if (chunk is SectionChunk) - { - Visit((SectionChunk)chunk); - } - else if (chunk is TemplateChunk) - { - Visit((TemplateChunk)chunk); - } - else if (chunk is ParentChunk) - { - Visit((ParentChunk)chunk); - } - } - - protected abstract void Visit(LiteralChunk chunk); - protected abstract void Visit(ParentLiteralChunk chunk); - protected abstract void Visit(ExpressionChunk chunk); - protected abstract void Visit(StatementChunk chunk); - protected abstract void Visit(TagHelperChunk chunk); - protected abstract void Visit(TagHelperPrefixDirectiveChunk chunk); - protected abstract void Visit(AddTagHelperChunk chunk); - protected abstract void Visit(RemoveTagHelperChunk chunk); - protected abstract void Visit(UsingChunk chunk); - protected abstract void Visit(ParentChunk chunk); - protected abstract void Visit(DynamicCodeAttributeChunk chunk); - protected abstract void Visit(LiteralCodeAttributeChunk chunk); - protected abstract void Visit(CodeAttributeChunk chunk); - protected abstract void Visit(SectionChunk chunk); - protected abstract void Visit(TypeMemberChunk chunk); - protected abstract void Visit(SetBaseTypeChunk chunk); - protected abstract void Visit(TemplateChunk chunk); - protected abstract void Visit(ExpressionBlockChunk chunk); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CodeVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CodeVisitor.cs deleted file mode 100644 index 93ff94a122..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/CodeVisitor.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public class CodeVisitor : ChunkVisitor - where TWriter : CodeWriter - { - public CodeVisitor(TWriter writer, CodeGeneratorContext context) - : base(writer, context) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - } - - protected override void Visit(LiteralChunk chunk) - { - } - protected override void Visit(ParentLiteralChunk chunk) - { - } - protected override void Visit(ExpressionBlockChunk chunk) - { - } - protected override void Visit(ExpressionChunk chunk) - { - } - protected override void Visit(StatementChunk chunk) - { - } - protected override void Visit(UsingChunk chunk) - { - } - protected override void Visit(ParentChunk chunk) - { - } - protected override void Visit(DynamicCodeAttributeChunk chunk) - { - } - protected override void Visit(TagHelperChunk chunk) - { - } - protected override void Visit(TagHelperPrefixDirectiveChunk chunk) - { - } - protected override void Visit(AddTagHelperChunk chunk) - { - } - protected override void Visit(RemoveTagHelperChunk chunk) - { - } - protected override void Visit(LiteralCodeAttributeChunk chunk) - { - } - protected override void Visit(CodeAttributeChunk chunk) - { - } - protected override void Visit(SectionChunk chunk) - { - } - protected override void Visit(TypeMemberChunk chunk) - { - } - protected override void Visit(SetBaseTypeChunk chunk) - { - } - protected override void Visit(TemplateChunk chunk) - { - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/IChunkVisitor.cs b/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/IChunkVisitor.cs deleted file mode 100644 index 489b83bc5a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CodeGenerators/Visitors/IChunkVisitor.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Chunks; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators.Visitors -{ - public interface IChunkVisitor - { - void Accept(IList chunks); - void Accept(Chunk chunk); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/CommonResources.resx b/src/Microsoft.AspNetCore.Razor/CommonResources.resx deleted file mode 100644 index 7cc5d5ecd7..0000000000 --- a/src/Microsoft.AspNetCore.Razor/CommonResources.resx +++ /dev/null @@ -1,144 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Value cannot be null or an empty string. - - - Value must be between {0} and {1}. - - - Value must be a value from the "{0}" enumeration. - - - Value must be greater than {0}. - - - Value must be greater than or equal to {0}. - - - Value must be less than {0}. - - - Value must be less than or equal to {0}. - - - Value cannot be an empty string. It must either be null or a non-empty string. - - \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/ITagHelperDescriptorResolver.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/ITagHelperDescriptorResolver.cs deleted file mode 100644 index 46616487f1..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/ITagHelperDescriptorResolver.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// Contract used to resolve s. - /// - public interface ITagHelperDescriptorResolver - { - /// - /// Resolves s based on the given . - /// - /// - /// used to resolve descriptors for the Razor page. - /// - /// An of s based - /// on the given . - IEnumerable Resolve(TagHelperDescriptorResolutionContext resolutionContext); - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDescriptor.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDescriptor.cs deleted file mode 100644 index ccb9a77feb..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDescriptor.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Reflection; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// A metadata class describing a tag helper attribute. - /// - public class TagHelperAttributeDescriptor - { - private string _typeName; - private string _name; - private string _propertyName; - - /// - /// Instantiates a new instance of the class. - /// - public TagHelperAttributeDescriptor() - { - } - - // Internal for testing i.e. for easy TagHelperAttributeDescriptor creation when PropertyInfo is available. - internal TagHelperAttributeDescriptor(string name, PropertyInfo propertyInfo) - { - Name = name; - PropertyName = propertyInfo.Name; - TypeName = propertyInfo.PropertyType.FullName; - IsEnum = propertyInfo.PropertyType.GetTypeInfo().IsEnum; - } - - /// - /// Gets an indication whether this is used for dictionary indexer - /// assignments. - /// - /// - /// If true this should be associated with all HTML - /// attributes that have names starting with . Otherwise this - /// is used for property assignment and is only associated with an - /// HTML attribute that has the exact . - /// - /// - /// HTML attribute names are matched case-insensitively, regardless of . - /// - public bool IsIndexer { get; set; } - - /// - /// Gets or sets an indication whether this property is an . - /// - public bool IsEnum { get; set; } - - /// - /// Gets or sets an indication whether this property is of type or, if - /// is true, whether the indexer's value is of type . - /// - /// - /// If true the is for . This causes the Razor parser - /// to allow empty values for HTML attributes matching this . If - /// false empty values for such matching attributes lead to errors. - /// - public bool IsStringProperty { get; set; } - - /// - /// The HTML attribute name or, if is true, the prefix for matching attribute - /// names. - /// - public string Name - { - get - { - return _name; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _name = value; - } - } - - - /// - /// The name of the CLR property that corresponds to the HTML attribute. - /// - public string PropertyName - { - get - { - return _propertyName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _propertyName = value; - } - } - - /// - /// The full name of the named (see ) property's or, if - /// is true, the full name of the indexer's value . - /// - public string TypeName - { - get - { - return _typeName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _typeName = value; - IsStringProperty = string.Equals(TypeName, typeof(string).FullName, StringComparison.Ordinal); - } - } - - /// - /// The that contains design time information about - /// this attribute. - /// - public TagHelperAttributeDesignTimeDescriptor DesignTimeDescriptor { get; set; } - - /// - /// Determines whether HTML attribute matches this - /// . - /// - /// Name of the HTML attribute to check. - /// - /// true if this matches . - /// false otherwise. - /// - public bool IsNameMatch(string name) - { - if (IsIndexer) - { - return name.StartsWith(Name, StringComparison.OrdinalIgnoreCase); - } - else - { - return string.Equals(name, Name, StringComparison.OrdinalIgnoreCase); - } - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDesignTimeDescriptor.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDesignTimeDescriptor.cs deleted file mode 100644 index 69be466b0b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperAttributeDesignTimeDescriptor.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// A metadata class containing information about tag helper use. - /// - public class TagHelperAttributeDesignTimeDescriptor - { - /// - /// A summary of how to use a tag helper. - /// - public string Summary { get; set; } - - /// - /// Remarks about how to use a tag helper. - /// - public string Remarks { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptor.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptor.cs deleted file mode 100644 index b3188dcc33..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptor.cs +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// A metadata class describing a tag helper. - /// - public class TagHelperDescriptor - { - private string _prefix = string.Empty; - private string _tagName; - private string _typeName; - private string _assemblyName; - private IDictionary _propertyBag; - private IEnumerable _attributes = - Enumerable.Empty(); - private IEnumerable _requiredAttributes = - Enumerable.Empty(); - - /// - /// Creates a new . - /// - public TagHelperDescriptor() - { - } - - /// - /// Creates a shallow copy of the given . - /// - /// The to copy. - public TagHelperDescriptor (TagHelperDescriptor descriptor) - { - Prefix = descriptor.Prefix; - TagName = descriptor.TagName; - TypeName = descriptor.TypeName; - AssemblyName = descriptor.AssemblyName; - Attributes = descriptor.Attributes; - RequiredAttributes = descriptor.RequiredAttributes; - AllowedChildren = descriptor.AllowedChildren; - RequiredParent = descriptor.RequiredParent; - TagStructure = descriptor.TagStructure; - DesignTimeDescriptor = descriptor.DesignTimeDescriptor; - - foreach (var property in descriptor.PropertyBag) - { - PropertyBag.Add(property.Key, property.Value); - } - } - - /// - /// Text used as a required prefix when matching HTML start and end tags in the Razor source to available - /// tag helpers. - /// - public string Prefix - { - get - { - return _prefix; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _prefix = value; - } - } - - /// - /// The tag name that the tag helper should target. - /// - public string TagName - { - get - { - return _tagName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _tagName = value; - } - } - - /// - /// The full tag name that is required for the tag helper to target an HTML element. - /// - /// This is equivalent to and concatenated. - public string FullTagName - { - get - { - return Prefix + TagName; - } - } - - /// - /// The full name of the tag helper class. - /// - public string TypeName - { - get - { - return _typeName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _typeName = value; - } - } - - /// - /// The name of the assembly containing the tag helper class. - /// - public string AssemblyName - { - get - { - return _assemblyName; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _assemblyName = value; - } - } - - /// - /// The list of attributes the tag helper expects. - /// - public IEnumerable Attributes - { - get - { - return _attributes; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _attributes = value; - } - } - - /// - /// The list of required attribute names the tag helper expects to target an element. - /// - /// - /// * at the end of an attribute name acts as a prefix match. - /// - public IEnumerable RequiredAttributes - { - get - { - return _requiredAttributes; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _requiredAttributes = value; - } - } - - /// - /// Get the names of elements allowed as children. - /// - /// null indicates all children are allowed. - public IEnumerable AllowedChildren { get; set; } - - /// - /// Get the name of the HTML element required as the immediate parent. - /// - /// null indicates no restriction on parent tag. - public string RequiredParent { get; set; } - - /// - /// The expected tag structure. - /// - /// - /// If and no other tag helpers applying to the same element specify - /// their the behavior is used: - /// - /// - /// <my-tag-helper></my-tag-helper> - /// <!-- OR --> - /// <my-tag-helper /> - /// - /// Otherwise, if another tag helper applying to the same element does specify their behavior, that behavior - /// is used. - /// - /// - /// If HTML elements can be written in the following formats: - /// - /// <my-tag-helper> - /// <!-- OR --> - /// <my-tag-helper /> - /// - /// - /// - public TagStructure TagStructure { get; set; } - - /// - /// The that contains design time information about this - /// tag helper. - /// - public TagHelperDesignTimeDescriptor DesignTimeDescriptor { get; set; } - - /// - /// A dictionary containing additional information about the . - /// - public IDictionary PropertyBag - { - get - { - if (_propertyBag == null) - { - _propertyBag = new Dictionary(); - } - - return _propertyBag; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorComparer.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorComparer.cs deleted file mode 100644 index cde2d5ba31..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorComparer.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// An used to check equality between - /// two s. - /// - public class TagHelperDescriptorComparer : IEqualityComparer - { - /// - /// A default instance of the . - /// - public static readonly TagHelperDescriptorComparer Default = new TagHelperDescriptorComparer(); - - /// - /// Initializes a new instance. - /// - protected TagHelperDescriptorComparer() - { - } - - /// - /// - /// Determines equality based on , - /// , , - /// , , - /// and . - /// Ignores because it can be inferred directly from - /// and . - /// - public virtual bool Equals(TagHelperDescriptor descriptorX, TagHelperDescriptor descriptorY) - { - if (object.ReferenceEquals(descriptorX, descriptorY)) - { - return true; - } - - if (descriptorX == null ^ descriptorY == null) - { - return false; - } - - return descriptorX != null && - string.Equals(descriptorX.TypeName, descriptorY.TypeName, StringComparison.Ordinal) && - string.Equals(descriptorX.TagName, descriptorY.TagName, StringComparison.OrdinalIgnoreCase) && - string.Equals(descriptorX.AssemblyName, descriptorY.AssemblyName, StringComparison.Ordinal) && - string.Equals( - descriptorX.RequiredParent, - descriptorY.RequiredParent, - StringComparison.OrdinalIgnoreCase) && - Enumerable.SequenceEqual( - descriptorX.RequiredAttributes.OrderBy(attribute => attribute.Name, StringComparer.OrdinalIgnoreCase), - descriptorY.RequiredAttributes.OrderBy(attribute => attribute.Name, StringComparer.OrdinalIgnoreCase), - TagHelperRequiredAttributeDescriptorComparer.Default) && - (descriptorX.AllowedChildren == descriptorY.AllowedChildren || - (descriptorX.AllowedChildren != null && - descriptorY.AllowedChildren != null && - Enumerable.SequenceEqual( - descriptorX.AllowedChildren.OrderBy(child => child, StringComparer.OrdinalIgnoreCase), - descriptorY.AllowedChildren.OrderBy(child => child, StringComparer.OrdinalIgnoreCase), - StringComparer.OrdinalIgnoreCase))) && - descriptorX.TagStructure == descriptorY.TagStructure && - Enumerable.SequenceEqual( - descriptorX.PropertyBag.OrderBy(propertyX => propertyX.Key, StringComparer.Ordinal), - descriptorY.PropertyBag.OrderBy(propertyY => propertyY.Key, StringComparer.Ordinal)); - } - - /// - public virtual int GetHashCode(TagHelperDescriptor descriptor) - { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } - - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(descriptor.TypeName, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.TagName, StringComparer.OrdinalIgnoreCase); - hashCodeCombiner.Add(descriptor.AssemblyName, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.RequiredParent, StringComparer.OrdinalIgnoreCase); - hashCodeCombiner.Add(descriptor.TagStructure); - - var attributes = descriptor.RequiredAttributes.OrderBy( - attribute => attribute.Name, - StringComparer.OrdinalIgnoreCase); - foreach (var attribute in attributes) - { - hashCodeCombiner.Add(TagHelperRequiredAttributeDescriptorComparer.Default.GetHashCode(attribute)); - } - - if (descriptor.AllowedChildren != null) - { - var allowedChildren = descriptor.AllowedChildren.OrderBy(child => child, StringComparer.OrdinalIgnoreCase); - foreach (var child in allowedChildren) - { - hashCodeCombiner.Add(child, StringComparer.OrdinalIgnoreCase); - } - } - - return hashCodeCombiner.CombinedHash; - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorProvider.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorProvider.cs deleted file mode 100644 index d3b540e060..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorProvider.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// Enables retrieval of 's. - /// - public class TagHelperDescriptorProvider - { - public const string ElementCatchAllTarget = "*"; - - private IDictionary> _registrations; - private string _tagHelperPrefix; - - /// - /// Instantiates a new instance of the . - /// - /// The descriptors that the will pull from. - public TagHelperDescriptorProvider(IEnumerable descriptors) - { - _registrations = new Dictionary>(StringComparer.OrdinalIgnoreCase); - - // Populate our registrations - foreach (var descriptor in descriptors) - { - Register(descriptor); - } - } - - /// - /// Gets all tag helpers that match the given . - /// - /// The name of the HTML tag to match. Providing a '*' tag name - /// retrieves catch-all s (descriptors that target every tag). - /// Attributes the HTML element must contain to match. - /// The parent tag name of the given tag. - /// s that apply to the given . - /// Will return an empty if no s are - /// found. - public IEnumerable GetDescriptors( - string tagName, - IEnumerable> attributes, - string parentTagName) - { - if (!string.IsNullOrEmpty(_tagHelperPrefix) && - (tagName.Length <= _tagHelperPrefix.Length || - !tagName.StartsWith(_tagHelperPrefix, StringComparison.OrdinalIgnoreCase))) - { - // The tagName doesn't have the tag helper prefix, we can short circuit. - return Enumerable.Empty(); - } - - HashSet catchAllDescriptors; - IEnumerable descriptors; - - // Ensure there's a HashSet to use. - if (!_registrations.TryGetValue(ElementCatchAllTarget, out catchAllDescriptors)) - { - descriptors = new HashSet(TagHelperDescriptorComparer.Default); - } - else - { - descriptors = catchAllDescriptors; - } - - // If we have a tag name associated with the requested name, we need to combine matchingDescriptors - // with all the catch-all descriptors. - HashSet matchingDescriptors; - if (_registrations.TryGetValue(tagName, out matchingDescriptors)) - { - descriptors = matchingDescriptors.Concat(descriptors); - } - - var applicableDescriptors = new List(); - foreach (var descriptor in descriptors) - { - if (HasRequiredAttributes(descriptor, attributes) && - HasRequiredParentTag(descriptor, parentTagName)) - { - applicableDescriptors.Add(descriptor); - } - } - - return applicableDescriptors; - } - - private bool HasRequiredParentTag( - TagHelperDescriptor descriptor, - string parentTagName) - { - return descriptor.RequiredParent == null || - string.Equals(parentTagName, descriptor.RequiredParent, StringComparison.OrdinalIgnoreCase); - } - - private bool HasRequiredAttributes( - TagHelperDescriptor descriptor, - IEnumerable> attributes) - { - return descriptor.RequiredAttributes.All( - requiredAttribute => attributes.Any( - attribute => requiredAttribute.IsMatch(attribute.Key, attribute.Value))); - } - - private void Register(TagHelperDescriptor descriptor) - { - HashSet descriptorSet; - - if (_tagHelperPrefix == null) - { - _tagHelperPrefix = descriptor.Prefix; - } - - var registrationKey = - string.Equals(descriptor.TagName, ElementCatchAllTarget, StringComparison.Ordinal) ? - ElementCatchAllTarget : - descriptor.FullTagName; - - // Ensure there's a HashSet to add the descriptor to. - if (!_registrations.TryGetValue(registrationKey, out descriptorSet)) - { - descriptorSet = new HashSet(TagHelperDescriptorComparer.Default); - _registrations[registrationKey] = descriptorSet; - } - - descriptorSet.Add(descriptor); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorResolutionContext.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorResolutionContext.cs deleted file mode 100644 index 0f983b5c1a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDescriptorResolutionContext.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// Contains information needed to resolve s. - /// - public class TagHelperDescriptorResolutionContext - { - // Internal for testing purposes - internal TagHelperDescriptorResolutionContext(IEnumerable directiveDescriptors) - : this(directiveDescriptors, new ErrorSink()) - { - } - - /// - /// Instantiates a new instance of . - /// - /// s used to resolve - /// s. - /// Used to aggregate s. - public TagHelperDescriptorResolutionContext( - IEnumerable directiveDescriptors, - ErrorSink errorSink) - { - if (directiveDescriptors == null) - { - throw new ArgumentNullException(nameof(directiveDescriptors)); - } - - if (errorSink == null) - { - throw new ArgumentNullException(nameof(errorSink)); - } - - DirectiveDescriptors = new List(directiveDescriptors); - ErrorSink = errorSink; - } - - /// - /// s used to resolve s. - /// - public IList DirectiveDescriptors { get; private set; } - - /// - /// Used to aggregate s. - /// - public ErrorSink ErrorSink { get; private set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDesignTimeDescriptor.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDesignTimeDescriptor.cs deleted file mode 100644 index 1bfd99c078..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDesignTimeDescriptor.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// A metadata class containing design time information about a tag helper. - /// - public class TagHelperDesignTimeDescriptor - { - /// - /// A summary of how to use a tag helper. - /// - public string Summary { get; set; } - - /// - /// Remarks about how to use a tag helper. - /// - public string Remarks { get; set; } - - /// - /// The HTML element a tag helper may output. - /// - /// - /// In IDEs supporting IntelliSense, may override the HTML information provided at design time. - /// - public string OutputElementHint { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveDescriptor.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveDescriptor.cs deleted file mode 100644 index ef59e2951c..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveDescriptor.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// Contains information needed to resolve s. - /// - public class TagHelperDirectiveDescriptor - { - private string _directiveText; - - /// - /// A used to find tag helper s. - /// - public string DirectiveText - { - get - { - return _directiveText; - } - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - _directiveText = value; - } - } - - /// - /// The of the directive. - /// - public SourceLocation Location { get; set; } = SourceLocation.Zero; - - /// - /// The of this directive. - /// - public TagHelperDirectiveType DirectiveType { get; set; } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveType.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveType.cs deleted file mode 100644 index c062d0f626..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperDirectiveType.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// The type of tag helper directive. - /// - public enum TagHelperDirectiveType - { - /// - /// An @addTagHelper directive. - /// - AddTagHelper, - - /// - /// A @removeTagHelper directive. - /// - RemoveTagHelper, - - /// - /// A @tagHelperPrefix directive. - /// - TagHelperPrefix - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptor.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptor.cs deleted file mode 100644 index b813cbf5ec..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptor.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Linq; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// A metadata class describing a required tag helper attribute. - /// - public class TagHelperRequiredAttributeDescriptor - { - /// - /// The HTML attribute name. - /// - public string Name { get; set; } - - /// - /// The comparison method to use for when determining if an HTML attribute name matches. - /// - public TagHelperRequiredAttributeNameComparison NameComparison { get; set; } - - /// - /// The HTML attribute value. - /// - public string Value { get; set; } - - /// - /// The comparison method to use for when determining if an HTML attribute value matches. - /// - public TagHelperRequiredAttributeValueComparison ValueComparison { get; set; } - - /// - /// Determines if the current matches the given - /// and . - /// - /// An HTML attribute name. - /// An HTML attribute value. - /// true if the current matches - /// and ; false otherwise. - public bool IsMatch(string attributeName, string attributeValue) - { - var nameMatches = false; - if (NameComparison == TagHelperRequiredAttributeNameComparison.FullMatch) - { - nameMatches = string.Equals(Name, attributeName, StringComparison.OrdinalIgnoreCase); - } - else if (NameComparison == TagHelperRequiredAttributeNameComparison.PrefixMatch) - { - // attributeName cannot equal the Name if comparing as a PrefixMatch. - nameMatches = attributeName.Length != Name.Length && - attributeName.StartsWith(Name, StringComparison.OrdinalIgnoreCase); - } - else - { - Debug.Assert(false, "Unknown name comparison."); - } - - if (!nameMatches) - { - return false; - } - - switch (ValueComparison) - { - case TagHelperRequiredAttributeValueComparison.None: - return true; - case TagHelperRequiredAttributeValueComparison.PrefixMatch: // Value starts with - return attributeValue.StartsWith(Value, StringComparison.Ordinal); - case TagHelperRequiredAttributeValueComparison.SuffixMatch: // Value ends with - return attributeValue.EndsWith(Value, StringComparison.Ordinal); - case TagHelperRequiredAttributeValueComparison.FullMatch: // Value equals - return string.Equals(attributeValue, Value, StringComparison.Ordinal); - default: - Debug.Assert(false, "Unknown value comparison."); - return false; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorComparer.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorComparer.cs deleted file mode 100644 index da600b517c..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorComparer.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// An used to check equality between - /// two s. - /// - public class TagHelperRequiredAttributeDescriptorComparer : IEqualityComparer - { - /// - /// A default instance of the . - /// - public static readonly TagHelperRequiredAttributeDescriptorComparer Default = - new TagHelperRequiredAttributeDescriptorComparer(); - - /// - /// Initializes a new instance. - /// - protected TagHelperRequiredAttributeDescriptorComparer() - { - } - - /// - public virtual bool Equals( - TagHelperRequiredAttributeDescriptor descriptorX, - TagHelperRequiredAttributeDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - return descriptorX != null && - descriptorX.NameComparison == descriptorY.NameComparison && - descriptorX.ValueComparison == descriptorY.ValueComparison && - string.Equals(descriptorX.Name, descriptorY.Name, StringComparison.OrdinalIgnoreCase) && - string.Equals(descriptorX.Value, descriptorY.Value, StringComparison.Ordinal); - } - - /// - public virtual int GetHashCode(TagHelperRequiredAttributeDescriptor descriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(descriptor.NameComparison); - hashCodeCombiner.Add(descriptor.ValueComparison); - hashCodeCombiner.Add(descriptor.Name, StringComparer.OrdinalIgnoreCase); - hashCodeCombiner.Add(descriptor.Value, StringComparer.Ordinal); - - return hashCodeCombiner.CombinedHash; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeNameComparison.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeNameComparison.cs deleted file mode 100644 index 46c76ea1e5..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeNameComparison.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// Acceptable comparison modes. - /// - public enum TagHelperRequiredAttributeNameComparison - { - /// - /// HTML attribute name case insensitively matches . - /// - FullMatch, - - /// - /// HTML attribute name case insensitively starts with . - /// - PrefixMatch, - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeValueComparison.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeValueComparison.cs deleted file mode 100644 index f84ab8c0ff..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TagHelperRequiredAttributeValueComparison.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// Acceptable comparison modes. - /// - public enum TagHelperRequiredAttributeValueComparison - { - /// - /// HTML attribute value always matches . - /// - None, - - /// - /// HTML attribute value case sensitively matches . - /// - FullMatch, - - /// - /// HTML attribute value case sensitively starts with . - /// - PrefixMatch, - - /// - /// HTML attribute value case sensitively ends with . - /// - SuffixMatch, - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TypeBasedTagHelperDescriptorComparer.cs b/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TypeBasedTagHelperDescriptorComparer.cs deleted file mode 100644 index 473cf1bdac..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Compilation/TagHelpers/TypeBasedTagHelperDescriptorComparer.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - /// - /// An that checks equality between two - /// s using only their s and - /// s. - /// - /// - /// This class is intended for scenarios where Reflection-based information is all important i.e. - /// , , and related - /// properties are not relevant. - /// - public class TypeBasedTagHelperDescriptorComparer : IEqualityComparer - { - /// - /// A default instance of the . - /// - public static readonly TypeBasedTagHelperDescriptorComparer Default = - new TypeBasedTagHelperDescriptorComparer(); - - private TypeBasedTagHelperDescriptorComparer() - { - } - - /// - /// - /// Determines equality based on and - /// . - /// - public bool Equals(TagHelperDescriptor descriptorX, TagHelperDescriptor descriptorY) - { - if (descriptorX == descriptorY) - { - return true; - } - - return descriptorX != null && - string.Equals(descriptorX.AssemblyName, descriptorY.AssemblyName, StringComparison.Ordinal) && - string.Equals(descriptorX.TypeName, descriptorY.TypeName, StringComparison.Ordinal); - } - - /// - public int GetHashCode(TagHelperDescriptor descriptor) - { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } - - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(descriptor.AssemblyName, StringComparer.Ordinal); - hashCodeCombiner.Add(descriptor.TypeName, StringComparer.Ordinal); - - return hashCodeCombiner; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/DocumentParseCompleteEventArgs.cs b/src/Microsoft.AspNetCore.Razor/DocumentParseCompleteEventArgs.cs deleted file mode 100644 index 17b18b67a0..0000000000 --- a/src/Microsoft.AspNetCore.Razor/DocumentParseCompleteEventArgs.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor -{ - /// - /// Arguments for the DocumentParseComplete event in RazorEditorParser - /// - public class DocumentParseCompleteEventArgs : EventArgs - { - /// - /// Indicates if the tree structure has actually changed since the previous re-parse. - /// - public bool TreeStructureChanged { get; set; } - - /// - /// The results of the chunk generation and parsing - /// - public GeneratorResults GeneratorResults { get; set; } - - /// - /// The TextChange which triggered the re-parse - /// - public TextChange SourceChange { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/AutoCompleteEditHandler.cs b/src/Microsoft.AspNetCore.Razor/Editor/AutoCompleteEditHandler.cs deleted file mode 100644 index 421a9c034d..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/AutoCompleteEditHandler.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class AutoCompleteEditHandler : SpanEditHandler - { - private static readonly int TypeHashCode = typeof(AutoCompleteEditHandler).GetHashCode(); - - public AutoCompleteEditHandler(Func> tokenizer) - : base(tokenizer) - { - } - - public AutoCompleteEditHandler(Func> tokenizer, bool autoCompleteAtEndOfSpan) - : this(tokenizer) - { - AutoCompleteAtEndOfSpan = autoCompleteAtEndOfSpan; - } - - public AutoCompleteEditHandler(Func> tokenizer, AcceptedCharacters accepted) - : base(tokenizer, accepted) - { - } - - public bool AutoCompleteAtEndOfSpan { get; } - - public string AutoCompleteString { get; set; } - - protected override PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange) - { - if (((AutoCompleteAtEndOfSpan && IsAtEndOfSpan(target, normalizedChange)) || IsAtEndOfFirstLine(target, normalizedChange)) && - normalizedChange.IsInsert && - ParserHelpers.IsNewLine(normalizedChange.NewText) && - AutoCompleteString != null) - { - return PartialParseResult.Rejected | PartialParseResult.AutoCompleteBlock; - } - return PartialParseResult.Rejected; - } - - public override string ToString() - { - return base.ToString() + ",AutoComplete:[" + (AutoCompleteString ?? "") + "]" + (AutoCompleteAtEndOfSpan ? ";AtEnd" : ";AtEOL"); - } - - public override bool Equals(object obj) - { - var other = obj as AutoCompleteEditHandler; - return base.Equals(other) && - string.Equals(other.AutoCompleteString, AutoCompleteString, StringComparison.Ordinal) && - AutoCompleteAtEndOfSpan == other.AutoCompleteAtEndOfSpan; - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties but Equals also checks the type. - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(TypeHashCode); - hashCodeCombiner.Add(AutoCompleteAtEndOfSpan); - - return hashCodeCombiner.CombinedHash; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/BackgroundParser.cs b/src/Microsoft.AspNetCore.Razor/Editor/BackgroundParser.cs deleted file mode 100644 index b7ec764d34..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/BackgroundParser.cs +++ /dev/null @@ -1,487 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - internal class BackgroundParser : IDisposable - { - private MainThreadState _main; - private BackgroundThread _bg; - - public BackgroundParser(RazorEngineHost host, string fileName) - { - _main = new MainThreadState(fileName); - _bg = new BackgroundThread(_main, host, fileName); - - _main.ResultsReady += (sender, args) => OnResultsReady(args); - } - - /// - /// Fired on the main thread. - /// - public event EventHandler ResultsReady; - - public bool IsIdle - { - get { return _main.IsIdle; } - } - - public void Start() - { - _bg.Start(); - } - - public void Cancel() - { - _main.Cancel(); - } - - public void QueueChange(TextChange change) - { - _main.QueueChange(change); - } - - public void Dispose() - { - _main.Cancel(); - } - - public IDisposable SynchronizeMainThreadState() - { - return _main.Lock(); - } - - protected virtual void OnResultsReady(DocumentParseCompleteEventArgs args) - { - var handler = ResultsReady; - if (handler != null) - { - handler(this, args); - } - } - - internal static bool TreesAreDifferent(Block leftTree, Block rightTree, IEnumerable changes) - { - return TreesAreDifferent(leftTree, rightTree, changes, CancellationToken.None); - } - - internal static bool TreesAreDifferent(Block leftTree, Block rightTree, IEnumerable changes, CancellationToken cancelToken) - { - // Apply all the pending changes to the original tree - // PERF: If this becomes a bottleneck, we can probably do it the other way around, - // i.e. visit the tree and find applicable changes for each node. - foreach (TextChange change in changes) - { - cancelToken.ThrowIfCancellationRequested(); - var changeOwner = leftTree.LocateOwner(change); - - // Apply the change to the tree - if (changeOwner == null) - { - return true; - } - var result = changeOwner.EditHandler.ApplyChange(changeOwner, change, force: true); - changeOwner.ReplaceWith(result.EditedSpan); - } - - // Now compare the trees - var treesDifferent = !leftTree.EquivalentTo(rightTree); - return treesDifferent; - } - - private abstract class ThreadStateBase - { -#if DEBUG - private int _id = -1; -#endif - protected ThreadStateBase() - { - } - - [Conditional("DEBUG")] - protected void SetThreadId(int id) - { -#if DEBUG - _id = id; -#endif - } - - [Conditional("DEBUG")] - protected void EnsureOnThread() - { -#if DEBUG - Debug.Assert(_id != -1, "SetThreadId was never called!"); - Debug.Assert(Thread.CurrentThread.ManagedThreadId == _id, "Called from an unexpected thread!"); -#endif - } - - [Conditional("DEBUG")] - protected void EnsureNotOnThread() - { -#if DEBUG - Debug.Assert(_id != -1, "SetThreadId was never called!"); - Debug.Assert(Thread.CurrentThread.ManagedThreadId != _id, "Called from an unexpected thread!"); -#endif - } - } - - private class MainThreadState : ThreadStateBase, IDisposable - { - private readonly CancellationTokenSource _cancelSource = new CancellationTokenSource(); - private readonly ManualResetEventSlim _hasParcel = new ManualResetEventSlim(false); - private CancellationTokenSource _currentParcelCancelSource; - - private string _fileName; - private readonly object _stateLock = new object(); - private IList _changes = new List(); - - public MainThreadState(string fileName) - { - _fileName = fileName; - - SetThreadId(Thread.CurrentThread.ManagedThreadId); - } - - public event EventHandler ResultsReady; - - public CancellationToken CancelToken - { - get { return _cancelSource.Token; } - } - - public bool IsIdle - { - get - { - lock (_stateLock) - { - return _currentParcelCancelSource == null; - } - } - } - - public void Cancel() - { - EnsureOnThread(); - _cancelSource.Cancel(); - } - - public IDisposable Lock() - { - Monitor.Enter(_stateLock); - return new DisposableAction(() => Monitor.Exit(_stateLock)); - } - - public void QueueChange(TextChange change) - { - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_QueuingParse(Path.GetFileName(_fileName), change)); - EnsureOnThread(); - lock (_stateLock) - { - // CurrentParcel token source is not null ==> There's a parse underway - if (_currentParcelCancelSource != null) - { - _currentParcelCancelSource.Cancel(); - } - - _changes.Add(change); - _hasParcel.Set(); - } - } - - public WorkParcel GetParcel() - { - EnsureNotOnThread(); // Only the background thread can get a parcel - _hasParcel.Wait(_cancelSource.Token); - _hasParcel.Reset(); - lock (_stateLock) - { - // Create a cancellation source for this parcel - _currentParcelCancelSource = new CancellationTokenSource(); - - var changes = _changes; - _changes = new List(); - return new WorkParcel(changes, _currentParcelCancelSource.Token); - } - } - - public void ReturnParcel(DocumentParseCompleteEventArgs args) - { - lock (_stateLock) - { - // Clear the current parcel cancellation source - if (_currentParcelCancelSource != null) - { - _currentParcelCancelSource.Dispose(); - _currentParcelCancelSource = null; - } - - // If there are things waiting to be parsed, just don't fire the event because we're already out of date - if (_changes.Any()) - { - return; - } - } - var handler = ResultsReady; - if (handler != null) - { - handler(this, args); - } - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - if (_currentParcelCancelSource != null) - { - _currentParcelCancelSource.Dispose(); - _currentParcelCancelSource = null; - } - _cancelSource.Dispose(); - _hasParcel.Dispose(); - } - } - } - - private class BackgroundThread : ThreadStateBase - { - private MainThreadState _main; - private Thread _backgroundThread; - private CancellationToken _shutdownToken; - private RazorEngineHost _host; - private string _fileName; - private Block _currentParseTree; - private IList _previouslyDiscarded = new List(); - - public BackgroundThread(MainThreadState main, RazorEngineHost host, string fileName) - { - // Run on MAIN thread! - _main = main; - _backgroundThread = new Thread(WorkerLoop); - _shutdownToken = _main.CancelToken; - _host = host; - _fileName = fileName; - - SetThreadId(_backgroundThread.ManagedThreadId); - } - - // **** ANY THREAD **** - public void Start() - { - _backgroundThread.Start(); - } - - // **** BACKGROUND THREAD **** - private void WorkerLoop() - { - long? elapsedMs = null; - var fileNameOnly = Path.GetFileName(_fileName); -#if EDITOR_TRACING - var sw = new Stopwatch(); -#endif - - try - { - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_BackgroundThreadStart(fileNameOnly)); - EnsureOnThread(); - -#if NETSTANDARD1_3 - var spinWait = new SpinWait(); -#endif - - while (!_shutdownToken.IsCancellationRequested) - { - // Grab the parcel of work to do - var parcel = _main.GetParcel(); - if (parcel.Changes.Any()) - { - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_ChangesArrived(fileNameOnly, parcel.Changes.Count)); - try - { - DocumentParseCompleteEventArgs args = null; - using (var linkedCancel = CancellationTokenSource.CreateLinkedTokenSource(_shutdownToken, parcel.CancelToken)) - { - if (!linkedCancel.IsCancellationRequested) - { - // Collect ALL changes -#if EDITOR_TRACING - if (_previouslyDiscarded != null && _previouslyDiscarded.Any()) - { - RazorEditorTrace.TraceLine(RazorResources.Trace_CollectedDiscardedChanges, fileNameOnly, _previouslyDiscarded.Count); - } -#endif - List allChanges; - - if (_previouslyDiscarded != null) - { - allChanges = Enumerable.Concat(_previouslyDiscarded, parcel.Changes).ToList(); - } - else - { - allChanges = parcel.Changes.ToList(); - } - - var finalChange = allChanges.Last(); -#if EDITOR_TRACING - sw.Start(); -#endif - var results = ParseChange(finalChange.NewBuffer, linkedCancel.Token); -#if EDITOR_TRACING - sw.Stop(); - elapsedMs = sw.ElapsedMilliseconds; - sw.Reset(); -#endif - RazorEditorTrace.TraceLine( - RazorResources.FormatTrace_ParseComplete( - fileNameOnly, - elapsedMs.HasValue ? elapsedMs.Value.ToString(CultureInfo.InvariantCulture) : "?")); - - if (results != null && !linkedCancel.IsCancellationRequested) - { - // Clear discarded changes list - _previouslyDiscarded = null; - - // Take the current tree and check for differences -#if EDITOR_TRACING - sw.Start(); -#endif - var treeStructureChanged = _currentParseTree == null || TreesAreDifferent(_currentParseTree, results.Document, allChanges, parcel.CancelToken); -#if EDITOR_TRACING - sw.Stop(); - elapsedMs = sw.ElapsedMilliseconds; - sw.Reset(); -#endif - _currentParseTree = results.Document; - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_TreesCompared( - fileNameOnly, - elapsedMs.HasValue ? elapsedMs.Value.ToString(CultureInfo.InvariantCulture) : "?", - treeStructureChanged)); - - // Build Arguments - args = new DocumentParseCompleteEventArgs() - { - GeneratorResults = results, - SourceChange = finalChange, - TreeStructureChanged = treeStructureChanged - }; - } - else - { - // Parse completed but we were cancelled in the mean time. Add these to the discarded changes set - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_ChangesDiscarded(fileNameOnly, allChanges.Count)); - _previouslyDiscarded = allChanges; - } - -#if CHECK_TREE - if (args != null) - { - // Rewind the buffer and sanity check the line mappings - finalChange.NewBuffer.Position = 0; - var lineCount = finalChange.NewBuffer.ReadToEnd().Split(new string[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.None).Count(); - Debug.Assert( - !args.GeneratorResults.DesignTimeLineMappings.Any(pair => pair.Value.StartLine > lineCount), - "Found a design-time line mapping referring to a line outside the source file!"); - Debug.Assert( - !args.GeneratorResults.Document.Flatten().Any(span => span.Start.LineIndex > lineCount), - "Found a span with a line number outside the source file"); - Debug.Assert( - !args.GeneratorResults.Document.Flatten().Any(span => span.Start.AbsoluteIndex > parcel.NewBuffer.Length), - "Found a span with an absolute offset outside the source file"); - } -#endif - } - } - if (args != null) - { - _main.ReturnParcel(args); - } - } - catch (OperationCanceledException) - { - } - } - else - { - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_NoChangesArrived(fileNameOnly)); -#if NETSTANDARD1_3 - // This does the equivalent of thread.yield under the covers. - spinWait.SpinOnce(); -#else - // No Yield in CoreCLR - - Thread.Yield(); -#endif - } - } - } - catch (OperationCanceledException) - { - // Do nothing. Just shut down. - } - finally - { - RazorEditorTrace.TraceLine(RazorResources.FormatTrace_BackgroundThreadShutdown(fileNameOnly)); - - // Clean up main thread resources - _main.Dispose(); - } - } - - private GeneratorResults ParseChange(ITextBuffer buffer, CancellationToken token) - { - EnsureOnThread(); - - // Create a template engine - var engine = new RazorTemplateEngine(_host); - - // Seek the buffer to the beginning - buffer.Position = 0; - - try - { - return engine.GenerateCode( - input: buffer, - className: null, - rootNamespace: null, - sourceFileName: _fileName, - cancelToken: token); - } - catch (OperationCanceledException) - { - return null; - } - } - } - - private class WorkParcel - { - public WorkParcel(IList changes, CancellationToken cancelToken) - { - Changes = changes; - CancelToken = cancelToken; - } - - public CancellationToken CancelToken { get; private set; } - public IList Changes { get; private set; } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/EditResult.cs b/src/Microsoft.AspNetCore.Razor/Editor/EditResult.cs deleted file mode 100644 index fddaf473e5..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/EditResult.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class EditResult - { - public EditResult(PartialParseResult result, SpanBuilder editedSpan) - { - Result = result; - EditedSpan = editedSpan; - } - - public PartialParseResult Result { get; set; } - public SpanBuilder EditedSpan { get; set; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/EditorHints.cs b/src/Microsoft.AspNetCore.Razor/Editor/EditorHints.cs deleted file mode 100644 index 719fa01e54..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/EditorHints.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - /// - /// This class is obsolete and will be removed in a future version. - /// - [Flags] - [Obsolete("This class is obsolete and will be removed in a future version.")] - public enum EditorHints - { - /// - /// The default (Markup or Code) editor behavior for Statement completion should be used. - /// Editors can always use the default behavior, even if the span is labeled with a different CompletionType. - /// - None = 0, // 0000 0000 - - /// - /// Indicates that Virtual Path completion should be used for this span if the editor supports it. - /// Editors need not support this mode of completion, and will use the default () behavior - /// if they do not support it. - /// - VirtualPath = 1, // 0000 0001 - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/ImplicitExpressionEditHandler.cs b/src/Microsoft.AspNetCore.Razor/Editor/ImplicitExpressionEditHandler.cs deleted file mode 100644 index 5edeaa8e2e..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/ImplicitExpressionEditHandler.cs +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class ImplicitExpressionEditHandler : SpanEditHandler - { - private readonly ISet _keywords; - private readonly IReadOnlyCollection _readOnlyKeywords; - - public ImplicitExpressionEditHandler(Func> tokenizer, ISet keywords, bool acceptTrailingDot) - : base(tokenizer) - { - _keywords = keywords ?? new HashSet(); - - // HashSet implements IReadOnlyCollection as of 4.6, but does not for 4.5.1. If the runtime cast - // succeeds, avoid creating a new collection. - _readOnlyKeywords = (_keywords as IReadOnlyCollection) ?? _keywords.ToArray(); - - AcceptTrailingDot = acceptTrailingDot; - } - - public bool AcceptTrailingDot { get; } - - public IReadOnlyCollection Keywords - { - get - { - return _readOnlyKeywords; - } - } - - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "{0};ImplicitExpression[{1}];K{2}", base.ToString(), AcceptTrailingDot ? "ATD" : "RTD", Keywords.Count); - } - - public override bool Equals(object obj) - { - var other = obj as ImplicitExpressionEditHandler; - return base.Equals(other) && - _keywords.SetEquals(other._keywords) && - AcceptTrailingDot == other.AcceptTrailingDot; - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties and base has none. - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(Keywords); - hashCodeCombiner.Add(AcceptTrailingDot); - - return hashCodeCombiner; - } - - protected override PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange) - { - if (AcceptedCharacters == AcceptedCharacters.Any) - { - return PartialParseResult.Rejected; - } - - // In some editors intellisense insertions are handled as "dotless commits". If an intellisense selection is confirmed - // via something like '.' a dotless commit will append a '.' and then insert the remaining intellisense selection prior - // to the appended '.'. This 'if' statement attempts to accept the intermediate steps of a dotless commit via - // intellisense. It will accept two cases: - // 1. '@foo.' -> '@foobaz.'. - // 2. '@foobaz..' -> '@foobaz.bar.'. Includes Sub-cases '@foobaz()..' -> '@foobaz().bar.' etc. - // The key distinction being the double '.' in the second case. - if (IsDotlessCommitInsertion(target, normalizedChange)) - { - return HandleDotlessCommitInsertion(target); - } - - if (IsAcceptableIdentifierReplacement(target, normalizedChange)) - { - return TryAcceptChange(target, normalizedChange); - } - - if (IsAcceptableReplace(target, normalizedChange)) - { - return HandleReplacement(target, normalizedChange); - } - var changeRelativePosition = normalizedChange.OldPosition - target.Start.AbsoluteIndex; - - // Get the edit context - char? lastChar = null; - if (changeRelativePosition > 0 && target.Content.Length > 0) - { - lastChar = target.Content[changeRelativePosition - 1]; - } - - // Don't support 0->1 length edits - if (lastChar == null) - { - return PartialParseResult.Rejected; - } - - // Accepts cases when insertions are made at the end of a span or '.' is inserted within a span. - if (IsAcceptableInsertion(target, normalizedChange)) - { - // Handle the insertion - return HandleInsertion(target, lastChar.Value, normalizedChange); - } - - if (IsAcceptableDeletion(target, normalizedChange)) - { - return HandleDeletion(target, lastChar.Value, normalizedChange); - } - - return PartialParseResult.Rejected; - } - - // A dotless commit is the process of inserting a '.' with an intellisense selection. - private static bool IsDotlessCommitInsertion(Span target, TextChange change) - { - return IsNewDotlessCommitInsertion(target, change) || IsSecondaryDotlessCommitInsertion(target, change); - } - - // Completing 'DateTime' in intellisense with a '.' could result in: '@DateT' -> '@DateT.' -> '@DateTime.' which is accepted. - private static bool IsNewDotlessCommitInsertion(Span target, TextChange change) - { - return !IsAtEndOfSpan(target, change) && - change.NewPosition > 0 && - change.NewLength > 0 && - target.Content.Last() == '.' && - ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false) && - (change.OldLength == 0 || ParserHelpers.IsIdentifier(change.OldText, requireIdentifierStart: false)); - } - - // Once a dotless commit has been performed you then have something like '@DateTime.'. This scenario is used to detect the - // situation when you try to perform another dotless commit resulting in a textchange with '..'. Completing 'DateTime.Now' - // in intellisense with a '.' could result in: '@DateTime.' -> '@DateTime..' -> '@DateTime.Now.' which is accepted. - private static bool IsSecondaryDotlessCommitInsertion(Span target, TextChange change) - { - // Do not need to worry about other punctuation, just looking for double '.' (after change) - return change.NewLength == 1 && - !string.IsNullOrEmpty(target.Content) && - target.Content.Last() == '.' && - change.NewText == "." && - change.OldLength == 0; - } - - private static bool IsAcceptableReplace(Span target, TextChange change) - { - return IsEndReplace(target, change) || - (change.IsReplace && RemainingIsWhitespace(target, change)); - } - - private bool IsAcceptableIdentifierReplacement(Span target, TextChange change) - { - if (!change.IsReplace) - { - return false; - } - - for (var i = 0; i < target.Symbols.Count; i++) - { - var symbol = target.Symbols[i] as CSharpSymbol; - - if (symbol == null) - { - break; - } - - var symbolStartIndex = target.Start.AbsoluteIndex + symbol.Start.AbsoluteIndex; - var symbolEndIndex = symbolStartIndex + symbol.Content.Length; - - // We're looking for the first symbol that contains the TextChange. - if (symbolEndIndex > change.OldPosition) - { - if (symbolEndIndex >= change.OldPosition + change.OldLength && symbol.Type == CSharpSymbolType.Identifier) - { - // The symbol we're changing happens to be an identifier. Need to check if its transformed state is also one. - // We do this transformation logic to capture the case that the new text change happens to not be an identifier; - // i.e. "5". Alone, it's numeric, within an identifier it's classified as identifier. - var transformedContent = change.ApplyChange(symbol.Content, symbolStartIndex); - var newSymbols = Tokenizer(transformedContent); - - if (newSymbols.Count() != 1) - { - // The transformed content resulted in more than one symbol; we can only replace a single identifier with - // another single identifier. - break; - } - - var newSymbol = (CSharpSymbol)newSymbols.First(); - if (newSymbol.Type == CSharpSymbolType.Identifier) - { - return true; - } - } - - // Change is touching a non-identifier symbol or spans multiple symbols. - - break; - } - } - - return false; - } - - private static bool IsAcceptableDeletion(Span target, TextChange change) - { - return IsEndDeletion(target, change) || - (change.IsDelete && RemainingIsWhitespace(target, change)); - } - - // Acceptable insertions can occur at the end of a span or when a '.' is inserted within a span. - private static bool IsAcceptableInsertion(Span target, TextChange change) - { - return change.IsInsert && - (IsAcceptableEndInsertion(target, change) || - IsAcceptableInnerInsertion(target, change)); - } - - // Accepts character insertions at the end of spans. AKA: '@foo' -> '@fooo' or '@foo' -> '@foo ' etc. - private static bool IsAcceptableEndInsertion(Span target, TextChange change) - { - Debug.Assert(change.IsInsert); - - return IsAtEndOfSpan(target, change) || - RemainingIsWhitespace(target, change); - } - - // Accepts '.' insertions in the middle of spans. Ex: '@foo.baz.bar' -> '@foo..baz.bar' - // This is meant to allow intellisense when editing a span. - private static bool IsAcceptableInnerInsertion(Span target, TextChange change) - { - Debug.Assert(change.IsInsert); - - // Ensure that we're actually inserting in the middle of a span and not at the end. - // This case will fail if the IsAcceptableEndInsertion does not capture an end insertion correctly. - Debug.Assert(!IsAtEndOfSpan(target, change)); - - return change.NewPosition > 0 && - change.NewText == "."; - } - - private static bool RemainingIsWhitespace(Span target, TextChange change) - { - var offset = (change.OldPosition - target.Start.AbsoluteIndex) + change.OldLength; - return string.IsNullOrWhiteSpace(target.Content.Substring(offset)); - } - - private PartialParseResult HandleDotlessCommitInsertion(Span target) - { - var result = PartialParseResult.Accepted; - if (!AcceptTrailingDot && target.Content.LastOrDefault() == '.') - { - result |= PartialParseResult.Provisional; - } - return result; - } - - private PartialParseResult HandleReplacement(Span target, TextChange change) - { - // Special Case for IntelliSense commits. - // When IntelliSense commits, we get two changes (for example user typed "Date", then committed "DateTime" by pressing ".") - // 1. Insert "." at the end of this span - // 2. Replace the "Date." at the end of the span with "DateTime." - // We need partial parsing to accept case #2. - var oldText = GetOldText(target, change); - - var result = PartialParseResult.Rejected; - if (EndsWithDot(oldText) && EndsWithDot(change.NewText)) - { - result = PartialParseResult.Accepted; - if (!AcceptTrailingDot) - { - result |= PartialParseResult.Provisional; - } - } - return result; - } - - private PartialParseResult HandleDeletion(Span target, char previousChar, TextChange change) - { - // What's left after deleting? - if (previousChar == '.') - { - return TryAcceptChange(target, change, PartialParseResult.Accepted | PartialParseResult.Provisional); - } - else if (ParserHelpers.IsIdentifierPart(previousChar)) - { - return TryAcceptChange(target, change); - } - else - { - return PartialParseResult.Rejected; - } - } - - private PartialParseResult HandleInsertion(Span target, char previousChar, TextChange change) - { - // What are we inserting after? - if (previousChar == '.') - { - return HandleInsertionAfterDot(target, change); - } - else if (ParserHelpers.IsIdentifierPart(previousChar) || previousChar == ')' || previousChar == ']') - { - return HandleInsertionAfterIdPart(target, change); - } - else - { - return PartialParseResult.Rejected; - } - } - - private PartialParseResult HandleInsertionAfterIdPart(Span target, TextChange change) - { - // If the insertion is a full identifier part, accept it - if (ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false)) - { - return TryAcceptChange(target, change); - } - else if (EndsWithDot(change.NewText)) - { - // Accept it, possibly provisionally - var result = PartialParseResult.Accepted; - if (!AcceptTrailingDot) - { - result |= PartialParseResult.Provisional; - } - return TryAcceptChange(target, change, result); - } - else - { - return PartialParseResult.Rejected; - } - } - - private static bool EndsWithDot(string content) - { - return (content.Length == 1 && content[0] == '.') || - (content[content.Length - 1] == '.' && - content.Take(content.Length - 1).All(ParserHelpers.IsIdentifierPart)); - } - - private PartialParseResult HandleInsertionAfterDot(Span target, TextChange change) - { - // If the insertion is a full identifier or another dot, accept it - if (ParserHelpers.IsIdentifier(change.NewText) || change.NewText == ".") - { - return TryAcceptChange(target, change); - } - return PartialParseResult.Rejected; - } - - private PartialParseResult TryAcceptChange(Span target, TextChange change, PartialParseResult acceptResult = PartialParseResult.Accepted) - { - var content = change.ApplyChange(target); - if (StartsWithKeyword(content)) - { - return PartialParseResult.Rejected | PartialParseResult.SpanContextChanged; - } - - return acceptResult; - } - - private bool StartsWithKeyword(string newContent) - { - using (var reader = new StringReader(newContent)) - { - return _keywords.Contains(reader.ReadWhile(ParserHelpers.IsIdentifierPart)); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/RazorEditorTrace.cs b/src/Microsoft.AspNetCore.Razor/Editor/RazorEditorTrace.cs deleted file mode 100644 index d093ee3701..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/RazorEditorTrace.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -#if NET451 -using System.Globalization; -#endif - -namespace Microsoft.AspNetCore.Razor.Editor -{ - internal static class RazorEditorTrace - { - private static bool? _enabled; - - private static bool IsEnabled() - { - if (_enabled == null) - { - bool enabled; - if (Boolean.TryParse(Environment.GetEnvironmentVariable("RAZOR_EDITOR_TRACE"), out enabled)) - { -#if NET451 - // No Trace in CoreCLR - - Trace.WriteLine(RazorResources.FormatTrace_Startup( - enabled ? RazorResources.Trace_Enabled : RazorResources.Trace_Disabled)); -#endif - _enabled = enabled; - } - else - { - _enabled = false; - } - } - return _enabled.Value; - } - - [Conditional("EDITOR_TRACING")] - public static void TraceLine(string format, params object[] args) - { - if (IsEnabled()) - { -#if NET451 - // No Trace in CoreCLR - - Trace.WriteLine(RazorResources.FormatTrace_Format( - string.Format(CultureInfo.CurrentCulture, format, args))); -#endif - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/SingleLineMarkupEditHandler.cs b/src/Microsoft.AspNetCore.Razor/Editor/SingleLineMarkupEditHandler.cs deleted file mode 100644 index 94da1293f6..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/SingleLineMarkupEditHandler.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class SingleLineMarkupEditHandler : SpanEditHandler - { - public SingleLineMarkupEditHandler(Func> tokenizer) - : base(tokenizer) - { - } - - public SingleLineMarkupEditHandler(Func> tokenizer, AcceptedCharacters accepted) - : base(tokenizer, accepted) - { - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Editor/SpanEditHandler.cs b/src/Microsoft.AspNetCore.Razor/Editor/SpanEditHandler.cs deleted file mode 100644 index c6934f93c9..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Editor/SpanEditHandler.cs +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - // Manages edits to a span - public class SpanEditHandler - { - private static readonly int TypeHashCode = typeof(SpanEditHandler).GetHashCode(); - - public SpanEditHandler(Func> tokenizer) - : this(tokenizer, AcceptedCharacters.Any) - { - } - - public SpanEditHandler(Func> tokenizer, AcceptedCharacters accepted) - { - AcceptedCharacters = accepted; - Tokenizer = tokenizer; - } - - public AcceptedCharacters AcceptedCharacters { get; set; } - - /// - /// This property is obsolete and will be removed in a future version. - /// - [Obsolete("This property is obsolete and will be removed in a future version.")] - public EditorHints EditorHints { get; set; } - - public Func> Tokenizer { get; set; } - - public static SpanEditHandler CreateDefault() - { - return CreateDefault(s => Enumerable.Empty()); - } - - public static SpanEditHandler CreateDefault(Func> tokenizer) - { - return new SpanEditHandler(tokenizer); - } - - public virtual EditResult ApplyChange(Span target, TextChange change) - { - return ApplyChange(target, change, force: false); - } - - public virtual EditResult ApplyChange(Span target, TextChange change, bool force) - { - var result = PartialParseResult.Accepted; - var normalized = change.Normalize(); - if (!force) - { - result = CanAcceptChange(target, normalized); - } - - // If the change is accepted then apply the change - if ((result & PartialParseResult.Accepted) == PartialParseResult.Accepted) - { - return new EditResult(result, UpdateSpan(target, normalized)); - } - return new EditResult(result, new SpanBuilder(target)); - } - - public virtual bool OwnsChange(Span target, TextChange change) - { - var end = target.Start.AbsoluteIndex + target.Length; - var changeOldEnd = change.OldPosition + change.OldLength; - return change.OldPosition >= target.Start.AbsoluteIndex && - (changeOldEnd < end || (changeOldEnd == end && AcceptedCharacters != AcceptedCharacters.None)); - } - - protected virtual PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange) - { - return PartialParseResult.Rejected; - } - - protected virtual SpanBuilder UpdateSpan(Span target, TextChange normalizedChange) - { - var newContent = normalizedChange.ApplyChange(target); - var newSpan = new SpanBuilder(target); - newSpan.ClearSymbols(); - foreach (ISymbol sym in Tokenizer(newContent)) - { - sym.OffsetStart(target.Start); - newSpan.Accept(sym); - } - if (target.Next != null) - { - var newEnd = SourceLocationTracker.CalculateNewLocation(target.Start, newContent); - target.Next.ChangeStart(newEnd); - } - return newSpan; - } - - protected internal static bool IsAtEndOfFirstLine(Span target, TextChange change) - { - var endOfFirstLine = target.Content.IndexOfAny(new char[] { (char)0x000d, (char)0x000a, (char)0x2028, (char)0x2029 }); - return (endOfFirstLine == -1 || (change.OldPosition - target.Start.AbsoluteIndex) <= endOfFirstLine); - } - - /// - /// Returns true if the specified change is an insertion of text at the end of this span. - /// - protected internal static bool IsEndInsertion(Span target, TextChange change) - { - return change.IsInsert && IsAtEndOfSpan(target, change); - } - - /// - /// Returns true if the specified change is an insertion of text at the end of this span. - /// - protected internal static bool IsEndDeletion(Span target, TextChange change) - { - return change.IsDelete && IsAtEndOfSpan(target, change); - } - - /// - /// Returns true if the specified change is a replacement of text at the end of this span. - /// - protected internal static bool IsEndReplace(Span target, TextChange change) - { - return change.IsReplace && IsAtEndOfSpan(target, change); - } - - protected internal static bool IsAtEndOfSpan(Span target, TextChange change) - { - return (change.OldPosition + change.OldLength) == (target.Start.AbsoluteIndex + target.Length); - } - - /// - /// Returns the old text referenced by the change. - /// - /// - /// If the content has already been updated by applying the change, this data will be _invalid_ - /// - protected internal static string GetOldText(Span target, TextChange change) - { - return target.Content.Substring(change.OldPosition - target.Start.AbsoluteIndex, change.OldLength); - } - - // Is the specified span to the right of this span and immediately adjacent? - internal static bool IsAdjacentOnRight(Span target, Span other) - { - return target.Start.AbsoluteIndex < other.Start.AbsoluteIndex && target.Start.AbsoluteIndex + target.Length == other.Start.AbsoluteIndex; - } - - // Is the specified span to the left of this span and immediately adjacent? - internal static bool IsAdjacentOnLeft(Span target, Span other) - { - return other.Start.AbsoluteIndex < target.Start.AbsoluteIndex && other.Start.AbsoluteIndex + other.Length == target.Start.AbsoluteIndex; - } - - public override string ToString() - { - return GetType().Name + ";Accepts:" + AcceptedCharacters + -#pragma warning disable 618 // Ignore obsolete warning for EditorHints - ((EditorHints == EditorHints.None) ? string.Empty : (";Hints: " + EditorHints.ToString())); -#pragma warning restore 618 // Ignore obsolete warning for EditorHints - } - - public override bool Equals(object obj) - { - var other = obj as SpanEditHandler; - return other != null && - GetType() == other.GetType() && - AcceptedCharacters == other.AcceptedCharacters && -#pragma warning disable 618 // Ignore obsolete warning for EditorHints - EditorHints == other.EditorHints; -#pragma warning restore 618 // Ignore obsolete warning for EditorHints - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties but Equals also checks the type. - return TypeHashCode; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/ErrorSink.cs b/src/Microsoft.AspNetCore.Razor/ErrorSink.cs deleted file mode 100644 index 6aa3e4a4a5..0000000000 --- a/src/Microsoft.AspNetCore.Razor/ErrorSink.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace Microsoft.AspNetCore.Razor -{ - /// - /// Used to manage s encountered during the Razor parsing phase. - /// - public class ErrorSink - { - private readonly List _errors; - - /// - /// Instantiates a new instance of . - /// - public ErrorSink() - { - _errors = new List(); - } - - /// - /// s collected. - /// - public IEnumerable Errors - { - get - { - return _errors; - } - } - - /// - /// Tracks the given . - /// - /// The to track. - public void OnError(RazorError error) - { - _errors.Add(error); - } - - /// - /// Creates and tracks a new . - /// - /// of the error. - /// A message describing the error. - /// The length of the error. - public void OnError(SourceLocation location, string message, int length) - { - _errors.Add(new RazorError(message, location, length)); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/Microsoft.AspNetCore.Razor.csproj b/src/Microsoft.AspNetCore.Razor/Microsoft.AspNetCore.Razor.csproj index 0403e5e964..34c28a3151 100644 --- a/src/Microsoft.AspNetCore.Razor/Microsoft.AspNetCore.Razor.csproj +++ b/src/Microsoft.AspNetCore.Razor/Microsoft.AspNetCore.Razor.csproj @@ -9,13 +9,4 @@ true aspnetcore;cshtml;razor - - - - - - - - - diff --git a/src/Microsoft.AspNetCore.Razor/Parser/BalancingModes.cs b/src/Microsoft.AspNetCore.Razor/Parser/BalancingModes.cs deleted file mode 100644 index 93b9475664..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/BalancingModes.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -namespace Microsoft.AspNetCore.Razor.Parser -{ - [Flags] - public enum BalancingModes - { - None = 0, - BacktrackOnFailure = 1, - NoErrorOnFailure = 2, - AllowCommentsAndTemplates = 4, - AllowEmbeddedTransitions = 8 - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Directives.cs b/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Directives.cs deleted file mode 100644 index 37c02d172c..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Directives.cs +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public partial class CSharpCodeParser - { - private void SetupDirectives() - { - MapDirectives(TagHelperPrefixDirective, SyntaxConstants.CSharp.TagHelperPrefixKeyword); - MapDirectives(AddTagHelperDirective, SyntaxConstants.CSharp.AddTagHelperKeyword); - MapDirectives(RemoveTagHelperDirective, SyntaxConstants.CSharp.RemoveTagHelperKeyword); - MapDirectives(InheritsDirective, SyntaxConstants.CSharp.InheritsKeyword); - MapDirectives(FunctionsDirective, SyntaxConstants.CSharp.FunctionsKeyword); - MapDirectives(SectionDirective, SyntaxConstants.CSharp.SectionKeyword); - } - - protected virtual void TagHelperPrefixDirective() - { - TagHelperDirective( - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - prefix => new TagHelperPrefixDirectiveChunkGenerator(prefix)); - } - - protected virtual void AddTagHelperDirective() - { - TagHelperDirective( - SyntaxConstants.CSharp.AddTagHelperKeyword, - lookupText => new AddTagHelperChunkGenerator(lookupText)); - } - - protected virtual void RemoveTagHelperDirective() - { - TagHelperDirective( - SyntaxConstants.CSharp.RemoveTagHelperKeyword, - lookupText => new RemoveTagHelperChunkGenerator(lookupText)); - } - - protected virtual void SectionDirective() - { - var nested = Context.IsWithin(BlockType.Section); - var errorReported = false; - - // Set the block and span type - Context.CurrentBlock.Type = BlockType.Section; - - // Verify we're on "section" and accept - AssertDirective(SyntaxConstants.CSharp.SectionKeyword); - var startLocation = CurrentLocation; - AcceptAndMoveNext(); - - if (nested) - { - Context.OnError( - startLocation, - RazorResources.FormatParseError_Sections_Cannot_Be_Nested(RazorResources.SectionExample_CS), - Span.GetContent().Value.Length); - errorReported = true; - } - - var whitespace = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: false)); - - // Get the section name - var sectionName = string.Empty; - if (!Required(CSharpSymbolType.Identifier, - errorIfNotFound: true, - errorBase: RazorResources.FormatParseError_Unexpected_Character_At_Section_Name_Start)) - { - if (!errorReported) - { - errorReported = true; - } - - PutCurrentBack(); - PutBack(whitespace); - AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: false)); - } - else - { - Accept(whitespace); - sectionName = CurrentSymbol.Content; - AcceptAndMoveNext(); - } - Context.CurrentBlock.ChunkGenerator = new SectionChunkGenerator(sectionName); - - var errorLocation = CurrentLocation; - whitespace = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: false)); - - // Get the starting brace - var sawStartingBrace = At(CSharpSymbolType.LeftBrace); - if (!sawStartingBrace) - { - if (!errorReported) - { - errorReported = true; - Context.OnError( - errorLocation, - RazorResources.ParseError_MissingOpenBraceAfterSection, - length: 1 /* { */); - } - - PutCurrentBack(); - PutBack(whitespace); - AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: false)); - Optional(CSharpSymbolType.NewLine); - Output(SpanKind.MetaCode); - CompleteBlock(); - return; - } - else - { - Accept(whitespace); - } - - var startingBraceLocation = CurrentLocation; - - // Set up edit handler - var editHandler = new AutoCompleteEditHandler(Language.TokenizeString, autoCompleteAtEndOfSpan: true); - - Span.EditHandler = editHandler; - Span.Accept(CurrentSymbol); - - // Output Metacode then switch to section parser - Output(SpanKind.MetaCode); - SectionBlock("{", "}", caseSensitive: true); - - Span.ChunkGenerator = SpanChunkGenerator.Null; - // Check for the terminating "}" - if (!Optional(CSharpSymbolType.RightBrace)) - { - editHandler.AutoCompleteString = "}"; - Context.OnError( - startingBraceLocation, - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF( - SyntaxConstants.CSharp.SectionKeyword, - Language.GetSample(CSharpSymbolType.RightBrace), - Language.GetSample(CSharpSymbolType.LeftBrace)), - length: 1 /* } */); - } - else - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - CompleteBlock(insertMarkerIfNecessary: false, captureWhitespaceToEndOfLine: true); - Output(SpanKind.MetaCode); - return; - } - - protected virtual void FunctionsDirective() - { - // Set the block type - Context.CurrentBlock.Type = BlockType.Functions; - - // Verify we're on "functions" and accept - AssertDirective(SyntaxConstants.CSharp.FunctionsKeyword); - var block = new Block(CurrentSymbol); - AcceptAndMoveNext(); - - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: false)); - - if (!At(CSharpSymbolType.LeftBrace)) - { - Context.OnError( - CurrentLocation, - RazorResources.FormatParseError_Expected_X(Language.GetSample(CSharpSymbolType.LeftBrace)), - length: 1 /* { */); - CompleteBlock(); - Output(SpanKind.MetaCode); - return; - } - else - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - - // Capture start point and continue - var blockStart = CurrentLocation; - AcceptAndMoveNext(); - - // Output what we've seen and continue - Output(SpanKind.MetaCode); - - var editHandler = new AutoCompleteEditHandler(Language.TokenizeString); - Span.EditHandler = editHandler; - - Balance(BalancingModes.NoErrorOnFailure, CSharpSymbolType.LeftBrace, CSharpSymbolType.RightBrace, blockStart); - Span.ChunkGenerator = new TypeMemberChunkGenerator(); - if (!At(CSharpSymbolType.RightBrace)) - { - editHandler.AutoCompleteString = "}"; - Context.OnError( - blockStart, - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(block.Name, "}", "{"), - length: 1 /* } */); - CompleteBlock(); - Output(SpanKind.Code); - } - else - { - Output(SpanKind.Code); - Assert(CSharpSymbolType.RightBrace); - Span.ChunkGenerator = SpanChunkGenerator.Null; - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - AcceptAndMoveNext(); - CompleteBlock(); - Output(SpanKind.MetaCode); - } - } - - protected virtual void InheritsDirective() - { - // Verify we're on the right keyword and accept - AssertDirective(SyntaxConstants.CSharp.InheritsKeyword); - AcceptAndMoveNext(); - - InheritsDirectiveCore(); - } - - [Conditional("DEBUG")] - protected void AssertDirective(string directive) - { - Assert(CSharpSymbolType.Identifier); - Debug.Assert(string.Equals(CurrentSymbol.Content, directive, StringComparison.Ordinal)); - } - - protected void InheritsDirectiveCore() - { - BaseTypeDirective( - RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName, - baseType => new SetBaseTypeChunkGenerator(baseType)); - } - - protected void BaseTypeDirective(string noTypeNameError, Func createChunkGenerator) - { - var keywordStartLocation = Span.Start; - - // Set the block type - Context.CurrentBlock.Type = BlockType.Directive; - - var keywordLength = Span.GetContent().Value.Length; - - // Accept whitespace - var remainingWhitespace = AcceptSingleWhiteSpaceCharacter(); - - if (Span.Symbols.Count > 1) - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - - Output(SpanKind.MetaCode); - - if (remainingWhitespace != null) - { - Accept(remainingWhitespace); - } - - AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); - - if (EndOfFile || At(CSharpSymbolType.WhiteSpace) || At(CSharpSymbolType.NewLine)) - { - Context.OnError( - keywordStartLocation, - noTypeNameError, - keywordLength); - } - - // Parse to the end of the line - AcceptUntil(CSharpSymbolType.NewLine); - if (!Context.DesignTimeMode) - { - // We want the newline to be treated as code, but it causes issues at design-time. - Optional(CSharpSymbolType.NewLine); - } - - // Pull out the type name - string baseType = Span.GetContent(); - - // Set up chunk generation - Span.ChunkGenerator = createChunkGenerator(baseType.Trim()); - - // Output the span and finish the block - CompleteBlock(); - Output(SpanKind.Code, AcceptedCharacters.AnyExceptNewline); - } - - private void TagHelperDirective(string keyword, Func chunkGeneratorFactory) - { - AssertDirective(keyword); - var keywordStartLocation = CurrentLocation; - - // Accept the directive name - AcceptAndMoveNext(); - - // Set the block type - Context.CurrentBlock.Type = BlockType.Directive; - - var keywordLength = Span.GetContent().Value.Length; - - var foundWhitespace = At(CSharpSymbolType.WhiteSpace); - AcceptWhile(CSharpSymbolType.WhiteSpace); - - // If we found whitespace then any content placed within the whitespace MAY cause a destructive change - // to the document. We can't accept it. - Output(SpanKind.MetaCode, foundWhitespace ? AcceptedCharacters.None : AcceptedCharacters.AnyExceptNewline); - - ISpanChunkGenerator chunkGenerator; - if (EndOfFile || At(CSharpSymbolType.NewLine)) - { - Context.OnError( - keywordStartLocation, - RazorResources.FormatParseError_DirectiveMustHaveValue(keyword), - keywordLength); - - chunkGenerator = chunkGeneratorFactory(string.Empty); - } - else - { - // Need to grab the current location before we accept until the end of the line. - var startLocation = CurrentLocation; - - // Parse to the end of the line. Essentially accepts anything until end of line, comments, invalid code - // etc. - AcceptUntil(CSharpSymbolType.NewLine); - - // Pull out the value and remove whitespaces and optional quotes - var rawValue = Span.GetContent().Value.Trim(); - - var startsWithQuote = rawValue.StartsWith("\"", StringComparison.Ordinal); - var endsWithQuote = rawValue.EndsWith("\"", StringComparison.Ordinal); - if (startsWithQuote != endsWithQuote) - { - Context.OnError( - startLocation, - RazorResources.FormatParseError_IncompleteQuotesAroundDirective(keyword), - rawValue.Length); - } - else if (startsWithQuote) - { - if (rawValue.Length > 2) - { - // Remove extra quotes - rawValue = rawValue.Substring(1, rawValue.Length - 2); - } - else - { - // raw value is only quotes - rawValue = string.Empty; - } - } - - chunkGenerator = chunkGeneratorFactory(rawValue); - } - - Span.ChunkGenerator = chunkGenerator; - - // Output the span and finish the block - CompleteBlock(); - Output(SpanKind.Code, AcceptedCharacters.AnyExceptNewline); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Expressions.cs b/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Expressions.cs deleted file mode 100644 index a952c780fa..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Expressions.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public partial class CSharpCodeParser - { - private void SetUpExpressions() - { - MapExpressionKeyword(AwaitExpression, CSharpKeyword.Await); - } - - private void AwaitExpression(bool topLevel) - { - // Ensure that we're on the await statement (only runs in debug) - Assert(CSharpKeyword.Await); - - // Accept the "await" and move on - AcceptAndMoveNext(); - - // Accept 1 or more spaces between the await and the following code. - AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); - - // Top level basically indicates if we're within an expression or statement. - // Ex: topLevel true = @await Foo() | topLevel false = @{ await Foo(); } - // Note that in this case @{ @await Foo() } top level is true for await. - // Therefore, if we're top level then we want to act like an implicit expression, - // otherwise just act as whatever we're contained in. - if (topLevel) - { - // Setup the Span to be an async implicit expression (an implicit expresison that allows spaces). - // Spaces are allowed because of "@await Foo()". - AsyncImplicitExpression(); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Statements.cs b/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Statements.cs deleted file mode 100644 index 005a17449b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.Statements.cs +++ /dev/null @@ -1,760 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public partial class CSharpCodeParser - { - private static readonly Func IsValidStatementSpacingSymbol = - IsSpacingToken(includeNewLines: true, includeComments: true); - - private void SetUpKeywords() - { - MapKeywords( - ConditionalBlock, - CSharpKeyword.For, - CSharpKeyword.Foreach, - CSharpKeyword.While, - CSharpKeyword.Switch, - CSharpKeyword.Lock); - MapKeywords(CaseStatement, false, CSharpKeyword.Case, CSharpKeyword.Default); - MapKeywords(IfStatement, CSharpKeyword.If); - MapKeywords(TryStatement, CSharpKeyword.Try); - MapKeywords(UsingKeyword, CSharpKeyword.Using); - MapKeywords(DoStatement, CSharpKeyword.Do); - MapKeywords(ReservedDirective, CSharpKeyword.Namespace, CSharpKeyword.Class); - } - - protected virtual void ReservedDirective(bool topLevel) - { - Context.OnError( - CurrentLocation, - RazorResources.FormatParseError_ReservedWord(CurrentSymbol.Content), - CurrentSymbol.Content.Length); - AcceptAndMoveNext(); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - Context.CurrentBlock.Type = BlockType.Directive; - CompleteBlock(); - Output(SpanKind.MetaCode); - } - - private void KeywordBlock(bool topLevel) - { - HandleKeyword(topLevel, () => - { - Context.CurrentBlock.Type = BlockType.Expression; - Context.CurrentBlock.ChunkGenerator = new ExpressionChunkGenerator(); - ImplicitExpression(); - }); - } - - private void CaseStatement(bool topLevel) - { - Assert(CSharpSymbolType.Keyword); - Debug.Assert(CurrentSymbol.Keyword != null && - (CurrentSymbol.Keyword.Value == CSharpKeyword.Case || - CurrentSymbol.Keyword.Value == CSharpKeyword.Default)); - AcceptUntil(CSharpSymbolType.Colon); - Optional(CSharpSymbolType.Colon); - } - - private void DoStatement(bool topLevel) - { - Assert(CSharpKeyword.Do); - UnconditionalBlock(); - WhileClause(); - if (topLevel) - { - CompleteBlock(); - } - } - - private void WhileClause() - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - IEnumerable ws = SkipToNextImportantToken(); - - if (At(CSharpKeyword.While)) - { - Accept(ws); - Assert(CSharpKeyword.While); - AcceptAndMoveNext(); - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - if (AcceptCondition() && Optional(CSharpSymbolType.Semicolon)) - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - } - else - { - PutCurrentBack(); - PutBack(ws); - } - } - - private void UsingKeyword(bool topLevel) - { - Assert(CSharpKeyword.Using); - var block = new Block(CurrentSymbol); - AcceptAndMoveNext(); - AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); - - if (At(CSharpSymbolType.LeftParenthesis)) - { - // using ( ==> Using Statement - UsingStatement(block); - } - else if (At(CSharpSymbolType.Identifier) || At(CSharpKeyword.Static)) - { - // using Identifier ==> Using Declaration - if (!topLevel) - { - Context.OnError( - block.Start, - RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock, - block.Name.Length); - StandardStatement(); - } - else - { - UsingDeclaration(); - } - } - - if (topLevel) - { - CompleteBlock(); - } - } - - private void UsingDeclaration() - { - // Set block type to directive - Context.CurrentBlock.Type = BlockType.Directive; - - if (At(CSharpSymbolType.Identifier)) - { - // non-static using - NamespaceOrTypeName(); - var whitespace = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - if (At(CSharpSymbolType.Assign)) - { - // Alias - Accept(whitespace); - Assert(CSharpSymbolType.Assign); - AcceptAndMoveNext(); - - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - - // One more namespace or type name - NamespaceOrTypeName(); - } - else - { - PutCurrentBack(); - PutBack(whitespace); - } - } - else if (At(CSharpKeyword.Static)) - { - // static using - AcceptAndMoveNext(); - AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); - NamespaceOrTypeName(); - } - - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.AnyExceptNewline; - Span.ChunkGenerator = new AddImportChunkGenerator( - Span.GetContent(symbols => symbols.Skip(1))); - - // Optional ";" - if (EnsureCurrent()) - { - Optional(CSharpSymbolType.Semicolon); - } - } - - protected bool NamespaceOrTypeName() - { - if (Optional(CSharpSymbolType.Identifier) || Optional(CSharpSymbolType.Keyword)) - { - Optional(CSharpSymbolType.QuestionMark); // Nullable - if (Optional(CSharpSymbolType.DoubleColon)) - { - if (!Optional(CSharpSymbolType.Identifier)) - { - Optional(CSharpSymbolType.Keyword); - } - } - if (At(CSharpSymbolType.LessThan)) - { - TypeArgumentList(); - } - if (Optional(CSharpSymbolType.Dot)) - { - NamespaceOrTypeName(); - } - while (At(CSharpSymbolType.LeftBracket)) - { - Balance(BalancingModes.None); - Optional(CSharpSymbolType.RightBracket); - } - return true; - } - else - { - return false; - } - } - - private void TypeArgumentList() - { - Assert(CSharpSymbolType.LessThan); - Balance(BalancingModes.None); - Optional(CSharpSymbolType.GreaterThan); - } - - private void UsingStatement(Block block) - { - Assert(CSharpSymbolType.LeftParenthesis); - - // Parse condition - if (AcceptCondition()) - { - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - - // Parse code block - ExpectCodeBlock(block); - } - } - - private void TryStatement(bool topLevel) - { - Assert(CSharpKeyword.Try); - UnconditionalBlock(); - AfterTryClause(); - if (topLevel) - { - CompleteBlock(); - } - } - - private void IfStatement(bool topLevel) - { - Assert(CSharpKeyword.If); - ConditionalBlock(topLevel: false); - AfterIfClause(); - if (topLevel) - { - CompleteBlock(); - } - } - - private void AfterTryClause() - { - // Grab whitespace - var whitespace = SkipToNextImportantToken(); - - // Check for a catch or finally part - if (At(CSharpKeyword.Catch)) - { - Accept(whitespace); - Assert(CSharpKeyword.Catch); - FilterableCatchBlock(); - AfterTryClause(); - } - else if (At(CSharpKeyword.Finally)) - { - Accept(whitespace); - Assert(CSharpKeyword.Finally); - UnconditionalBlock(); - } - else - { - // Return whitespace and end the block - PutCurrentBack(); - PutBack(whitespace); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - } - } - - private void AfterIfClause() - { - // Grab whitespace and razor comments - IEnumerable ws = SkipToNextImportantToken(); - - // Check for an else part - if (At(CSharpKeyword.Else)) - { - Accept(ws); - Assert(CSharpKeyword.Else); - ElseClause(); - } - else - { - // No else, return whitespace - PutCurrentBack(); - PutBack(ws); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - } - } - - private void ElseClause() - { - if (!At(CSharpKeyword.Else)) - { - return; - } - var block = new Block(CurrentSymbol); - - AcceptAndMoveNext(); - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - if (At(CSharpKeyword.If)) - { - // ElseIf - block.Name = SyntaxConstants.CSharp.ElseIfKeyword; - ConditionalBlock(block); - AfterIfClause(); - } - else if (!EndOfFile) - { - // Else - ExpectCodeBlock(block); - } - } - - private void ExpectCodeBlock(Block block) - { - if (!EndOfFile) - { - // Check for "{" to make sure we're at a block - if (!At(CSharpSymbolType.LeftBrace)) - { - Context.OnError( - CurrentLocation, - RazorResources.FormatParseError_SingleLine_ControlFlowStatements_Not_Allowed( - Language.GetSample(CSharpSymbolType.LeftBrace), - CurrentSymbol.Content), - CurrentSymbol.Content.Length); - } - - // Parse the statement and then we're done - Statement(block); - } - } - - private void UnconditionalBlock() - { - Assert(CSharpSymbolType.Keyword); - var block = new Block(CurrentSymbol); - AcceptAndMoveNext(); - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - ExpectCodeBlock(block); - } - - private void FilterableCatchBlock() - { - Assert(CSharpKeyword.Catch); - - var block = new Block(CurrentSymbol); - - // Accept "catch" - AcceptAndMoveNext(); - AcceptWhile(IsValidStatementSpacingSymbol); - - // Parse the catch condition if present. If not present, let the C# compiler complain. - if (AcceptCondition()) - { - AcceptWhile(IsValidStatementSpacingSymbol); - - if (At(CSharpKeyword.When)) - { - // Accept "when". - AcceptAndMoveNext(); - AcceptWhile(IsValidStatementSpacingSymbol); - - // Parse the filter condition if present. If not present, let the C# compiler complain. - if (!AcceptCondition()) - { - // Incomplete condition. - return; - } - - AcceptWhile(IsValidStatementSpacingSymbol); - } - - ExpectCodeBlock(block); - } - } - - private void ConditionalBlock(bool topLevel) - { - Assert(CSharpSymbolType.Keyword); - var block = new Block(CurrentSymbol); - ConditionalBlock(block); - if (topLevel) - { - CompleteBlock(); - } - } - - private void ConditionalBlock(Block block) - { - AcceptAndMoveNext(); - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - - // Parse the condition, if present (if not present, we'll let the C# compiler complain) - if (AcceptCondition()) - { - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - ExpectCodeBlock(block); - } - } - - private bool AcceptCondition() - { - if (At(CSharpSymbolType.LeftParenthesis)) - { - var complete = Balance(BalancingModes.BacktrackOnFailure | BalancingModes.AllowCommentsAndTemplates); - if (!complete) - { - AcceptUntil(CSharpSymbolType.NewLine); - } - else - { - Optional(CSharpSymbolType.RightParenthesis); - } - return complete; - } - return true; - } - - private void Statement() - { - Statement(null); - } - - private void Statement(Block block) - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - - // Accept whitespace but always keep the last whitespace node so we can put it back if necessary - var lastWhitespace = AcceptWhiteSpaceInLines(); - Debug.Assert(lastWhitespace == null || - (lastWhitespace.Start.AbsoluteIndex + lastWhitespace.Content.Length == CurrentLocation.AbsoluteIndex)); - - if (EndOfFile) - { - if (lastWhitespace != null) - { - Accept(lastWhitespace); - } - return; - } - - var type = CurrentSymbol.Type; - var loc = CurrentLocation; - - // Both cases @: and @:: are triggered as markup, second colon in second case will be triggered as a plain text - var isSingleLineMarkup = type == CSharpSymbolType.Transition && - (NextIs(CSharpSymbolType.Colon, CSharpSymbolType.DoubleColon)); - - var isMarkup = isSingleLineMarkup || - type == CSharpSymbolType.LessThan || - (type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.LessThan)); - - if (Context.DesignTimeMode || !isMarkup) - { - // CODE owns whitespace, MARKUP owns it ONLY in DesignTimeMode. - if (lastWhitespace != null) - { - Accept(lastWhitespace); - } - } - else - { - var nextSymbol = Lookahead(1); - - // MARKUP owns whitespace EXCEPT in DesignTimeMode. - PutCurrentBack(); - - // Put back the whitespace unless it precedes a '' tag. - if (nextSymbol != null && - !string.Equals(nextSymbol.Content, SyntaxConstants.TextTagName, StringComparison.Ordinal)) - { - PutBack(lastWhitespace); - } - } - - if (isMarkup) - { - if (type == CSharpSymbolType.Transition && !isSingleLineMarkup) - { - Context.OnError( - loc, - RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start, - length: 1 /* @ */); - } - - // Markup block - Output(SpanKind.Code); - if (Context.DesignTimeMode && CurrentSymbol != null && - (CurrentSymbol.Type == CSharpSymbolType.LessThan || CurrentSymbol.Type == CSharpSymbolType.Transition)) - { - PutCurrentBack(); - } - OtherParserBlock(); - } - else - { - // What kind of statement is this? - HandleStatement(block, type); - } - } - - private void HandleStatement(Block block, CSharpSymbolType type) - { - switch (type) - { - case CSharpSymbolType.RazorCommentTransition: - Output(SpanKind.Code); - RazorComment(); - Statement(block); - break; - case CSharpSymbolType.LeftBrace: - // Verbatim Block - block = block ?? new Block(RazorResources.BlockName_Code, CurrentLocation); - AcceptAndMoveNext(); - CodeBlock(block); - break; - case CSharpSymbolType.Keyword: - // Keyword block - HandleKeyword(false, StandardStatement); - break; - case CSharpSymbolType.Transition: - // Embedded Expression block - EmbeddedExpression(); - break; - case CSharpSymbolType.RightBrace: - // Possible end of Code Block, just run the continuation - break; - case CSharpSymbolType.Comment: - AcceptAndMoveNext(); - break; - default: - // Other statement - StandardStatement(); - break; - } - } - - private void EmbeddedExpression() - { - // First, verify the type of the block - Assert(CSharpSymbolType.Transition); - var transition = CurrentSymbol; - NextToken(); - - if (At(CSharpSymbolType.Transition)) - { - // Escaped "@" - Output(SpanKind.Code); - - // Output "@" as hidden span - Accept(transition); - Span.ChunkGenerator = SpanChunkGenerator.Null; - Output(SpanKind.Code); - - Assert(CSharpSymbolType.Transition); - AcceptAndMoveNext(); - StandardStatement(); - } - else - { - // Throw errors as necessary, but continue parsing - if (At(CSharpSymbolType.LeftBrace)) - { - Context.OnError( - CurrentLocation, - RazorResources.ParseError_Unexpected_Nested_CodeBlock, - length: 1 /* { */); - } - - // @( or @foo - Nested expression, parse a child block - PutCurrentBack(); - PutBack(transition); - - // Before exiting, add a marker span if necessary - AddMarkerSymbolIfNecessary(); - - NestedBlock(); - } - } - - private void StandardStatement() - { - while (!EndOfFile) - { - var bookmark = CurrentLocation.AbsoluteIndex; - IEnumerable read = ReadWhile(sym => sym.Type != CSharpSymbolType.Semicolon && - sym.Type != CSharpSymbolType.RazorCommentTransition && - sym.Type != CSharpSymbolType.Transition && - sym.Type != CSharpSymbolType.LeftBrace && - sym.Type != CSharpSymbolType.LeftParenthesis && - sym.Type != CSharpSymbolType.LeftBracket && - sym.Type != CSharpSymbolType.RightBrace); - if (At(CSharpSymbolType.LeftBrace) || - At(CSharpSymbolType.LeftParenthesis) || - At(CSharpSymbolType.LeftBracket)) - { - Accept(read); - if (Balance(BalancingModes.AllowCommentsAndTemplates | BalancingModes.BacktrackOnFailure)) - { - Optional(CSharpSymbolType.RightBrace); - } - else - { - // Recovery - AcceptUntil(CSharpSymbolType.LessThan, CSharpSymbolType.RightBrace); - return; - } - } - else if (At(CSharpSymbolType.Transition) && (NextIs(CSharpSymbolType.LessThan, CSharpSymbolType.Colon))) - { - Accept(read); - Output(SpanKind.Code); - Template(); - } - else if (At(CSharpSymbolType.RazorCommentTransition)) - { - Accept(read); - RazorComment(); - } - else if (At(CSharpSymbolType.Semicolon)) - { - Accept(read); - AcceptAndMoveNext(); - return; - } - else if (At(CSharpSymbolType.RightBrace)) - { - Accept(read); - return; - } - else - { - Context.Source.Position = bookmark; - NextToken(); - AcceptUntil(CSharpSymbolType.LessThan, CSharpSymbolType.LeftBrace, CSharpSymbolType.RightBrace); - return; - } - } - } - - private void CodeBlock(Block block) - { - CodeBlock(true, block); - } - - private void CodeBlock(bool acceptTerminatingBrace, Block block) - { - EnsureCurrent(); - while (!EndOfFile && !At(CSharpSymbolType.RightBrace)) - { - // Parse a statement, then return here - Statement(); - EnsureCurrent(); - } - - if (EndOfFile) - { - Context.OnError( - block.Start, - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(block.Name, '}', '{'), - length: 1 /* { OR } */); - } - else if (acceptTerminatingBrace) - { - Assert(CSharpSymbolType.RightBrace); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - AcceptAndMoveNext(); - } - } - - private void HandleKeyword(bool topLevel, Action fallback) - { - Debug.Assert(CurrentSymbol.Type == CSharpSymbolType.Keyword && CurrentSymbol.Keyword != null); - Action handler; - if (_keywordParsers.TryGetValue(CurrentSymbol.Keyword.Value, out handler)) - { - handler(topLevel); - } - else - { - fallback(); - } - } - - private IEnumerable SkipToNextImportantToken() - { - while (!EndOfFile) - { - IEnumerable ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - if (At(CSharpSymbolType.RazorCommentTransition)) - { - Accept(ws); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - RazorComment(); - } - else - { - return ws; - } - } - return Enumerable.Empty(); - } - - // Common code for Parsers, but FxCop REALLY doesn't like it in the base class.. moving it here for now. - protected override void OutputSpanBeforeRazorComment() - { - AddMarkerSymbolIfNecessary(); - Output(SpanKind.Code); - } - - protected class Block - { - public Block(string name, SourceLocation start) - { - Name = name; - Start = start; - } - - public Block(CSharpSymbol symbol) - : this(GetName(symbol), symbol.Start) - { - } - - public string Name { get; set; } - public SourceLocation Start { get; set; } - - private static string GetName(CSharpSymbol sym) - { - if (sym.Type == CSharpSymbolType.Keyword) - { - return CSharpLanguageCharacteristics.GetKeyword(sym.Keyword.Value); - } - return sym.Content; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.cs b/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.cs deleted file mode 100644 index 5069e3d712..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/CSharpCodeParser.cs +++ /dev/null @@ -1,675 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public partial class CSharpCodeParser : TokenizerBackedParser - { - internal static readonly int UsingKeywordLength = 5; // using - - internal static ISet DefaultKeywords = new HashSet() - { - SyntaxConstants.CSharp.AddTagHelperKeyword, - SyntaxConstants.CSharp.RemoveTagHelperKeyword, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - "class", - "do", - "for", - "foreach", - "functions", - "if", - "inherits", - "lock", - "namespace", - "section", - "switch", - "try", - "using", - "while", - }; - - private Dictionary _directiveParsers = new Dictionary(); - private Dictionary> _keywordParsers = new Dictionary>(); - - public CSharpCodeParser() - { - Keywords = new HashSet(); - SetUpKeywords(); - SetupDirectives(); - SetUpExpressions(); - } - - protected internal ISet Keywords { get; private set; } - - public bool IsNested { get; set; } - - protected override ParserBase OtherParser - { - get { return Context.MarkupParser; } - } - - protected override LanguageCharacteristics Language - { - get { return CSharpLanguageCharacteristics.Instance; } - } - - protected override bool SymbolTypeEquals(CSharpSymbolType x, CSharpSymbolType y) => x == y; - - protected void MapDirectives(Action handler, params string[] directives) - { - foreach (string directive in directives) - { - _directiveParsers.Add(directive, handler); - Keywords.Add(directive); - } - } - - protected bool TryGetDirectiveHandler(string directive, out Action handler) - { - return _directiveParsers.TryGetValue(directive, out handler); - } - - private void MapExpressionKeyword(Action handler, CSharpKeyword keyword) - { - _keywordParsers.Add(keyword, handler); - - // Expression keywords don't belong in the regular keyword list - } - - private void MapKeywords(Action handler, params CSharpKeyword[] keywords) - { - MapKeywords(handler, topLevel: true, keywords: keywords); - } - - private void MapKeywords(Action handler, bool topLevel, params CSharpKeyword[] keywords) - { - foreach (CSharpKeyword keyword in keywords) - { - _keywordParsers.Add(keyword, handler); - if (topLevel) - { - Keywords.Add(CSharpLanguageCharacteristics.GetKeyword(keyword)); - } - } - } - - [Conditional("DEBUG")] - internal void Assert(CSharpKeyword expectedKeyword) - { - Debug.Assert(CurrentSymbol.Type == CSharpSymbolType.Keyword && - CurrentSymbol.Keyword.HasValue && - CurrentSymbol.Keyword.Value == expectedKeyword); - } - - protected internal bool At(CSharpKeyword keyword) - { - return At(CSharpSymbolType.Keyword) && - CurrentSymbol.Keyword.HasValue && - CurrentSymbol.Keyword.Value == keyword; - } - - protected internal bool AcceptIf(CSharpKeyword keyword) - { - if (At(keyword)) - { - AcceptAndMoveNext(); - return true; - } - return false; - } - - protected static Func IsSpacingToken(bool includeNewLines, bool includeComments) - { - return sym => sym.Type == CSharpSymbolType.WhiteSpace || - (includeNewLines && sym.Type == CSharpSymbolType.NewLine) || - (includeComments && sym.Type == CSharpSymbolType.Comment); - } - - public override void ParseBlock() - { - using (PushSpanConfig(DefaultSpanConfig)) - { - if (Context == null) - { - throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set); - } - - // Unless changed, the block is a statement block - using (Context.StartBlock(BlockType.Statement)) - { - NextToken(); - - AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true)); - - var current = CurrentSymbol; - if (At(CSharpSymbolType.StringLiteral) && - CurrentSymbol.Content.Length > 0 && - CurrentSymbol.Content[0] == SyntaxConstants.TransitionCharacter) - { - var split = Language.SplitSymbol(CurrentSymbol, 1, CSharpSymbolType.Transition); - current = split.Item1; - Context.Source.Position = split.Item2.Start.AbsoluteIndex; - NextToken(); - } - else if (At(CSharpSymbolType.Transition)) - { - NextToken(); - } - - // Accept "@" if we see it, but if we don't, that's OK. We assume we were started for a good reason - if (current.Type == CSharpSymbolType.Transition) - { - if (Span.Symbols.Count > 0) - { - Output(SpanKind.Code); - } - AtTransition(current); - } - else - { - // No "@" => Jump straight to AfterTransition - AfterTransition(); - } - Output(SpanKind.Code); - } - } - } - - private void DefaultSpanConfig(SpanBuilder span) - { - span.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString); - span.ChunkGenerator = new StatementChunkGenerator(); - } - - private void AtTransition(CSharpSymbol current) - { - Debug.Assert(current.Type == CSharpSymbolType.Transition); - Accept(current); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - - // Output the "@" span and continue here - Output(SpanKind.Transition); - AfterTransition(); - } - - private void AfterTransition() - { - using (PushSpanConfig(DefaultSpanConfig)) - { - EnsureCurrent(); - try - { - // What type of block is this? - if (!EndOfFile) - { - if (CurrentSymbol.Type == CSharpSymbolType.LeftParenthesis) - { - Context.CurrentBlock.Type = BlockType.Expression; - Context.CurrentBlock.ChunkGenerator = new ExpressionChunkGenerator(); - ExplicitExpression(); - return; - } - else if (CurrentSymbol.Type == CSharpSymbolType.Identifier) - { - Action handler; - if (TryGetDirectiveHandler(CurrentSymbol.Content, out handler)) - { - Span.ChunkGenerator = SpanChunkGenerator.Null; - handler(); - return; - } - else - { - if (string.Equals( - CurrentSymbol.Content, - SyntaxConstants.CSharp.HelperKeyword, - StringComparison.Ordinal)) - { - Context.OnError( - CurrentLocation, - RazorResources.FormatParseError_HelperDirectiveNotAvailable( - SyntaxConstants.CSharp.HelperKeyword), - CurrentSymbol.Content.Length); - } - - Context.CurrentBlock.Type = BlockType.Expression; - Context.CurrentBlock.ChunkGenerator = new ExpressionChunkGenerator(); - ImplicitExpression(); - return; - } - } - else if (CurrentSymbol.Type == CSharpSymbolType.Keyword) - { - KeywordBlock(topLevel: true); - return; - } - else if (CurrentSymbol.Type == CSharpSymbolType.LeftBrace) - { - VerbatimBlock(); - return; - } - } - - // Invalid character - Context.CurrentBlock.Type = BlockType.Expression; - Context.CurrentBlock.ChunkGenerator = new ExpressionChunkGenerator(); - AddMarkerSymbolIfNecessary(); - Span.ChunkGenerator = new ExpressionChunkGenerator(); - Span.EditHandler = new ImplicitExpressionEditHandler( - Language.TokenizeString, - DefaultKeywords, - acceptTrailingDot: IsNested) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace - }; - if (At(CSharpSymbolType.WhiteSpace) || At(CSharpSymbolType.NewLine)) - { - Context.OnError( - CurrentLocation, - RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, - CurrentSymbol.Content.Length); - } - else if (EndOfFile) - { - Context.OnError( - CurrentLocation, - RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, - length: 1 /* end of file */); - } - else - { - Context.OnError( - CurrentLocation, - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS( - CurrentSymbol.Content), - CurrentSymbol.Content.Length); - } - } - finally - { - // Always put current character back in the buffer for the next parser. - PutCurrentBack(); - } - } - } - - private void VerbatimBlock() - { - Assert(CSharpSymbolType.LeftBrace); - var block = new Block(RazorResources.BlockName_Code, CurrentLocation); - AcceptAndMoveNext(); - - // Set up the "{" span and output - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - Output(SpanKind.MetaCode); - - // Set up auto-complete and parse the code block - var editHandler = new AutoCompleteEditHandler(Language.TokenizeString); - Span.EditHandler = editHandler; - CodeBlock(false, block); - - Span.ChunkGenerator = new StatementChunkGenerator(); - AddMarkerSymbolIfNecessary(); - if (!At(CSharpSymbolType.RightBrace)) - { - editHandler.AutoCompleteString = "}"; - } - Output(SpanKind.Code); - - if (Optional(CSharpSymbolType.RightBrace)) - { - // Set up the "}" span - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - } - - if (!IsNested) - { - EnsureCurrent(); - if (At(CSharpSymbolType.NewLine) || - (At(CSharpSymbolType.WhiteSpace) && NextIs(CSharpSymbolType.NewLine))) - { - Context.NullGenerateWhitespaceAndNewLine = true; - } - } - - Output(SpanKind.MetaCode); - } - - private void ImplicitExpression() - { - ImplicitExpression(AcceptedCharacters.NonWhiteSpace); - } - - // Async implicit expressions include the "await" keyword and therefore need to allow spaces to - // separate the "await" and the following code. - private void AsyncImplicitExpression() - { - ImplicitExpression(AcceptedCharacters.AnyExceptNewline); - } - - private void ImplicitExpression(AcceptedCharacters acceptedCharacters) - { - Context.CurrentBlock.Type = BlockType.Expression; - Context.CurrentBlock.ChunkGenerator = new ExpressionChunkGenerator(); - - using (PushSpanConfig(span => - { - span.EditHandler = new ImplicitExpressionEditHandler( - Language.TokenizeString, - Keywords, - acceptTrailingDot: IsNested); - span.EditHandler.AcceptedCharacters = acceptedCharacters; - span.ChunkGenerator = new ExpressionChunkGenerator(); - })) - { - do - { - if (AtIdentifier(allowKeywords: true)) - { - AcceptAndMoveNext(); - } - } - while (MethodCallOrArrayIndex(acceptedCharacters)); - - PutCurrentBack(); - Output(SpanKind.Code); - } - } - - private bool MethodCallOrArrayIndex(AcceptedCharacters acceptedCharacters) - { - if (!EndOfFile) - { - if (CurrentSymbol.Type == CSharpSymbolType.LeftParenthesis || - CurrentSymbol.Type == CSharpSymbolType.LeftBracket) - { - // If we end within "(", whitespace is fine - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - - CSharpSymbolType right; - bool success; - - using (PushSpanConfig((span, prev) => - { - prev(span); - span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - })) - { - right = Language.FlipBracket(CurrentSymbol.Type); - success = Balance(BalancingModes.BacktrackOnFailure | BalancingModes.AllowCommentsAndTemplates); - } - - if (!success) - { - AcceptUntil(CSharpSymbolType.LessThan); - } - if (At(right)) - { - AcceptAndMoveNext(); - - // At the ending brace, restore the initial accepted characters. - Span.EditHandler.AcceptedCharacters = acceptedCharacters; - } - return MethodCallOrArrayIndex(acceptedCharacters); - } - if (At(CSharpSymbolType.QuestionMark)) - { - var next = Lookahead(count: 1); - - if (next != null) - { - if (next.Type == CSharpSymbolType.Dot) - { - // Accept null conditional dot operator (?.). - AcceptAndMoveNext(); - AcceptAndMoveNext(); - - // If the next piece after the ?. is a keyword or identifier then we want to continue. - return At(CSharpSymbolType.Identifier) || At(CSharpSymbolType.Keyword); - } - else if (next.Type == CSharpSymbolType.LeftBracket) - { - // We're at the ? for a null conditional bracket operator (?[). - AcceptAndMoveNext(); - - // Accept the [ and any content inside (it will attempt to balance). - return MethodCallOrArrayIndex(acceptedCharacters); - } - } - } - else if (At(CSharpSymbolType.Dot)) - { - var dot = CurrentSymbol; - if (NextToken()) - { - if (At(CSharpSymbolType.Identifier) || At(CSharpSymbolType.Keyword)) - { - // Accept the dot and return to the start - Accept(dot); - return true; // continue - } - else - { - // Put the symbol back - PutCurrentBack(); - } - } - if (!IsNested) - { - // Put the "." back - PutBack(dot); - } - else - { - Accept(dot); - } - } - else if (!(At(CSharpSymbolType.WhiteSpace) || At(CSharpSymbolType.NewLine))) - { - PutCurrentBack(); - } - } - - // Implicit Expression is complete - return false; - } - - protected void CompleteBlock() - { - CompleteBlock(insertMarkerIfNecessary: true); - } - - protected void CompleteBlock(bool insertMarkerIfNecessary) - { - CompleteBlock(insertMarkerIfNecessary, captureWhitespaceToEndOfLine: insertMarkerIfNecessary); - } - - protected void CompleteBlock(bool insertMarkerIfNecessary, bool captureWhitespaceToEndOfLine) - { - if (insertMarkerIfNecessary && Context.LastAcceptedCharacters != AcceptedCharacters.Any) - { - AddMarkerSymbolIfNecessary(); - } - - EnsureCurrent(); - - // Read whitespace, but not newlines - // If we're not inserting a marker span, we don't need to capture whitespace - if (!Context.WhiteSpaceIsSignificantToAncestorBlock && - Context.CurrentBlock.Type != BlockType.Expression && - captureWhitespaceToEndOfLine && - !Context.DesignTimeMode && - !IsNested) - { - CaptureWhitespaceAtEndOfCodeOnlyLine(); - } - else - { - PutCurrentBack(); - } - } - - private void CaptureWhitespaceAtEndOfCodeOnlyLine() - { - IEnumerable ws = ReadWhile(sym => sym.Type == CSharpSymbolType.WhiteSpace); - if (At(CSharpSymbolType.NewLine)) - { - Accept(ws); - AcceptAndMoveNext(); - PutCurrentBack(); - } - else - { - PutCurrentBack(); - PutBack(ws); - } - } - - private void ConfigureExplicitExpressionSpan(SpanBuilder sb) - { - sb.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString); - sb.ChunkGenerator = new ExpressionChunkGenerator(); - } - - private void ExplicitExpression() - { - var block = new Block(RazorResources.BlockName_ExplicitExpression, CurrentLocation); - Assert(CSharpSymbolType.LeftParenthesis); - AcceptAndMoveNext(); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - Output(SpanKind.MetaCode); - using (PushSpanConfig(ConfigureExplicitExpressionSpan)) - { - var success = Balance( - BalancingModes.BacktrackOnFailure | - BalancingModes.NoErrorOnFailure | - BalancingModes.AllowCommentsAndTemplates, - CSharpSymbolType.LeftParenthesis, - CSharpSymbolType.RightParenthesis, - block.Start); - - if (!success) - { - AcceptUntil(CSharpSymbolType.LessThan); - Context.OnError( - block.Start, - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(block.Name, ")", "("), - length: 1 /* ( */); - } - - // If necessary, put an empty-content marker symbol here - if (Span.Symbols.Count == 0) - { - Accept(new CSharpSymbol(CurrentLocation, string.Empty, CSharpSymbolType.Unknown)); - } - - // Output the content span and then capture the ")" - Output(SpanKind.Code); - } - Optional(CSharpSymbolType.RightParenthesis); - if (!EndOfFile) - { - PutCurrentBack(); - } - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - CompleteBlock(insertMarkerIfNecessary: false); - Output(SpanKind.MetaCode); - } - - private void Template() - { - if (Context.IsWithin(BlockType.Template)) - { - Context.OnError( - CurrentLocation, - RazorResources.ParseError_InlineMarkup_Blocks_Cannot_Be_Nested, - length: 1 /* @ */); - } - Output(SpanKind.Code); - using (Context.StartBlock(BlockType.Template)) - { - Context.CurrentBlock.ChunkGenerator = new TemplateBlockChunkGenerator(); - PutCurrentBack(); - OtherParserBlock(); - } - } - - private void OtherParserBlock() - { - ParseWithOtherParser(p => p.ParseBlock()); - } - - private void SectionBlock(string left, string right, bool caseSensitive) - { - ParseWithOtherParser(p => p.ParseSection(Tuple.Create(left, right), caseSensitive)); - } - - private void NestedBlock() - { - Output(SpanKind.Code); - var wasNested = IsNested; - IsNested = true; - using (PushSpanConfig()) - { - ParseBlock(); - } - Initialize(Span); - IsNested = wasNested; - NextToken(); - } - - protected override bool IsAtEmbeddedTransition(bool allowTemplatesAndComments, bool allowTransitions) - { - // No embedded transitions in C#, so ignore that param - return allowTemplatesAndComments - && ((Language.IsTransition(CurrentSymbol) - && NextIs(CSharpSymbolType.LessThan, CSharpSymbolType.Colon, CSharpSymbolType.DoubleColon)) - || Language.IsCommentStart(CurrentSymbol)); - } - - protected override void HandleEmbeddedTransition() - { - if (Language.IsTransition(CurrentSymbol)) - { - PutCurrentBack(); - Template(); - } - else if (Language.IsCommentStart(CurrentSymbol)) - { - RazorComment(); - } - } - - private void ParseWithOtherParser(Action parseAction) - { - // When transitioning to the HTML parser we no longer want to act as if we're in a nested C# state. - // For instance, if
@hello.
is in a nested C# block we don't want the trailing '.' to be handled - // as C#; it should be handled as a period because it's wrapped in markup. - var wasNested = IsNested; - IsNested = false; - using (PushSpanConfig()) - { - Context.SwitchActiveParser(); - parseAction(Context.MarkupParser); - Context.SwitchActiveParser(); - } - Initialize(Span); - IsNested = wasNested; - NextToken(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/CSharpLanguageCharacteristics.cs b/src/Microsoft.AspNetCore.Razor/Parser/CSharpLanguageCharacteristics.cs deleted file mode 100644 index 87bee2821b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/CSharpLanguageCharacteristics.cs +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpLanguageCharacteristics : LanguageCharacteristics - { - private static readonly CSharpLanguageCharacteristics _instance = new CSharpLanguageCharacteristics(); - - private static Dictionary _symbolSamples = new Dictionary() - { - { CSharpSymbolType.Arrow, "->" }, - { CSharpSymbolType.Minus, "-" }, - { CSharpSymbolType.Decrement, "--" }, - { CSharpSymbolType.MinusAssign, "-=" }, - { CSharpSymbolType.NotEqual, "!=" }, - { CSharpSymbolType.Not, "!" }, - { CSharpSymbolType.Modulo, "%" }, - { CSharpSymbolType.ModuloAssign, "%=" }, - { CSharpSymbolType.AndAssign, "&=" }, - { CSharpSymbolType.And, "&" }, - { CSharpSymbolType.DoubleAnd, "&&" }, - { CSharpSymbolType.LeftParenthesis, "(" }, - { CSharpSymbolType.RightParenthesis, ")" }, - { CSharpSymbolType.Star, "*" }, - { CSharpSymbolType.MultiplyAssign, "*=" }, - { CSharpSymbolType.Comma, "," }, - { CSharpSymbolType.Dot, "." }, - { CSharpSymbolType.Slash, "/" }, - { CSharpSymbolType.DivideAssign, "/=" }, - { CSharpSymbolType.DoubleColon, "::" }, - { CSharpSymbolType.Colon, ":" }, - { CSharpSymbolType.Semicolon, ";" }, - { CSharpSymbolType.QuestionMark, "?" }, - { CSharpSymbolType.NullCoalesce, "??" }, - { CSharpSymbolType.RightBracket, "]" }, - { CSharpSymbolType.LeftBracket, "[" }, - { CSharpSymbolType.XorAssign, "^=" }, - { CSharpSymbolType.Xor, "^" }, - { CSharpSymbolType.LeftBrace, "{" }, - { CSharpSymbolType.OrAssign, "|=" }, - { CSharpSymbolType.DoubleOr, "||" }, - { CSharpSymbolType.Or, "|" }, - { CSharpSymbolType.RightBrace, "}" }, - { CSharpSymbolType.Tilde, "~" }, - { CSharpSymbolType.Plus, "+" }, - { CSharpSymbolType.PlusAssign, "+=" }, - { CSharpSymbolType.Increment, "++" }, - { CSharpSymbolType.LessThan, "<" }, - { CSharpSymbolType.LessThanEqual, "<=" }, - { CSharpSymbolType.LeftShift, "<<" }, - { CSharpSymbolType.LeftShiftAssign, "<<=" }, - { CSharpSymbolType.Assign, "=" }, - { CSharpSymbolType.Equals, "==" }, - { CSharpSymbolType.GreaterThan, ">" }, - { CSharpSymbolType.GreaterThanEqual, ">=" }, - { CSharpSymbolType.RightShift, ">>" }, - { CSharpSymbolType.RightShiftAssign, ">>=" }, - { CSharpSymbolType.Hash, "#" }, - { CSharpSymbolType.Transition, "@" }, - }; - - private CSharpLanguageCharacteristics() - { - } - - public static CSharpLanguageCharacteristics Instance - { - get { return _instance; } - } - - public override CSharpTokenizer CreateTokenizer(ITextDocument source) - { - return new CSharpTokenizer(source); - } - - protected override CSharpSymbol CreateSymbol(SourceLocation location, string content, CSharpSymbolType type, IReadOnlyList errors) - { - return new CSharpSymbol(location, content, type, errors); - } - - public override string GetSample(CSharpSymbolType type) - { - return GetSymbolSample(type); - } - - public override CSharpSymbol CreateMarkerSymbol(SourceLocation location) - { - return new CSharpSymbol(location, string.Empty, CSharpSymbolType.Unknown); - } - - public override CSharpSymbolType GetKnownSymbolType(KnownSymbolType type) - { - switch (type) - { - case KnownSymbolType.Identifier: - return CSharpSymbolType.Identifier; - case KnownSymbolType.Keyword: - return CSharpSymbolType.Keyword; - case KnownSymbolType.NewLine: - return CSharpSymbolType.NewLine; - case KnownSymbolType.WhiteSpace: - return CSharpSymbolType.WhiteSpace; - case KnownSymbolType.Transition: - return CSharpSymbolType.Transition; - case KnownSymbolType.CommentStart: - return CSharpSymbolType.RazorCommentTransition; - case KnownSymbolType.CommentStar: - return CSharpSymbolType.RazorCommentStar; - case KnownSymbolType.CommentBody: - return CSharpSymbolType.RazorComment; - default: - return CSharpSymbolType.Unknown; - } - } - - public override CSharpSymbolType FlipBracket(CSharpSymbolType bracket) - { - switch (bracket) - { - case CSharpSymbolType.LeftBrace: - return CSharpSymbolType.RightBrace; - case CSharpSymbolType.LeftBracket: - return CSharpSymbolType.RightBracket; - case CSharpSymbolType.LeftParenthesis: - return CSharpSymbolType.RightParenthesis; - case CSharpSymbolType.LessThan: - return CSharpSymbolType.GreaterThan; - case CSharpSymbolType.RightBrace: - return CSharpSymbolType.LeftBrace; - case CSharpSymbolType.RightBracket: - return CSharpSymbolType.LeftBracket; - case CSharpSymbolType.RightParenthesis: - return CSharpSymbolType.LeftParenthesis; - case CSharpSymbolType.GreaterThan: - return CSharpSymbolType.LessThan; - default: -#if NET451 - // No Debug.Fail - Debug.Fail("FlipBracket must be called with a bracket character"); -#else - Debug.Assert(false, "FlipBracket must be called with a bracket character"); -#endif - return CSharpSymbolType.Unknown; - } - } - - public static string GetKeyword(CSharpKeyword keyword) - { - return keyword.ToString().ToLowerInvariant(); - } - - public static string GetSymbolSample(CSharpSymbolType type) - { - string sample; - if (!_symbolSamples.TryGetValue(type, out sample)) - { - switch (type) - { - case CSharpSymbolType.Identifier: - return RazorResources.CSharpSymbol_Identifier; - case CSharpSymbolType.Keyword: - return RazorResources.CSharpSymbol_Keyword; - case CSharpSymbolType.IntegerLiteral: - return RazorResources.CSharpSymbol_IntegerLiteral; - case CSharpSymbolType.NewLine: - return RazorResources.CSharpSymbol_Newline; - case CSharpSymbolType.WhiteSpace: - return RazorResources.CSharpSymbol_Whitespace; - case CSharpSymbolType.Comment: - return RazorResources.CSharpSymbol_Comment; - case CSharpSymbolType.RealLiteral: - return RazorResources.CSharpSymbol_RealLiteral; - case CSharpSymbolType.CharacterLiteral: - return RazorResources.CSharpSymbol_CharacterLiteral; - case CSharpSymbolType.StringLiteral: - return RazorResources.CSharpSymbol_StringLiteral; - default: - return RazorResources.Symbol_Unknown; - } - } - return sample; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/ConditionalAttributeCollapser.cs b/src/Microsoft.AspNetCore.Razor/Parser/ConditionalAttributeCollapser.cs deleted file mode 100644 index e870fecad0..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/ConditionalAttributeCollapser.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Text; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - internal class ConditionalAttributeCollapser : MarkupRewriter - { - public ConditionalAttributeCollapser(Action markupSpanFactory) : base(markupSpanFactory) - { - } - - protected override bool CanRewrite(Block block) - { - var gen = block.ChunkGenerator as AttributeBlockChunkGenerator; - if (gen != null && block.Children.Count > 0) - { - // Perf: Avoid allocating an enumerator. - for (var i = 0; i < block.Children.Count; i++) - { - if (!IsLiteralAttributeValue(block.Children[i])) - { - return false; - } - } - - return true; - } - - return false; - } - - protected override SyntaxTreeNode RewriteBlock(BlockBuilder parent, Block block) - { - // Collect the content of this node - var builder = new StringBuilder(); - for (var i = 0; i < block.Children.Count; i++) - { - var childSpan = (Span)block.Children[i]; - builder.Append(childSpan.Content); - } - - // Create a new span containing this content - var span = new SpanBuilder(); - span.EditHandler = new SpanEditHandler(HtmlTokenizer.Tokenize); - Debug.Assert(block.Children.Count > 0); - var start = ((Span)block.Children[0]).Start; - FillSpan(span, start, builder.ToString()); - return span.Build(); - } - - private bool IsLiteralAttributeValue(SyntaxTreeNode node) - { - if (node.IsBlock) - { - return false; - } - var span = node as Span; - Debug.Assert(span != null); - - var litGen = span.ChunkGenerator as LiteralAttributeChunkGenerator; - - return span != null && - ((litGen != null && litGen.ValueGenerator == null) || - span.ChunkGenerator == SpanChunkGenerator.Null || - span.ChunkGenerator is MarkupChunkGenerator); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/DisposableAction.cs b/src/Microsoft.AspNetCore.Razor/Parser/DisposableAction.cs deleted file mode 100644 index a7538dc011..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/DisposableAction.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - internal class DisposableAction : IDisposable - { - private Action _action; - private bool _invoked; - - public DisposableAction(Action action) - { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - _action = action; - } - - public void Dispose() - { - if (!_invoked) - { - _action(); - _invoked = true; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/ISyntaxTreeRewriter.cs b/src/Microsoft.AspNetCore.Razor/Parser/ISyntaxTreeRewriter.cs deleted file mode 100644 index d6404d678e..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/ISyntaxTreeRewriter.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - -namespace Microsoft.AspNetCore.Razor.Parser -{ - /// - /// Contract for rewriting a syntax tree. - /// - public interface ISyntaxTreeRewriter - { - /// - /// Rewrites the provided s . - /// - /// Contains information on the rewriting of the syntax tree. - /// - /// To modify the syntax tree replace the s . - /// - void Rewrite(RewritingContext context); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/Internal/CallbackVisitor.cs b/src/Microsoft.AspNetCore.Razor/Parser/Internal/CallbackVisitor.cs deleted file mode 100644 index 7713488cc9..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/Internal/CallbackVisitor.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class CallbackVisitor : ParserVisitor - { - private Action _spanCallback; - private Action _errorCallback; - private Action _endBlockCallback; - private Action _startBlockCallback; - private Action _completeCallback; - - public CallbackVisitor(Action spanCallback) - : this(spanCallback, _ => - { - }) - { - } - - public CallbackVisitor(Action spanCallback, Action errorCallback) - : this(spanCallback, errorCallback, _ => - { - }, _ => - { - }) - { - } - - public CallbackVisitor(Action spanCallback, Action errorCallback, Action startBlockCallback, Action endBlockCallback) - : this(spanCallback, errorCallback, startBlockCallback, endBlockCallback, () => - { - }) - { - } - - public CallbackVisitor(Action spanCallback, Action errorCallback, Action startBlockCallback, Action endBlockCallback, Action completeCallback) - { - _spanCallback = spanCallback; - _errorCallback = errorCallback; - _startBlockCallback = startBlockCallback; - _endBlockCallback = endBlockCallback; - _completeCallback = completeCallback; - } - - public SynchronizationContext SynchronizationContext { get; set; } - - public override void VisitStartBlock(Block block) - { - base.VisitStartBlock(block); - RaiseCallback(SynchronizationContext, block.Type, _startBlockCallback); - } - - public override void VisitSpan(Span span) - { - base.VisitSpan(span); - RaiseCallback(SynchronizationContext, span, _spanCallback); - } - - public override void VisitEndBlock(Block block) - { - base.VisitEndBlock(block); - RaiseCallback(SynchronizationContext, block.Type, _endBlockCallback); - } - - public override void VisitError(RazorError err) - { - base.VisitError(err); - RaiseCallback(SynchronizationContext, err, _errorCallback); - } - - public override void OnComplete() - { - base.OnComplete(); - RaiseCallback(SynchronizationContext, null, _ => _completeCallback()); - } - - private static void RaiseCallback(SynchronizationContext syncContext, T param, Action callback) - { - if (callback != null) - { - if (syncContext != null) - { - syncContext.Post(state => callback((T)state), param); - } - else - { - callback(param); - } - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlLanguageCharacteristics.cs b/src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlLanguageCharacteristics.cs deleted file mode 100644 index 1f572bc39d..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlLanguageCharacteristics.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class HtmlLanguageCharacteristics : LanguageCharacteristics - { - private static readonly HtmlLanguageCharacteristics _instance = new HtmlLanguageCharacteristics(); - - private HtmlLanguageCharacteristics() - { - } - - public static HtmlLanguageCharacteristics Instance - { - get { return _instance; } - } - - public override string GetSample(HtmlSymbolType type) - { - switch (type) - { - case HtmlSymbolType.Text: - return RazorResources.HtmlSymbol_Text; - case HtmlSymbolType.WhiteSpace: - return RazorResources.HtmlSymbol_WhiteSpace; - case HtmlSymbolType.NewLine: - return RazorResources.HtmlSymbol_NewLine; - case HtmlSymbolType.OpenAngle: - return "<"; - case HtmlSymbolType.Bang: - return "!"; - case HtmlSymbolType.ForwardSlash: - return "/"; - case HtmlSymbolType.QuestionMark: - return "?"; - case HtmlSymbolType.DoubleHyphen: - return "--"; - case HtmlSymbolType.LeftBracket: - return "["; - case HtmlSymbolType.CloseAngle: - return ">"; - case HtmlSymbolType.RightBracket: - return "]"; - case HtmlSymbolType.Equals: - return "="; - case HtmlSymbolType.DoubleQuote: - return "\""; - case HtmlSymbolType.SingleQuote: - return "'"; - case HtmlSymbolType.Transition: - return "@"; - case HtmlSymbolType.Colon: - return ":"; - case HtmlSymbolType.RazorComment: - return RazorResources.HtmlSymbol_RazorComment; - case HtmlSymbolType.RazorCommentStar: - return "*"; - case HtmlSymbolType.RazorCommentTransition: - return "@"; - default: - return RazorResources.Symbol_Unknown; - } - } - - public override HtmlTokenizer CreateTokenizer(ITextDocument source) - { - return new HtmlTokenizer(source); - } - - public override HtmlSymbolType FlipBracket(HtmlSymbolType bracket) - { - switch (bracket) - { - case HtmlSymbolType.LeftBracket: - return HtmlSymbolType.RightBracket; - case HtmlSymbolType.OpenAngle: - return HtmlSymbolType.CloseAngle; - case HtmlSymbolType.RightBracket: - return HtmlSymbolType.LeftBracket; - case HtmlSymbolType.CloseAngle: - return HtmlSymbolType.OpenAngle; - default: -#if NET451 - // No Debug.Fail in CoreCLR - - Debug.Fail("FlipBracket must be called with a bracket character"); -#else - Debug.Assert(false, "FlipBracket must be called with a bracket character"); -#endif - return HtmlSymbolType.Unknown; - } - } - - public override HtmlSymbol CreateMarkerSymbol(SourceLocation location) - { - return new HtmlSymbol(location, string.Empty, HtmlSymbolType.Unknown); - } - - public override HtmlSymbolType GetKnownSymbolType(KnownSymbolType type) - { - switch (type) - { - case KnownSymbolType.CommentStart: - return HtmlSymbolType.RazorCommentTransition; - case KnownSymbolType.CommentStar: - return HtmlSymbolType.RazorCommentStar; - case KnownSymbolType.CommentBody: - return HtmlSymbolType.RazorComment; - case KnownSymbolType.Identifier: - return HtmlSymbolType.Text; - case KnownSymbolType.Keyword: - return HtmlSymbolType.Text; - case KnownSymbolType.NewLine: - return HtmlSymbolType.NewLine; - case KnownSymbolType.Transition: - return HtmlSymbolType.Transition; - case KnownSymbolType.WhiteSpace: - return HtmlSymbolType.WhiteSpace; - default: - return HtmlSymbolType.Unknown; - } - } - - protected override HtmlSymbol CreateSymbol(SourceLocation location, string content, HtmlSymbolType type, IReadOnlyList errors) - { - return new HtmlSymbol(location, content, type, errors); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.Block.cs b/src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.Block.cs deleted file mode 100644 index 1fd74b3382..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Parser/Internal/HtmlMarkupParser.Block.cs +++ /dev/null @@ -1,1191 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public partial class HtmlMarkupParser - { - private const string ScriptTagName = "script"; - - private SourceLocation _lastTagStart = SourceLocation.Zero; - private HtmlSymbol _bufferedOpenAngle; - - public override void ParseBlock() - { - if (Context == null) - { - throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set); - } - - using (PushSpanConfig(DefaultMarkupSpan)) - { - using (Context.StartBlock(BlockType.Markup)) - { - if (!NextToken()) - { - return; - } - - AcceptWhile(IsSpacingToken(includeNewLines: true)); - - if (CurrentSymbol.Type == HtmlSymbolType.OpenAngle) - { - // "<" => Implicit Tag Block - TagBlock(new Stack>()); - } - else if (CurrentSymbol.Type == HtmlSymbolType.Transition) - { - // "@" => Explicit Tag/Single Line Block OR Template - Output(SpanKind.Markup); - - // Definitely have a transition span - Assert(HtmlSymbolType.Transition); - AcceptAndMoveNext(); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - Span.ChunkGenerator = SpanChunkGenerator.Null; - Output(SpanKind.Transition); - if (At(HtmlSymbolType.Transition)) - { - Span.ChunkGenerator = SpanChunkGenerator.Null; - AcceptAndMoveNext(); - Output(SpanKind.MetaCode); - } - AfterTransition(); - } - else - { - Context.OnError( - CurrentSymbol.Start, - RazorResources.ParseError_MarkupBlock_Must_Start_With_Tag, - CurrentSymbol.Content.Length); - } - Output(SpanKind.Markup); - } - } - } - - private void DefaultMarkupSpan(SpanBuilder span) - { - span.ChunkGenerator = new MarkupChunkGenerator(); - span.EditHandler = new SpanEditHandler(Language.TokenizeString, AcceptedCharacters.Any); - } - - private void AfterTransition() - { - // "@:" => Explicit Single Line Block - if (CurrentSymbol.Type == HtmlSymbolType.Text && CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == ':') - { - // Split the token - Tuple split = Language.SplitSymbol(CurrentSymbol, 1, HtmlSymbolType.Colon); - - // The first part (left) is added to this span and we return a MetaCode span - Accept(split.Item1); - Span.ChunkGenerator = SpanChunkGenerator.Null; - Output(SpanKind.MetaCode); - if (split.Item2 != null) - { - Accept(split.Item2); - } - NextToken(); - SingleLineMarkup(); - } - else if (CurrentSymbol.Type == HtmlSymbolType.OpenAngle) - { - TagBlock(new Stack>()); - } - } - - private void SingleLineMarkup() - { - // Parse until a newline, it's that simple! - // First, signal to code parser that whitespace is significant to us. - var old = Context.WhiteSpaceIsSignificantToAncestorBlock; - Context.WhiteSpaceIsSignificantToAncestorBlock = true; - Span.EditHandler = new SingleLineMarkupEditHandler(Language.TokenizeString); - SkipToAndParseCode(HtmlSymbolType.NewLine); - if (!EndOfFile && CurrentSymbol.Type == HtmlSymbolType.NewLine) - { - AcceptAndMoveNext(); - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - PutCurrentBack(); - Context.WhiteSpaceIsSignificantToAncestorBlock = old; - Output(SpanKind.Markup); - } - - private void TagBlock(Stack> tags) - { - // Skip Whitespace and Text - var complete = false; - do - { - SkipToAndParseCode(HtmlSymbolType.OpenAngle); - - // Output everything prior to the OpenAngle into a markup span - Output(SpanKind.Markup); - - // Do not want to start a new tag block if we're at the end of the file. - IDisposable tagBlockWrapper = null; - try - { - var atSpecialTag = AtSpecialTag; - - if (!EndOfFile && !atSpecialTag) - { - // Start a Block tag. This is used to wrap things like

or etc. - tagBlockWrapper = Context.StartBlock(BlockType.Tag); - } - - if (EndOfFile) - { - EndTagBlock(tags, complete: true); - } - else - { - _bufferedOpenAngle = null; - _lastTagStart = CurrentLocation; - Assert(HtmlSymbolType.OpenAngle); - _bufferedOpenAngle = CurrentSymbol; - var tagStart = CurrentLocation; - if (!NextToken()) - { - Accept(_bufferedOpenAngle); - EndTagBlock(tags, complete: false); - } - else - { - complete = AfterTagStart(tagStart, tags, atSpecialTag, tagBlockWrapper); - } - } - - if (complete) - { - // Completed tags have no accepted characters inside of blocks. - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - - // Output the contents of the tag into its own markup span. - Output(SpanKind.Markup); - } - finally - { - // Will be null if we were at end of file or special tag when initially created. - if (tagBlockWrapper != null) - { - // End tag block - tagBlockWrapper.Dispose(); - } - } - } - while (tags.Count > 0); - - EndTagBlock(tags, complete); - } - - private bool AfterTagStart(SourceLocation tagStart, - Stack> tags, - bool atSpecialTag, - IDisposable tagBlockWrapper) - { - if (!EndOfFile) - { - switch (CurrentSymbol.Type) - { - case HtmlSymbolType.ForwardSlash: - // End Tag - return EndTag(tagStart, tags, tagBlockWrapper); - case HtmlSymbolType.Bang: - // Comment, CDATA, DOCTYPE, or a parser-escaped HTML tag. - if (atSpecialTag) - { - Accept(_bufferedOpenAngle); - return BangTag(); - } - else - { - goto default; - } - case HtmlSymbolType.QuestionMark: - // XML PI - Accept(_bufferedOpenAngle); - return XmlPI(); - default: - // Start Tag - return StartTag(tags, tagBlockWrapper); - } - } - if (tags.Count == 0) - { - Context.OnError( - CurrentLocation, - RazorResources.ParseError_OuterTagMissingName, - length: 1 /* end of file */); - } - return false; - } - - private bool XmlPI() - { - // Accept "?" - Assert(HtmlSymbolType.QuestionMark); - AcceptAndMoveNext(); - return AcceptUntilAll(HtmlSymbolType.QuestionMark, HtmlSymbolType.CloseAngle); - } - - private bool BangTag() - { - // Accept "!" - Assert(HtmlSymbolType.Bang); - - if (AcceptAndMoveNext()) - { - if (CurrentSymbol.Type == HtmlSymbolType.DoubleHyphen) - { - AcceptAndMoveNext(); - - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - while (!EndOfFile) - { - SkipToAndParseCode(HtmlSymbolType.DoubleHyphen); - if (At(HtmlSymbolType.DoubleHyphen)) - { - AcceptWhile(HtmlSymbolType.DoubleHyphen); - - if (At(HtmlSymbolType.Text) && - string.Equals(CurrentSymbol.Content, "-", StringComparison.Ordinal)) - { - AcceptAndMoveNext(); - } - - if (At(HtmlSymbolType.CloseAngle)) - { - AcceptAndMoveNext(); - return true; - } - } - } - - return false; - } - else if (CurrentSymbol.Type == HtmlSymbolType.LeftBracket) - { - if (AcceptAndMoveNext()) - { - return CData(); - } - } - else - { - AcceptAndMoveNext(); - return AcceptUntilAll(HtmlSymbolType.CloseAngle); - } - } - - return false; - } - - private bool CData() - { - if (CurrentSymbol.Type == HtmlSymbolType.Text && string.Equals(CurrentSymbol.Content, "cdata", StringComparison.OrdinalIgnoreCase)) - { - if (AcceptAndMoveNext()) - { - if (CurrentSymbol.Type == HtmlSymbolType.LeftBracket) - { - return AcceptUntilAll(HtmlSymbolType.RightBracket, HtmlSymbolType.RightBracket, HtmlSymbolType.CloseAngle); - } - } - } - - return false; - } - - private bool EndTag(SourceLocation tagStart, - Stack> tags, - IDisposable tagBlockWrapper) - { - // Accept "/" and move next - Assert(HtmlSymbolType.ForwardSlash); - var forwardSlash = CurrentSymbol; - if (!NextToken()) - { - Accept(_bufferedOpenAngle); - Accept(forwardSlash); - return false; - } - else - { - var tagName = string.Empty; - HtmlSymbol bangSymbol = null; - - if (At(HtmlSymbolType.Bang)) - { - bangSymbol = CurrentSymbol; - - var nextSymbol = Lookahead(count: 1); - - if (nextSymbol != null && nextSymbol.Type == HtmlSymbolType.Text) - { - tagName = "!" + nextSymbol.Content; - } - } - else if (At(HtmlSymbolType.Text)) - { - tagName = CurrentSymbol.Content; - } - - var matched = RemoveTag(tags, tagName, tagStart); - - if (tags.Count == 0 && - // Note tagName may contain a '!' escape character. This ensures doesn't match here. - // tags are treated like any other escaped HTML end tag. - string.Equals(tagName, SyntaxConstants.TextTagName, StringComparison.OrdinalIgnoreCase) && - matched) - { - return EndTextTag(forwardSlash, tagBlockWrapper); - } - Accept(_bufferedOpenAngle); - Accept(forwardSlash); - - OptionalBangEscape(); - - AcceptUntil(HtmlSymbolType.CloseAngle); - - // Accept the ">" - return Optional(HtmlSymbolType.CloseAngle); - } - } - - private void RecoverTextTag() - { - // We don't want to skip-to and parse because there shouldn't be anything in the body of text tags. - AcceptUntil(HtmlSymbolType.CloseAngle, HtmlSymbolType.NewLine); - - // Include the close angle in the text tag block if it's there, otherwise just move on - Optional(HtmlSymbolType.CloseAngle); - } - - private bool EndTextTag(HtmlSymbol solidus, IDisposable tagBlockWrapper) - { - Accept(_bufferedOpenAngle); - Accept(solidus); - - var textLocation = CurrentLocation; - Assert(HtmlSymbolType.Text); - AcceptAndMoveNext(); - - var seenCloseAngle = Optional(HtmlSymbolType.CloseAngle); - - if (!seenCloseAngle) - { - Context.OnError( - textLocation, - RazorResources.ParseError_TextTagCannotContainAttributes, - length: 4 /* text */); - - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any; - RecoverTextTag(); - } - else - { - Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None; - } - - Span.ChunkGenerator = SpanChunkGenerator.Null; - - CompleteTagBlockWithSpan(tagBlockWrapper, Span.EditHandler.AcceptedCharacters, SpanKind.Transition); - - return seenCloseAngle; - } - - // Special tags include - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - The active parser must be the same as either the markup or code parser. - - - code - This is a literal used when composing ParserError_* messages. Most blocks are named by the keyword that starts them, for example "if". However, for those without keywords, a (localizable) name must be used. This literal is ALWAYS used mid-sentence, thus should not be capitalized. - - - explicit expression - This is a literal used when composing ParserError_* messages. Most blocks are named by the keyword that starts them, for example "if". However, for those without keywords, a (localizable) name must be used. This literal is ALWAYS used mid-sentence, thus should not be capitalized. - - - The "CancelBacktrack" method can be called only while in a look-ahead process started with the "BeginLookahead" method. - - - "EndBlock" was called without a matching call to "StartBlock". - - - The "@" character must be followed by a ":", "(", or a C# identifier. If you intended to switch to markup, use an HTML start tag, for example: - -@if(isLoggedIn) { - <p>Hello, @user!</p> -} - - - End of file was reached before the end of the block comment. All comments started with "/*" sequence must be terminated with a matching "*/" sequence. - - - An opening "{0}" is missing the corresponding closing "{1}". - - - The {0} block is missing a closing "{1}" character. Make sure you have a matching "{1}" character for all the "{2}" characters within this block, and that none of the "{1}" characters are being interpreted as markup. - - - Expected "{0}". - - - Inline markup blocks (@<p>Content</p>) cannot be nested. Only one level of inline markup is allowed. - - - Markup in a code block must start with a tag and all start tags must be matched with end tags. Do not use unclosed tags like "<br>". Instead use self-closing tags like "<br/>". - - - The "{0}" element was not closed. All elements must be either self-closing or have a matching end tag. - - - Sections cannot be empty. The "@section" keyword must be followed by a block of markup surrounded by "{}". For example: - -@section Sidebar { - <!-- Markup and text goes here --> -} - - - Namespace imports and type aliases cannot be placed within code blocks. They must immediately follow an "@" character in markup. It is recommended that you put them at the top of the page, as in the following example: - -@using System.Drawing; -@{ - // OK here to use types from System.Drawing in the page. -} - - - Expected a "{0}" but found a "{1}". Block statements must be enclosed in "{{" and "}}". You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed: - -@if(isLoggedIn) - <p>Hello, @user</p> - -Instead, wrap the contents of the block in "{{}}": - -@if(isLoggedIn) {{ - <p>Hello, @user</p> -}} - {0} is only ever a single character - - - Encountered end tag "{0}" with no matching start tag. Are your start/end tags properly balanced? - - - Unexpected {0} after section keyword. Section names must start with an "_" or alphabetic character, and the remaining characters must be either "_" or alphanumeric. - - - "{0}" is not valid at the start of a code block. Only identifiers, keywords, comments, "(" and "{{" are valid. - "{{" is an escape sequence for string.Format, when outputted to the user it will be displayed as "{" - - - End of file or an unexpected character was reached before the "{0}" tag could be parsed. Elements inside markup blocks must be complete. They must either be self-closing ("<br />") or have matching end tags ("<p>Hello</p>"). If you intended to display a "<" character, use the "&lt;" HTML entity. - - - Unterminated string literal. Strings that start with a quotation mark (") must be terminated before the end of the line. However, strings that start with @ and a quotation mark (@") can span multiple lines. - - - @section Header { ... } - In CSHTML, the @section keyword is case-sensitive and lowercase (as with all C# keywords) - - - "<text>" and "</text>" tags cannot contain attributes. - - - 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. - - - The 'inherits' keyword must be followed by a type name on the same line. - - - Outer tag is missing a name. The first character of a markup block must be an HTML tag with a valid name. - - - End of file was reached before the end of the block comment. All comments that start with the "@*" sequence must be terminated with a matching "*@" sequence. - - - "{0}" character - - - end of file - - - space or line break - - - End-of-file was found after the "@" character. "@" must be followed by a valid code block. If you want to output an "@", escape it using the sequence: "@@" - - - The {0} property of the {1} structure cannot be null. - - - Parser was started with a null Context property. The Context property must be set BEFORE calling any methods on the parser. - - - "{0}" is a reserved word and cannot be used in implicit expressions. An explicit expression ("@()") must be used. - - - Cannot resume this symbol. Only the symbol immediately preceding the current one can be resumed. - - - Cannot finish span, there is no current block. Call StartBlock at least once before finishing a span - - - Cannot complete the tree, there are still open blocks. - - - Cannot complete the tree, StartBlock must be called at least once. - - - Cannot complete action, the parser has finished. Only CompleteParse can be called to extract the final parser results after the parser has finished - - - Block cannot be built because a Type has not been specified in the BlockBuilder - - - <<character literal>> - - - <<comment>> - - - <<identifier>> - - - <<integer literal>> - - - <<keyword>> - - - <<newline sequence>> - - - <<real literal>> - - - <<string literal>> - - - <<white space>> - - - <<unknown>> - - - In order to put a symbol back, it must have been the symbol which ended at the current position. The specified symbol ends at {0}, but the current position is {1} - - - Unexpected "{" after "@" character. Once inside the body of a code block (@if {}, @{}, etc.) you do not need to use "@{" to switch to code. - - - line break - - - <<newline sequence>> - - - <<razor comment>> - - - <<text>> - - - <<white space>> - - - The parser provided to the ParserContext was not a Markup Parser. - - - Cannot use built-in RazorComment handler, language characteristics does not define the CommentStart, CommentStar and CommentBody known symbol types or parser does not override TokenizerBackedParser.OutputSpanBeforeRazorComment - - - [BG][{0}] Shutdown - - - [BG][{0}] Startup - - - [BG][{0}] {1} changes arrived - - - [BG][{0}] Discarded {1} changes - - - [BG][{0}] Collecting {1} discarded changes - - - Disabled - - - [P][{0}] {3} Change in {2} milliseconds: {1} - - - [P][{0}] Received Change: {1} - - - Enabled - - - [Razor] {0} - - - [BG][{0}] no changes arrived? - - - [BG][{0}] Parse Complete in {1} milliseconds - - - [M][{0}] Queuing Parse for: {1} - - - [Razor] Editor Tracing {0} - - - [BG][{0}] Trees Compared in {1} milliseconds. Different = {2} - - - Section blocks ("{0}") cannot be nested. Only one level of section blocks are allowed. - - - Tag Helper '{0}'s attributes must have names. - - - The tag helper '{0}' must not have C# in the element's attribute declaration area. - - - Directive '{0}' must have a value. - - - Found a malformed '{0}' tag helper. Tag helpers must have a start and end tag or be self closing. - - - Missing close angle for tag helper '{0}'. - - - TagHelper attributes must be well-formed. - - - The tag helper attribute '{0}' in element '{1}' is missing a key. The syntax is '<{1} {0}{{ key }}="value">'. - - - Non-string tag helper attribute values must not be empty. Add an expression to this attribute value. - - - Code blocks (e.g. @{{var variable = 23;}}) must not appear in non-string tag helper attribute values. - Already in an expression (code) context. If necessary an explicit expression (e.g. @(@readonly)) may be used. - - - @'{0}' directives must not appear in non-string tag helper attribute values. - - - Inline markup blocks (e.g. @<p>content</p>) must not appear in non-string tag helper attribute values. - Expected a '{0}' attribute value, not a string. - - - Attribute '{0}' on tag helper element '{1}' requires a value. Tag helper bound attributes of type '{2}' cannot be empty or contain only whitespace. - - - Cannot perform '{1}' operations on '{0}' instances with different file paths. - - - Tag helpers '{0}' and '{1}' targeting element '{2}' must not expect different {3} values. - - - Found an end tag (</{0}>) for tag helper '{1}' with tag structure that disallows an end tag ('{2}'). - - - The parent <{0}> tag helper does not allow non-tag content. Only child tag helper(s) targeting tag name(s) '{1}' are allowed. - - - The <{0}> tag is not allowed by parent <{1}> tag helper. Only child tags with name(s) '{2}' are allowed. - - - The {0} directive is not supported. - - - Optional quote around the directive '{0}' is missing the corresponding opening or closing quote. - - - A fatal exception occurred when trying to parse '{0}':{1}{2} - - \ No newline at end of file diff --git a/src/Microsoft.AspNetCore.Razor/RazorTemplateEngine.cs b/src/Microsoft.AspNetCore.Razor/RazorTemplateEngine.cs deleted file mode 100644 index dcbe13473c..0000000000 --- a/src/Microsoft.AspNetCore.Razor/RazorTemplateEngine.cs +++ /dev/null @@ -1,463 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor -{ - ///

- /// Entry-point to the Razor Template Engine - /// - public class RazorTemplateEngine - { - private const int BufferSize = 1024; - public static readonly string DefaultClassName = "Template"; - public static readonly string DefaultNamespace = string.Empty; - - /// - /// Constructs a new RazorTemplateEngine with the specified host - /// - /// - /// The host which defines the environment in which the generated template code will live. - /// - public RazorTemplateEngine(RazorEngineHost host) - { - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } - - Host = host; - } - - /// - /// The RazorEngineHost which defines the environment in which the generated template code will live - /// - public RazorEngineHost Host { get; } - - public ParserResults ParseTemplate(ITextBuffer input) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return ParseTemplate(input, cancelToken: null); - } - - /// - /// Parses the template specified by the TextBuffer and returns it's result - /// - /// - /// - /// IMPORTANT: This does NOT need to be called before GeneratedCode! GenerateCode will automatically - /// parse the document first. - /// - /// - /// The cancel token provided can be used to cancel the parse. However, please note - /// that the parse occurs _synchronously_, on the callers thread. This parameter is - /// provided so that if the caller is in a background thread with a CancellationToken, - /// it can pass it along to the parser. - /// - /// - /// The input text to parse. - /// A token used to cancel the parser. - /// The resulting parse tree. - public ParserResults ParseTemplate(ITextBuffer input, CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return ParseTemplateCore(input.ToDocument(), sourceFileName: null, cancelToken: cancelToken); - } - - // See ParseTemplate(ITextBuffer, CancellationToken?), - // this overload simply wraps a TextReader in a TextBuffer (see ITextBuffer) - public ParserResults ParseTemplate(TextReader input, string sourceFileName) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return ParseTemplateCore(new SeekableTextReader(input), sourceFileName, cancelToken: null); - } - - public ParserResults ParseTemplate(TextReader input, CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return ParseTemplateCore(new SeekableTextReader(input), sourceFileName: null, cancelToken: cancelToken); - } - - protected internal virtual ParserResults ParseTemplateCore( - ITextDocument input, - string sourceFileName, - CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - // Construct the parser - var parser = CreateParser(sourceFileName); - Debug.Assert(parser != null); - return parser.Parse(input); - } - - public GeneratorResults GenerateCode(ITextBuffer input) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCode(input, className: null, rootNamespace: null, sourceFileName: null, cancelToken: null); - } - - public GeneratorResults GenerateCode(ITextBuffer input, CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCode( - input, - className: null, - rootNamespace: null, - sourceFileName: null, - cancelToken: cancelToken); - } - - public GeneratorResults GenerateCode( - ITextBuffer input, - string className, - string rootNamespace, - string sourceFileName) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCode(input, className, rootNamespace, sourceFileName, cancelToken: null); - } - - /// - /// Parses the template specified by the TextBuffer, generates code for it, and returns the constructed code. - /// - /// - /// - /// The cancel token provided can be used to cancel the parse. However, please note - /// that the parse occurs _synchronously_, on the callers thread. This parameter is - /// provided so that if the caller is in a background thread with a CancellationToken, - /// it can pass it along to the parser. - /// - /// - /// The className, rootNamespace and sourceFileName parameters are optional and override the default - /// specified by the Host. For example, the WebPageRazorHost in System.Web.WebPages.Razor configures the - /// Class Name, Root Namespace and Source File Name based on the virtual path of the page being compiled. - /// However, the built-in RazorEngineHost class uses constant defaults, so the caller will likely want to - /// change them using these parameters. - /// - /// - /// The input text to parse. - /// A token used to cancel the parser. - /// - /// The name of the generated class, overriding whatever is specified in the Host. The default value (defined - /// in the Host) can be used by providing null for this argument. - /// - /// The namespace in which the generated class will reside, overriding whatever is - /// specified in the Host. The default value (defined in the Host) can be used by providing null for this - /// argument. - /// - /// - /// The file name to use in line pragmas, usually the original Razor file, overriding whatever is specified in - /// the Host. The default value (defined in the Host) can be used by providing null for this argument. - /// - /// The resulting parse tree AND generated code. - public GeneratorResults GenerateCode( - ITextBuffer input, - string className, - string rootNamespace, - string sourceFileName, - CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCodeCore( - input.ToDocument(), - className, - rootNamespace, - sourceFileName, - checksum: null, - cancelToken: cancelToken); - } - - // See GenerateCode override which takes ITextBuffer, and BufferingTextReader for details. - public GeneratorResults GenerateCode(TextReader input) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCode(input, className: null, rootNamespace: null, sourceFileName: null, cancelToken: null); - } - - public GeneratorResults GenerateCode(TextReader input, CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCode( - input, - className: null, - rootNamespace: null, - sourceFileName: null, - cancelToken: cancelToken); - } - - public GeneratorResults GenerateCode( - TextReader input, - string className, - - string rootNamespace, string sourceFileName) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCode(input, className, rootNamespace, sourceFileName, cancelToken: null); - } - - /// - /// Parses the contents specified by the and returns the generated code. - /// - /// A that represents the contents to be parsed. - /// The name of the generated class. When null, defaults to - /// (Host.DefaultClassName). - /// The namespace in which the generated class will reside. When null, - /// defaults to (Host.DefaultNamespace). - /// - /// The file name to use in line pragmas, usually the original Razor file. - /// - /// A that represents the results of parsing the content. - /// - /// This overload calculates the checksum of the contents of prior to code - /// generation. The checksum is used for producing the #pragma checksum line pragma required for - /// debugging. - /// - public GeneratorResults GenerateCode( - Stream inputStream, - string className, - string rootNamespace, - string sourceFileName) - { - if (inputStream == null) - { - throw new ArgumentNullException(nameof(inputStream)); - } - - MemoryStream memoryStream = null; - string checksum = null; - try - { - if (!Host.DesignTimeMode) - { - // We don't need to calculate the checksum in design time. - if (!inputStream.CanSeek) - { - memoryStream = new MemoryStream(); - inputStream.CopyTo(memoryStream); - - // We don't have to dispose the input stream since it is owned externally. - inputStream = memoryStream; - } - - inputStream.Position = 0; - checksum = ComputeChecksum(inputStream); - inputStream.Position = 0; - } - - using (var reader = - new StreamReader( - inputStream, - Encoding.UTF8, - detectEncodingFromByteOrderMarks: true, - bufferSize: BufferSize, - leaveOpen: true)) - { - var seekableStream = new SeekableTextReader(reader); - return GenerateCodeCore( - seekableStream, - className, - rootNamespace, - sourceFileName, - checksum, - cancelToken: null); - } - } - finally - { - if (memoryStream != null) - { - memoryStream.Dispose(); - } - } - } - - public GeneratorResults GenerateCode( - TextReader input, - string className, - string rootNamespace, - string sourceFileName, - CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return GenerateCodeCore( - new SeekableTextReader(input), - className, - rootNamespace, - sourceFileName, - checksum: null, - cancelToken: cancelToken); - } - - protected internal virtual GeneratorResults GenerateCodeCore( - ITextDocument input, - string className, - string rootNamespace, - string sourceFileName, - string checksum, - CancellationToken? cancelToken) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - try - { - className = (className ?? Host.DefaultClassName) ?? DefaultClassName; - rootNamespace = (rootNamespace ?? Host.DefaultNamespace) ?? DefaultNamespace; - - // Run the parser - var parser = CreateParser(sourceFileName); - Debug.Assert(parser != null); - var results = parser.Parse(input); - - // Generate code - var chunkGenerator = CreateChunkGenerator(className, rootNamespace, sourceFileName); - chunkGenerator.DesignTimeMode = Host.DesignTimeMode; - chunkGenerator.Visit(results); - - var codeGeneratorContext = new CodeGeneratorContext(chunkGenerator.Context, results.ErrorSink); - codeGeneratorContext.Checksum = checksum; - var codeGenerator = CreateCodeGenerator(codeGeneratorContext); - var codeGeneratorResult = codeGenerator.Generate(); - - // Collect results and return - return new GeneratorResults(results, codeGeneratorResult, codeGeneratorContext.ChunkTreeBuilder.Root); - } - // During runtime we want code generation explosions to flow up into the calling code. At design time - // we want to capture these exceptions to prevent IDEs from crashing. - catch (Exception ex) when (Host.DesignTimeMode) - { - var errorSink = new ErrorSink(); - errorSink.OnError( - SourceLocation.Undefined, - RazorResources.FormatFatalException(sourceFileName, Environment.NewLine, ex.Message), - length: -1); - var emptyBlock = new BlockBuilder(); - emptyBlock.Type = default(BlockType); - - return new GeneratorResults( - document: emptyBlock.Build(), - tagHelperDescriptors: Enumerable.Empty(), - errorSink: errorSink, - codeGeneratorResult: new CodeGeneratorResult( - code: string.Empty, - designTimeLineMappings: new List()), - chunkTree: new ChunkTree()); - } - } - - protected internal virtual RazorChunkGenerator CreateChunkGenerator( - string className, - string rootNamespace, - string sourceFileName) - { - return Host.DecorateChunkGenerator( - Host.CodeLanguage.CreateChunkGenerator(className, rootNamespace, sourceFileName, Host)); - } - - 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); - } - - protected internal virtual CodeGenerator CreateCodeGenerator(CodeGeneratorContext context) - { - return Host.DecorateCodeGenerator(Host.CodeLanguage.CreateCodeGenerator(context), context); - } - - private static string ComputeChecksum(Stream inputStream) - { - byte[] hashedBytes; - using (var hashAlgorithm = SHA1.Create()) - { - hashedBytes = hashAlgorithm.ComputeHash(inputStream); - } - - var fileHashBuilder = new StringBuilder(hashedBytes.Length * 2); - foreach (var value in hashedBytes) - { - fileHashBuilder.Append(value.ToString("x2")); - } - return fileHashBuilder.ToString(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/SourceLocation.cs b/src/Microsoft.AspNetCore.Razor/SourceLocation.cs deleted file mode 100644 index 2593fd6d91..0000000000 --- a/src/Microsoft.AspNetCore.Razor/SourceLocation.cs +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor -{ - /// - /// A location in a Razor file. - /// -#if NET451 - // No Serializable attribute in CoreCLR (no need for it anymore?) - [Serializable] -#endif - public struct SourceLocation : IEquatable, IComparable - { - /// - /// An undefined . - /// - public static readonly SourceLocation Undefined = - new SourceLocation(absoluteIndex: -1, lineIndex: -1, characterIndex: -1); - - /// - /// A with , , and - /// initialized to 0. - /// - public static readonly SourceLocation Zero = - new SourceLocation(absoluteIndex: 0, lineIndex: 0, characterIndex: 0); - - /// - /// Initializes a new instance of . - /// - /// The absolute index. - /// The line index. - /// The character index. - public SourceLocation(int absoluteIndex, int lineIndex, int characterIndex) - : this(filePath: null, absoluteIndex: absoluteIndex, lineIndex: lineIndex, characterIndex: characterIndex) - { - } - - /// - /// Initializes a new instance of . - /// - /// The file path. - /// The absolute index. - /// The line index. - /// The character index. - public SourceLocation(string filePath, int absoluteIndex, int lineIndex, int characterIndex) - { - FilePath = filePath; - AbsoluteIndex = absoluteIndex; - LineIndex = lineIndex; - CharacterIndex = characterIndex; - } - - /// - /// Path of the file. - /// - /// When null, the parser assumes the location is in the file currently being processed. - /// - public string FilePath { get; set; } - - /// Set property is only accessible for deserialization purposes. - public int AbsoluteIndex { get; set; } - - /// - /// Gets the 1-based index of the line referred to by this Source Location. - /// - /// Set property is only accessible for deserialization purposes. - public int LineIndex { get; set; } - - /// Set property is only accessible for deserialization purposes. - public int CharacterIndex { get; set; } - - /// - public override string ToString() - { - return string.Format( - CultureInfo.CurrentCulture, - "({0}:{1},{2})", - AbsoluteIndex, - LineIndex, - CharacterIndex); - } - - /// - public override bool Equals(object obj) - { - return obj is SourceLocation && - Equals((SourceLocation)obj); - } - - /// - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(FilePath, StringComparer.Ordinal); - hashCodeCombiner.Add(AbsoluteIndex); - - return hashCodeCombiner; - } - - /// - public bool Equals(SourceLocation other) - { - // LineIndex and CharacterIndex can be calculated from AbsoluteIndex and the document content. - return CompareTo(other) == 0; - } - - /// - public int CompareTo(SourceLocation other) - { - var filePathOrdinal = string.Compare(FilePath, other.FilePath, StringComparison.Ordinal); - if (filePathOrdinal != 0) - { - return filePathOrdinal; - } - - return AbsoluteIndex.CompareTo(other.AbsoluteIndex); - } - - /// - /// Advances the by the length of the . - /// - /// The to advance. - /// The to advance by. - /// The advanced . - public static SourceLocation Advance(SourceLocation left, string text) - { - if (text == null) - { - throw new ArgumentNullException(nameof(text)); - } - - var tracker = new SourceLocationTracker(left); - tracker.UpdateLocation(text); - return tracker.CurrentLocation; - } - - /// - /// Adds two s. - /// - /// The left operand. - /// The right operand. - /// A that is the sum of the left and right operands. - /// if the of the left and right operands - /// are different, and neither is null. - public static SourceLocation operator +(SourceLocation left, SourceLocation right) - { - if (!string.Equals(left.FilePath, right.FilePath, StringComparison.Ordinal) && - left.FilePath != null && - right.FilePath != null) - { - // Throw if FilePath for left and right are different, and neither is null. - throw new ArgumentException( - RazorResources.FormatSourceLocationFilePathDoesNotMatch(nameof(SourceLocation), "+"), - nameof(right)); - } - - var resultFilePath = left.FilePath ?? right.FilePath; - if (right.LineIndex > 0) - { - // Column index doesn't matter - return new SourceLocation( - resultFilePath, - left.AbsoluteIndex + right.AbsoluteIndex, - left.LineIndex + right.LineIndex, - right.CharacterIndex); - } - else - { - return new SourceLocation( - resultFilePath, - left.AbsoluteIndex + right.AbsoluteIndex, - left.LineIndex + right.LineIndex, - left.CharacterIndex + right.CharacterIndex); - } - } - - /// - /// Subtracts two s. - /// - /// The left operand. - /// The right operand. - /// A that is the difference of the left and right operands. - /// if the of the left and right operands - /// are different. - public static SourceLocation operator -(SourceLocation left, SourceLocation right) - { - if (!string.Equals(left.FilePath, right.FilePath, StringComparison.Ordinal)) - { - throw new ArgumentException( - RazorResources.FormatSourceLocationFilePathDoesNotMatch(nameof(SourceLocation), "-"), - nameof(right)); - } - - var characterIndex = left.LineIndex != right.LineIndex ? - left.CharacterIndex : left.CharacterIndex - right.CharacterIndex; - - return new SourceLocation( - filePath: null, - absoluteIndex: left.AbsoluteIndex - right.AbsoluteIndex, - lineIndex: left.LineIndex - right.LineIndex, - characterIndex: characterIndex); - } - - /// - /// Determines whether the first operand is less than the second operand. - /// - /// The left operand. - /// The right operand. - /// true if is less than . - public static bool operator <(SourceLocation left, SourceLocation right) - { - return left.CompareTo(right) < 0; - } - - /// - /// Determines whether the first operand is greater than the second operand. - /// - /// The left operand. - /// The right operand. - /// true if is greater than . - public static bool operator >(SourceLocation left, SourceLocation right) - { - return left.CompareTo(right) > 0; - } - - /// - /// Determines whether the operands are equal. - /// - /// The left operand. - /// The right operand. - /// true if and are equal. - public static bool operator ==(SourceLocation left, SourceLocation right) - { - return left.Equals(right); - } - - /// - /// Determines whether the operands are not equal. - /// - /// The left operand. - /// The right operand. - /// true if and are not equal. - public static bool operator !=(SourceLocation left, SourceLocation right) - { - return !left.Equals(right); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/ITextBuffer.cs b/src/Microsoft.AspNetCore.Razor/Text/ITextBuffer.cs deleted file mode 100644 index d3165ba410..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/ITextBuffer.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Text -{ - public interface ITextBuffer - { - int Length { get; } - int Position { get; set; } - int Read(); - int Peek(); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/ITextDocument.cs b/src/Microsoft.AspNetCore.Razor/Text/ITextDocument.cs deleted file mode 100644 index 767941661a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/ITextDocument.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Text -{ - public interface ITextDocument : ITextBuffer - { - SourceLocation Location { get; } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/LineTrackingStringBuffer.cs b/src/Microsoft.AspNetCore.Razor/Text/LineTrackingStringBuffer.cs deleted file mode 100644 index 202cad89b9..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/LineTrackingStringBuffer.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using Microsoft.AspNetCore.Razor.Parser; - -namespace Microsoft.AspNetCore.Razor.Text -{ - internal class LineTrackingStringBuffer - { - private TextLine _currentLine; - private TextLine _endLine; - private IList _lines; - - public LineTrackingStringBuffer() - { - _endLine = new TextLine(0, 0); - _lines = new List() { _endLine }; - } - - public int Length - { - get { return _endLine.End; } - } - - public SourceLocation EndLocation - { - get { return new SourceLocation(Length, _lines.Count - 1, _lines[_lines.Count - 1].Length); } - } - - public void Append(string content) - { - var previousIndex = 0; - for (var i = 0; i < content.Length; i++) - { - // \r on it's own: Start a new line, otherwise wait for \n - // Other Newline: Start a new line - if ((content[i] == '\r' && (i + 1 == content.Length || content[i + 1] != '\n')) || - (content[i] != '\r' && ParserHelpers.IsNewLine(content[i]))) - { - AppendCore(content, previousIndex, i - previousIndex + 1); - previousIndex = i + 1; - PushNewLine(); - } - } - - if (previousIndex < content.Length) - { - AppendCore(content, previousIndex, content.Length - previousIndex); - } - } - - public CharacterReference CharAt(int absoluteIndex) - { - var line = FindLine(absoluteIndex); - if (line == null) - { - throw new ArgumentOutOfRangeException(nameof(absoluteIndex)); - } - var idx = absoluteIndex - line.Start; - return new CharacterReference(line.Content[idx], new SourceLocation(absoluteIndex, line.Index, idx)); - } - - private void PushNewLine() - { - _endLine = new TextLine(_endLine.End, _endLine.Index + 1); - _lines.Add(_endLine); - } - - private void AppendCore(string content, int index, int length) - { - Debug.Assert(_lines.Count > 0); - _lines[_lines.Count - 1].Content.Append(content, index, length); - } - - private void AppendCore(char chr) - { - Debug.Assert(_lines.Count > 0); - _lines[_lines.Count - 1].Content.Append(chr); - } - - private TextLine FindLine(int absoluteIndex) - { - TextLine selected = null; - - if (_currentLine != null) - { - if (_currentLine.Contains(absoluteIndex)) - { - // This index is on the last read line - selected = _currentLine; - } - else if (absoluteIndex > _currentLine.Index && _currentLine.Index + 1 < _lines.Count) - { - // This index is ahead of the last read line - selected = ScanLines(absoluteIndex, _currentLine.Index); - } - } - - // Have we found a line yet? - if (selected == null) - { - // Scan from line 0 - selected = ScanLines(absoluteIndex, 0); - } - - Debug.Assert(selected == null || selected.Contains(absoluteIndex)); - _currentLine = selected; - return selected; - } - - private TextLine ScanLines(int absoluteIndex, int startPos) - { - for (int i = 0; i < _lines.Count; i++) - { - var idx = (i + startPos) % _lines.Count; - Debug.Assert(idx >= 0 && idx < _lines.Count); - - if (_lines[idx].Contains(absoluteIndex)) - { - return _lines[idx]; - } - } - return null; - } - - internal struct CharacterReference - { - private readonly char _character; - private readonly SourceLocation _location; - - public CharacterReference(char character, SourceLocation location) - { - _character = character; - _location = location; - } - - public char Character { get { return _character; } } - public SourceLocation Location { get { return _location; } } - } - - private class TextLine - { - private StringBuilder _content = new StringBuilder(); - - public TextLine(int start, int index) - { - Start = start; - Index = index; - } - - public StringBuilder Content - { - get { return _content; } - } - - public int Length - { - get { return Content.Length; } - } - - public int Start { get; set; } - public int Index { get; set; } - - public int End - { - get { return Start + Length; } - } - - public bool Contains(int index) - { - return index < End && index >= Start; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/LocationTagged.cs b/src/Microsoft.AspNetCore.Razor/Text/LocationTagged.cs deleted file mode 100644 index abd4e8fad4..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/LocationTagged.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Globalization; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Text -{ - [DebuggerDisplay("({Location})\"{Value}\"")] - public class LocationTagged : IFormattable - { - private LocationTagged() - { - Location = SourceLocation.Undefined; - Value = default(TValue); - } - - public LocationTagged(TValue value, int offset, int line, int col) - : this(value, new SourceLocation(offset, line, col)) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - } - - public LocationTagged(TValue value, SourceLocation location) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - Location = location; - Value = value; - } - - public SourceLocation Location { get; } - - public TValue Value { get; } - - public override bool Equals(object obj) - { - var other = obj as LocationTagged; - if (ReferenceEquals(other, null)) - { - return false; - } - - return Equals(other.Location, Location) && - Equals(other.Value, Value); - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(Location); - hashCodeCombiner.Add(Value); - - return hashCodeCombiner.CombinedHash; - } - - public override string ToString() - { - return Value.ToString(); - } - - public string ToString(string format, IFormatProvider formatProvider) - { - if (string.IsNullOrEmpty(format)) - { - format = "P"; - } - if (formatProvider == null) - { - formatProvider = CultureInfo.CurrentCulture; - } - switch (format.ToUpperInvariant()) - { - case "F": - return string.Format(formatProvider, "{0}@{1}", Value, Location); - default: - return Value.ToString(); - } - } - - public static implicit operator TValue(LocationTagged value) - { - return value == null ? default(TValue) : value.Value; - } - - public static bool operator ==(LocationTagged left, LocationTagged right) - { - return Equals(left, right); - } - - public static bool operator !=(LocationTagged left, LocationTagged right) - { - return !Equals(left, right); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/LookaheadTextReader.cs b/src/Microsoft.AspNetCore.Razor/Text/LookaheadTextReader.cs deleted file mode 100644 index ecb8fc04cf..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/LookaheadTextReader.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public abstract class LookaheadTextReader : TextReader - { - public abstract SourceLocation CurrentLocation { get; } - public abstract IDisposable BeginLookahead(); - public abstract void CancelBacktrack(); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/LookaheadToken.cs b/src/Microsoft.AspNetCore.Razor/Text/LookaheadToken.cs deleted file mode 100644 index 375d837b42..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/LookaheadToken.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public struct LookaheadToken : IDisposable - { - private readonly ITextBuffer _buffer; - private readonly int _position; - - private bool _accepted; - - public LookaheadToken(ITextBuffer buffer) - { - _buffer = buffer; - _position = buffer.Position; - - _accepted = false; - } - - public void Accept() - { - _accepted = true; - } - - public void Dispose() - { - if (!_accepted) - { - _buffer.Position = _position; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/SeekableTextReader.cs b/src/Microsoft.AspNetCore.Razor/Text/SeekableTextReader.cs deleted file mode 100644 index 7b7d13a5dc..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/SeekableTextReader.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public class SeekableTextReader : TextReader, ITextDocument - { - private int _position = 0; - private LineTrackingStringBuffer _buffer = new LineTrackingStringBuffer(); - private SourceLocation _location = SourceLocation.Zero; - private char? _current; - - public SeekableTextReader(string content) - { - _buffer.Append(content); - UpdateState(); - } - - public SeekableTextReader(TextReader source) - : this(source.ReadToEnd()) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - } - - public SeekableTextReader(ITextBuffer buffer) - : this(buffer.ReadToEnd()) - { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - } - - public SourceLocation Location - { - get { return _location; } - } - - public int Length - { - get { return _buffer.Length; } - } - - public int Position - { - get { return _position; } - set - { - if (_position != value) - { - _position = value; - UpdateState(); - } - } - } - - internal LineTrackingStringBuffer Buffer - { - get { return _buffer; } - } - - public override int Read() - { - if (_current == null) - { - return -1; - } - var chr = _current.Value; - _position++; - UpdateState(); - return chr; - } - - public override int Peek() - { - if (_current == null) - { - return -1; - } - return _current.Value; - } - - private void UpdateState() - { - if (_position < _buffer.Length) - { - LineTrackingStringBuffer.CharacterReference chr = _buffer.CharAt(_position); - _current = chr.Character; - _location = chr.Location; - } - else if (_buffer.Length == 0) - { - _current = null; - _location = SourceLocation.Zero; - } - else - { - _current = null; - _location = _buffer.EndLocation; - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/SourceLocationTracker.cs b/src/Microsoft.AspNetCore.Razor/Text/SourceLocationTracker.cs deleted file mode 100644 index 54baf62a14..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/SourceLocationTracker.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public class SourceLocationTracker - { - private int _absoluteIndex = 0; - private int _characterIndex = 0; - private int _lineIndex = 0; - private SourceLocation _currentLocation; - - public SourceLocationTracker() - : this(SourceLocation.Zero) - { - } - - public SourceLocationTracker(SourceLocation currentLocation) - { - CurrentLocation = currentLocation; - - UpdateInternalState(); - } - - public SourceLocation CurrentLocation - { - get - { - return _currentLocation; - } - set - { - if (_currentLocation != value) - { - _currentLocation = value; - UpdateInternalState(); - } - } - } - - public void UpdateLocation(char characterRead, char nextCharacter) - { - UpdateCharacterCore(characterRead, nextCharacter); - RecalculateSourceLocation(); - } - - public SourceLocationTracker UpdateLocation(string content) - { - for (int i = 0; i < content.Length; i++) - { - var nextCharacter = '\0'; - if (i < content.Length - 1) - { - nextCharacter = content[i + 1]; - } - UpdateCharacterCore(content[i], nextCharacter); - } - RecalculateSourceLocation(); - return this; - } - - private void UpdateCharacterCore(char characterRead, char nextCharacter) - { - _absoluteIndex++; - - if (Environment.NewLine.Length == 1 && characterRead == Environment.NewLine[0] || - ParserHelpers.IsNewLine(characterRead) && (characterRead != '\r' || nextCharacter != '\n')) - { - _lineIndex++; - _characterIndex = 0; - } - else - { - _characterIndex++; - } - } - - private void UpdateInternalState() - { - _absoluteIndex = CurrentLocation.AbsoluteIndex; - _characterIndex = CurrentLocation.CharacterIndex; - _lineIndex = CurrentLocation.LineIndex; - } - - private void RecalculateSourceLocation() - { - _currentLocation = new SourceLocation( - _currentLocation.FilePath, - _absoluteIndex, - _lineIndex, - _characterIndex); - } - - public static SourceLocation CalculateNewLocation(SourceLocation lastPosition, string newContent) - { - return new SourceLocationTracker(lastPosition).UpdateLocation(newContent).CurrentLocation; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/TextChange.cs b/src/Microsoft.AspNetCore.Razor/Text/TextChange.cs deleted file mode 100644 index 7ea7664d9f..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/TextChange.cs +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Globalization; -using System.Text; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public struct TextChange - { - private string _newText; - private string _oldText; - - /// - /// Constructor for changes where the position hasn't moved (primarily for tests) - /// - internal TextChange(int position, int oldLength, ITextBuffer oldBuffer, int newLength, ITextBuffer newBuffer) - : this(position, oldLength, oldBuffer, position, newLength, newBuffer) - { - } - - public TextChange( - int oldPosition, - int oldLength, - ITextBuffer oldBuffer, - int newPosition, - int newLength, - ITextBuffer newBuffer) - : this() - { - if (oldBuffer == null) - { - throw new ArgumentNullException(nameof(oldBuffer)); - } - - if (newBuffer == null) - { - throw new ArgumentNullException(nameof(newBuffer)); - } - - if (oldPosition < 0) - { - throw new ArgumentOutOfRangeException(nameof(oldPosition), CommonResources.FormatArgument_Must_Be_GreaterThanOrEqualTo(0)); - } - if (newPosition < 0) - { - throw new ArgumentOutOfRangeException(nameof(newPosition), CommonResources.FormatArgument_Must_Be_GreaterThanOrEqualTo(0)); - } - if (oldLength < 0) - { - throw new ArgumentOutOfRangeException(nameof(oldLength), CommonResources.FormatArgument_Must_Be_GreaterThanOrEqualTo(0)); - } - if (newLength < 0) - { - throw new ArgumentOutOfRangeException(nameof(newLength), CommonResources.FormatArgument_Must_Be_GreaterThanOrEqualTo(0)); - } - - OldPosition = oldPosition; - NewPosition = newPosition; - OldLength = oldLength; - NewLength = newLength; - NewBuffer = newBuffer; - OldBuffer = oldBuffer; - } - - public int OldPosition { get; } - - public int NewPosition { get; } - - public int OldLength { get; } - - public int NewLength { get; } - - public ITextBuffer NewBuffer { get; } - - public ITextBuffer OldBuffer { get; } - - /// - /// Note: This property is not thread safe, and will move position on the textbuffer while being read. - /// https://aspnetwebstack.codeplex.com/workitem/1317, tracks making this immutable and improving the access - /// to ITextBuffer to be thread safe. - /// - public string OldText - { - get - { - if (_oldText == null && OldBuffer != null) - { - _oldText = GetText(OldBuffer, OldPosition, OldLength); - } - return _oldText; - } - } - - /// - /// Note: This property is not thread safe, and will move position on the textbuffer while being read. - /// https://aspnetwebstack.codeplex.com/workitem/1317, tracks making this immutable and improving the access - /// to ITextBuffer to be thread safe. - /// - public string NewText - { - get - { - if (_newText == null) - { - _newText = GetText(NewBuffer, NewPosition, NewLength); - } - return _newText; - } - } - - public bool IsInsert - { - get { return OldLength == 0 && NewLength > 0; } - } - - public bool IsDelete - { - get { return OldLength > 0 && NewLength == 0; } - } - - public bool IsReplace - { - get { return OldLength > 0 && NewLength > 0; } - } - - public override bool Equals(object obj) - { - if (!(obj is TextChange)) - { - return false; - } - - var change = (TextChange)obj; - return change.OldPosition == OldPosition && - change.NewPosition == NewPosition && - change.OldLength == OldLength && - change.NewLength == NewLength && - OldBuffer.Equals(change.OldBuffer) && - NewBuffer.Equals(change.NewBuffer); - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(OldPosition); - hashCodeCombiner.Add(NewPosition); - hashCodeCombiner.Add(OldLength); - hashCodeCombiner.Add(NewLength); - hashCodeCombiner.Add(OldBuffer); - hashCodeCombiner.Add(NewBuffer); - - return hashCodeCombiner; - } - - public string ApplyChange(string content, int changeOffset) - { - var changeRelativePosition = OldPosition - changeOffset; - - Debug.Assert(changeRelativePosition >= 0); - return content.Remove(changeRelativePosition, OldLength) - .Insert(changeRelativePosition, NewText); - } - - /// - /// Applies the text change to the content of the span and returns the new content. - /// This method doesn't update the span content. - /// - public string ApplyChange(Span span) - { - return ApplyChange(span.Content, span.Start.AbsoluteIndex); - } - - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "({0}:{1}) \"{3}\" -> ({0}:{2}) \"{4}\"", OldPosition, OldLength, NewLength, OldText, NewText); - } - - /// - /// Removes a common prefix from the edit to turn IntelliSense replacements into insertions where possible - /// - /// A normalized text change - public TextChange Normalize() - { - if (OldBuffer != null && IsReplace && NewLength > OldLength && NewText.StartsWith(OldText, StringComparison.Ordinal) && NewPosition == OldPosition) - { - // Normalize the change into an insertion of the uncommon suffix (i.e. strip out the common prefix) - return new TextChange(oldPosition: OldPosition + OldLength, - oldLength: 0, - oldBuffer: OldBuffer, - newPosition: OldPosition + OldLength, - newLength: NewLength - OldLength, - newBuffer: NewBuffer); - } - return this; - } - - private static string GetText(ITextBuffer buffer, int position, int length) - { - // Optimization for the common case of one char inserts, in this case we don't even need to seek the buffer. - if (length == 0) - { - return string.Empty; - } - - var oldPosition = buffer.Position; - try - { - buffer.Position = position; - - // Optimization for the common case of one char inserts, in this case we seek the buffer. - if (length == 1) - { - return ((char)buffer.Read()).ToString(); - } - else - { - var builder = new StringBuilder(); - for (int i = 0; i < length; i++) - { - var c = (char)buffer.Read(); - builder.Append(c); - - // This check is probably not necessary, will revisit when fixing https://aspnetwebstack.codeplex.com/workitem/1317 - if (Char.IsHighSurrogate(c)) - { - builder.Append((char)buffer.Read()); - } - } - return builder.ToString(); - } - } - finally - { - buffer.Position = oldPosition; - } - } - - public static bool operator ==(TextChange left, TextChange right) - { - return left.Equals(right); - } - - public static bool operator !=(TextChange left, TextChange right) - { - return !left.Equals(right); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/TextDocumentReader.cs b/src/Microsoft.AspNetCore.Razor/Text/TextDocumentReader.cs deleted file mode 100644 index f1bfc71f88..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/TextDocumentReader.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.IO; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public class TextDocumentReader : TextReader, ITextDocument - { - public TextDocumentReader(ITextDocument source) - { - Document = source; - } - - internal ITextDocument Document { get; private set; } - - public SourceLocation Location - { - get { return Document.Location; } - } - - public int Length - { - get { return Document.Length; } - } - - public int Position - { - get { return Document.Position; } - set { Document.Position = value; } - } - - public override int Read() - { - return Document.Read(); - } - - public override int Peek() - { - return Document.Peek(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Text/TextExtensions.cs b/src/Microsoft.AspNetCore.Razor/Text/TextExtensions.cs deleted file mode 100644 index 7bc38d858b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Text/TextExtensions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; - -namespace Microsoft.AspNetCore.Razor.Text -{ - internal static class TextExtensions - { - public static void Seek(this ITextBuffer self, int characters) - { - self.Position += characters; - } - - public static ITextDocument ToDocument(this ITextBuffer self) - { - var ret = self as ITextDocument; - if (ret == null) - { - ret = new SeekableTextReader(self); - } - return ret; - } - - public static LookaheadToken BeginLookahead(this ITextBuffer self) - { - var start = self.Position; - return new LookaheadToken(self); - } - - public static string ReadToEnd(this ITextBuffer self) - { - var builder = new StringBuilder(); - int read; - while ((read = self.Read()) != -1) - { - builder.Append((char)read); - } - return builder.ToString(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/CSharpKeywordDetector.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/CSharpKeywordDetector.cs deleted file mode 100644 index 2942d4c31a..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/CSharpKeywordDetector.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Tokenizer -{ - internal static class CSharpKeywordDetector - { - private static readonly Dictionary _keywords = new Dictionary(StringComparer.Ordinal) - { - { "await", CSharpKeyword.Await }, - { "abstract", CSharpKeyword.Abstract }, - { "byte", CSharpKeyword.Byte }, - { "class", CSharpKeyword.Class }, - { "delegate", CSharpKeyword.Delegate }, - { "event", CSharpKeyword.Event }, - { "fixed", CSharpKeyword.Fixed }, - { "if", CSharpKeyword.If }, - { "internal", CSharpKeyword.Internal }, - { "new", CSharpKeyword.New }, - { "override", CSharpKeyword.Override }, - { "readonly", CSharpKeyword.Readonly }, - { "short", CSharpKeyword.Short }, - { "struct", CSharpKeyword.Struct }, - { "try", CSharpKeyword.Try }, - { "unsafe", CSharpKeyword.Unsafe }, - { "volatile", CSharpKeyword.Volatile }, - { "as", CSharpKeyword.As }, - { "do", CSharpKeyword.Do }, - { "is", CSharpKeyword.Is }, - { "params", CSharpKeyword.Params }, - { "ref", CSharpKeyword.Ref }, - { "switch", CSharpKeyword.Switch }, - { "ushort", CSharpKeyword.Ushort }, - { "while", CSharpKeyword.While }, - { "case", CSharpKeyword.Case }, - { "const", CSharpKeyword.Const }, - { "explicit", CSharpKeyword.Explicit }, - { "float", CSharpKeyword.Float }, - { "null", CSharpKeyword.Null }, - { "sizeof", CSharpKeyword.Sizeof }, - { "typeof", CSharpKeyword.Typeof }, - { "implicit", CSharpKeyword.Implicit }, - { "private", CSharpKeyword.Private }, - { "this", CSharpKeyword.This }, - { "using", CSharpKeyword.Using }, - { "extern", CSharpKeyword.Extern }, - { "return", CSharpKeyword.Return }, - { "stackalloc", CSharpKeyword.Stackalloc }, - { "uint", CSharpKeyword.Uint }, - { "base", CSharpKeyword.Base }, - { "catch", CSharpKeyword.Catch }, - { "continue", CSharpKeyword.Continue }, - { "double", CSharpKeyword.Double }, - { "for", CSharpKeyword.For }, - { "in", CSharpKeyword.In }, - { "lock", CSharpKeyword.Lock }, - { "object", CSharpKeyword.Object }, - { "protected", CSharpKeyword.Protected }, - { "static", CSharpKeyword.Static }, - { "false", CSharpKeyword.False }, - { "public", CSharpKeyword.Public }, - { "sbyte", CSharpKeyword.Sbyte }, - { "throw", CSharpKeyword.Throw }, - { "virtual", CSharpKeyword.Virtual }, - { "decimal", CSharpKeyword.Decimal }, - { "else", CSharpKeyword.Else }, - { "operator", CSharpKeyword.Operator }, - { "string", CSharpKeyword.String }, - { "ulong", CSharpKeyword.Ulong }, - { "bool", CSharpKeyword.Bool }, - { "char", CSharpKeyword.Char }, - { "default", CSharpKeyword.Default }, - { "foreach", CSharpKeyword.Foreach }, - { "long", CSharpKeyword.Long }, - { "void", CSharpKeyword.Void }, - { "enum", CSharpKeyword.Enum }, - { "finally", CSharpKeyword.Finally }, - { "int", CSharpKeyword.Int }, - { "out", CSharpKeyword.Out }, - { "sealed", CSharpKeyword.Sealed }, - { "true", CSharpKeyword.True }, - { "goto", CSharpKeyword.Goto }, - { "unchecked", CSharpKeyword.Unchecked }, - { "interface", CSharpKeyword.Interface }, - { "break", CSharpKeyword.Break }, - { "checked", CSharpKeyword.Checked }, - { "namespace", CSharpKeyword.Namespace }, - { "when", CSharpKeyword.When } - }; - - public static CSharpKeyword? SymbolTypeForIdentifier(string id) - { - CSharpKeyword type; - if (!_keywords.TryGetValue(id, out type)) - { - return null; - } - return type; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/ITokenizer.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/ITokenizer.cs deleted file mode 100644 index cb56b3ef47..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/ITokenizer.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Tokenizer -{ - public interface ITokenizer - { - ISymbol NextSymbol(); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpHelpers.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpHelpers.cs deleted file mode 100644 index c99a6e72ec..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpHelpers.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public static class CSharpHelpers - { - // CSharp Spec §2.4.2 - public static bool IsIdentifierStart(char character) - { - return Char.IsLetter(character) || - character == '_' || - CharUnicodeInfo.GetUnicodeCategory(character) == UnicodeCategory.LetterNumber; - } - - public static bool IsIdentifierPart(char character) - { - return Char.IsDigit(character) || - IsIdentifierStart(character) || - IsIdentifierPartByUnicodeCategory(character); - } - - public static bool IsRealLiteralSuffix(char character) - { - return character == 'F' || - character == 'f' || - character == 'D' || - character == 'd' || - character == 'M' || - character == 'm'; - } - - private static bool IsIdentifierPartByUnicodeCategory(char character) - { - var category = CharUnicodeInfo.GetUnicodeCategory(character); - - return category == UnicodeCategory.NonSpacingMark || // Mn - category == UnicodeCategory.SpacingCombiningMark || // Mc - category == UnicodeCategory.ConnectorPunctuation || // Pc - category == UnicodeCategory.Format; // Cf - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpTokenizer.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpTokenizer.cs deleted file mode 100644 index 46f762cae9..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/CSharpTokenizer.cs +++ /dev/null @@ -1,515 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class CSharpTokenizer : Tokenizer - { - private Dictionary> _operatorHandlers; - - public CSharpTokenizer(ITextDocument source) - : base(source) - { - base.CurrentState = StartState; - - _operatorHandlers = new Dictionary>() - { - { '-', MinusOperator }, - { '<', LessThanOperator }, - { '>', GreaterThanOperator }, - { '&', CreateTwoCharOperatorHandler(CSharpSymbolType.And, '=', CSharpSymbolType.AndAssign, '&', CSharpSymbolType.DoubleAnd) }, - { '|', CreateTwoCharOperatorHandler(CSharpSymbolType.Or, '=', CSharpSymbolType.OrAssign, '|', CSharpSymbolType.DoubleOr) }, - { '+', CreateTwoCharOperatorHandler(CSharpSymbolType.Plus, '=', CSharpSymbolType.PlusAssign, '+', CSharpSymbolType.Increment) }, - { '=', CreateTwoCharOperatorHandler(CSharpSymbolType.Assign, '=', CSharpSymbolType.Equals, '>', CSharpSymbolType.GreaterThanEqual) }, - { '!', CreateTwoCharOperatorHandler(CSharpSymbolType.Not, '=', CSharpSymbolType.NotEqual) }, - { '%', CreateTwoCharOperatorHandler(CSharpSymbolType.Modulo, '=', CSharpSymbolType.ModuloAssign) }, - { '*', CreateTwoCharOperatorHandler(CSharpSymbolType.Star, '=', CSharpSymbolType.MultiplyAssign) }, - { ':', CreateTwoCharOperatorHandler(CSharpSymbolType.Colon, ':', CSharpSymbolType.DoubleColon) }, - { '?', CreateTwoCharOperatorHandler(CSharpSymbolType.QuestionMark, '?', CSharpSymbolType.NullCoalesce) }, - { '^', CreateTwoCharOperatorHandler(CSharpSymbolType.Xor, '=', CSharpSymbolType.XorAssign) }, - { '(', () => CSharpSymbolType.LeftParenthesis }, - { ')', () => CSharpSymbolType.RightParenthesis }, - { '{', () => CSharpSymbolType.LeftBrace }, - { '}', () => CSharpSymbolType.RightBrace }, - { '[', () => CSharpSymbolType.LeftBracket }, - { ']', () => CSharpSymbolType.RightBracket }, - { ',', () => CSharpSymbolType.Comma }, - { ';', () => CSharpSymbolType.Semicolon }, - { '~', () => CSharpSymbolType.Tilde }, - { '#', () => CSharpSymbolType.Hash } - }; - } - - protected override int StartState => (int)CSharpTokenizerState.Data; - - private new CSharpTokenizerState? CurrentState => (CSharpTokenizerState?)base.CurrentState; - - public override CSharpSymbolType RazorCommentType - { - get { return CSharpSymbolType.RazorComment; } - } - - public override CSharpSymbolType RazorCommentTransitionType - { - get { return CSharpSymbolType.RazorCommentTransition; } - } - - public override CSharpSymbolType RazorCommentStarType - { - get { return CSharpSymbolType.RazorCommentStar; } - } - - protected override StateResult Dispatch() - { - switch (CurrentState) - { - case CSharpTokenizerState.Data: - return Data(); - case CSharpTokenizerState.BlockComment: - return BlockComment(); - case CSharpTokenizerState.QuotedCharacterLiteral: - return QuotedCharacterLiteral(); - case CSharpTokenizerState.QuotedStringLiteral: - return QuotedStringLiteral(); - case CSharpTokenizerState.VerbatimStringLiteral: - return VerbatimStringLiteral(); - case CSharpTokenizerState.AfterRazorCommentTransition: - return AfterRazorCommentTransition(); - case CSharpTokenizerState.EscapedRazorCommentTransition: - return EscapedRazorCommentTransition(); - case CSharpTokenizerState.RazorCommentBody: - return RazorCommentBody(); - case CSharpTokenizerState.StarAfterRazorCommentBody: - return StarAfterRazorCommentBody(); - case CSharpTokenizerState.AtSymbolAfterRazorCommentBody: - return AtSymbolAfterRazorCommentBody(); - default: -#if NET451 - // No Debug.Fail - Debug.Fail("Invalid TokenizerState"); -#else - Debug.Assert(false, "Invalid TokenizerState"); -#endif - return default(StateResult); - } - } - - protected override CSharpSymbol CreateSymbol(SourceLocation start, string content, CSharpSymbolType type, IReadOnlyList errors) - { - return new CSharpSymbol(start, content, type, errors); - } - - private StateResult Data() - { - if (ParserHelpers.IsNewLine(CurrentCharacter)) - { - // CSharp Spec §2.3.1 - var checkTwoCharNewline = CurrentCharacter == '\r'; - TakeCurrent(); - if (checkTwoCharNewline && CurrentCharacter == '\n') - { - TakeCurrent(); - } - return Stay(EndSymbol(CSharpSymbolType.NewLine)); - } - else if (ParserHelpers.IsWhitespace(CurrentCharacter)) - { - // CSharp Spec §2.3.3 - TakeUntil(c => !ParserHelpers.IsWhitespace(c)); - return Stay(EndSymbol(CSharpSymbolType.WhiteSpace)); - } - else if (CSharpHelpers.IsIdentifierStart(CurrentCharacter)) - { - return Identifier(); - } - else if (char.IsDigit(CurrentCharacter)) - { - return NumericLiteral(); - } - switch (CurrentCharacter) - { - case '@': - return AtSymbol(); - case '\'': - TakeCurrent(); - return Transition(CSharpTokenizerState.QuotedCharacterLiteral); - case '"': - TakeCurrent(); - return Transition(CSharpTokenizerState.QuotedStringLiteral); - case '.': - if (char.IsDigit(Peek())) - { - return RealLiteral(); - } - return Stay(Single(CSharpSymbolType.Dot)); - case '/': - TakeCurrent(); - if (CurrentCharacter == '/') - { - TakeCurrent(); - return SingleLineComment(); - } - else if (CurrentCharacter == '*') - { - TakeCurrent(); - return Transition(CSharpTokenizerState.BlockComment); - } - else if (CurrentCharacter == '=') - { - TakeCurrent(); - return Stay(EndSymbol(CSharpSymbolType.DivideAssign)); - } - else - { - return Stay(EndSymbol(CSharpSymbolType.Slash)); - } - default: - return Stay(EndSymbol(Operator())); - } - } - - private StateResult AtSymbol() - { - TakeCurrent(); - if (CurrentCharacter == '"') - { - TakeCurrent(); - return Transition(CSharpTokenizerState.VerbatimStringLiteral); - } - else if (CurrentCharacter == '*') - { - return Transition( - CSharpTokenizerState.AfterRazorCommentTransition, - EndSymbol(CSharpSymbolType.RazorCommentTransition)); - } - else if (CurrentCharacter == '@') - { - // Could be escaped comment transition - return Transition( - CSharpTokenizerState.EscapedRazorCommentTransition, - EndSymbol(CSharpSymbolType.Transition)); - } - - return Stay(EndSymbol(CSharpSymbolType.Transition)); - } - - private StateResult EscapedRazorCommentTransition() - { - TakeCurrent(); - return Transition(CSharpTokenizerState.Data, EndSymbol(CSharpSymbolType.Transition)); - } - - private CSharpSymbolType Operator() - { - var first = CurrentCharacter; - TakeCurrent(); - Func handler; - if (_operatorHandlers.TryGetValue(first, out handler)) - { - return handler(); - } - return CSharpSymbolType.Unknown; - } - - private CSharpSymbolType LessThanOperator() - { - if (CurrentCharacter == '=') - { - TakeCurrent(); - return CSharpSymbolType.LessThanEqual; - } - return CSharpSymbolType.LessThan; - } - - private CSharpSymbolType GreaterThanOperator() - { - if (CurrentCharacter == '=') - { - TakeCurrent(); - return CSharpSymbolType.GreaterThanEqual; - } - return CSharpSymbolType.GreaterThan; - } - - private CSharpSymbolType MinusOperator() - { - if (CurrentCharacter == '>') - { - TakeCurrent(); - return CSharpSymbolType.Arrow; - } - else if (CurrentCharacter == '-') - { - TakeCurrent(); - return CSharpSymbolType.Decrement; - } - else if (CurrentCharacter == '=') - { - TakeCurrent(); - return CSharpSymbolType.MinusAssign; - } - return CSharpSymbolType.Minus; - } - - private Func CreateTwoCharOperatorHandler(CSharpSymbolType typeIfOnlyFirst, char second, CSharpSymbolType typeIfBoth) - { - return () => - { - if (CurrentCharacter == second) - { - TakeCurrent(); - return typeIfBoth; - } - return typeIfOnlyFirst; - }; - } - - private Func CreateTwoCharOperatorHandler(CSharpSymbolType typeIfOnlyFirst, char option1, CSharpSymbolType typeIfOption1, char option2, CSharpSymbolType typeIfOption2) - { - return () => - { - if (CurrentCharacter == option1) - { - TakeCurrent(); - return typeIfOption1; - } - else if (CurrentCharacter == option2) - { - TakeCurrent(); - return typeIfOption2; - } - return typeIfOnlyFirst; - }; - } - - private StateResult VerbatimStringLiteral() - { - TakeUntil(c => c == '"'); - if (CurrentCharacter == '"') - { - TakeCurrent(); - if (CurrentCharacter == '"') - { - TakeCurrent(); - // Stay in the literal, this is an escaped " - return Stay(); - } - } - else if (EndOfFile) - { - CurrentErrors.Add( - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - CurrentStart, - length: 1 /* end of file */)); - } - return Transition(CSharpTokenizerState.Data, EndSymbol(CSharpSymbolType.StringLiteral)); - } - - private StateResult QuotedCharacterLiteral() => QuotedLiteral('\'', CSharpSymbolType.CharacterLiteral); - - private StateResult QuotedStringLiteral() => QuotedLiteral('\"', CSharpSymbolType.StringLiteral); - - private StateResult QuotedLiteral(char quote, CSharpSymbolType literalType) - { - TakeUntil(c => c == '\\' || c == quote || ParserHelpers.IsNewLine(c)); - if (CurrentCharacter == '\\') - { - TakeCurrent(); // Take the '\' - - // If the next char is the same quote that started this - if (CurrentCharacter == quote || CurrentCharacter == '\\') - { - TakeCurrent(); // Take it so that we don't prematurely end the literal. - } - return Stay(); - } - else if (EndOfFile || ParserHelpers.IsNewLine(CurrentCharacter)) - { - CurrentErrors.Add( - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - CurrentStart, - length: 1 /* " */)); - } - else - { - TakeCurrent(); // No-op if at EOF - } - return Transition(CSharpTokenizerState.Data, EndSymbol(literalType)); - } - - // CSharp Spec §2.3.2 - private StateResult BlockComment() - { - TakeUntil(c => c == '*'); - if (EndOfFile) - { - CurrentErrors.Add( - new RazorError( - RazorResources.ParseError_BlockComment_Not_Terminated, - CurrentStart, - length: 1 /* end of file */)); - return Transition(CSharpTokenizerState.Data, EndSymbol(CSharpSymbolType.Comment)); - } - if (CurrentCharacter == '*') - { - TakeCurrent(); - if (CurrentCharacter == '/') - { - TakeCurrent(); - return Transition(CSharpTokenizerState.Data, EndSymbol(CSharpSymbolType.Comment)); - } - } - return Stay(); - } - - // CSharp Spec §2.3.2 - private StateResult SingleLineComment() - { - TakeUntil(c => ParserHelpers.IsNewLine(c)); - return Stay(EndSymbol(CSharpSymbolType.Comment)); - } - - // CSharp Spec §2.4.4 - private StateResult NumericLiteral() - { - if (TakeAll("0x", caseSensitive: true)) - { - return HexLiteral(); - } - else - { - return DecimalLiteral(); - } - } - - private StateResult HexLiteral() - { - TakeUntil(c => !ParserHelpers.IsHexDigit(c)); - TakeIntegerSuffix(); - return Stay(EndSymbol(CSharpSymbolType.IntegerLiteral)); - } - - private StateResult DecimalLiteral() - { - TakeUntil(c => !Char.IsDigit(c)); - if (CurrentCharacter == '.' && Char.IsDigit(Peek())) - { - return RealLiteral(); - } - else if (CSharpHelpers.IsRealLiteralSuffix(CurrentCharacter) || - CurrentCharacter == 'E' || CurrentCharacter == 'e') - { - return RealLiteralExponentPart(); - } - else - { - TakeIntegerSuffix(); - return Stay(EndSymbol(CSharpSymbolType.IntegerLiteral)); - } - } - - private StateResult RealLiteralExponentPart() - { - if (CurrentCharacter == 'E' || CurrentCharacter == 'e') - { - TakeCurrent(); - if (CurrentCharacter == '+' || CurrentCharacter == '-') - { - TakeCurrent(); - } - TakeUntil(c => !Char.IsDigit(c)); - } - if (CSharpHelpers.IsRealLiteralSuffix(CurrentCharacter)) - { - TakeCurrent(); - } - return Stay(EndSymbol(CSharpSymbolType.RealLiteral)); - } - - // CSharp Spec §2.4.4.3 - private StateResult RealLiteral() - { - AssertCurrent('.'); - TakeCurrent(); - Debug.Assert(Char.IsDigit(CurrentCharacter)); - TakeUntil(c => !Char.IsDigit(c)); - return RealLiteralExponentPart(); - } - - private void TakeIntegerSuffix() - { - if (Char.ToLowerInvariant(CurrentCharacter) == 'u') - { - TakeCurrent(); - if (Char.ToLowerInvariant(CurrentCharacter) == 'l') - { - TakeCurrent(); - } - } - else if (Char.ToLowerInvariant(CurrentCharacter) == 'l') - { - TakeCurrent(); - if (Char.ToLowerInvariant(CurrentCharacter) == 'u') - { - TakeCurrent(); - } - } - } - - // CSharp Spec §2.4.2 - private StateResult Identifier() - { - Debug.Assert(CSharpHelpers.IsIdentifierStart(CurrentCharacter)); - TakeCurrent(); - TakeUntil(c => !CSharpHelpers.IsIdentifierPart(c)); - CSharpSymbol symbol = null; - if (HaveContent) - { - var keyword = CSharpKeywordDetector.SymbolTypeForIdentifier(Buffer.ToString()); - var type = CSharpSymbolType.Identifier; - if (keyword != null) - { - type = CSharpSymbolType.Keyword; - } - symbol = new CSharpSymbol(CurrentStart, Buffer.ToString(), type) { Keyword = keyword }; - } - StartSymbol(); - return Stay(symbol); - } - - private StateResult Transition(CSharpTokenizerState state) - { - return Transition((int)state, result: null); - } - - private StateResult Transition(CSharpTokenizerState state, CSharpSymbol result) - { - return Transition((int)state, result); - } - - private enum CSharpTokenizerState - { - Data, - BlockComment, - QuotedCharacterLiteral, - QuotedStringLiteral, - VerbatimStringLiteral, - - // Razor Comments - need to be the same for HTML and CSharp - AfterRazorCommentTransition = RazorCommentTokenizerState.AfterRazorCommentTransition, - EscapedRazorCommentTransition = RazorCommentTokenizerState.EscapedRazorCommentTransition, - RazorCommentBody = RazorCommentTokenizerState.RazorCommentBody, - StarAfterRazorCommentBody = RazorCommentTokenizerState.StarAfterRazorCommentBody, - AtSymbolAfterRazorCommentBody = RazorCommentTokenizerState.AtSymbolAfterRazorCommentBody, - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/HtmlTokenizer.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/HtmlTokenizer.cs deleted file mode 100644 index a618fb9212..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Internal/HtmlTokenizer.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - // Tokenizer _loosely_ based on http://dev.w3.org/html5/spec/Overview.html#tokenization - public class HtmlTokenizer : Tokenizer - { - private const char TransitionChar = '@'; - - public HtmlTokenizer(ITextDocument source) - : base(source) - { - base.CurrentState = StartState; - } - - protected override int StartState => (int)HtmlTokenizerState.Data; - - private new HtmlTokenizerState? CurrentState => (HtmlTokenizerState?)base.CurrentState; - - public override HtmlSymbolType RazorCommentType - { - get { return HtmlSymbolType.RazorComment; } - } - - public override HtmlSymbolType RazorCommentTransitionType - { - get { return HtmlSymbolType.RazorCommentTransition; } - } - - public override HtmlSymbolType RazorCommentStarType - { - get { return HtmlSymbolType.RazorCommentStar; } - } - - internal static IEnumerable Tokenize(string content) - { - using (SeekableTextReader reader = new SeekableTextReader(content)) - { - var tokenizer = new HtmlTokenizer(reader); - HtmlSymbol symbol; - while ((symbol = tokenizer.NextSymbol()) != null) - { - yield return symbol; - } - } - } - - protected override HtmlSymbol CreateSymbol(SourceLocation start, string content, HtmlSymbolType type, IReadOnlyList errors) - { - return new HtmlSymbol(start, content, type, errors); - } - - protected override StateResult Dispatch() - { - switch (CurrentState) - { - case HtmlTokenizerState.Data: - return Data(); - case HtmlTokenizerState.Text: - return Text(); - case HtmlTokenizerState.AfterRazorCommentTransition: - return AfterRazorCommentTransition(); - case HtmlTokenizerState.EscapedRazorCommentTransition: - return EscapedRazorCommentTransition(); - case HtmlTokenizerState.RazorCommentBody: - return RazorCommentBody(); - case HtmlTokenizerState.StarAfterRazorCommentBody: - return StarAfterRazorCommentBody(); - case HtmlTokenizerState.AtSymbolAfterRazorCommentBody: - return AtSymbolAfterRazorCommentBody(); - default: -#if NET451 - // No Debug.Fail - Debug.Fail("Invalid TokenizerState"); -#else - Debug.Assert(false, "Invalid TokenizerState"); -#endif - return default(StateResult); - } - } - - // http://dev.w3.org/html5/spec/Overview.html#data-state - private StateResult Data() - { - if (ParserHelpers.IsWhitespace(CurrentCharacter)) - { - return Stay(Whitespace()); - } - else if (ParserHelpers.IsNewLine(CurrentCharacter)) - { - return Stay(Newline()); - } - else if (CurrentCharacter == '@') - { - TakeCurrent(); - if (CurrentCharacter == '*') - { - return Transition( - HtmlTokenizerState.AfterRazorCommentTransition, - EndSymbol(HtmlSymbolType.RazorCommentTransition)); - } - else if (CurrentCharacter == '@') - { - // Could be escaped comment transition - return Transition( - HtmlTokenizerState.EscapedRazorCommentTransition, - EndSymbol(HtmlSymbolType.Transition)); - } - - return Stay(EndSymbol(HtmlSymbolType.Transition)); - } - else if (AtSymbol()) - { - return Stay(Symbol()); - } - else - { - return Transition(HtmlTokenizerState.Text); - } - } - - private StateResult EscapedRazorCommentTransition() - { - TakeCurrent(); - return Transition(HtmlTokenizerState.Data, EndSymbol(HtmlSymbolType.Transition)); - } - - private StateResult Text() - { - var prev = '\0'; - while (!EndOfFile && !ParserHelpers.IsWhitespaceOrNewLine(CurrentCharacter) && !AtSymbol()) - { - prev = CurrentCharacter; - TakeCurrent(); - } - - if (CurrentCharacter == '@') - { - var next = Peek(); - if (ParserHelpers.IsLetterOrDecimalDigit(prev) && ParserHelpers.IsLetterOrDecimalDigit(next)) - { - TakeCurrent(); // Take the "@" - return Stay(); // Stay in the Text state - } - } - - // Output the Text token and return to the Data state to tokenize the next character (if there is one) - return Transition(HtmlTokenizerState.Data, EndSymbol(HtmlSymbolType.Text)); - } - - private HtmlSymbol Symbol() - { - Debug.Assert(AtSymbol()); - var sym = CurrentCharacter; - TakeCurrent(); - switch (sym) - { - case '<': - return EndSymbol(HtmlSymbolType.OpenAngle); - case '!': - return EndSymbol(HtmlSymbolType.Bang); - case '/': - return EndSymbol(HtmlSymbolType.ForwardSlash); - case '?': - return EndSymbol(HtmlSymbolType.QuestionMark); - case '[': - return EndSymbol(HtmlSymbolType.LeftBracket); - case '>': - return EndSymbol(HtmlSymbolType.CloseAngle); - case ']': - return EndSymbol(HtmlSymbolType.RightBracket); - case '=': - return EndSymbol(HtmlSymbolType.Equals); - case '"': - return EndSymbol(HtmlSymbolType.DoubleQuote); - case '\'': - return EndSymbol(HtmlSymbolType.SingleQuote); - case '-': - Debug.Assert(CurrentCharacter == '-'); - TakeCurrent(); - return EndSymbol(HtmlSymbolType.DoubleHyphen); - default: -#if NET451 - // No Debug.Fail in CoreCLR - - Debug.Fail("Unexpected symbol!"); -#else - Debug.Assert(false, "Unexpected symbol"); -#endif - return EndSymbol(HtmlSymbolType.Unknown); - } - } - - private HtmlSymbol Whitespace() - { - while (ParserHelpers.IsWhitespace(CurrentCharacter)) - { - TakeCurrent(); - } - return EndSymbol(HtmlSymbolType.WhiteSpace); - } - - private HtmlSymbol Newline() - { - Debug.Assert(ParserHelpers.IsNewLine(CurrentCharacter)); - // CSharp Spec §2.3.1 - var checkTwoCharNewline = CurrentCharacter == '\r'; - TakeCurrent(); - if (checkTwoCharNewline && CurrentCharacter == '\n') - { - TakeCurrent(); - } - return EndSymbol(HtmlSymbolType.NewLine); - } - - private bool AtSymbol() - { - return CurrentCharacter == '<' || - CurrentCharacter == '<' || - CurrentCharacter == '!' || - CurrentCharacter == '/' || - CurrentCharacter == '?' || - CurrentCharacter == '[' || - CurrentCharacter == '>' || - CurrentCharacter == ']' || - CurrentCharacter == '=' || - CurrentCharacter == '"' || - CurrentCharacter == '\'' || - CurrentCharacter == '@' || - (CurrentCharacter == '-' && Peek() == '-'); - } - - private StateResult Transition(HtmlTokenizerState state) - { - return Transition((int)state, result: null); - } - - private StateResult Transition(HtmlTokenizerState state, HtmlSymbol result) - { - return Transition((int)state, result); - } - - private enum HtmlTokenizerState - { - Data, - Text, - - // Razor Comments - need to be the same for HTML and CSharp - AfterRazorCommentTransition = RazorCommentTokenizerState.AfterRazorCommentTransition, - EscapedRazorCommentTransition = RazorCommentTokenizerState.EscapedRazorCommentTransition, - RazorCommentBody = RazorCommentTokenizerState.RazorCommentBody, - StarAfterRazorCommentBody = RazorCommentTokenizerState.StarAfterRazorCommentBody, - AtSymbolAfterRazorCommentBody = RazorCommentTokenizerState.AtSymbolAfterRazorCommentBody, - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpKeyword.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpKeyword.cs deleted file mode 100644 index cfc581853b..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpKeyword.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public enum CSharpKeyword - { - Await, - Abstract, - Byte, - Class, - Delegate, - Event, - Fixed, - If, - Internal, - New, - Override, - Readonly, - Short, - Struct, - Try, - Unsafe, - Volatile, - As, - Do, - Is, - Params, - Ref, - Switch, - Ushort, - While, - Case, - Const, - Explicit, - Float, - Null, - Sizeof, - Typeof, - Implicit, - Private, - This, - Using, - Extern, - Return, - Stackalloc, - Uint, - Base, - Catch, - Continue, - Double, - For, - In, - Lock, - Object, - Protected, - Static, - False, - Public, - Sbyte, - Throw, - Virtual, - Decimal, - Else, - Operator, - String, - Ulong, - Bool, - Char, - Default, - Foreach, - Long, - Void, - Enum, - Finally, - Int, - Out, - Sealed, - True, - Goto, - Unchecked, - Interface, - Break, - Checked, - Namespace, - When - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbol.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbol.cs deleted file mode 100644 index c03031a463..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbol.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public class CSharpSymbol : SymbolBase - { - // Helper constructor - public CSharpSymbol(int offset, int line, int column, string content, CSharpSymbolType type) - : this(new SourceLocation(offset, line, column), content, type, RazorError.EmptyArray) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public CSharpSymbol(SourceLocation start, string content, CSharpSymbolType type) - : this(start, content, type, RazorError.EmptyArray) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public CSharpSymbol( - int offset, - int line, - int column, - string content, - CSharpSymbolType type, - IReadOnlyList errors) - : base(new SourceLocation(offset, line, column), content, type, errors) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public CSharpSymbol( - SourceLocation start, - string content, - CSharpSymbolType type, - IReadOnlyList errors) - : base(start, content, type, errors) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public bool? EscapedIdentifier { get; set; } - public CSharpKeyword? Keyword { get; set; } - - public override bool Equals(object obj) - { - var other = obj as CSharpSymbol; - return base.Equals(other) && other.Keyword == Keyword; - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties. - return base.GetHashCode(); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbolType.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbolType.cs deleted file mode 100644 index efa673fe46..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/CSharpSymbolType.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public enum CSharpSymbolType - { - Unknown, - Identifier, - Keyword, - IntegerLiteral, - NewLine, - WhiteSpace, - Comment, - RealLiteral, - CharacterLiteral, - StringLiteral, - - // Operators - Arrow, - Minus, - Decrement, - MinusAssign, - NotEqual, - Not, - Modulo, - ModuloAssign, - AndAssign, - And, - DoubleAnd, - LeftParenthesis, - RightParenthesis, - Star, - MultiplyAssign, - Comma, - Dot, - Slash, - DivideAssign, - DoubleColon, - Colon, - Semicolon, - QuestionMark, - NullCoalesce, - RightBracket, - LeftBracket, - XorAssign, - Xor, - LeftBrace, - OrAssign, - DoubleOr, - Or, - RightBrace, - Tilde, - Plus, - PlusAssign, - Increment, - LessThan, - LessThanEqual, - LeftShift, - LeftShiftAssign, - Assign, - Equals, - GreaterThan, - GreaterThanEqual, - RightShift, - RightShiftAssign, - Hash, - Transition, - - // Razor specific - RazorCommentTransition, - RazorCommentStar, - RazorComment - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/ISymbol.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/ISymbol.cs deleted file mode 100644 index 23c26226e0..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/ISymbol.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public interface ISymbol - { - SourceLocation Start { get; } - string Content { get; } - - void OffsetStart(SourceLocation documentStart); - void ChangeStart(SourceLocation newStart); - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbol.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbol.cs deleted file mode 100644 index 52b698b447..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbol.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal -{ - public class HtmlSymbol : SymbolBase - { - // Helper constructor - public HtmlSymbol(int offset, int line, int column, string content, HtmlSymbolType type) - : this(new SourceLocation(offset, line, column), content, type, RazorError.EmptyArray) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public HtmlSymbol(SourceLocation start, string content, HtmlSymbolType type) - : base(start, content, type, RazorError.EmptyArray) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public HtmlSymbol( - int offset, - int line, - int column, - string content, - HtmlSymbolType type, - IReadOnlyList errors) - : base(new SourceLocation(offset, line, column), content, type, errors) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - - public HtmlSymbol( - SourceLocation start, - string content, - HtmlSymbolType type, - IReadOnlyList errors) - : base(start, content, type, errors) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbolType.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbolType.cs deleted file mode 100644 index 7e72a26f56..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/Internal/HtmlSymbolType.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal -{ - [Flags] - public enum HtmlSymbolType - { - Unknown, - Text, // Text which isn't one of the below - WhiteSpace, // Non-newline Whitespace - NewLine, // Newline - OpenAngle, // < - Bang, // ! - ForwardSlash, // / - QuestionMark, // ? - DoubleHyphen, // -- - LeftBracket, // [ - CloseAngle, // > - RightBracket, // ] - Equals, // = - DoubleQuote, // " - SingleQuote, // ' - Transition, // @ - Colon, - RazorComment, - RazorCommentStar, - RazorCommentTransition - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/KnownSymbolType.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/KnownSymbolType.cs deleted file mode 100644 index 207de8b429..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/KnownSymbolType.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public enum KnownSymbolType - { - WhiteSpace, - NewLine, - Identifier, - Keyword, - Transition, - Unknown, - CommentStart, - CommentStar, - CommentBody - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolBase.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolBase.cs deleted file mode 100644 index ba34a79b20..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolBase.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public abstract class SymbolBase : ISymbol - where TType : struct - { - protected SymbolBase( - SourceLocation start, - string content, - TType type, - IReadOnlyList errors) - { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - Start = start; - Content = content; - Type = type; - Errors = errors; - } - - public SourceLocation Start { get; private set; } - - public string Content { get; } - - public IReadOnlyList Errors { get; } - - public TType Type { get; } - - public override bool Equals(object obj) - { - var other = obj as SymbolBase; - return other != null && - Start.Equals(other.Start) && - string.Equals(Content, other.Content, StringComparison.Ordinal) && - Type.Equals(other.Type); - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties. - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(Content, StringComparer.Ordinal); - hashCodeCombiner.Add(Type); - - return hashCodeCombiner; - } - - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "{0} {1} - [{2}]", Start, Type, Content); - } - - public void OffsetStart(SourceLocation documentStart) - { - Start = documentStart + Start; - } - - public void ChangeStart(SourceLocation newStart) - { - Start = newStart; - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolExtensions.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolExtensions.cs deleted file mode 100644 index 65ae598176..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Symbols/SymbolExtensions.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Symbols -{ - public static class SymbolExtensions - { - public static LocationTagged GetContent(this SpanBuilder span) - { - var symbols = span.Symbols; - if (symbols.Count > 0) - { - var text = new StringBuilder(); - for (var i = 0; i < symbols.Count; i++) - { - text.Append(symbols[i].Content); - } - - return new LocationTagged(text.ToString(), span.Start + symbols[0].Start); - } - else - { - return new LocationTagged(string.Empty, span.Start); - } - } - - public static LocationTagged GetContent(this SpanBuilder span, Func, IEnumerable> filter) - { - return GetContent(filter(span.Symbols), span.Start); - } - - public static LocationTagged GetContent(this IEnumerable symbols, SourceLocation spanStart) - { - StringBuilder builder = null; - var location = spanStart; - - foreach (var symbol in symbols) - { - if (builder == null) - { - builder = new StringBuilder(); - location += symbol.Start; - } - - builder.Append(symbol.Content); - } - - return new LocationTagged(builder?.ToString() ?? string.Empty, location); - } - - public static LocationTagged GetContent(this ISymbol symbol) - { - return new LocationTagged(symbol.Content, symbol.Start); - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/Tokenizer.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/Tokenizer.cs deleted file mode 100644 index a9b3de5534..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/Tokenizer.cs +++ /dev/null @@ -1,441 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -#if DEBUG -using System.Globalization; -#endif -using System.Text; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Tokenizer -{ - [DebuggerDisplay("{DebugDisplay}")] - public abstract partial class Tokenizer : ITokenizer - where TSymbolType : struct - where TSymbol : SymbolBase - { -#if DEBUG - private StringBuilder _read = new StringBuilder(); -#endif - - protected Tokenizer(ITextDocument source) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - Source = new TextDocumentReader(source); - Buffer = new StringBuilder(); - CurrentErrors = new List(); - StartSymbol(); - } - - protected abstract int StartState { get; } - - protected int? CurrentState { get; set; } - - protected TSymbol CurrentSymbol { get; private set; } - - public TextDocumentReader Source { get; private set; } - - protected StringBuilder Buffer { get; private set; } - - protected bool EndOfFile - { - get { return Source.Peek() == -1; } - } - - protected IList CurrentErrors { get; private set; } - - public abstract TSymbolType RazorCommentStarType { get; } - public abstract TSymbolType RazorCommentType { get; } - public abstract TSymbolType RazorCommentTransitionType { get; } - - protected bool HaveContent - { - get { return Buffer.Length > 0; } - } - - protected char CurrentCharacter - { - get - { - var peek = Source.Peek(); - return peek == -1 ? '\0' : (char)peek; - } - } - - protected SourceLocation CurrentLocation - { - get { return Source.Location; } - } - - protected SourceLocation CurrentStart { get; private set; } - - protected abstract TSymbol CreateSymbol(SourceLocation start, string content, TSymbolType type, IReadOnlyList errors); - - protected abstract StateResult Dispatch(); - - public virtual TSymbol NextSymbol() - { - // Post-Condition: Buffer should be empty at the start of Next() - Debug.Assert(Buffer.Length == 0); - StartSymbol(); - - if (EndOfFile) - { - return null; - } - - var symbol = Turn(); - - // Post-Condition: Buffer should be empty at the end of Next() - Debug.Assert(Buffer.Length == 0); - - return symbol; - } - - protected virtual TSymbol Turn() - { - if (CurrentState != null) - { - // Run until we get into the stop state or have a result. - do - { - var next = Dispatch(); - - CurrentState = next.State; - CurrentSymbol = next.Result; - } - while (CurrentState != null && CurrentSymbol == null); - - if (CurrentState == null) - { - return default(TSymbol); // Terminated - } - - return CurrentSymbol; - } - - return default(TSymbol); - } - - public void Reset() - { - CurrentState = StartState; - } - - /// - /// Returns a result indicating that the machine should stop executing and return null output. - /// - protected StateResult Stop() - { - return default(StateResult); - } - - /// - /// Returns a result indicating that this state has no output and the machine should immediately invoke the specified state - /// - /// - /// By returning no output, the state machine will invoke the next state immediately, before returning - /// controller to the caller of - /// - protected StateResult Transition(int state) - { - return new StateResult(state, result: null); - } - - /// - /// Returns a result containing the specified output and indicating that the next call to - /// should invoke the provided state. - /// - protected StateResult Transition(int state, TSymbol result) - { - return new StateResult(state, result); - } - - protected StateResult Transition(RazorCommentTokenizerState state) - { - return new StateResult((int)state, result: null); - } - - protected StateResult Transition(RazorCommentTokenizerState state, TSymbol result) - { - return new StateResult((int)state, result); - } - - /// - /// Returns a result indicating that this state has no output and the machine should remain in this state - /// - /// - /// By returning no output, the state machine will re-invoke the current state again before returning - /// controller to the caller of - /// - protected StateResult Stay() - { - return new StateResult(CurrentState, result: null); - } - - /// - /// Returns a result containing the specified output and indicating that the next call to - /// should re-invoke the current state. - /// - protected StateResult Stay(TSymbol result) - { - return new StateResult(CurrentState, result); - } - - protected TSymbol Single(TSymbolType type) - { - TakeCurrent(); - return EndSymbol(type); - } - - protected void StartSymbol() - { - Buffer.Clear(); - CurrentStart = CurrentLocation; - CurrentErrors.Clear(); - } - - protected TSymbol EndSymbol(TSymbolType type) - { - return EndSymbol(CurrentStart, type); - } - - protected TSymbol EndSymbol(SourceLocation start, TSymbolType type) - { - TSymbol sym = null; - if (HaveContent) - { - // Perf: Don't allocate a new errors array unless necessary. - var errors = CurrentErrors.Count == 0 ? RazorError.EmptyArray : new RazorError[CurrentErrors.Count]; - for (var i = 0; i < CurrentErrors.Count; i++) - { - errors[i] = CurrentErrors[i]; - } - - sym = CreateSymbol(start, Buffer.ToString(), type, errors); - } - StartSymbol(); - return sym; - } - - protected bool TakeUntil(Func predicate) - { - // Take all the characters up to the end character - while (!EndOfFile && !predicate(CurrentCharacter)) - { - TakeCurrent(); - } - - // Why did we end? - return !EndOfFile; - } - - protected void TakeCurrent() - { - if (EndOfFile) - { - return; - } // No-op - Buffer.Append(CurrentCharacter); - MoveNext(); - } - - protected void MoveNext() - { -#if DEBUG - _read.Append(CurrentCharacter); -#endif - Source.Read(); - } - - protected bool TakeAll(string expected, bool caseSensitive) - { - return Lookahead(expected, takeIfMatch: true, caseSensitive: caseSensitive); - } - - protected char Peek() - { - using (var lookahead = Source.BeginLookahead()) - { - MoveNext(); - return CurrentCharacter; - } - } - - protected StateResult AfterRazorCommentTransition() - { - if (CurrentCharacter != '*') - { - // We've been moved since last time we were asked for a symbol... reset the state - return Transition(StartState); - } - - AssertCurrent('*'); - TakeCurrent(); - return Transition(1002, EndSymbol(RazorCommentStarType)); - } - - protected StateResult RazorCommentBody() - { - TakeUntil(c => c == '*'); - if (CurrentCharacter == '*') - { - if (Peek() == '@') - { - if (HaveContent) - { - return Transition( - RazorCommentTokenizerState.StarAfterRazorCommentBody, - EndSymbol(RazorCommentType)); - } - else - { - return Transition(RazorCommentTokenizerState.StarAfterRazorCommentBody); - } - } - else - { - TakeCurrent(); - return Stay(); - } - } - - return Transition(StartState, EndSymbol(RazorCommentType)); - } - - protected StateResult StarAfterRazorCommentBody() - { - AssertCurrent('*'); - TakeCurrent(); - return Transition( - RazorCommentTokenizerState.AtSymbolAfterRazorCommentBody, - EndSymbol(RazorCommentStarType)); - } - - protected StateResult AtSymbolAfterRazorCommentBody() - { - AssertCurrent('@'); - TakeCurrent(); - return Transition(StartState, EndSymbol(RazorCommentTransitionType)); - } - - /// - /// Internal for unit testing - /// - internal bool Lookahead(string expected, bool takeIfMatch, bool caseSensitive) - { - Func filter = c => c; - if (!caseSensitive) - { - filter = char.ToLowerInvariant; - } - - if (expected.Length == 0 || filter(CurrentCharacter) != filter(expected[0])) - { - return false; - } - - // Capture the current buffer content in case we have to backtrack - string oldBuffer = null; - if (takeIfMatch) - { - oldBuffer = Buffer.ToString(); - } - - using (var lookahead = Source.BeginLookahead()) - { - for (int i = 0; i < expected.Length; i++) - { - if (filter(CurrentCharacter) != filter(expected[i])) - { - if (takeIfMatch) - { - // Clear the buffer and put the old buffer text back - Buffer.Clear(); - Buffer.Append(oldBuffer); - } - // Return without accepting lookahead (thus rejecting it) - return false; - } - if (takeIfMatch) - { - TakeCurrent(); - } - else - { - MoveNext(); - } - } - if (takeIfMatch) - { - lookahead.Accept(); - } - } - return true; - } - - [Conditional("DEBUG")] - internal void AssertCurrent(char current) - { -#if NET451 - // No Debug.Assert with this many arguments in CoreCLR - - Debug.Assert(CurrentCharacter == current, "CurrentCharacter Assumption violated", "Assumed that the current character would be {0}, but it is actually {1}", current, CurrentCharacter); -#else - Debug.Assert(CurrentCharacter == current, string.Format("CurrentCharacter Assumption violated. Assumed that the current character would be {0}, but it is actually {1}", current, CurrentCharacter)); -#endif - } - - ISymbol ITokenizer.NextSymbol() - { - return (ISymbol)NextSymbol(); - } - -#if DEBUG - public string DebugDisplay - { - get { return string.Format(CultureInfo.InvariantCulture, "[{0}] [{1}] [{2}]", _read.ToString(), CurrentCharacter, Remaining); } - } - - public string Remaining - { - get - { - var remaining = Source.ReadToEnd(); - Source.Seek(-remaining.Length); - return remaining; - } - } -#endif - - protected enum RazorCommentTokenizerState - { - AfterRazorCommentTransition = 1000, - EscapedRazorCommentTransition, - RazorCommentBody, - StarAfterRazorCommentBody, - AtSymbolAfterRazorCommentBody, - } - - protected struct StateResult - { - public StateResult(int? state, TSymbol result) - { - State = state; - Result = result; - } - - public int? State { get; } - - public TSymbol Result { get; } - } - } -} diff --git a/src/Microsoft.AspNetCore.Razor/Tokenizer/TokenizerView.cs b/src/Microsoft.AspNetCore.Razor/Tokenizer/TokenizerView.cs deleted file mode 100644 index a4f8ae6acc..0000000000 --- a/src/Microsoft.AspNetCore.Razor/Tokenizer/TokenizerView.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Tokenizer -{ - public class TokenizerView - where TSymbolType : struct - where TTokenizer : Tokenizer - where TSymbol : SymbolBase - { - public TokenizerView(TTokenizer tokenizer) - { - Tokenizer = tokenizer; - } - - public TTokenizer Tokenizer { get; private set; } - public bool EndOfFile { get; private set; } - public TSymbol Current { get; private set; } - - public ITextDocument Source - { - get { return Tokenizer.Source; } - } - - public bool Next() - { - Current = Tokenizer.NextSymbol(); - EndOfFile = (Current == null); - return !EndOfFile; - } - - public void PutBack(TSymbol symbol) - { - Debug.Assert(Source.Position == symbol.Start.AbsoluteIndex + symbol.Content.Length); - if (Source.Position != symbol.Start.AbsoluteIndex + symbol.Content.Length) - { - // We've already passed this symbol - throw new InvalidOperationException( - RazorResources.FormatTokenizerView_CannotPutBack( - symbol.Start.AbsoluteIndex + symbol.Content.Length, - Source.Position)); - } - Source.Position -= symbol.Content.Length; - Current = null; - EndOfFile = Source.Position >= Source.Length; - Tokenizer.Reset(); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorFactoryTest.cs b/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorFactoryTest.cs deleted file mode 100644 index 75ed9d1863..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorFactoryTest.cs +++ /dev/null @@ -1,2541 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers.Testing; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - public class TagHelperDescriptorFactoryTest - { - protected static readonly AssemblyName TagHelperDescriptorFactoryTestAssembly = - typeof(TagHelperDescriptorFactoryTest).GetTypeInfo().Assembly.GetName(); - - protected static readonly string AssemblyName = TagHelperDescriptorFactoryTestAssembly.Name; - - public static TheoryData RequiredAttributeParserErrorData - { - get - { - Func error = (message) => new RazorError(message, SourceLocation.Zero, 0); - - return new TheoryData - { - { "name,", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("name,")) }, - { " ", error(Resources.FormatHtmlTargetElementAttribute_NameCannotBeNullOrWhitespace("Attribute")) }, - { "n@me", error(Resources.FormatHtmlTargetElementAttribute_InvalidName("attribute", "n@me", '@')) }, - { "name extra", error(Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeCharacter('e', "name extra")) }, - { "[[ ", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("[[ ")) }, - { "[ ", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("[ ")) }, - { - "[name='unended]", - error(Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeMismatchedQuotes("[name='unended]", '\'')) - }, - { - "[name='unended", - error(Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeMismatchedQuotes("[name='unended", '\'')) - }, - { "[name", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("[name")) }, - { "[ ]", error(Resources.FormatHtmlTargetElementAttribute_NameCannotBeNullOrWhitespace("Attribute")) }, - { "[n@me]", error(Resources.FormatHtmlTargetElementAttribute_InvalidName("attribute", "n@me", '@')) }, - { "[name@]", error(Resources.FormatHtmlTargetElementAttribute_InvalidName("attribute", "name@", '@')) }, - { "[name^]", error(Resources.FormatTagHelperDescriptorFactory_PartialRequiredAttributeOperator("[name^]", '^')) }, - { "[name='value'", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("[name='value'")) }, - { "[name ", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("[name ")) }, - { "[name extra]", error(Resources.FormatTagHelperDescriptorFactory_InvalidRequiredAttributeOperator('e', "[name extra]")) }, - { "[name=value ", error(Resources.FormatTagHelperDescriptorFactory_CouldNotFindMatchingEndBrace("[name=value ")) }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredAttributeParserErrorData))] - public void RequiredAttributeParser_ParsesRequiredAttributesAndLogsErrorCorrectly( - string requiredAttributes, - RazorError expectedError) - { - // Arrange - var parser = new TagHelperDescriptorFactory.RequiredAttributeParser(requiredAttributes); - var errorSink = new ErrorSink(); - IEnumerable descriptors; - - // Act - var parsedCorrectly = parser.TryParse(errorSink, out descriptors); - - // Assert - Assert.False(parsedCorrectly); - Assert.Null(descriptors); - var error = Assert.Single(errorSink.Errors); - Assert.Equal(expectedError, error); - } - - public static TheoryData RequiredAttributeParserData - { - get - { - Func plain = - (name, nameComparison) => new TagHelperRequiredAttributeDescriptor - { - Name = name, - NameComparison = nameComparison - }; - Func css = - (name, value, valueComparison) => new TagHelperRequiredAttributeDescriptor - { - Name = name, - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = value, - ValueComparison = valueComparison, - }; - - return new TheoryData> - { - { null, Enumerable.Empty() }, - { string.Empty, Enumerable.Empty() }, - { "name", new[] { plain("name", TagHelperRequiredAttributeNameComparison.FullMatch) } }, - { "name-*", new[] { plain("name-", TagHelperRequiredAttributeNameComparison.PrefixMatch) } }, - { " name-* ", new[] { plain("name-", TagHelperRequiredAttributeNameComparison.PrefixMatch) } }, - { - "asp-route-*,valid , name-* ,extra", - new[] - { - plain("asp-route-", TagHelperRequiredAttributeNameComparison.PrefixMatch), - plain("valid", TagHelperRequiredAttributeNameComparison.FullMatch), - plain("name-", TagHelperRequiredAttributeNameComparison.PrefixMatch), - plain("extra", TagHelperRequiredAttributeNameComparison.FullMatch), - } - }, - { "[name]", new[] { css("name", "", TagHelperRequiredAttributeValueComparison.None) } }, - { "[ name ]", new[] { css("name", "", TagHelperRequiredAttributeValueComparison.None) } }, - { " [ name ] ", new[] { css("name", "", TagHelperRequiredAttributeValueComparison.None) } }, - { "[name=]", new[] { css("name", "", TagHelperRequiredAttributeValueComparison.FullMatch) } }, - { "[name='']", new[] { css("name", "", TagHelperRequiredAttributeValueComparison.FullMatch) } }, - { "[name ^=]", new[] { css("name", "", TagHelperRequiredAttributeValueComparison.PrefixMatch) } }, - { "[name=hello]", new[] { css("name", "hello", TagHelperRequiredAttributeValueComparison.FullMatch) } }, - { "[name= hello]", new[] { css("name", "hello", TagHelperRequiredAttributeValueComparison.FullMatch) } }, - { "[name='hello']", new[] { css("name", "hello", TagHelperRequiredAttributeValueComparison.FullMatch) } }, - { "[name=\"hello\"]", new[] { css("name", "hello", TagHelperRequiredAttributeValueComparison.FullMatch) } }, - { " [ name $= \" hello\" ] ", new[] { css("name", " hello", TagHelperRequiredAttributeValueComparison.SuffixMatch) } }, - { - "[name=\"hello\"],[other^=something ], [val = 'cool']", - new[] - { - css("name", "hello", TagHelperRequiredAttributeValueComparison.FullMatch), - css("other", "something", TagHelperRequiredAttributeValueComparison.PrefixMatch), - css("val", "cool", TagHelperRequiredAttributeValueComparison.FullMatch) } - }, - { - "asp-route-*,[name=\"hello\"],valid ,[other^=something ], name-* ,[val = 'cool'],extra", - new[] - { - plain("asp-route-", TagHelperRequiredAttributeNameComparison.PrefixMatch), - css("name", "hello", TagHelperRequiredAttributeValueComparison.FullMatch), - plain("valid", TagHelperRequiredAttributeNameComparison.FullMatch), - css("other", "something", TagHelperRequiredAttributeValueComparison.PrefixMatch), - plain("name-", TagHelperRequiredAttributeNameComparison.PrefixMatch), - css("val", "cool", TagHelperRequiredAttributeValueComparison.FullMatch), - plain("extra", TagHelperRequiredAttributeNameComparison.FullMatch), - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredAttributeParserData))] - public void RequiredAttributeParser_ParsesRequiredAttributesCorrectly( - string requiredAttributes, - IEnumerable expectedDescriptors) - { - // Arrange - var parser = new TagHelperDescriptorFactory.RequiredAttributeParser(requiredAttributes); - var errorSink = new ErrorSink(); - IEnumerable descriptors; - - // Act - //System.Diagnostics.Debugger.Launch(); - var parsedCorrectly = parser.TryParse(errorSink, out descriptors); - - // Assert - Assert.True(parsedCorrectly); - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperRequiredAttributeDescriptorComparer.Default); - } - - public static TheoryData IsEnumData - { - get - { - var attributeDescriptors = new[] - { - new TagHelperAttributeDescriptor - { - Name = "non-enum-property", - PropertyName = nameof(EnumTagHelper.NonEnumProperty), - TypeName = typeof(int).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "enum-property", - PropertyName = nameof(EnumTagHelper.EnumProperty), - TypeName = typeof(CustomEnum).FullName, - IsEnum = true - }, - }; - - // tagHelperType, expectedDescriptors - return new TheoryData - { - { - typeof(EnumTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "enum", - TypeName = typeof(EnumTagHelper).FullName, - AssemblyName = AssemblyName, - Attributes = attributeDescriptors - } - } - }, - { - typeof(MultiEnumTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(MultiEnumTagHelper).FullName, - AssemblyName = AssemblyName, - Attributes = attributeDescriptors - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MultiEnumTagHelper).FullName, - AssemblyName = AssemblyName, - Attributes = attributeDescriptors - } - } - } - }; - } - } - - [Theory] - [MemberData(nameof(IsEnumData))] - public void CreateDescriptors_IsEnumIsSetCorrectly( - Type tagHelperType, - TagHelperDescriptor[] expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData RequiredParentData - { - get - { - // tagHelperType, expectedDescriptors - return new TheoryData - { - { - typeof(RequiredParentTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(RequiredParentTagHelper).FullName, - AssemblyName = AssemblyName, - RequiredParent = "div" - } - } - }, - { - typeof(MultiSpecifiedRequiredParentTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(MultiSpecifiedRequiredParentTagHelper).FullName, - AssemblyName = AssemblyName, - RequiredParent = "section" - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MultiSpecifiedRequiredParentTagHelper).FullName, - AssemblyName = AssemblyName, - RequiredParent = "div" - } - } - }, - { - typeof(MultiWithUnspecifiedRequiredParentTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(MultiWithUnspecifiedRequiredParentTagHelper).FullName, - AssemblyName = AssemblyName, - RequiredParent = "div" - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MultiWithUnspecifiedRequiredParentTagHelper).FullName, - AssemblyName = AssemblyName - } - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredParentData))] - public void CreateDescriptors_CreatesDesignTimeDescriptorsWithRequiredParent( - Type tagHelperType, - TagHelperDescriptor[] expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData RestrictChildrenData - { - get - { - // tagHelperType, expectedDescriptors - return new TheoryData - { - { - typeof(RestrictChildrenTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "restrict-children", - TypeName = typeof(RestrictChildrenTagHelper).FullName, - AssemblyName = AssemblyName, - AllowedChildren = new[] { "p" }, - } - } - }, - { - typeof(DoubleRestrictChildrenTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "double-restrict-children", - TypeName = typeof(DoubleRestrictChildrenTagHelper).FullName, - AssemblyName = AssemblyName, - AllowedChildren = new[] { "p", "strong" }, - } - } - }, - { - typeof(MultiTargetRestrictChildrenTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = typeof(MultiTargetRestrictChildrenTagHelper).FullName, - AssemblyName = AssemblyName, - AllowedChildren = new[] { "p", "strong" }, - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MultiTargetRestrictChildrenTagHelper).FullName, - AssemblyName = AssemblyName, - AllowedChildren = new[] { "p", "strong" }, - } - } - }, - }; - } - } - - - [Theory] - [MemberData(nameof(RestrictChildrenData))] - public void CreateDescriptors_CreatesDescriptorsWithAllowedChildren( - Type tagHelperType, - TagHelperDescriptor[] expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData TagStructureData - { - get - { - // tagHelperType, expectedDescriptors - return new TheoryData - { - { - typeof(TagStructureTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(TagStructureTagHelper).FullName, - AssemblyName = AssemblyName, - TagStructure = TagStructure.WithoutEndTag - } - } - }, - { - typeof(MultiSpecifiedTagStructureTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(MultiSpecifiedTagStructureTagHelper).FullName, - AssemblyName = AssemblyName, - TagStructure = TagStructure.WithoutEndTag - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MultiSpecifiedTagStructureTagHelper).FullName, - AssemblyName = AssemblyName, - TagStructure = TagStructure.NormalOrSelfClosing - } - } - }, - { - typeof(MultiWithUnspecifiedTagStructureTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = typeof(MultiWithUnspecifiedTagStructureTagHelper).FullName, - AssemblyName = AssemblyName, - TagStructure = TagStructure.WithoutEndTag - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MultiWithUnspecifiedTagStructureTagHelper).FullName, - AssemblyName = AssemblyName - } - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(TagStructureData))] - public void CreateDescriptors_CreatesDesignTimeDescriptorsWithTagStructure( - Type tagHelperType, - TagHelperDescriptor[] expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData EditorBrowsableData - { - get - { - // tagHelperType, designTime, expectedDescriptors - return new TheoryData - { - { - typeof(InheritedEditorBrowsableTagHelper), - true, - new[] - { - CreateTagHelperDescriptor( - tagName: "inherited-editor-browsable", - typeName: typeof(InheritedEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(InheritedEditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - } - }) - } - }, - { typeof(EditorBrowsableTagHelper), true, new TagHelperDescriptor[0] }, - { - typeof(EditorBrowsableTagHelper), - false, - new[] - { - CreateTagHelperDescriptor( - tagName: "editor-browsable", - typeName: typeof(EditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(EditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - } - }) - } - }, - { - typeof(HiddenPropertyEditorBrowsableTagHelper), - true, - new[] - { - CreateTagHelperDescriptor( - tagName: "hidden-property-editor-browsable", - typeName: typeof(HiddenPropertyEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new TagHelperAttributeDescriptor[0]) - } - }, - { - typeof(HiddenPropertyEditorBrowsableTagHelper), - false, - new[] - { - CreateTagHelperDescriptor( - tagName: "hidden-property-editor-browsable", - typeName: typeof(HiddenPropertyEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(HiddenPropertyEditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - } - }) - } - }, - { - typeof(OverriddenEditorBrowsableTagHelper), - true, - new[] - { - CreateTagHelperDescriptor( - tagName: "overridden-editor-browsable", - typeName: typeof(OverriddenEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(OverriddenEditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - } - }) - } - }, - { - typeof(MultiPropertyEditorBrowsableTagHelper), - true, - new[] - { - CreateTagHelperDescriptor( - tagName: "multi-property-editor-browsable", - typeName: typeof(MultiPropertyEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property2", - PropertyName = nameof(MultiPropertyEditorBrowsableTagHelper.Property2), - TypeName = typeof(int).FullName - } - }) - } - }, - { - typeof(MultiPropertyEditorBrowsableTagHelper), - false, - new[] - { - CreateTagHelperDescriptor( - tagName: "multi-property-editor-browsable", - typeName: typeof(MultiPropertyEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(MultiPropertyEditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "property2", - PropertyName = nameof(MultiPropertyEditorBrowsableTagHelper.Property2), - TypeName = typeof(int).FullName - } - }) - } - }, - { - typeof(OverriddenPropertyEditorBrowsableTagHelper), - true, - new[] - { - CreateTagHelperDescriptor( - tagName: "overridden-property-editor-browsable", - typeName: typeof(OverriddenPropertyEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new TagHelperAttributeDescriptor[0]) - } - }, - { - typeof(OverriddenPropertyEditorBrowsableTagHelper), - false, - new[] - { - CreateTagHelperDescriptor( - tagName: "overridden-property-editor-browsable", - typeName: typeof(OverriddenPropertyEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property2", - PropertyName = nameof(OverriddenPropertyEditorBrowsableTagHelper.Property2), - TypeName = typeof(int).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(OverriddenPropertyEditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - } - }) - } - }, - { - typeof(DefaultEditorBrowsableTagHelper), - true, - new[] - { - CreateTagHelperDescriptor( - tagName: "default-editor-browsable", - typeName: typeof(DefaultEditorBrowsableTagHelper).FullName, - assemblyName: AssemblyName, - attributes: new[] - { - new TagHelperAttributeDescriptor - { - Name = "property", - PropertyName = nameof(DefaultEditorBrowsableTagHelper.Property), - TypeName = typeof(int).FullName - } - }) - } - }, - { typeof(MultiEditorBrowsableTagHelper), true, new TagHelperDescriptor[0] } - }; - } - } - - [Theory] - [MemberData(nameof(EditorBrowsableData))] - public void CreateDescriptors_UnderstandsEditorBrowsableAttribute( - Type tagHelperType, - bool designTime, - TagHelperDescriptor[] expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData AttributeTargetData - { - get - { - var attributes = Enumerable.Empty(); - - // tagHelperType, expectedDescriptors - return new TheoryData> - { - { - typeof(AttributeTargetingTagHelper), - new[] - { - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(AttributeTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" } - }) - } - }, - { - typeof(MultiAttributeTargetingTagHelper), - new[] - { - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(MultiAttributeTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }) - } - }, - { - typeof(MultiAttributeAttributeTargetingTagHelper), - new[] - { - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(MultiAttributeAttributeTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "custom" } - }), - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(MultiAttributeAttributeTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }) - } - }, - { - typeof(InheritedAttributeTargetingTagHelper), - new[] - { - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(InheritedAttributeTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }) - } - }, - { - typeof(RequiredAttributeTagHelper), - new[] - { - CreateTagHelperDescriptor( - "input", - typeof(RequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" } - }) - } - }, - { - typeof(InheritedRequiredAttributeTagHelper), - new[] - { - CreateTagHelperDescriptor( - "div", - typeof(InheritedRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" } - }) - } - }, - { - typeof(MultiAttributeRequiredAttributeTagHelper), - new[] - { - CreateTagHelperDescriptor( - "div", - typeof(MultiAttributeRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" } - }), - CreateTagHelperDescriptor( - "input", - typeof(MultiAttributeRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" } - }) - } - }, - { - typeof(MultiAttributeSameTagRequiredAttributeTagHelper), - new[] - { - CreateTagHelperDescriptor( - "input", - typeof(MultiAttributeSameTagRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }), - CreateTagHelperDescriptor( - "input", - typeof(MultiAttributeSameTagRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" } - }) - } - }, - { - typeof(MultiRequiredAttributeTagHelper), - new[] - { - CreateTagHelperDescriptor( - "input", - typeof(MultiRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }) - } - }, - { - typeof(MultiTagMultiRequiredAttributeTagHelper), - new[] - { - CreateTagHelperDescriptor( - "div", - typeof(MultiTagMultiRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }), - CreateTagHelperDescriptor( - "input", - typeof(MultiTagMultiRequiredAttributeTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - }), - } - }, - { - typeof(AttributeWildcardTargetingTagHelper), - new[] - { - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(AttributeWildcardTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "class", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - } - }) - } - }, - { - typeof(MultiAttributeWildcardTargetingTagHelper), - new[] - { - CreateTagHelperDescriptor( - TagHelperDescriptorProvider.ElementCatchAllTarget, - typeof(MultiAttributeWildcardTargetingTagHelper).FullName, - AssemblyName, - attributes, - requiredAttributes: new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "class", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - }, - new TagHelperRequiredAttributeDescriptor - { - Name = "style", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - } - }) - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(AttributeTargetData))] - public void CreateDescriptors_ReturnsExpectedDescriptors( - Type tagHelperType, - IEnumerable expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy( - descriptor => CaseSensitiveTagHelperDescriptorComparer.Default.GetHashCode(descriptor)).ToArray(); - expectedDescriptors = expectedDescriptors.OrderBy( - descriptor => CaseSensitiveTagHelperDescriptorComparer.Default.GetHashCode(descriptor)).ToArray(); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData HtmlCaseData - { - get - { - // tagHelperType, expectedTagName, expectedAttributeName - return new TheoryData - { - { typeof(SingleAttributeTagHelper), "single-attribute", "int-attribute" }, - { typeof(ALLCAPSTAGHELPER), "allcaps", "allcapsattribute" }, - { typeof(CAPSOnOUTSIDETagHelper), "caps-on-outside", "caps-on-outsideattribute" }, - { typeof(capsONInsideTagHelper), "caps-on-inside", "caps-on-insideattribute" }, - { typeof(One1Two2Three3TagHelper), "one1-two2-three3", "one1-two2-three3-attribute" }, - { typeof(ONE1TWO2THREE3TagHelper), "one1two2three3", "one1two2three3-attribute" }, - { typeof(First_Second_ThirdHiTagHelper), "first_second_third-hi", "first_second_third-attribute" }, - { typeof(UNSuffixedCLASS), "un-suffixed-class", "un-suffixed-attribute" }, - }; - } - } - - [Theory] - [MemberData(nameof(HtmlCaseData))] - public void CreateDescriptors_HtmlCasesTagNameAndAttributeName( - Type tagHelperType, - string expectedTagName, - string expectedAttributeName) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedTagName, descriptor.TagName, StringComparer.Ordinal); - var attributeDescriptor = Assert.Single(descriptor.Attributes); - Assert.Equal(expectedAttributeName, attributeDescriptor.Name); - } - - [Fact] - public void CreateDescriptors_OverridesAttributeNameFromAttribute() - { - // Arrange - var errorSink = new ErrorSink(); - var validProperty1 = typeof(OverriddenAttributeTagHelper).GetProperty( - nameof(OverriddenAttributeTagHelper.ValidAttribute1)); - var validProperty2 = typeof(OverriddenAttributeTagHelper).GetProperty( - nameof(OverriddenAttributeTagHelper.ValidAttribute2)); - var expectedDescriptors = new[] - { - CreateTagHelperDescriptor( - "overridden-attribute", - typeof(OverriddenAttributeTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("SomethingElse", validProperty1), - CreateTagHelperAttributeDescriptor("Something-Else", validProperty2) - }) - }; - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(OverriddenAttributeTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_DoesNotInheritOverridenAttributeName() - { - // Arrange - var errorSink = new ErrorSink(); - var validProperty1 = typeof(InheritedOverriddenAttributeTagHelper).GetProperty( - nameof(InheritedOverriddenAttributeTagHelper.ValidAttribute1)); - var validProperty2 = typeof(InheritedOverriddenAttributeTagHelper).GetProperty( - nameof(InheritedOverriddenAttributeTagHelper.ValidAttribute2)); - var expectedDescriptors = new[] - { - CreateTagHelperDescriptor( - "inherited-overridden-attribute", - typeof(InheritedOverriddenAttributeTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("valid-attribute1", validProperty1), - CreateTagHelperAttributeDescriptor("Something-Else", validProperty2) - }) - }; - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(InheritedOverriddenAttributeTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_AllowsOverridenAttributeNameOnUnimplementedVirtual() - { - // Arrange - var errorSink = new ErrorSink(); - var validProperty1 = typeof(InheritedNotOverriddenAttributeTagHelper).GetProperty( - nameof(InheritedNotOverriddenAttributeTagHelper.ValidAttribute1)); - var validProperty2 = typeof(InheritedNotOverriddenAttributeTagHelper).GetProperty( - nameof(InheritedNotOverriddenAttributeTagHelper.ValidAttribute2)); - var expectedDescriptors = new[] - { - CreateTagHelperDescriptor( - "inherited-not-overridden-attribute", - typeof(InheritedNotOverriddenAttributeTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("SomethingElse", validProperty1), - CreateTagHelperAttributeDescriptor("Something-Else", validProperty2) - }) - }; - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(InheritedNotOverriddenAttributeTagHelper), - errorSink: errorSink); - // Assert - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_BuildsDescriptorsWithInheritedProperties() - { - // Arrange - var errorSink = new ErrorSink(); - var expectedDescriptor = CreateTagHelperDescriptor( - "inherited-single-attribute", - typeof(InheritedSingleAttributeTagHelper).FullName, - AssemblyName, - new[] - { - new TagHelperAttributeDescriptor - { - Name = "int-attribute", - PropertyName = nameof(InheritedSingleAttributeTagHelper.IntAttribute), - TypeName = typeof(int).FullName - } - }); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(InheritedSingleAttributeTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_BuildsDescriptorsWithConventionNames() - { - // Arrange - var errorSink = new ErrorSink(); - var intProperty = typeof(SingleAttributeTagHelper).GetProperty(nameof(SingleAttributeTagHelper.IntAttribute)); - var expectedDescriptor = CreateTagHelperDescriptor( - "single-attribute", - typeof(SingleAttributeTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("int-attribute", intProperty) - }); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(SingleAttributeTagHelper), - errorSink: new ErrorSink()); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_OnlyAcceptsPropertiesWithGetAndSet() - { - // Arrange - var errorSink = new ErrorSink(); - var validProperty = typeof(MissingAccessorTagHelper).GetProperty( - nameof(MissingAccessorTagHelper.ValidAttribute)); - var expectedDescriptor = CreateTagHelperDescriptor( - "missing-accessor", - typeof(MissingAccessorTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("valid-attribute", validProperty) - }); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(MissingAccessorTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_OnlyAcceptsPropertiesWithPublicGetAndSet() - { - // Arrange - var errorSink = new ErrorSink(); - var validProperty = typeof(NonPublicAccessorTagHelper).GetProperty( - nameof(NonPublicAccessorTagHelper.ValidAttribute)); - var expectedDescriptor = CreateTagHelperDescriptor( - "non-public-accessor", - typeof(NonPublicAccessorTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("valid-attribute", validProperty) - }); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(NonPublicAccessorTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_DoesNotIncludePropertiesWithNotBound() - { - // Arrange - var errorSink = new ErrorSink(); - var expectedDescriptor = CreateTagHelperDescriptor( - "not-bound-attribute", - typeof(NotBoundAttributeTagHelper).FullName, - AssemblyName, - new[] - { - new TagHelperAttributeDescriptor - { - Name = "bound-property", - PropertyName = nameof(NotBoundAttributeTagHelper.BoundProperty), - TypeName = typeof(object).FullName - } - }); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(NotBoundAttributeTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact(Skip = "#364")] - public void CreateDescriptors_AddsErrorForTagHelperWithDuplicateAttributeNames() - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(DuplicateAttributeNameTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(descriptors); - var error = Assert.Single(errorSink.Errors); - } - - [Fact] - public void CreateDescriptors_ResolvesMultipleTagHelperDescriptorsFromSingleType() - { - // Arrange - var errorSink = new ErrorSink(); - var expectedDescriptors = new[] - { - CreateTagHelperDescriptor( - "div", - typeof(MultiTagTagHelper).FullName, - AssemblyName, - new[] - { - new TagHelperAttributeDescriptor - { - Name = "valid-attribute", - PropertyName = nameof(MultiTagTagHelper.ValidAttribute), - TypeName = typeof(string).FullName, - IsStringProperty = true - } - }), - CreateTagHelperDescriptor( - "p", - typeof(MultiTagTagHelper).FullName, - AssemblyName, - new[] - { - new TagHelperAttributeDescriptor - { - Name = "valid-attribute", - PropertyName = nameof(MultiTagTagHelper.ValidAttribute), - TypeName = typeof(string).FullName, - IsStringProperty = true - } - }) - }; - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(MultiTagTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName).ToArray(); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_DoesNotResolveInheritedTagNames() - { - // Arrange - var errorSink = new ErrorSink(); - var validProp = typeof(InheritedMultiTagTagHelper).GetProperty(nameof(InheritedMultiTagTagHelper.ValidAttribute)); - var expectedDescriptor = CreateTagHelperDescriptor( - "inherited-multi-tag", - typeof(InheritedMultiTagTagHelper).FullName, - AssemblyName, - new[] - { - CreateTagHelperAttributeDescriptor("valid-attribute", validProp) - }); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(InheritedMultiTagTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_IgnoresDuplicateTagNamesFromAttribute() - { - // Arrange - var errorSink = new ErrorSink(); - var expectedDescriptors = new[] - { - CreateTagHelperDescriptor( - "div", - typeof(DuplicateTagNameTagHelper).FullName, - AssemblyName), - CreateTagHelperDescriptor( - "p", - typeof(DuplicateTagNameTagHelper).FullName, - AssemblyName) - }; - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(DuplicateTagNameTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName).ToArray(); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptors_OverridesTagNameFromAttribute() - { - // Arrange - var errorSink = new ErrorSink(); - var expectedDescriptors = new[] - { - CreateTagHelperDescriptor( - "data-condition", - typeof(OverrideNameTagHelper).FullName, - AssemblyName), - }; - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - typeof(OverrideNameTagHelper), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - // name, expectedErrorMessages - public static TheoryData InvalidNameData - { - get - { - Func onNameError = - (invalidText, invalidCharacter) => $"Tag helpers cannot target tag name '{ invalidText }' " + - $"because it contains a '{ invalidCharacter }' character."; - var whitespaceErrorString = "Tag name cannot be null or whitespace."; - - var data = GetInvalidNameOrPrefixData(onNameError, whitespaceErrorString, onDataError: null); - data.Add(string.Empty, new[] { whitespaceErrorString }); - - return data; - } - } - - [Theory] - [MemberData(nameof(InvalidNameData))] - public void ValidHtmlTargetElementAttributeNames_CreatesErrorOnInvalidNames( - string name, string[] expectedErrorMessages) - { - // Arrange - var errorSink = new ErrorSink(); - var attribute = new HtmlTargetElementAttribute(name); - - // Act - TagHelperDescriptorFactory.ValidHtmlTargetElementAttributeNames(attribute, errorSink); - - // Assert - var errors = errorSink.Errors.ToArray(); - Assert.Equal(expectedErrorMessages.Length, errors.Length); - for (var i = 0; i < expectedErrorMessages.Length; i++) - { - Assert.Equal(0, errors[i].Length); - Assert.Equal(SourceLocation.Zero, errors[i].Location); - Assert.Equal(expectedErrorMessages[i], errors[i].Message, StringComparer.Ordinal); - } - } - - public static TheoryData ValidNameData - { - get - { - // name, expectedNames - return new TheoryData> - { - { "p", new[] { "p" } }, - { " p", new[] { "p" } }, - { "p ", new[] { "p" } }, - { " p ", new[] { "p" } }, - { "p,div", new[] { "p", "div" } }, - { " p,div", new[] { "p", "div" } }, - { "p ,div", new[] { "p", "div" } }, - { " p ,div", new[] { "p", "div" } }, - { "p, div", new[] { "p", "div" } }, - { "p,div ", new[] { "p", "div" } }, - { "p, div ", new[] { "p", "div" } }, - { " p, div ", new[] { "p", "div" } }, - { " p , div ", new[] { "p", "div" } }, - }; - } - } - - public static TheoryData InvalidTagHelperAttributeDescriptorData - { - get - { - var errorFormat = "Invalid tag helper bound property '{0}.{1}'. Tag helpers cannot bind to HTML " + - "attributes with name '{2}' because name starts with 'data-'."; - - // type, expectedAttributeDescriptors, expectedErrors - return new TheoryData, string[]> - { - { - typeof(InvalidBoundAttribute), - Enumerable.Empty(), - new[] - { - string.Format( - errorFormat, - typeof(InvalidBoundAttribute).FullName, - nameof(InvalidBoundAttribute.DataSomething), - "data-something") - } - }, - { - typeof(InvalidBoundAttributeWithValid), - new[] - { - CreateTagHelperAttributeDescriptor( - "int-attribute", - typeof(InvalidBoundAttributeWithValid) - .GetProperty(nameof(InvalidBoundAttributeWithValid.IntAttribute))) - }, - new[] - { - string.Format( - errorFormat, - typeof(InvalidBoundAttributeWithValid).FullName, - nameof(InvalidBoundAttributeWithValid.DataSomething), - "data-something") - } - }, - { - typeof(OverriddenInvalidBoundAttributeWithValid), - new[] - { - CreateTagHelperAttributeDescriptor( - "valid-something", - typeof(OverriddenInvalidBoundAttributeWithValid) - .GetProperty(nameof(OverriddenInvalidBoundAttributeWithValid.DataSomething))) - }, - new string[0] - }, - { - typeof(OverriddenValidBoundAttributeWithInvalid), - Enumerable.Empty(), - new[] - { - string.Format( - errorFormat, - typeof(OverriddenValidBoundAttributeWithInvalid).FullName, - nameof(OverriddenValidBoundAttributeWithInvalid.ValidSomething), - "data-something") - } - }, - { - typeof(OverriddenValidBoundAttributeWithInvalidUpperCase), - Enumerable.Empty(), - new[] - { - string.Format( - errorFormat, - typeof(OverriddenValidBoundAttributeWithInvalidUpperCase).FullName, - nameof(OverriddenValidBoundAttributeWithInvalidUpperCase.ValidSomething), - "DATA-SOMETHING") - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(InvalidTagHelperAttributeDescriptorData))] - public void CreateDescriptors_DoesNotAllowDataDashAttributes( - Type type, - IEnumerable expectedAttributeDescriptors, - string[] expectedErrors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - type, - errorSink: errorSink); - - // Assert - var actualErrors = errorSink.Errors.ToArray(); - Assert.Equal(expectedErrors.Length, actualErrors.Length); - - for (var i = 0; i < actualErrors.Length; i++) - { - var actualError = actualErrors[i]; - Assert.Equal(0, actualError.Length); - Assert.Equal(SourceLocation.Zero, actualError.Location); - Assert.Equal(expectedErrors[i], actualError.Message, StringComparer.Ordinal); - } - - var actualDescriptor = Assert.Single(descriptors); - Assert.Equal( - expectedAttributeDescriptors, - actualDescriptor.Attributes, - TagHelperAttributeDescriptorComparer.Default); - } - - // tagTelperType, expectedAttributeDescriptors, expectedErrorMessages - public static TheoryData, string[]> TagHelperWithPrefixData - { - get - { - Func onError = (typeName, propertyName) => - $"Invalid tag helper bound property '{ typeName }.{ propertyName }'. " + - $"'{ nameof(HtmlAttributeNameAttribute) }." + - $"{ nameof(HtmlAttributeNameAttribute.DictionaryAttributePrefix) }' must be null unless " + - "property type implements 'IDictionary'."; - - // tagTelperType, expectedAttributeDescriptors, expectedErrorMessages - return new TheoryData, string[]> - { - { - typeof(DefaultValidHtmlAttributePrefix), - new[] - { - new TagHelperAttributeDescriptor - { - Name = "dictionary-property", - PropertyName = nameof(DefaultValidHtmlAttributePrefix.DictionaryProperty), - TypeName = typeof(IDictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "dictionary-property-", - PropertyName = nameof(DefaultValidHtmlAttributePrefix.DictionaryProperty), - TypeName = typeof(string).FullName, - IsIndexer = true - } - }, - new string[0] - }, - { - typeof(SingleValidHtmlAttributePrefix), - new[] - { - new TagHelperAttributeDescriptor - { - Name = "valid-name", - PropertyName = nameof(SingleValidHtmlAttributePrefix.DictionaryProperty), - TypeName = typeof(IDictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "valid-name-", - PropertyName = nameof(SingleValidHtmlAttributePrefix.DictionaryProperty), - TypeName = typeof(string).FullName, - IsIndexer = true - } - }, - new string[0] - }, - { - typeof(MultipleValidHtmlAttributePrefix), - new[] - { - new TagHelperAttributeDescriptor - { - Name = "valid-name1", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.DictionaryProperty), - TypeName = typeof(Dictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "valid-name2", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.DictionarySubclassProperty), - TypeName = typeof(DictionarySubclass).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "valid-name3", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.DictionaryWithoutParameterlessConstructorProperty), - TypeName = typeof(DictionaryWithoutParameterlessConstructor).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "valid-name4", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.GenericDictionarySubclassProperty), - TypeName = typeof(GenericDictionarySubclass).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "valid-name5", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.SortedDictionaryProperty), - TypeName = typeof(SortedDictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "valid-name6", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.StringProperty), - TypeName = typeof(string).FullName, - IsStringProperty = true, - }, - new TagHelperAttributeDescriptor - { - Name = "valid-prefix1-", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.DictionaryProperty), - TypeName = typeof(object).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "valid-prefix2-", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.DictionarySubclassProperty), - TypeName = typeof(string).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "valid-prefix3-", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.DictionaryWithoutParameterlessConstructorProperty), - TypeName = typeof(string).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "valid-prefix4-", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.GenericDictionarySubclassProperty), - TypeName = typeof(object).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "valid-prefix5-", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.SortedDictionaryProperty), - TypeName = typeof(int).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "get-only-dictionary-property-", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.GetOnlyDictionaryProperty), - TypeName = typeof(int).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "valid-prefix6", - PropertyName = nameof(MultipleValidHtmlAttributePrefix.GetOnlyDictionaryPropertyWithAttributePrefix), - TypeName = typeof(string).FullName, - IsIndexer = true - } - }, - new string[0] - }, - { - typeof(SingleInvalidHtmlAttributePrefix), - Enumerable.Empty(), - new[] - { - onError( - typeof(SingleInvalidHtmlAttributePrefix).FullName, - nameof(SingleInvalidHtmlAttributePrefix.StringProperty)), - } - }, - { - typeof(MultipleInvalidHtmlAttributePrefix), - new[] - { - new TagHelperAttributeDescriptor - { - Name = "valid-name1", - PropertyName = nameof(MultipleInvalidHtmlAttributePrefix.LongProperty), - TypeName = typeof(long).FullName - } - }, - new[] - { - onError( - typeof(MultipleInvalidHtmlAttributePrefix).FullName, - nameof(MultipleInvalidHtmlAttributePrefix.DictionaryOfIntProperty)), - onError( - typeof(MultipleInvalidHtmlAttributePrefix).FullName, - nameof(MultipleInvalidHtmlAttributePrefix.ReadOnlyDictionaryProperty)), - onError( - typeof(MultipleInvalidHtmlAttributePrefix).FullName, - nameof(MultipleInvalidHtmlAttributePrefix.IntProperty)), - onError( - typeof(MultipleInvalidHtmlAttributePrefix).FullName, - nameof(MultipleInvalidHtmlAttributePrefix.DictionaryOfIntSubclassProperty)), - onError( - typeof(MultipleInvalidHtmlAttributePrefix).FullName, - nameof(MultipleInvalidHtmlAttributePrefix.GetOnlyDictionaryAttributePrefix)), - $"Invalid tag helper bound property '{ typeof(MultipleInvalidHtmlAttributePrefix).FullName }." + - $"{ nameof(MultipleInvalidHtmlAttributePrefix.GetOnlyDictionaryPropertyWithAttributeName) }'. " + - $"'{ typeof(HtmlAttributeNameAttribute).FullName }." + - $"{ nameof(HtmlAttributeNameAttribute.Name) }' must be null or empty if property has " + - "no public setter.", - } - }, - }; - } - } - - public static TheoryData ValidAttributeNameData - { - get - { - return new TheoryData - { - "data", - "dataa-", - "ValidName", - "valid-name", - "--valid--name--", - ",,--__..oddly.valid::;;", - }; - } - } - - [Theory] - [MemberData(nameof(ValidAttributeNameData))] - public void ValidateTagHelperAttributeDescriptor_WithValidName_ReturnsTrue(string name) - { - // Arrange - var descriptor = new TagHelperAttributeDescriptor - { - Name = name, - PropertyName = "ValidProperty", - TypeName = "PropertyType" - }; - var errorSink = new ErrorSink(); - - // Act - var result = TagHelperDescriptorFactory.ValidateTagHelperAttributeDescriptor( - descriptor, - typeof(MultiTagTagHelper), - errorSink); - - // Assert - Assert.True(result); - Assert.Empty(errorSink.Errors); - } - - public static TheoryData ValidAttributePrefixData - { - get - { - return new TheoryData - { - string.Empty, - "data", - "dataa-", - "ValidName", - "valid-name", - "--valid--name--", - ",,--__..oddly.valid::;;", - }; - } - } - - [Theory] - [MemberData(nameof(ValidAttributePrefixData))] - public void ValidateTagHelperAttributeDescriptor_WithValidPrefix_ReturnsTrue(string prefix) - { - // Arrange - var descriptor = new TagHelperAttributeDescriptor - { - Name = prefix, - PropertyName = "ValidProperty", - TypeName = "PropertyType", - IsIndexer = true - }; - var errorSink = new ErrorSink(); - - // Act - var result = TagHelperDescriptorFactory.ValidateTagHelperAttributeDescriptor( - descriptor, - typeof(MultiTagTagHelper), - errorSink); - - // Assert - Assert.True(result); - Assert.Empty(errorSink.Errors); - } - - // name, expectedErrorMessages - public static TheoryData InvalidAttributeNameData - { - get - { - Func onNameError = (invalidText, invalidCharacter) => "Invalid tag helper " + - $"bound property '{ typeof(MultiTagTagHelper).FullName }.InvalidProperty'. Tag helpers cannot " + - $"bind to HTML attributes with name '{ invalidText }' because name contains a " + - $"'{ invalidCharacter }' character."; - var whitespaceErrorString = "Invalid tag helper bound property " + - $"'{ typeof(MultiTagTagHelper).FullName }.InvalidProperty'. Tag helpers cannot bind to HTML " + - "attributes with a whitespace name."; - Func onDataError = invalidText => "Invalid tag helper bound property " + - $"'{ typeof(MultiTagTagHelper).FullName }.InvalidProperty'. Tag helpers cannot bind to HTML " + - $"attributes with name '{ invalidText }' because name starts with 'data-'."; - - return GetInvalidNameOrPrefixData(onNameError, whitespaceErrorString, onDataError); - } - } - - [Theory] - [MemberData(nameof(InvalidAttributeNameData))] - public void ValidateTagHelperAttributeDescriptor_WithInvalidName_AddsExpectedErrors( - string name, - string[] expectedErrorMessages) - { - // Arrange - var descriptor = new TagHelperAttributeDescriptor - { - Name = name, - PropertyName = "InvalidProperty", - TypeName = "PropertyType" - }; - var errorSink = new ErrorSink(); - - // Act - var result = TagHelperDescriptorFactory.ValidateTagHelperAttributeDescriptor( - descriptor, - typeof(MultiTagTagHelper), - errorSink); - - // Assert - Assert.False(result); - - var errors = errorSink.Errors.ToArray(); - Assert.Equal(expectedErrorMessages.Length, errors.Length); - for (var i = 0; i < expectedErrorMessages.Length; i++) - { - Assert.Equal(0, errors[i].Length); - Assert.Equal(SourceLocation.Zero, errors[i].Location); - Assert.Equal(expectedErrorMessages[i], errors[i].Message, StringComparer.Ordinal); - } - } - - // prefix, expectedErrorMessages - public static TheoryData InvalidAttributePrefixData - { - get - { - Func onPrefixError = (invalidText, invalidCharacter) => "Invalid tag helper " + - $"bound property '{ typeof(MultiTagTagHelper).FullName }.InvalidProperty'. Tag helpers cannot " + - $"bind to HTML attributes with prefix '{ invalidText }' because prefix contains a " + - $"'{ invalidCharacter }' character."; - var whitespaceErrorString = "Invalid tag helper bound property " + - $"'{ typeof(MultiTagTagHelper).FullName }.InvalidProperty'. Tag helpers cannot bind to HTML " + - "attributes with a whitespace prefix."; - Func onDataError = invalidText => "Invalid tag helper bound property " + - $"'{ typeof(MultiTagTagHelper).FullName }.InvalidProperty'. Tag helpers cannot bind to HTML " + - $"attributes with prefix '{ invalidText }' because prefix starts with 'data-'."; - - return GetInvalidNameOrPrefixData(onPrefixError, whitespaceErrorString, onDataError); - } - } - - [Theory] - [MemberData(nameof(InvalidAttributePrefixData))] - public void ValidateTagHelperAttributeDescriptor_WithInvalidPrefix_AddsExpectedErrors( - string prefix, - string[] expectedErrorMessages) - { - // Arrange - var descriptor = new TagHelperAttributeDescriptor - { - Name = prefix, - PropertyName = "InvalidProperty", - TypeName = "ValuesType", - IsIndexer = true - }; - var errorSink = new ErrorSink(); - - // Act - var result = TagHelperDescriptorFactory.ValidateTagHelperAttributeDescriptor( - descriptor, - typeof(MultiTagTagHelper), - errorSink); - - // Assert - Assert.False(result); - - var errors = errorSink.Errors.ToArray(); - Assert.Equal(expectedErrorMessages.Length, errors.Length); - for (var i = 0; i < expectedErrorMessages.Length; i++) - { - Assert.Equal(0, errors[i].Length); - Assert.Equal(SourceLocation.Zero, errors[i].Location); - Assert.Equal(expectedErrorMessages[i], errors[i].Message, StringComparer.Ordinal); - } - } - - public static TheoryData InvalidRestrictChildrenNameData - { - get - { - var nullOrWhiteSpaceError = - Resources.FormatTagHelperDescriptorFactory_InvalidRestrictChildrenAttributeNameNullWhitespace( - nameof(RestrictChildrenAttribute), - "SomeTagHelper"); - - return GetInvalidNameOrPrefixData( - onNameError: (invalidInput, invalidCharacter) => - Resources.FormatTagHelperDescriptorFactory_InvalidRestrictChildrenAttributeName( - nameof(RestrictChildrenAttribute), - invalidInput, - "SomeTagHelper", - invalidCharacter), - whitespaceErrorString: nullOrWhiteSpaceError, - onDataError: null); - } - } - - [Theory] - [MemberData(nameof(InvalidRestrictChildrenNameData))] - public void GetValidAllowedChildren_AddsExpectedErrors(string name, string[] expectedErrorMessages) - { - // Arrange - var errorSink = new ErrorSink(); - var expectedErrors = expectedErrorMessages.Select( - message => new RazorError(message, SourceLocation.Zero, 0)); - - // Act - TagHelperDescriptorFactory.GetValidAllowedChildren(new[] { name }, "SomeTagHelper", errorSink); - - // Assert - Assert.Equal(expectedErrors, errorSink.Errors); - } - - public static TheoryData InvalidParentTagData - { - get - { - var nullOrWhiteSpaceError = - Resources.FormatHtmlTargetElementAttribute_NameCannotBeNullOrWhitespace( - Resources.TagHelperDescriptorFactory_ParentTag); - - return GetInvalidNameOrPrefixData( - onNameError: (invalidInput, invalidCharacter) => - Resources.FormatHtmlTargetElementAttribute_InvalidName( - Resources.TagHelperDescriptorFactory_ParentTag.ToLower(), - invalidInput, - invalidCharacter), - whitespaceErrorString: nullOrWhiteSpaceError, - onDataError: null); - } - } - - [Theory] - [MemberData(nameof(InvalidParentTagData))] - public void ValidateParentTagName_AddsExpectedErrors(string name, string[] expectedErrorMessages) - { - // Arrange - var errorSink = new ErrorSink(); - var expectedErrors = expectedErrorMessages.Select( - message => new RazorError(message, SourceLocation.Zero, 0)); - - // Act - TagHelperDescriptorFactory.ValidateParentTagName(name, errorSink); - - // Assert - Assert.Equal(expectedErrors, errorSink.Errors); - } - - [Fact] - public void CreateDescriptors_BuildsDescriptorsFromSimpleTypes() - { - // Arrange - var errorSink = new ErrorSink(); - var objectAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; - var expectedDescriptor = - CreateTagHelperDescriptor("object", "System.Object", objectAssemblyName); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - objectAssemblyName, - typeof(object), - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - var descriptor = Assert.Single(descriptors); - Assert.Equal(expectedDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Theory] - [MemberData(nameof(TagHelperWithPrefixData))] - public void CreateDescriptors_WithPrefixes_ReturnsExpectedAttributeDescriptors( - Type tagHelperType, - IEnumerable expectedAttributeDescriptors, - string[] expectedErrorMessages) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: false); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - var errors = errorSink.Errors.ToArray(); - Assert.Equal(expectedErrorMessages.Length, errors.Length); - - for (var i = 0; i < errors.Length; i++) - { - Assert.Equal(0, errors[i].Length); - Assert.Equal(SourceLocation.Zero, errors[i].Location); - Assert.Equal(expectedErrorMessages[i], errors[i].Message, StringComparer.Ordinal); - } - - var descriptor = Assert.Single(descriptors); - Assert.Equal( - expectedAttributeDescriptors, - descriptor.Attributes, - TagHelperAttributeDescriptorComparer.Default); - } - - public static TheoryData HtmlConversionData - { - get - { - return new TheoryData - { - { "SomeThing", "some-thing" }, - { "someOtherThing", "some-other-thing" }, - { "capsONInside", "caps-on-inside" }, - { "CAPSOnOUTSIDE", "caps-on-outside" }, - { "ALLCAPS", "allcaps" }, - { "One1Two2Three3", "one1-two2-three3" }, - { "ONE1TWO2THREE3", "one1two2three3" }, - { "First_Second_ThirdHi", "first_second_third-hi" } - }; - } - } - - [Theory] - [MemberData(nameof(HtmlConversionData))] - public void ToHtmlCase_ReturnsExpectedConversions(string input, string expectedOutput) - { - // Arrange, Act - var output = TagHelperDescriptorFactory.ToHtmlCase(input); - - // Assert - Assert.Equal(output, expectedOutput); - } - - // TagHelperDesignTimeDescriptors are not created in CoreCLR. -#if !NETCOREAPP1_1 - public static TheoryData OutputElementHintData - { - get - { - // tagHelperType, expectedDescriptors - return new TheoryData - { - { - typeof(OutputElementHintTagHelper), - new[] - { - new TagHelperDescriptor - { - TagName = "output-element-hint", - TypeName = typeof(OutputElementHintTagHelper).FullName, - AssemblyName = AssemblyName, - DesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - OutputElementHint = "strong" - } - } - } - }, - { - typeof(MulitpleDescriptorTagHelperWithOutputElementHint), - new[] - { - new TagHelperDescriptor - { - TagName = "a", - TypeName = typeof(MulitpleDescriptorTagHelperWithOutputElementHint).FullName, - AssemblyName = AssemblyName, - DesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - OutputElementHint = "div" - } - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = typeof(MulitpleDescriptorTagHelperWithOutputElementHint).FullName, - AssemblyName = AssemblyName, - DesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - OutputElementHint = "div" - } - } - } - } - }; - } - } - - [Theory] - [MemberData(nameof(OutputElementHintData))] - public void CreateDescriptors_CreatesDesignTimeDescriptorsWithOutputElementHint( - Type tagHelperType, - TagHelperDescriptor[] expectedDescriptors) - { - // Arrange - var errorSink = new ErrorSink(); - var factory = new TagHelperDescriptorFactory(designTime: true); - - // Act - var descriptors = factory.CreateDescriptors( - AssemblyName, - tagHelperType, - errorSink: errorSink); - - // Assert - Assert.Empty(errorSink.Errors); - - // We don't care about order. Mono returns reflected attributes differently so we need to ensure order - // doesn't matter by sorting. - descriptors = descriptors.OrderBy(descriptor => descriptor.TagName); - - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } -#endif - - private static TheoryData GetInvalidNameOrPrefixData( - Func onNameError, - string whitespaceErrorString, - Func onDataError) - { - // name, expectedErrorMessages - var data = new TheoryData - { - { "!", new[] { onNameError("!", "!") } }, - { "hello!", new[] { onNameError("hello!", "!") } }, - { "!hello", new[] { onNameError("!hello", "!") } }, - { "he!lo", new[] { onNameError("he!lo", "!") } }, - { - "!he!lo!", - new[] - { - onNameError("!he!lo!", "!"), - onNameError("!he!lo!", "!"), - onNameError("!he!lo!", "!"), - } - }, - { "@", new[] { onNameError("@", "@") } }, - { "hello@", new[] { onNameError("hello@", "@") } }, - { "@hello", new[] { onNameError("@hello", "@") } }, - { "he@lo", new[] { onNameError("he@lo", "@") } }, - { - "@he@lo@", - new[] - { - onNameError("@he@lo@", "@"), - onNameError("@he@lo@", "@"), - onNameError("@he@lo@", "@"), - } - }, - { "/", new[] { onNameError("/", "/") } }, - { "hello/", new[] { onNameError("hello/", "/") } }, - { "/hello", new[] { onNameError("/hello", "/") } }, - { "he/lo", new[] { onNameError("he/lo", "/") } }, - { - "/he/lo/", - new[] - { - onNameError("/he/lo/", "/"), - onNameError("/he/lo/", "/"), - onNameError("/he/lo/", "/"), - } - }, - { "<", new[] { onNameError("<", "<") } }, - { "hello<", new[] { onNameError("hello<", "<") } }, - { "", new[] { onNameError(">", ">") } }, - { "hello>", new[] { onNameError("hello>", ">") } }, - { ">hello", new[] { onNameError(">hello", ">") } }, - { "he>lo", new[] { onNameError("he>lo", ">") } }, - { - ">he>lo>", - new[] - { - onNameError(">he>lo>", ">"), - onNameError(">he>lo>", ">"), - onNameError(">he>lo>", ">"), - } - }, - { "]", new[] { onNameError("]", "]") } }, - { "hello]", new[] { onNameError("hello]", "]") } }, - { "]hello", new[] { onNameError("]hello", "]") } }, - { "he]lo", new[] { onNameError("he]lo", "]") } }, - { - "]he]lo]", - new[] - { - onNameError("]he]lo]", "]"), - onNameError("]he]lo]", "]"), - onNameError("]he]lo]", "]"), - } - }, - { "=", new[] { onNameError("=", "=") } }, - { "hello=", new[] { onNameError("hello=", "=") } }, - { "=hello", new[] { onNameError("=hello", "=") } }, - { "he=lo", new[] { onNameError("he=lo", "=") } }, - { - "=he=lo=", - new[] - { - onNameError("=he=lo=", "="), - onNameError("=he=lo=", "="), - onNameError("=he=lo=", "="), - } - }, - { "\"", new[] { onNameError("\"", "\"") } }, - { "hello\"", new[] { onNameError("hello\"", "\"") } }, - { "\"hello", new[] { onNameError("\"hello", "\"") } }, - { "he\"lo", new[] { onNameError("he\"lo", "\"") } }, - { - "\"he\"lo\"", - new[] - { - onNameError("\"he\"lo\"", "\""), - onNameError("\"he\"lo\"", "\""), - onNameError("\"he\"lo\"", "\""), - } - }, - { "'", new[] { onNameError("'", "'") } }, - { "hello'", new[] { onNameError("hello'", "'") } }, - { "'hello", new[] { onNameError("'hello", "'") } }, - { "he'lo", new[] { onNameError("he'lo", "'") } }, - { - "'he'lo'", - new[] - { - onNameError("'he'lo'", "'"), - onNameError("'he'lo'", "'"), - onNameError("'he'lo'", "'"), - } - }, - { "hello*", new[] { onNameError("hello*", "*") } }, - { "*hello", new[] { onNameError("*hello", "*") } }, - { "he*lo", new[] { onNameError("he*lo", "*") } }, - { - "*he*lo*", - new[] - { - onNameError("*he*lo*", "*"), - onNameError("*he*lo*", "*"), - onNameError("*he*lo*", "*"), - } - }, - { Environment.NewLine, new[] { whitespaceErrorString } }, - { "\t", new[] { whitespaceErrorString } }, - { " \t ", new[] { whitespaceErrorString } }, - { " ", new[] { whitespaceErrorString } }, - { Environment.NewLine + " ", new[] { whitespaceErrorString } }, - { - "! \t\r\n@/<>?[]=\"'*", - new[] - { - onNameError("! \t\r\n@/<>?[]=\"'*", "!"), - onNameError("! \t\r\n@/<>?[]=\"'*", " "), - onNameError("! \t\r\n@/<>?[]=\"'*", "\t"), - onNameError("! \t\r\n@/<>?[]=\"'*", "\r"), - onNameError("! \t\r\n@/<>?[]=\"'*", "\n"), - onNameError("! \t\r\n@/<>?[]=\"'*", "@"), - onNameError("! \t\r\n@/<>?[]=\"'*", "/"), - onNameError("! \t\r\n@/<>?[]=\"'*", "<"), - onNameError("! \t\r\n@/<>?[]=\"'*", ">"), - onNameError("! \t\r\n@/<>?[]=\"'*", "?"), - onNameError("! \t\r\n@/<>?[]=\"'*", "["), - onNameError("! \t\r\n@/<>?[]=\"'*", "]"), - onNameError("! \t\r\n@/<>?[]=\"'*", "="), - onNameError("! \t\r\n@/<>?[]=\"'*", "\""), - onNameError("! \t\r\n@/<>?[]=\"'*", "'"), - onNameError("! \t\r\n@/<>?[]=\"'*", "*"), - } - }, - { - "! \tv\ra\nl@i/d<>?[]=\"'*", - new[] - { - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "!"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", " "), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "\t"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "\r"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "\n"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "@"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "/"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "<"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", ">"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "?"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "["), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "]"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "="), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "\""), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "'"), - onNameError("! \tv\ra\nl@i/d<>?[]=\"'*", "*"), - } - }, - }; - - if (onDataError != null) - { - data.Add("data-", new[] { onDataError("data-") }); - data.Add("data-something", new[] { onDataError("data-something") }); - data.Add("Data-Something", new[] { onDataError("Data-Something") }); - data.Add("DATA-SOMETHING", new[] { onDataError("DATA-SOMETHING") }); - } - - return data; - } - - protected static TagHelperDescriptor CreateTagHelperDescriptor( - string tagName, - string typeName, - string assemblyName, - IEnumerable attributes = null, - IEnumerable requiredAttributes = null) - { - return new TagHelperDescriptor - { - TagName = tagName, - TypeName = typeName, - AssemblyName = assemblyName, - Attributes = attributes ?? Enumerable.Empty(), - RequiredAttributes = requiredAttributes ?? Enumerable.Empty() - }; - } - - private static TagHelperAttributeDescriptor CreateTagHelperAttributeDescriptor( - string name, - PropertyInfo propertyInfo) - { - return new TagHelperAttributeDescriptor - { - Name = name, - PropertyName = propertyInfo.Name, - TypeName = propertyInfo.PropertyType.FullName, - IsStringProperty = propertyInfo.PropertyType.FullName == typeof(string).FullName - }; - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorResolverTest.cs b/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorResolverTest.cs deleted file mode 100644 index f81f71002f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDescriptorResolverTest.cs +++ /dev/null @@ -1,1462 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers.Testing; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - public class TagHelperDescriptorResolverTest : TagHelperTypeResolverTest - { - private static readonly string AssemblyName = - typeof(TagHelperDescriptorFactoryTest).GetTypeInfo().Assembly.GetName().Name; - - private static readonly Type Valid_PlainTagHelperType = typeof(Valid_PlainTagHelper); - - private static readonly Type Valid_InheritedTagHelperType = typeof(Valid_InheritedTagHelper); - - private static TagHelperDescriptor Valid_PlainTagHelperDescriptor - { - get - { - return new TagHelperDescriptor - { - TagName = "valid_plain", - TypeName = Valid_PlainTagHelperType.FullName, - AssemblyName = AssemblyName - }; - } - } - - private static TagHelperDescriptor Valid_InheritedTagHelperDescriptor - { - get - { - return new TagHelperDescriptor - { - TagName = "valid_inherited", - TypeName = Valid_InheritedTagHelperType.FullName, - AssemblyName = AssemblyName - }; - } - } - - [Theory] - [InlineData("foo,assemblyName", 4)] - [InlineData("foo, assemblyName", 5)] - [InlineData(" foo, assemblyName", 8)] - [InlineData(" foo , assemblyName", 11)] - [InlineData("foo, assemblyName", 8)] - [InlineData(" foo , assemblyName ", 14)] - public void Resolve_CalculatesAssemblyLocationInLookupText(string lookupText, int assemblyLocation) - { - // Arrange - var errorSink = new ErrorSink(); - var tagHelperDescriptorResolver = new InspectableTagHelperDescriptorResolver(); - var directiveType = TagHelperDirectiveType.AddTagHelper; - var resolutionContext = new TagHelperDescriptorResolutionContext( - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = lookupText, - Location = SourceLocation.Zero, - DirectiveType = directiveType - } - }, - errorSink); - var expectedSourceLocation = new SourceLocation(assemblyLocation, 0, assemblyLocation); - - // Act - tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - Assert.Empty(errorSink.Errors); - Assert.Equal(expectedSourceLocation, tagHelperDescriptorResolver.DocumentLocation); - } - - public static TheoryData ResolveDirectiveDescriptorsInvalidTagHelperPrefixData - { - get - { - var assemblyA = AssemblyName; - var stringType = typeof(string); - var assemblyB = stringType.GetTypeInfo().Assembly.GetName().Name; - var defaultAssemblyLookups = new Dictionary> - { - { assemblyA, new[] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new[] { stringType } } - }; - var directiveLocation1 = new SourceLocation(1, 2, 3); - var directiveLocation2 = new SourceLocation(4, 5, 6); - var multipleDirectiveError = - "Invalid tag helper directive '{0}'. Cannot have multiple '{0}' directives on a page."; - var invalidTagHelperPrefixValueError = - "Invalid tag helper directive '{0}' value. '{1}' is not allowed in prefix '{2}'."; - - return new TheoryData>, // descriptorAssemblyLookups - IEnumerable, // directiveDescriptors - IEnumerable, // expectedDescriptors - IEnumerable> // expectedErrors - { - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th:", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "different", - Location = directiveLocation2, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format(multipleDirectiveError, SyntaxConstants.CSharp.TagHelperPrefixKeyword), - directiveLocation2, - length: 9) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th:", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "different", - Location = directiveLocation2, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "Microsoft.AspNetCore.Razor.TagHelpers.Valid_P*, " + assemblyA, - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.AddTagHelper - } - }, - new[] { CreatePrefixedValidPlainDescriptor("th:") }, - new[] - { - new RazorError( - string.Format(multipleDirectiveError, SyntaxConstants.CSharp.TagHelperPrefixKeyword), - directiveLocation2, - length: 9) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th:", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "different", - Location = directiveLocation2, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Plain*, " + assemblyA, - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.AddTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "System.String, " + assemblyB, - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.AddTagHelper - } - }, - new[] { CreatePrefixedValidPlainDescriptor("th:"), CreatePrefixedStringDescriptor("th:") }, - new[] - { - new RazorError( - string.Format(multipleDirectiveError, SyntaxConstants.CSharp.TagHelperPrefixKeyword), - directiveLocation2, - length: 9) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th ", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - ' ', - "th "), - directiveLocation1, - length: 3) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th\t", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - '\t', - "th\t"), - directiveLocation1, - length: 3) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th" + Environment.NewLine, - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - Environment.NewLine[0], - "th" + Environment.NewLine), - directiveLocation1, - length: 2 + Environment.NewLine.Length) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = " th ", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - ' ', - " th "), - directiveLocation1, - length: 4) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "@", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - '@', - "@"), - directiveLocation1, - length: 1) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "t@h", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - '@', - "t@h"), - directiveLocation1, - length: 3) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "!", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - '!', - "!"), - directiveLocation1, - length: 1) - } - }, - { - defaultAssemblyLookups, - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "!th", - Location = directiveLocation1, - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }, - new TagHelperDescriptor[0], - new[] - { - new RazorError( - string.Format( - invalidTagHelperPrefixValueError, - SyntaxConstants.CSharp.TagHelperPrefixKeyword, - '!', - "!th"), - directiveLocation1, - length: 3) - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(ResolveDirectiveDescriptorsInvalidTagHelperPrefixData))] - public void Resolve_CreatesExpectedErrorsForTagHelperPrefixDirectives( - Dictionary> descriptorAssemblyLookups, - IEnumerable directiveDescriptors, - IEnumerable expectedDescriptors, - IEnumerable expectedErrors) - { - // Arrange - var tagHelperDescriptorResolver = - new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver(descriptorAssemblyLookups)); - var errorSink = new ErrorSink(); - var resolutionContext = new TagHelperDescriptorResolutionContext( - directiveDescriptors, - errorSink); - - // Act - var descriptors = tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - Assert.Equal(expectedErrors, errorSink.Errors); - Assert.Equal(expectedDescriptors.Count(), descriptors.Count()); - - foreach (var expectedDescriptor in expectedDescriptors) - { - Assert.Contains(expectedDescriptor, descriptors, TagHelperDescriptorComparer.Default); - } - } - - public static TheoryData ResolveDirectiveDescriptorsTagHelperPrefixData - { - get - { - var assemblyA = AssemblyName; - var stringType = typeof(string); - var assemblyB = stringType.GetTypeInfo().Assembly.GetName().Name; - var defaultAssemblyLookups = new Dictionary> - { - { assemblyA, new[] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new[] { stringType } } - }; - - return new TheoryData< - Dictionary>, // descriptorAssemblyLookups - IEnumerable, // directiveDescriptors - IEnumerable> // expectedDescriptors - { - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor("", TagHelperDirectiveType.TagHelperPrefix), - CreateTagHelperDirectiveDescriptor( - "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Plain*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor("th:", TagHelperDirectiveType.TagHelperPrefix), - CreateTagHelperDirectiveDescriptor( - "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Plain*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - }, - new [] { CreatePrefixedValidPlainDescriptor("th:") } - }, - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("th:", TagHelperDirectiveType.TagHelperPrefix) - }, - new [] - { - CreatePrefixedValidPlainDescriptor("th:"), - CreatePrefixedValidInheritedDescriptor("th:") - } - }, - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor("th-", TagHelperDirectiveType.TagHelperPrefix), - CreateTagHelperDirectiveDescriptor( - "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Plain*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Inherited*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper) - }, - new [] - { - CreatePrefixedValidPlainDescriptor("th-"), - CreatePrefixedValidInheritedDescriptor("th-") - } - }, - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor("", TagHelperDirectiveType.TagHelperPrefix), - CreateTagHelperDirectiveDescriptor( - "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Plain*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "Microsoft.AspNetCore.Razor.TagHelpers.Valid_Inherited*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor, Valid_InheritedTagHelperDescriptor } - }, - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor("th", TagHelperDirectiveType.TagHelperPrefix), - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyB, - TagHelperDirectiveType.AddTagHelper), - }, - new [] - { - CreatePrefixedValidPlainDescriptor("th"), - CreatePrefixedValidInheritedDescriptor("th"), - CreatePrefixedStringDescriptor("th") - } - }, - { - defaultAssemblyLookups, - new [] - { - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("th:-", TagHelperDirectiveType.TagHelperPrefix), - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyB, - TagHelperDirectiveType.AddTagHelper), - }, - new [] - { - CreatePrefixedValidPlainDescriptor("th:-"), - CreatePrefixedValidInheritedDescriptor("th:-"), - CreatePrefixedStringDescriptor("th:-") - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(ResolveDirectiveDescriptorsTagHelperPrefixData))] - public void Resolve_ReturnsPrefixedDescriptorsBasedOnDirectiveDescriptors( - Dictionary> descriptorAssemblyLookups, - IEnumerable directiveDescriptors, - IEnumerable expectedDescriptors) - { - // Arrange - var tagHelperDescriptorResolver = - new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver(descriptorAssemblyLookups)); - var resolutionContext = new TagHelperDescriptorResolutionContext( - directiveDescriptors, - new ErrorSink()); - - // Act - var descriptors = tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - Assert.Equal(expectedDescriptors.Count(), descriptors.Count()); - - foreach (var expectedDescriptor in expectedDescriptors) - { - Assert.Contains(expectedDescriptor, descriptors, TagHelperDescriptorComparer.Default); - } - } - - [Theory] - [InlineData("MyType, MyAssembly", "MyAssembly")] - [InlineData("*, MyAssembly2", "MyAssembly2")] - public void Resolve_AllowsOverridenResolveDescriptorsInAssembly(string lookupText, string expectedAssemblyName) - { - // Arrange - var tagHelperDescriptorResolver = new AssemblyCheckingTagHelperDescriptorResolver(); - var context = new TagHelperDescriptorResolutionContext( - new[] { CreateTagHelperDirectiveDescriptor(lookupText, TagHelperDirectiveType.AddTagHelper) }, - new ErrorSink()); - - // Act - tagHelperDescriptorResolver.Resolve(context); - - // Assert - Assert.Equal(expectedAssemblyName, tagHelperDescriptorResolver.CalledWithAssemblyName); - } - - public static TheoryData ResolveDirectiveDescriptorsData - { - get - { - var assemblyA = AssemblyName; - var stringType = typeof(string); - - var assemblyB = stringType.GetTypeInfo().Assembly.GetName().Name; - - // We're treating 'string' as a TagHelper so we can test TagHelpers in multiple assemblies without - // building a separate assembly with a single TagHelper. - var stringTagHelperDescriptor = - new TagHelperDescriptor - { - TagName = "string", - TypeName = "System.String", - AssemblyName = assemblyB - }; - - return new TheoryData>, // descriptorAssemblyLookups - IEnumerable, // directiveDescriptors - IEnumerable> // expectedDescriptors - { - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor, stringTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] { stringTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.FullName + ", " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor, Valid_InheritedTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.FullName + ", " + assemblyA, - TagHelperDirectiveType.RemoveTagHelper) - }, - new [] { Valid_InheritedTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.FullName + ", " + assemblyA, - TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_InheritedTagHelperDescriptor, Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - }, - new [] { Valid_InheritedTagHelperDescriptor, Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.Namespace + ".Valid_Plain*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.Namespace + "*, " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - }, - new [] { Valid_PlainTagHelperDescriptor, Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.Namespace + "." + Valid_PlainTagHelperType.Name + ", " + assemblyA, - TagHelperDirectiveType.AddTagHelper), - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - Valid_PlainTagHelperType.Namespace + ".Valid_P*, " + assemblyA, - TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_InheritedTagHelperDescriptor, Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("Str*, " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("System." + stringType.FullName + ", " + assemblyB, TagHelperDirectiveType.AddTagHelper) - }, - new [] { Valid_PlainTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("Microsoft.*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] { stringTagHelperDescriptor } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "?Microsoft*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor( - "System." + stringType.FullName + ", " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] - { - Valid_InheritedTagHelperDescriptor, - Valid_PlainTagHelperDescriptor, - stringTagHelperDescriptor - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } } - }, - new [] - { - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor( - "TagHelper*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor( - "System." + stringType.FullName + ", " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - }, - new [] - { - Valid_InheritedTagHelperDescriptor, - Valid_PlainTagHelperDescriptor, - stringTagHelperDescriptor - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(ResolveDirectiveDescriptorsData))] - public void Resolve_ReturnsDescriptorsBasedOnDirectiveDescriptors( - Dictionary> descriptorAssemblyLookups, - IEnumerable directiveDescriptors, - IEnumerable expectedDescriptors) - { - // Arrange - var tagHelperDescriptorResolver = - new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver(descriptorAssemblyLookups)); - var resolutionContext = new TagHelperDescriptorResolutionContext( - directiveDescriptors, - new ErrorSink()); - - // Act - var descriptors = tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - Assert.Equal(expectedDescriptors.Count(), descriptors.Count()); - - foreach (var expectedDescriptor in expectedDescriptors) - { - Assert.Contains(expectedDescriptor, descriptors, TagHelperDescriptorComparer.Default); - } - } - - public static TheoryData ResolveDirectiveDescriptorsData_EmptyResult - { - get - { - var assemblyA = AssemblyName; - var stringType = typeof(string); - - var assemblyB = stringType.GetTypeInfo().Assembly.GetName().Name; - var stringTagHelperDescriptor = - new TagHelperDescriptor - { - TagName = "string", - TypeName = "System.String", - AssemblyName = assemblyB - }; - - return new TheoryData>, // descriptorAssemblyLookups - IEnumerable> // directiveDescriptors - { - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_PlainTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_InheritedTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper) - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_PlainTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_InheritedTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor(stringType.FullName + ", " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - } - }, - { - new Dictionary>(), - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_PlainTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("Mic*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("Mic*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_PlainTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_InheritedTagHelperType.FullName + ", " + assemblyA, TagHelperDirectiveType.RemoveTagHelper) - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("Microsoft.*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("System.*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor(Valid_PlainTagHelperType.Namespace + "*, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor("System.*, " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("?icrosoft.*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("?ystem.*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("*?????r, " + assemblyA, TagHelperDirectiveType.RemoveTagHelper), - CreateTagHelperDirectiveDescriptor("Sy??em.*, " + assemblyB, TagHelperDirectiveType.RemoveTagHelper) - } - }, - { - new Dictionary> - { - { assemblyA, new [] { Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - { assemblyB, new [] { stringType } }, - }, - new [] - { - CreateTagHelperDirectiveDescriptor("?i?crosoft.*, " + assemblyA, TagHelperDirectiveType.AddTagHelper), - CreateTagHelperDirectiveDescriptor("??ystem.*, " + assemblyB, TagHelperDirectiveType.AddTagHelper), - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(ResolveDirectiveDescriptorsData_EmptyResult))] - public void Resolve_CanReturnEmptyDescriptorsBasedOnDirectiveDescriptors( - Dictionary> descriptorAssemblyLookups, - IEnumerable directiveDescriptors) - { - // Arrange - var tagHelperDescriptorResolver = - new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver(descriptorAssemblyLookups)); - var resolutionContext = new TagHelperDescriptorResolutionContext( - directiveDescriptors, - new ErrorSink()); - - // Act - var descriptors = tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - Assert.Empty(descriptors); - } - - [Fact] - public void DescriptorResolver_DoesNotReturnInvalidTagHelpersWhenSpecified() - { - // Arrange - var tagHelperDescriptorResolver = - new TestTagHelperDescriptorResolver( - new TestTagHelperTypeResolver(TestableTagHelpers)); - - // Act - var descriptors = tagHelperDescriptorResolver.Resolve( - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_AbstractTagHelper, " + AssemblyName, - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_GenericTagHelper`, " + AssemblyName, - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_NestedPublicTagHelper, " + AssemblyName, - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_NestedInternalTagHelper, " + AssemblyName, - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_PrivateTagHelper, " + AssemblyName, - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_ProtectedTagHelper, " + AssemblyName, - "Microsoft.AspNetCore.Razor.Runtime.Test.TagHelpers.Invalid_InternalTagHelper, " + AssemblyName); - - // Assert - Assert.Empty(descriptors); - } - - public static TheoryData DescriptorResolver_IgnoresSpacesData - { - get - { - var typeName = typeof(Valid_PlainTagHelper).FullName; - return new TheoryData - { - $"{typeName},{AssemblyName}", - $" {typeName},{AssemblyName}", - $"{typeName} ,{AssemblyName}", - $" {typeName} ,{AssemblyName}", - $"{typeName}, {AssemblyName}", - $"{typeName},{AssemblyName} ", - $"{typeName}, {AssemblyName} ", - $" {typeName}, {AssemblyName} ", - $" {typeName} , {AssemblyName} " - }; - } - } - - [Theory] - [MemberData(nameof(DescriptorResolver_IgnoresSpacesData))] - public void DescriptorResolver_IgnoresSpaces(string lookupText) - { - // Arrange - var invoked = false; - var tagHelperTypeResolver = new TestTagHelperTypeResolver(TestableTagHelpers) - { - OnGetExportedTypes = (assemblyName) => - { - Assert.Equal(AssemblyName, assemblyName.Name); - invoked = true; - } - }; - var tagHelperDescriptorResolver = new TestTagHelperDescriptorResolver(tagHelperTypeResolver); - - // Act - var descriptors = tagHelperDescriptorResolver.Resolve(lookupText); - - // Assert - Assert.True(invoked); - var descriptor = Assert.Single(descriptors); - Assert.Equal(AssemblyName, descriptor.AssemblyName); - Assert.Equal(typeof(Valid_PlainTagHelper).FullName, descriptor.TypeName); - } - - [Fact] - public void DescriptorResolver_ResolvesOnlyTypeResolverProvidedTypes() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver( - new Dictionary>(StringComparer.OrdinalIgnoreCase) - { - { AssemblyName, ValidTestableTagHelpers }, - { - Valid_PlainTagHelperType.FullName + ", " + AssemblyName, - new Type[] { Valid_PlainTagHelperType } - } - })); - - // Act - var descriptors = resolver.Resolve(Valid_PlainTagHelperType + ", " + AssemblyName); - - // Assert - var descriptor = Assert.Single(descriptors); - Assert.Equal(Valid_PlainTagHelperDescriptor, descriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void DescriptorResolver_ResolvesMultipleTypes() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver( - new Dictionary>(StringComparer.OrdinalIgnoreCase) - { - { AssemblyName, new Type[]{ Valid_PlainTagHelperType, Valid_InheritedTagHelperType } }, - })); - var expectedDescriptors = new TagHelperDescriptor[] - { - Valid_PlainTagHelperDescriptor, - Valid_InheritedTagHelperDescriptor - }; - - // Act - var descriptors = resolver.Resolve("*, " + AssemblyName).ToArray(); - - // Assert - Assert.Equal(descriptors.Length, 2); - Assert.Equal(expectedDescriptors, descriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void DescriptorResolver_DoesNotResolveTypesForNoTypeResolvingLookupText() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver( - new LookupBasedTagHelperTypeResolver( - new Dictionary>(StringComparer.OrdinalIgnoreCase) - { - { AssemblyName, ValidTestableTagHelpers }, - { - Valid_PlainTagHelperType.FullName + ", " + AssemblyName, - new Type[]{ Valid_PlainTagHelperType } - } - })); - - // Act - var descriptors = resolver.Resolve("*, lookupText").ToArray(); - - // Assert - Assert.Empty(descriptors); - } - - [Theory] - [InlineData("", 1)] - [InlineData("*,", 2)] - [InlineData("?,", 2)] - [InlineData(",", 1)] - [InlineData(",,,", 3)] - [InlineData("First, ", 7)] - [InlineData("First , ", 8)] - [InlineData(" ,Second", 8)] - [InlineData(" , Second", 9)] - [InlineData("SomeType,", 9)] - [InlineData("SomeAssembly", 12)] - [InlineData("First,Second,Third", 18)] - public void DescriptorResolver_CreatesErrorIfInvalidLookupText_DoesNotThrow(string lookupText, int errorLength) - { - // Arrange - var errorSink = new ErrorSink(); - var tagHelperDescriptorResolver = - new TestTagHelperDescriptorResolver( - new TestTagHelperTypeResolver(InvalidTestableTagHelpers)); - var documentLocation = new SourceLocation(1, 2, 3); - var directiveType = TagHelperDirectiveType.AddTagHelper; - var expectedErrorMessage = string.Format( - "Invalid tag helper directive look up text '{0}'. The correct look up text " + - "format is: \"typeName, assemblyName\".", - lookupText); - var resolutionContext = new TagHelperDescriptorResolutionContext( - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = lookupText, - Location = documentLocation, - DirectiveType = directiveType - } - }, - errorSink); - - // Act - tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - var error = Assert.Single(errorSink.Errors); - Assert.Equal(errorLength, error.Length); - Assert.Equal(documentLocation, error.Location); - Assert.Equal(expectedErrorMessage, error.Message); - } - - [Fact] - public void DescriptorResolver_UnderstandsUnexpectedExceptions_DoesNotThrow() - { - // Arrange - var expectedErrorMessage = "Encountered an unexpected error when attempting to resolve tag helper " + - "directive '@addTagHelper' with value 'A custom, lookup text'. Error: A " + - "custom exception"; - var documentLocation = new SourceLocation(1, 2, 3); - var directiveType = TagHelperDirectiveType.AddTagHelper; - var errorSink = new ErrorSink(); - var expectedError = new Exception("A custom exception"); - var tagHelperDescriptorResolver = new ThrowingTagHelperDescriptorResolver(expectedError); - var resolutionContext = new TagHelperDescriptorResolutionContext( - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "A custom, lookup text", - Location = documentLocation, - DirectiveType = directiveType - } - }, - errorSink); - - - // Act - tagHelperDescriptorResolver.Resolve(resolutionContext); - - // Assert - var error = Assert.Single(errorSink.Errors); - Assert.Equal(21, error.Length); - Assert.Equal(documentLocation, error.Location); - Assert.Equal(expectedErrorMessage, error.Message); - } - - private static TagHelperDescriptor CreateDescriptor( - string prefix, - string tagName, - string typeName, - string assemblyName) - { - return new TagHelperDescriptor - { - Prefix = prefix, - TagName = tagName, - TypeName = typeName, - AssemblyName = assemblyName - }; - } - - private static TagHelperDescriptor CreatePrefixedValidPlainDescriptor(string prefix) - { - return CreateDescriptor( - prefix, - tagName: "valid_plain", - typeName: Valid_PlainTagHelperType.FullName, - assemblyName: AssemblyName); - } - - private static TagHelperDescriptor CreatePrefixedValidInheritedDescriptor(string prefix) - { - return CreateDescriptor( - prefix, - tagName: "valid_inherited", - typeName: Valid_InheritedTagHelperType.FullName, - assemblyName: AssemblyName); - } - - private static TagHelperDescriptor CreatePrefixedStringDescriptor(string prefix) - { - var stringType = typeof(string); - - return CreateDescriptor( - prefix, - tagName: "string", - typeName: stringType.FullName, - assemblyName: stringType.GetTypeInfo().Assembly.GetName().Name); - } - - private static TagHelperDirectiveDescriptor CreateTagHelperDirectiveDescriptor( - string directiveText, - TagHelperDirectiveType directiveType) - { - return new TagHelperDirectiveDescriptor - { - DirectiveText = directiveText, - Location = SourceLocation.Zero, - DirectiveType = directiveType - }; - } - - public class InspectableTagHelperDescriptorResolver : TagHelperDescriptorResolver - { - public InspectableTagHelperDescriptorResolver() - : base(designTime: false) - { - } - - public SourceLocation DocumentLocation { get; private set; } - - protected override IEnumerable ResolveDescriptorsInAssembly( - string assemblyName, - SourceLocation documentLocation, - ErrorSink errorSink) - { - DocumentLocation = documentLocation; - - return Enumerable.Empty(); - } - } - - private class TestTagHelperDescriptorResolver : TagHelperDescriptorResolver - { - public TestTagHelperDescriptorResolver(TagHelperTypeResolver typeResolver) - : base(typeResolver, new TagHelperDescriptorFactory(designTime: false)) - { - } - - public IEnumerable Resolve(params string[] lookupTexts) - { - return Resolve( - new TagHelperDescriptorResolutionContext( - lookupTexts.Select( - lookupText => - CreateTagHelperDirectiveDescriptor(lookupText, TagHelperDirectiveType.AddTagHelper)), - new ErrorSink())); - } - } - - private class LookupBasedTagHelperTypeResolver : TagHelperTypeResolver - { - private Dictionary> _lookupValues; - - public LookupBasedTagHelperTypeResolver(Dictionary> lookupValues) - { - _lookupValues = lookupValues; - } - - protected override IEnumerable GetExportedTypes(AssemblyName assemblyName) - { - IEnumerable types; - - _lookupValues.TryGetValue(assemblyName.Name, out types); - - return types?.Select(type => type.GetTypeInfo()) ?? Enumerable.Empty(); - } - - protected override bool IsTagHelper(TypeInfo typeInfo) - { - return true; - } - } - - private class AssemblyCheckingTagHelperDescriptorResolver : TagHelperDescriptorResolver - { - public AssemblyCheckingTagHelperDescriptorResolver() - : base(designTime: false) - { - } - - public string CalledWithAssemblyName { get; set; } - - protected override IEnumerable ResolveDescriptorsInAssembly( - string assemblyName, - SourceLocation documentLocation, - ErrorSink errorSink) - { - CalledWithAssemblyName = assemblyName; - - return Enumerable.Empty(); - } - } - - private class ThrowingTagHelperDescriptorResolver : TagHelperDescriptorResolver - { - private readonly Exception _error; - - public ThrowingTagHelperDescriptorResolver(Exception error) - : base(designTime: false) - { - _error = error; - } - - protected override IEnumerable ResolveDescriptorsInAssembly( - string assemblyName, - SourceLocation documentLocation, - ErrorSink errorSink) - { - throw _error; - } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactoryTest.cs b/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactoryTest.cs deleted file mode 100644 index ddff02bc1f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperDesignTimeDescriptorFactoryTest.cs +++ /dev/null @@ -1,567 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Reflection; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers.Testing; -using Microsoft.AspNetCore.Testing; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - public class TagHelperDesignTimeDescriptorFactoryTest - { - private const string TypeSummary = "The summary for ."; - private const string TypeRemarks = "Inherits from ."; - private const string PropertySummary = "This is of type ."; - private const string PropertyRemarks = "The may be null."; - private const string PropertyWithSummaryAndRemarks_Summary = "This is a complex ."; - private const string PropertyWithSummaryAndRemarks_Remarks = ""; - - private static readonly string BaseDir = -#if NET452 - AppDomain.CurrentDomain.BaseDirectory; -#else - AppContext.BaseDirectory; -#endif - - // These test assemblies don't really exist. They are used to look up corresponding XML for a fake assembly - // which is based on the DocumentedTagHelper type. - public static readonly string TestRoot = Path.GetFullPath(Path.Combine(BaseDir, "..", "..", "..")); - - public static readonly string DocumentedAssemblyLocation = - Path.Combine(TestRoot, "TestFiles", "NotLocalized", "TagHelperDocumentation.dll"); - public static readonly string LocalizedDocumentedAssemblyLocation = - Path.Combine(TestRoot, "TestFiles", "Localized", "TagHelperDocumentation.dll"); - public static readonly string DocumentedAssemblyCodeBase = - "file:" + - new string(Path.DirectorySeparatorChar, 3) + - DocumentedAssemblyLocation.TrimStart(Path.DirectorySeparatorChar); - - public static TheoryData OutputElementHintData - { - get - { - // tagHelperType, expectedDescriptor - return new TheoryData - { - { typeof(InheritedOutputElementHintTagHelper), null }, - { - typeof(OutputElementHintTagHelper), - new TagHelperDesignTimeDescriptor - { - OutputElementHint = "hinted-value" - } - }, - { - typeof(OverriddenOutputElementHintTagHelper), - new TagHelperDesignTimeDescriptor - { - OutputElementHint = "overridden" - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(OutputElementHintData))] - public void CreateDescriptor_CapturesOutputElementHint( - Type tagHelperType, - TagHelperDesignTimeDescriptor expectedDescriptor) - { - // Arrange - var factory = new TagHelperDesignTimeDescriptorFactory(); - - // Act - var descriptors = factory.CreateDescriptor(tagHelperType); - - // Assert - Assert.Equal(expectedDescriptor, descriptors, TagHelperDesignTimeDescriptorComparer.Default); - } - - public static TheoryData CreateDescriptor_TypeDocumentationData - { - get - { - var defaultLocation = DocumentedAssemblyLocation; - var defaultCodeBase = DocumentedAssemblyCodeBase; - var nonExistentLocation = defaultLocation.Replace("TestFiles", "TestFile"); - var nonExistentCodeBase = defaultCodeBase.Replace("TestFiles", "TestFile"); - var invalidLocation = defaultLocation + '\0'; - var invalidCodeBase = defaultCodeBase + '\0'; - var onlyHint = new TagHelperDesignTimeDescriptor - { - OutputElementHint = "p" - }; - - // tagHelperType, assemblyLocation, expectedDesignTimeDescriptor - return new TheoryData - { - { typeof(DocumentedTagHelper), null, onlyHint }, - { - typeof(DocumentedTagHelper), - defaultLocation, - new TagHelperDesignTimeDescriptor - { - Summary = TypeSummary, - Remarks = TypeRemarks, - OutputElementHint = "p" - } - }, - { typeof(SingleAttributeTagHelper), defaultLocation, null }, - { typeof(DocumentedTagHelper), nonExistentLocation, onlyHint }, - { typeof(SingleAttributeTagHelper), invalidLocation, null }, - }; - } - } - - [Theory] - [MemberData(nameof(CreateDescriptor_TypeDocumentationData))] - public void CreateDescriptor_WithType_ReturnsExpectedDescriptors( - Type tagHelperType, - string assemblyLocation, - TagHelperDesignTimeDescriptor expectedDesignTimeDescriptor) - { - // Arrange - var factory = new TestTagHelperDesignTimeDescriptorFactory(assemblyLocation); - - // Act - var designTimeDescriptor = factory.CreateDescriptor(tagHelperType); - - // Assert - Assert.Equal(expectedDesignTimeDescriptor, designTimeDescriptor, TagHelperDesignTimeDescriptorComparer.Default); - } - - public static TheoryData CreateDescriptor_LocalizedTypeDocumentationData - { - get - { - // tagHelperType, assemblyLocation, expectedDesignTimeDescriptor, culture - return new TheoryData - { - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperDesignTimeDescriptor - { - Summary = "en-GB: " + TypeSummary, - Remarks = "en-GB: " + TypeRemarks, - OutputElementHint = "p" - }, - "en-GB" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperDesignTimeDescriptor - { - Summary = "en: " + TypeSummary, - Remarks = "en: " + TypeRemarks, - OutputElementHint = "p" - }, - "en-US" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperDesignTimeDescriptor - { - Summary = "fr-FR: " + TypeSummary, - Remarks = "fr-FR: " + TypeRemarks, - OutputElementHint = "p" - }, - "fr-FR" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperDesignTimeDescriptor - { - Summary = "fr: " + TypeSummary, - Remarks = "fr: " + TypeRemarks, - OutputElementHint = "p" - }, - "fr-BE" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperDesignTimeDescriptor - { - Summary = "nl-BE: " + TypeSummary, - Remarks = "nl-BE: " + TypeRemarks, - OutputElementHint = "p" - }, - "nl-BE" - } - }; - } - } - - [Theory] - [MemberData(nameof(CreateDescriptor_LocalizedTypeDocumentationData))] - public void CreateDescriptor_WithLocalizedType_ReturnsExpectedDescriptors( - Type tagHelperType, - string assemblyLocation, - TagHelperDesignTimeDescriptor expectedDesignTimeDescriptor, - string culture) - { - // Arrange - TagHelperDesignTimeDescriptor designTimeDescriptor; - var factory = new TestTagHelperDesignTimeDescriptorFactory(assemblyLocation); - - // Act - using (new CultureReplacer(culture)) - { - designTimeDescriptor = factory.CreateDescriptor(tagHelperType); - } - - // Assert - Assert.Equal(expectedDesignTimeDescriptor, designTimeDescriptor, TagHelperDesignTimeDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptor_WithLocalizedType_CachesBasedOnCulture() - { - // Arrange - var factory = new TestTagHelperDesignTimeDescriptorFactory(LocalizedDocumentedAssemblyLocation); - var expectedFRDesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - Summary = "fr-FR: " + TypeSummary, - Remarks = "fr-FR: " + TypeRemarks, - OutputElementHint = "p", - }; - var expectedNLBEDesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - Summary = "nl-BE: " + TypeSummary, - Remarks = "nl-BE: " + TypeRemarks, - OutputElementHint = "p", - }; - var tagHelperType = typeof(DocumentedTagHelper); - TagHelperDesignTimeDescriptor frDesignTimeDescriptor, nlBEDesignTimeDescriptor; - - // Act - using (new CultureReplacer("fr-FR")) - { - frDesignTimeDescriptor = factory.CreateDescriptor(tagHelperType); - } - using (new CultureReplacer("nl-BE")) - { - nlBEDesignTimeDescriptor = factory.CreateDescriptor(tagHelperType); - } - - // Assert - Assert.Equal( - expectedFRDesignTimeDescriptor, - frDesignTimeDescriptor, - TagHelperDesignTimeDescriptorComparer.Default); - Assert.Equal( - expectedNLBEDesignTimeDescriptor, - nlBEDesignTimeDescriptor, - TagHelperDesignTimeDescriptorComparer.Default); - } - - public static TheoryData CreateAttributeDescriptor_PropertyDocumentationData - { - get - { - var defaultLocation = DocumentedAssemblyLocation; - var defaultCodeBase = DocumentedAssemblyCodeBase; - var nonExistentLocation = defaultLocation.Replace("TestFiles", "TestFile"); - var nonExistentCodeBase = defaultCodeBase.Replace("TestFiles", "TestFile"); - var invalidLocation = defaultLocation + '\0'; - var invalidCodeBase = defaultCodeBase + '\0'; - - // tagHelperType, propertyName, assemblyLocation, expectedDesignTimeDescriptor - return new TheoryData - { - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.SummaryProperty), - null, - null - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksProperty), - null, - null - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksAndSummaryProperty), - null, - null - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.UndocumentedProperty), - defaultLocation, - null - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.SummaryProperty), - defaultLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = PropertySummary - } - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksProperty), - defaultLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Remarks = PropertyRemarks - } - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksAndSummaryProperty), - defaultLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = PropertyWithSummaryAndRemarks_Summary, - Remarks = PropertyWithSummaryAndRemarks_Remarks - } - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.SummaryProperty), - defaultLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = PropertySummary - } - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksProperty), - defaultLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Remarks = PropertyRemarks - } - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksAndSummaryProperty), - nonExistentLocation, - null - }, - { - typeof(DocumentedTagHelper), - nameof(DocumentedTagHelper.RemarksAndSummaryProperty), - invalidLocation, - null - }, - }; - } - } - - [Theory] - [MemberData(nameof(CreateAttributeDescriptor_PropertyDocumentationData))] - public void CreateAttributeDescriptor_ReturnsExpectedDescriptors( - Type tagHelperType, - string propertyName, - string assemblyLocation, - TagHelperAttributeDesignTimeDescriptor expectedDesignTimeDescriptor) - { - // Arrange - var mockPropertyInfo = new Mock(); - mockPropertyInfo.Setup(propertyInfo => propertyInfo.DeclaringType).Returns(tagHelperType); - mockPropertyInfo.Setup(propertyInfo => propertyInfo.Name).Returns(propertyName); - var factory = new TestTagHelperDesignTimeDescriptorFactory(assemblyLocation); - - // Act - var designTimeDescriptor = factory.CreateAttributeDescriptor( - mockPropertyInfo.Object); - - // Assert - Assert.Equal( - expectedDesignTimeDescriptor, - designTimeDescriptor, - TagHelperAttributeDesignTimeDescriptorComparer.Default); - } - - public static TheoryData CreateAttributeDescriptor_LocalizedPropertyData - { - get - { - // tagHelperType, assemblyLocation, expectedDesignTimeDescriptor, culture - return new TheoryData - { - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = "en-GB: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "en-GB: " + PropertyWithSummaryAndRemarks_Remarks - }, - "en-GB" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = "en: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "en: " + PropertyWithSummaryAndRemarks_Remarks - }, - "en-US" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = "fr-FR: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "fr-FR: " + PropertyWithSummaryAndRemarks_Remarks - }, - "fr-FR" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = "fr: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "fr: " + PropertyWithSummaryAndRemarks_Remarks - }, - "fr-BE" - }, - { - typeof(DocumentedTagHelper), - LocalizedDocumentedAssemblyLocation, - new TagHelperAttributeDesignTimeDescriptor - { - Summary = "nl-BE: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "nl-BE: " + PropertyWithSummaryAndRemarks_Remarks - }, - "nl-BE" - } - }; - } - } - - [Theory] - [MemberData(nameof(CreateAttributeDescriptor_LocalizedPropertyData))] - public void CreateAttributeDescriptor_WithLocalizedProperty_ReturnsExpectedDescriptors( - Type tagHelperType, - string assemblyLocation, - TagHelperAttributeDesignTimeDescriptor expectedDesignTimeDescriptor, - string culture) - { - // Arrange - var mockPropertyInfo = new Mock(); - mockPropertyInfo.Setup(propertyInfo => propertyInfo.DeclaringType).Returns(tagHelperType); - mockPropertyInfo - .Setup(propertyInfo => propertyInfo.Name) - .Returns(nameof(DocumentedTagHelper.RemarksAndSummaryProperty)); - TagHelperAttributeDesignTimeDescriptor designTimeDescriptor; - var factory = new TestTagHelperDesignTimeDescriptorFactory(assemblyLocation); - - // Act - using (new CultureReplacer(culture)) - { - designTimeDescriptor = factory.CreateAttributeDescriptor( - mockPropertyInfo.Object); - } - - // Assert - Assert.Equal( - expectedDesignTimeDescriptor, - designTimeDescriptor, - TagHelperAttributeDesignTimeDescriptorComparer.Default); - } - - [Fact] - public void CreateDescriptor_WithLocalizedProperty_CachesBasedOnCulture() - { - // Arrange - var tagHelperType = typeof(DocumentedTagHelper); - var mockPropertyInfo = new Mock(); - mockPropertyInfo.Setup(propertyInfo => propertyInfo.DeclaringType).Returns(tagHelperType); - mockPropertyInfo - .Setup(propertyInfo => propertyInfo.Name) - .Returns(nameof(DocumentedTagHelper.RemarksAndSummaryProperty)); - var factory = new TestTagHelperDesignTimeDescriptorFactory(LocalizedDocumentedAssemblyLocation); - var expectedFRDesignTimeDescriptor = new TagHelperAttributeDesignTimeDescriptor - { - Summary = "fr-FR: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "fr-FR: " + PropertyWithSummaryAndRemarks_Remarks - }; - var expectedNLBEDesignTimeDescriptor = new TagHelperAttributeDesignTimeDescriptor - { - Summary = "nl-BE: " + PropertyWithSummaryAndRemarks_Summary, - Remarks = "nl-BE: " + PropertyWithSummaryAndRemarks_Remarks - }; - TagHelperAttributeDesignTimeDescriptor frDesignTimeDescriptor, nlBEDesignTimeDescriptor; - - // Act - using (new CultureReplacer("fr-FR")) - { - frDesignTimeDescriptor = factory.CreateAttributeDescriptor(mockPropertyInfo.Object); - } - using (new CultureReplacer("nl-BE")) - { - nlBEDesignTimeDescriptor = factory.CreateAttributeDescriptor(mockPropertyInfo.Object); - } - - // Assert - Assert.Equal( - expectedFRDesignTimeDescriptor, - frDesignTimeDescriptor, - TagHelperAttributeDesignTimeDescriptorComparer.Default); - Assert.Equal( - expectedNLBEDesignTimeDescriptor, - nlBEDesignTimeDescriptor, - TagHelperAttributeDesignTimeDescriptorComparer.Default); - } - - private class TestTagHelperDesignTimeDescriptorFactory : TagHelperDesignTimeDescriptorFactory - { - private readonly string _assemblyLocation; - - public TestTagHelperDesignTimeDescriptorFactory(string assemblyLocation) - : base() - { - _assemblyLocation = assemblyLocation; - } - - public override string GetAssemblyLocation(Assembly assembly) - { - return _assemblyLocation; - } - } - - [OutputElementHint("hinted-value")] - private class OutputElementHintTagHelper : TagHelper - { - } - - private class InheritedOutputElementHintTagHelper : OutputElementHintTagHelper - { - } - - [OutputElementHint("overridden")] - private class OverriddenOutputElementHintTagHelper : OutputElementHintTagHelper - { - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperTypeResolverTest.cs b/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperTypeResolverTest.cs deleted file mode 100644 index 5d668ba6a5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/TagHelperTypeResolverTest.cs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - public class TagHelperTypeResolverTest - { - protected static readonly Type[] ValidTestableTagHelpers = - { - typeof(Valid_PlainTagHelper), - typeof(Valid_InheritedTagHelper) - }; - - protected static readonly Type[] InvalidTestableTagHelpers = - { - typeof(Invalid_AbstractTagHelper), - typeof(Invalid_GenericTagHelper<>), - typeof(Invalid_NestedPublicTagHelper), - typeof(Invalid_NestedInternalTagHelper), - typeof(Invalid_PrivateTagHelper), - typeof(Invalid_ProtectedTagHelper), - typeof(Invalid_InternalTagHelper) - }; - - protected static readonly Type[] TestableTagHelpers = - ValidTestableTagHelpers.Concat(InvalidTestableTagHelpers).ToArray(); - - [Fact] - public void TypeResolver_RecordsErrorWhenCannotResolveAssembly() - { - // Arrange - var tagHelperTypeResolver = new TagHelperTypeResolver(); - var errorSink = new ErrorSink(); - var documentLocation = new SourceLocation(1, 2, 3); - - // Act - tagHelperTypeResolver.Resolve("abcd", documentLocation, errorSink); - - // Assert - var error = Assert.Single(errorSink.Errors); - Assert.Equal(4, error.Length); - Assert.Equal(documentLocation, error.Location); - - // The framework throws the underlying Exception. Only confirm Message mentions expected assembly. - Assert.Contains("assembly 'abcd'", error.Message); - } - - [Fact] - public void TypeResolver_OnlyReturnsValidTagHelpersForAssemblyLookup() - { - // Arrange - var tagHelperTypeResolver = new TestTagHelperTypeResolver(TestableTagHelpers); - - // Act - var types = tagHelperTypeResolver.Resolve("Foo", SourceLocation.Zero, new ErrorSink()); - - // Assert - Assert.Collection(types, - type => - { - Assert.Equal(typeof(Valid_PlainTagHelper), type); - }, - type => - { - Assert.Equal(typeof(Valid_InheritedTagHelper), type); - }); - } - - [Fact] - public void TypeResolver_ReturnsEmptyEnumerableIfNoValidTagHelpersFound() - { - // Arrange - var tagHelperTypeResolver = new TestTagHelperTypeResolver(InvalidTestableTagHelpers); - - // Act - var types = tagHelperTypeResolver.Resolve("Foo", SourceLocation.Zero, new ErrorSink()); - - // Assert - Assert.Empty(types); - } - - [Theory] - [InlineData("")] - [InlineData(null)] - public void TypeResolver_CreatesErrorIfNullOrEmptyAssmblyName_DoesNotThrow(string name) - { - // Arrange - var tagHelperTypeResolver = new TestTagHelperTypeResolver(InvalidTestableTagHelpers); - var errorSink = new ErrorSink(); - var documentLocation = new SourceLocation(1, 2, 3); - var expectedErrorMessage = "Tag helper directive assembly name cannot be null or empty."; - - // Act - tagHelperTypeResolver.Resolve(name, documentLocation, errorSink); - - // Assert - var error = Assert.Single(errorSink.Errors); - Assert.Equal(1, error.Length); - Assert.Equal(documentLocation, error.Location); - Assert.Equal(expectedErrorMessage, error.Message); - } - - protected class TestTagHelperTypeResolver : TagHelperTypeResolver - { - private IEnumerable _assemblyTypeInfos; - - public TestTagHelperTypeResolver(IEnumerable assemblyTypes) - { - _assemblyTypeInfos = assemblyTypes.Select(type => type.GetTypeInfo()); - OnGetExportedTypes = (_) => { }; - } - - public Action OnGetExportedTypes { get; set; } - - protected override IEnumerable GetExportedTypes(AssemblyName assemblyName) - { - OnGetExportedTypes(assemblyName); - - return _assemblyTypeInfos; - } - } - - public class Invalid_NestedPublicTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } - - internal class Invalid_NestedInternalTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } - - private class Invalid_PrivateTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } - - protected class Invalid_ProtectedTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } - } - - // These tag helper types must be unnested and public to potentially be valid tag helpers. - // In this case they do not fulfill other TagHelper requirements. - public abstract class Invalid_AbstractTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } - - public class Invalid_GenericTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } - - internal class Invalid_InternalTagHelper : ITagHelper - { - public int Order { get { return 0; } } - - public void Init(TagHelperContext context) - { - } - - public Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - return Task.FromResult(result: true); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/XmlDocumentationProviderTest.cs b/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/XmlDocumentationProviderTest.cs deleted file mode 100644 index 5d99dac577..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Runtime.Test/Runtime/TagHelpers/XmlDocumentationProviderTest.cs +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -#if !NETCOREAPP1_1 -using System; -using System.Globalization; -using System.IO; -using System.Reflection; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers -{ - public class XmlDocumentationProviderTest - { - private static readonly string BaseDir = -#if NET452 - AppDomain.CurrentDomain.BaseDirectory; -#else - AppContext.BaseDirectory; -#endif - - private static readonly string TestRoot = Path.GetFullPath(Path.Combine(BaseDir, "..", "..", "..")); - - private static readonly string XmlTestFileLocation = - TestRoot + "/TestFiles/NotLocalized/TagHelperDocumentation.xml"; - private static readonly TypeInfo DocumentedTagHelperTypeInfo = typeof(DocumentedTagHelper).GetTypeInfo(); - private static readonly PropertyInfo DocumentedTagHelperSummaryPropertyInfo = - DocumentedTagHelperTypeInfo.GetProperty(nameof(DocumentedTagHelper.SummaryProperty)); - private static readonly PropertyInfo DocumentedTagHelperRemarksPropertyInfo = - DocumentedTagHelperTypeInfo.GetProperty(nameof(DocumentedTagHelper.RemarksProperty)); - private static readonly PropertyInfo DocumentedTagHelperRemarksSummaryPropertyInfo = - DocumentedTagHelperTypeInfo.GetProperty(nameof(DocumentedTagHelper.RemarksAndSummaryProperty)); - - [Fact] - public void CanReadXml() - { - // Act. Ensuring that reading the Xml file doesn't throw. - new XmlDocumentationProvider(XmlTestFileLocation); - } - - public static TheoryData SummaryDocumentationData - { - get - { - var fullTypeName = DocumentedTagHelperTypeInfo.FullName; - - // id, expectedSummary - return new TheoryData - { - { - $"T:{fullTypeName}", - "The summary for ." - }, - { - $"P:{fullTypeName}.{DocumentedTagHelperSummaryPropertyInfo.Name}", - "This is of type ." - }, - { - $"P:{fullTypeName}.{DocumentedTagHelperRemarksPropertyInfo.Name}", - null - }, - { - $"P:{fullTypeName}.{DocumentedTagHelperRemarksSummaryPropertyInfo.Name}", - "This is a complex ." - } - }; - } - } - - [Theory] - [MemberData(nameof(SummaryDocumentationData))] - public void GetSummary_ReturnsExpectedSummarys(string id, string expectedSummary) - { - // Arrange - var xmlDocumentationProvider = new XmlDocumentationProvider(XmlTestFileLocation); - - // Act - var summary = xmlDocumentationProvider.GetSummary(id); - - // Assert - Assert.Equal(expectedSummary, summary, StringComparer.Ordinal); - } - - public static TheoryData RemarksDocumentationData - { - get - { - var fullTypeName = DocumentedTagHelperTypeInfo.FullName; - - // id, expectedRemarks - return new TheoryData - { - { - $"T:{fullTypeName}", - "Inherits from ." - }, - { - $"P:{fullTypeName}.{DocumentedTagHelperSummaryPropertyInfo.Name}", - null - }, - { - $"P:{fullTypeName}.{DocumentedTagHelperRemarksPropertyInfo.Name}", - "The may be null." - }, - { - $"P:{fullTypeName}.{DocumentedTagHelperRemarksSummaryPropertyInfo.Name}", - "" - } - }; - } - } - - [Theory] - [MemberData(nameof(RemarksDocumentationData))] - public void GetRemarks_ReturnsExpectedRemarks(string id, string expectedRemarks) - { - // Arrange - var xmlDocumentationProvider = new XmlDocumentationProvider(XmlTestFileLocation); - - // Act - var remarks = xmlDocumentationProvider.GetRemarks(id); - - // Assert - Assert.Equal(expectedRemarks, remarks, StringComparer.Ordinal); - } - - [Fact] - public void GetId_UnderstandsTypeInfo() - { - // Arrange - var expectedId = "T:" + typeof(DocumentedTagHelper).FullName; - - // Act - var id = XmlDocumentationProvider.GetId(DocumentedTagHelperTypeInfo); - - // Assert - Assert.Equal(expectedId, id, StringComparer.Ordinal); - } - - [Fact] - public void GetId_UnderstandsPropertyInfo() - { - // Arrange - var expectedId = string.Format( - CultureInfo.InvariantCulture, - "P:{0}.{1}", - typeof(DocumentedTagHelper).FullName, - nameof(DocumentedTagHelper.RemarksAndSummaryProperty)); - - // Act - var id = XmlDocumentationProvider.GetId(DocumentedTagHelperRemarksSummaryPropertyInfo); - - // Assert - Assert.Equal(expectedId, id, StringComparer.Ordinal); - } - } -} -#endif \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CSharpRazorCodeLanguageTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CSharpRazorCodeLanguageTest.cs deleted file mode 100644 index 4b7cacf381..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CSharpRazorCodeLanguageTest.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Parser; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class CSharpRazorCodeLanguageTest - { - [Fact] - public void CreateCodeParserReturnsNewCSharpCodeParser() - { - // Arrange - var service = new CSharpRazorCodeLanguage(); - - // Act - var parser = service.CreateCodeParser(); - - // Assert - Assert.NotNull(parser); - Assert.IsType(parser); - } - - [Fact] - public void CreateChunkGeneratorParserListenerReturnsNewCSharpChunkGeneratorParserListener() - { - // Arrange - var service = new CSharpRazorCodeLanguage(); - - // Act - var host = new RazorEngineHost(service); - var generator = service.CreateChunkGenerator("Foo", "Bar", "Baz", host); - - // Assert - Assert.NotNull(generator); - Assert.IsType(generator); - Assert.Equal("Foo", generator.ClassName); - Assert.Equal("Bar", generator.RootNamespaceName); - Assert.Equal("Baz", generator.SourceFileName); - Assert.Same(host, generator.Host); - } - - [Fact] - public void CreateCodeGenerator_ReturnsNewCSharpCodeGenerator() - { - // Arrange - var language = new CSharpRazorCodeLanguage(); - var host = new RazorEngineHost(language); - var codeGeneratorContext = new CodeGeneratorContext( - host, - "myclass", - "myns", - string.Empty, - shouldGenerateLinePragmas: false, - errorSink: new ErrorSink()); - - // Act - var generator = language.CreateCodeGenerator(codeGeneratorContext); - - // Assert - Assert.IsType(generator); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkTreeBuilderTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkTreeBuilderTest.cs deleted file mode 100644 index 170203304b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkTreeBuilderTest.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ChunkTreeBuilderTest - { - [Fact] - public void AddAddTagHelperChunk_AddsChunkToTopLevelChunkTree() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var builder = new ChunkTreeBuilder(); - var block = new ExpressionBlock(); - var addTagHelperDirective = spanFactory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " "); - - // Act - builder.StartParentChunk(block); - builder.AddAddTagHelperChunk("some text", addTagHelperDirective); - builder.EndParentChunk(); - - // Assert - Assert.Equal(2, builder.Root.Children.Count); - - var parentChunk = Assert.IsType(builder.Root.Children.First()); - Assert.Empty(parentChunk.Children); - - var addTagHelperChunk = Assert.IsType(builder.Root.Children.Last()); - Assert.Equal(addTagHelperChunk.LookupText, "some text"); - } - - [Fact] - public void AddRemoveTagHelperChunk_AddsChunkToTopLevelChunkTree() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var builder = new ChunkTreeBuilder(); - var block = new ExpressionBlock(); - var removeTagHelperDirective = spanFactory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " "); - - // Act - builder.StartParentChunk(block); - builder.AddRemoveTagHelperChunk("some text", removeTagHelperDirective); - builder.EndParentChunk(); - - // Assert - Assert.Equal(2, builder.Root.Children.Count); - - var parentChunk = Assert.IsType(builder.Root.Children.First()); - Assert.Empty(parentChunk.Children); - - var removeTagHelperChunk = Assert.IsType(builder.Root.Children.Last()); - Assert.Equal(removeTagHelperChunk.LookupText, "some text"); - } - - [Fact] - public void AddLiteralChunk_AddsChunkToChunkTree() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var previousSpan = spanFactory.EmptyHtml().Builder.Build(); - var builder = new ChunkTreeBuilder(); - - // Act - builder.AddLiteralChunk("some text", previousSpan); - - // Assert - var chunk = Assert.Single(builder.Root.Children); - var literalChunk = Assert.IsType(chunk); - Assert.Equal("some text", literalChunk.Text); - Assert.Same(previousSpan, literalChunk.Association); - } - - [Fact] - public void AddLiteralChunk_AppendsToPreviousChunk_IfChunkWasLiteral() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var previousSpan = spanFactory.Markup("").Builder.Build(); - var newSpan = spanFactory.Markup("

").Builder.Build(); - var builder = new ChunkTreeBuilder(); - - // Act - builder.AddLiteralChunk("", previousSpan); - builder.AddLiteralChunk("

", newSpan); - - // Assert - var chunk = Assert.Single(builder.Root.Children); - - var literalChunk = Assert.IsType(chunk); - Assert.Equal(2, literalChunk.Children.Count); - - var span = Assert.IsType(literalChunk.Children[0].Association); - Assert.Same(span, previousSpan); - - span = Assert.IsType(literalChunk.Children[1].Association); - Assert.Same(span, newSpan); - } - - [Fact] - public void AddLiteralChunk_CreatesNewChunk_IfChunkIsNotLiteral() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var span1 = spanFactory.Markup("").Builder.Build(); - var span2 = spanFactory.Markup("

").Builder.Build(); - var span3 = spanFactory.Code("Hi!").AsExpression().Builder.Build(); - var builder = new ChunkTreeBuilder(); - - // Act - builder.AddLiteralChunk("", span1); - builder.AddLiteralChunk("

", span2); - builder.AddExpressionChunk("Hi!", span3); - - // Assert - Assert.Equal(2, builder.Root.Children.Count); - - var literalChunk = Assert.IsType(builder.Root.Children[0]); - Assert.Equal(2, literalChunk.Children.Count); - - var span = Assert.IsType(literalChunk.Children[0].Association); - Assert.Same(span, span1); - - span = Assert.IsType(literalChunk.Children[1].Association); - Assert.Same(span, span2); - - Assert.IsType(builder.Root.Children[1]); - } - - [Fact] - public void AddLiteralChunk_AddsChunkToChunkTree_IfPreviousChunkWasNotLiteral() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var codeSpan = spanFactory.Code("int a = 10;") - .AsStatement() - .Builder.Build(); - var literalSpan = spanFactory.Markup("

").Builder.Build(); - var builder = new ChunkTreeBuilder(); - - // Act - builder.AddStatementChunk("int a = 10;", codeSpan); - builder.AddLiteralChunk("

", literalSpan); - - // Assert - var chunks = builder.Root.Children; - Assert.Equal(2, chunks.Count); - var statementChunk = Assert.IsType(chunks[0]); - Assert.Equal("int a = 10;", statementChunk.Code); - Assert.Same(codeSpan, statementChunk.Association); - var literalChunk = Assert.IsType(chunks[1]); - Assert.Equal("

", literalChunk.Text); - Assert.Same(literalSpan, literalChunk.Association); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkVisitorTests.cs b/test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkVisitorTests.cs deleted file mode 100644 index 12c629cf8a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Chunks/ChunkVisitorTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; -using Moq; -using Moq.Protected; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Chunks -{ - public class ChunkVisitorTests - { - [Fact] - public void Accept_InvokesAppropriateOverload() - { - // Arrange - var chunks = new Chunk[] { new LiteralChunk(), new StatementChunk() }; - var visitor = CreateVisitor(); - - // Act - visitor.Object.Accept(chunks); - - // Assert - visitor.Protected().Verify("Visit", Times.AtMostOnce(), chunks[0]); - visitor.Protected().Verify("Visit", Times.AtMostOnce(), chunks[1]); - } - - private static Mock> CreateVisitor() - { - var codeGeneratorContext = new CodeGeneratorContext( - new RazorEngineHost(new CSharpRazorCodeLanguage()), - "myclass", - "myns", - string.Empty, - shouldGenerateLinePragmas: false, - errorSink: new ErrorSink()); - var writer = Mock.Of(); - return new Mock>(writer, codeGeneratorContext); - } - - private class MyTestChunk : Chunk - { - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AddImportChunkGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AddImportChunkGeneratorTest.cs deleted file mode 100644 index 251ab3b7a4..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AddImportChunkGeneratorTest.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class AddImportChunkGeneratorTest - { - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { - new AddImportChunkGenerator(ns: null), - new AddImportChunkGenerator(ns: null) - }, - { - new AddImportChunkGenerator(ns: "Fred"), - new AddImportChunkGenerator(ns: "Fred") - }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { - new AddImportChunkGenerator(ns: null), - null - }, - { - new AddImportChunkGenerator(ns: "Fred"), - null - }, - { - new AddImportChunkGenerator(ns: "Fred"), - new object() - }, - { - new AddImportChunkGenerator(ns: "Fred"), - SpanChunkGenerator.Null - }, - { - new AddImportChunkGenerator(ns: "Fred"), - new StatementChunkGenerator() - }, - { - // Different Namespace. - new AddImportChunkGenerator(ns: "Fred"), - new AddImportChunkGenerator(ns: "Ginger") - }, - { - // Different Namespace (case sensitive). - new AddImportChunkGenerator(ns: "fred"), - new AddImportChunkGenerator(ns: "FRED") - } - }; - } - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected(AddImportChunkGenerator leftObject, AddImportChunkGenerator rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(AddImportChunkGenerator leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual( - AddImportChunkGenerator leftObject, - AddImportChunkGenerator rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AttributeBlockChunkGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AttributeBlockChunkGeneratorTest.cs deleted file mode 100644 index 68ed98933f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/AttributeBlockChunkGeneratorTest.cs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class AttributeBlockChunkGeneratorTest - { - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { - new AttributeBlockChunkGenerator(name: null, prefix: null, suffix: null), - new AttributeBlockChunkGenerator(name: null, prefix: null, suffix: null) - }, - { - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 0, line: 0, col: 0), - suffix: new LocationTagged(value: "George", offset: 0, line: 0, col: 0)), - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 0, line: 0, col: 0), - suffix: new LocationTagged(value: "George", offset: 0, line: 0, col: 0)) - }, - { - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: new LocationTagged(value: "George", offset: 13, line: 14, col: 15)), - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: new LocationTagged(value: "George", offset: 13, line: 14, col: 15)) - }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { - new AttributeBlockChunkGenerator(name: null, prefix: null, suffix: null), - null - }, - { - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 0, line: 0, col: 0), - suffix: new LocationTagged(value: "George", offset: 0, line: 0, col: 0)), - null - }, - { - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: new LocationTagged(value: "George", offset: 13, line: 14, col: 15)), - null - }, - { - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: new LocationTagged(value: "George", offset: 13, line: 14, col: 15)), - new object() - }, - { - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: new LocationTagged(value: "George", offset: 13, line: 14, col: 15)), - new RazorCommentChunkGenerator() - }, - { - // Different Name. - new AttributeBlockChunkGenerator(name: "Fred", prefix: null, suffix: null), - new AttributeBlockChunkGenerator(name: "Ginger", prefix: null, suffix: null) - }, - { - // Different Name (case sensitive). - new AttributeBlockChunkGenerator(name: "fred", prefix: null, suffix: null), - new AttributeBlockChunkGenerator(name: "FRED", prefix: null, suffix: null) - }, - { - // Different Prefix. - new AttributeBlockChunkGenerator( - name: null, - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: null), - new AttributeBlockChunkGenerator( - name: null, - prefix: new LocationTagged(value: "George", offset: 10, line: 11, col: 12), - suffix: null) - }, - { - // Different Suffix. - new AttributeBlockChunkGenerator( - name: null, - prefix: null, - suffix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12)), - new AttributeBlockChunkGenerator( - name: null, - prefix: null, - suffix: new LocationTagged(value: "George", offset: 10, line: 11, col: 12)) - }, - }; - } - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected( - AttributeBlockChunkGenerator leftObject, - AttributeBlockChunkGenerator rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(AttributeBlockChunkGenerator leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual( - AttributeBlockChunkGenerator leftObject, - AttributeBlockChunkGenerator rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/RazorCommentChunkGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/RazorCommentChunkGeneratorTest.cs deleted file mode 100644 index c607a4464c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Chunks/Generators/RazorCommentChunkGeneratorTest.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - // Really tests underlying ParentChunkGenerator - public class RazorCommentChunkGeneratorTest - { - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { new RazorCommentChunkGenerator(), new RazorCommentChunkGenerator() }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { new RazorCommentChunkGenerator(), null }, - { new RazorCommentChunkGenerator(), new object() }, - { new RazorCommentChunkGenerator(), ParentChunkGenerator.Null }, - { - new RazorCommentChunkGenerator(), - new AttributeBlockChunkGenerator(name: null, prefix: null, suffix: null) - }, - { - new RazorCommentChunkGenerator(), - new DynamicAttributeBlockChunkGenerator(prefix: null, offset: 0, line: 0, col: 0) - }, - { new RazorCommentChunkGenerator(), new ExpressionChunkGenerator() }, - { new RazorCommentChunkGenerator(), new SectionChunkGenerator(sectionName: null) }, - { - new RazorCommentChunkGenerator(), - new TagHelperChunkGenerator(Enumerable.Empty()) - }, - { new RazorCommentChunkGenerator(), new TemplateBlockChunkGenerator() }, - { - new RazorCommentChunkGenerator(), - new AddImportChunkGenerator(ns: "Fred") - }, - }; - } - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected(RazorCommentChunkGenerator leftObject, IParentChunkGenerator rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(IParentChunkGenerator leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual( - RazorCommentChunkGenerator leftObject, - IParentChunkGenerator rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeGeneratorTest.cs deleted file mode 100644 index d2e8fdcfa4..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeGeneratorTest.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -#if GENERATE_BASELINES -using System; -#endif -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.CodeGenerators; -using Microsoft.AspNetCore.Razor.Test.Utils; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpCodeGeneratorTest - { -#if GENERATE_BASELINES - private static readonly string _baselinePathStart = "test/Microsoft.AspNetCore.Razor.Test"; -#endif - private static readonly string _testOutputDirectory = "TestFiles/CodeGenerator/Output/CSharpCodeGenerator"; - - [Fact] - public void ChunkTreeWithUsings() - { - // Arrange - var syntaxTreeNode = new Mock(new SpanBuilder()); - var language = new CSharpRazorCodeLanguage(); - var host = new CodeGenTestHost(language); - var codeGeneratorContext = new CodeGeneratorContext( - host, - "TestClass", - "TestNamespace", - "Foo.cs", - shouldGenerateLinePragmas: false, - errorSink: new ErrorSink()); - codeGeneratorContext.ChunkTreeBuilder.AddUsingChunk("FakeNamespace1", syntaxTreeNode.Object); - codeGeneratorContext.ChunkTreeBuilder.AddUsingChunk("FakeNamespace2.SubNamespace", syntaxTreeNode.Object); - var codeGenerator = new CodeGenTestCodeGenerator(codeGeneratorContext); - - var path = $"{_testOutputDirectory}/ChunkTreeWithUsings.cs"; - var testFile = TestFile.Create(path); - - string expectedOutput; -#if GENERATE_BASELINES - if (testFile.Exists()) - { - expectedOutput = testFile.ReadAllText(); - } - else - { - expectedOutput = null; - } -#else - expectedOutput = testFile.ReadAllText(); -#endif - - // Act - var result = codeGenerator.Generate(); - - // Assert -#if GENERATE_BASELINES - // Update baseline files if files do not already match. - if (!string.Equals(expectedOutput, result.Code, StringComparison.Ordinal)) - { - var baselinePath = $"{_baselinePathStart}/{_testOutputDirectory}/ChunkTreeWithUsings.cs"; - BaselineWriter.WriteBaseline( baselinePath, result.Code); - } -#else - Assert.Equal(expectedOutput, NormalizeLineEndings(result.Code)); -#endif - } - - public static TheoryData ModifyOutputData - { - get - { - var addFileName = "AddGenerateChunkTest.cs"; - var addGenerator = new AddGenerateTestCodeGenerator(CreateContext()); - var addResult = CreateCodeGeneratorResult(addFileName); - - var clearFileName = "ClearGenerateChunkTest.cs"; - var clearGenerator = new ClearGenerateTestCodeGenerator(CreateContext()); - var clearResult = CreateCodeGeneratorResult(clearFileName); - - var defaultFileName = "DefaultGenerateChunkTest.cs"; - var defaultGenerator = new CSharpCodeGenerator(CreateContext()); - var defaultResult = CreateCodeGeneratorResult(defaultFileName); - - var commentFileName = "BuildAfterExecuteContentTest.cs"; - var commentGenerator = new BuildAfterExecuteContentTestCodeGenerator(CreateContext()); - var commentResult = CreateCodeGeneratorResult(commentFileName); - - return new TheoryData - { - {addGenerator, addResult, addFileName}, - {clearGenerator, clearResult, clearFileName }, - {defaultGenerator, defaultResult, defaultFileName }, - {commentGenerator, commentResult, commentFileName } - }; - } - } - - [Theory] - [MemberData(nameof(ModifyOutputData))] - public void BuildAfterExecuteContent_ModifyChunks_ModifyOutput( - CSharpCodeGenerator generator, - CodeGeneratorResult expectedResult, - string fileName) - { - // Arrange, Act - var result = generator.Generate(); - - // Assert -#if GENERATE_BASELINES - // Update baseline files if files do not already match. - if (!string.Equals(expectedResult.Code, result.Code, StringComparison.Ordinal)) - { - var baselinePath = $"{_baselinePathStart}/{_testOutputDirectory}/{fileName}"; - BaselineWriter.WriteBaseline( baselinePath, result.Code); - } -#else - Assert.Equal(expectedResult.Code, NormalizeLineEndings(result.Code)); -#endif - } - - - private static CodeGeneratorResult CreateCodeGeneratorResult(string fileName) - { - var path = $"{_testOutputDirectory}/{fileName}"; - var file = TestFile.Create(path); - string code; - -#if GENERATE_BASELINES - if (file.Exists()) - { - code = file.ReadAllText(); - } - else - { - code = null; - } -#else - code = file.ReadAllText(); -#endif - - var result = new CodeGeneratorResult(code, new List()); - return result; - } - - // Returns a context with two literal chunks. - private static CodeGeneratorContext CreateContext() - { - var language = new CSharpRazorCodeLanguage(); - var host = new CodeGenTestHost(language); - - var codeGeneratorContext = new CodeGeneratorContext( - new ChunkGeneratorContext( - host, - host.DefaultClassName, - host.DefaultNamespace, - "", - shouldGenerateLinePragmas: false), - new ErrorSink()); - - codeGeneratorContext.ChunkTreeBuilder = new ChunkTreeBuilder(); - var syntaxTreeNode = new Mock(new SpanBuilder()); - codeGeneratorContext.ChunkTreeBuilder.AddLiteralChunk("hello", syntaxTreeNode.Object); - codeGeneratorContext.ChunkTreeBuilder.AddStatementChunk("// asdf", syntaxTreeNode.Object); - codeGeneratorContext.ChunkTreeBuilder.AddLiteralChunk("world", syntaxTreeNode.Object); - return codeGeneratorContext; - } - - private class BuildAfterExecuteContentTestCodeGenerator : CSharpCodeGenerator - { - public BuildAfterExecuteContentTestCodeGenerator(CodeGeneratorContext context) : base(context) - { - } - - protected override void BuildAfterExecuteContent(CSharpCodeWriter writer, IList chunks) - { - writer.WriteLine("// test add content."); - } - } - - private class AddGenerateTestCodeGenerator : CSharpCodeGenerator - { - public AddGenerateTestCodeGenerator(CodeGeneratorContext context) : base(context) - { - } - - public override CodeGeneratorResult Generate() - { - var firstChunk = Tree.Children.First(); - Tree.Children.Add(firstChunk); - return base.Generate(); - } - } - - private class ClearGenerateTestCodeGenerator : CSharpCodeGenerator - { - public ClearGenerateTestCodeGenerator(CodeGeneratorContext context) : base(context) - { - } - - public override CodeGeneratorResult Generate() - { - Tree.Children.Clear(); - return base.Generate(); - } - } - - private static string NormalizeLineEndings(string content) => - content.Replace("\r", "").Replace("\n", "\r\n"); - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeWriterTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeWriterTest.cs deleted file mode 100644 index 25e9422410..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpCodeWriterTest.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpCodeWriterTest - { - [Fact] - public void WriteLineNumberDirective_UsesFilePath_WhenFileInSourceLocationIsNull() - { - // Arrange - var filePath = "some-path"; - var writer = new CSharpCodeWriter(); - var expected = $"#line 5 \"{filePath}\"" + writer.NewLine; - var sourceLocation = new SourceLocation(10, 4, 3); - - // Act - writer.WriteLineNumberDirective(sourceLocation, filePath); - var code = writer.GenerateCode(); - - // Assert - Assert.Equal(expected, code); - } - - [Theory] - [InlineData("")] - [InlineData("source-location-file-path")] - public void WriteLineNumberDirective_UsesSourceLocationFilePath_IfAvailable( - string sourceLocationFilePath) - { - // Arrange - var filePath = "some-path"; - var writer = new CSharpCodeWriter(); - var expected = $"#line 5 \"{sourceLocationFilePath}\"" + writer.NewLine; - var sourceLocation = new SourceLocation(sourceLocationFilePath, 10, 4, 3); - - // Act - writer.WriteLineNumberDirective(sourceLocation, filePath); - var code = writer.GenerateCode(); - - // Assert - Assert.Equal(expected, code); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpLineMappingWriterTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpLineMappingWriterTest.cs deleted file mode 100644 index b8304ae7dd..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpLineMappingWriterTest.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpLineMappingWriterTest - { - [Fact] - public void WriterConstructedWithContentLength_AddsLineMappings_OnDispose() - { - // Arrange - var location = new SourceLocation(10, 15, 20); - var expected = new LineMapping( - new MappingLocation(location, 30), - new MappingLocation(new SourceLocation(0, 0, 0), 11)); - var writer = new CSharpCodeWriter(); - - // Act - using (var mappingWriter = new CSharpLineMappingWriter(writer, location, 30)) - { - writer.Write("Hello world"); - } - - // Assert - Assert.Equal("Hello world", writer.GenerateCode()); - var mapping = Assert.Single(writer.LineMappingManager.Mappings); - Assert.Equal(expected, mapping); - } - - [Fact] - public void WriterConstructedWithContentLengthAndSourceFile_AddsLineMappingsAndLinePragmas_OnDispose() - { - // Arrange - var location = new SourceLocation(10, 1, 20); - var expected = string.Join(Environment.NewLine, - @"#line 2 ""myfile""", - "Hello world", - "", - "#line default", - "#line hidden", - ""); - var expectedMappings = new LineMapping( - new MappingLocation(location, 30), - new MappingLocation(new SourceLocation(16 + Environment.NewLine.Length, 1, 0), 11)); - var writer = new CSharpCodeWriter(); - - // Act - using (var mappingWriter = new CSharpLineMappingWriter(writer, location, 30, "myfile")) - { - writer.Write("Hello world"); - } - - // Assert - Assert.Equal(expected, writer.GenerateCode()); - var mapping = Assert.Single(writer.LineMappingManager.Mappings); - Assert.Equal(expectedMappings, mapping); - } - - [Fact] - public void WriterConstructedWithoutContentLengthAndSourceFile_AddsLinePragmas_OnDispose() - { - // Arrange - var location = new SourceLocation(10, 1, 20); - var expected = string.Join(Environment.NewLine, - @"#line 2 ""myfile""", - "Hello world", - "", - "#line default", - "#line hidden", - ""); - var expectedMappings = new LineMapping( - new MappingLocation(location, 30), - new MappingLocation(new SourceLocation(18, 1, 0), 11)); - var writer = new CSharpCodeWriter(); - - // Act - using (var mappingWriter = new CSharpLineMappingWriter(writer, location, "myfile")) - { - writer.Write("Hello world"); - } - - // Assert - Assert.Equal(expected, writer.GenerateCode()); - Assert.Empty(writer.LineMappingManager.Mappings); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpPaddingBuilderTests.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpPaddingBuilderTests.cs deleted file mode 100644 index d2e39e757d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpPaddingBuilderTests.cs +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpPaddingBuilderTests - { - [Fact] - public void CalculatePaddingForEmptySpanReturnsZero() - { - // Arrange - var host = CreateHost(designTime: true); - - var span = new Span(new SpanBuilder()); - - var paddingBuilder = new CSharpPaddingBuilder(host); - - // Act - var padding = paddingBuilder.CalculatePadding(span, 0); - - // Assert - Assert.Equal(0, padding); - } - - [Theory] - [MemberData("SpacePropertyData")] - public void CalculatePaddingForEmptySpanWith4Spaces(bool designTime, bool isIndentingWithTabs, int tabSize) - { - // Arrange - var host = CreateHost(designTime, isIndentingWithTabs, tabSize); - - var span = GenerateSpan(@" @{", SpanKind.Code, 3, ""); - - var paddingBuilder = new CSharpPaddingBuilder(host); - - // Act - var padding = paddingBuilder.CalculatePadding(span, 1); - - // Assert - Assert.Equal(5, padding); - } - - [Theory] - [MemberData("SpacePropertyData")] - public void CalculatePaddingForIfSpanWith5Spaces(bool designTime, bool isIndentingWithTabs, int tabSize) - { - // Arrange - var host = CreateHost(designTime, isIndentingWithTabs, tabSize); - - var span = GenerateSpan(@" @if (true)", SpanKind.Code, 2, "if (true)"); - - var paddingBuilder = new CSharpPaddingBuilder(host); - - // Act - var padding = paddingBuilder.CalculatePadding(span, 1); - - // Assert - Assert.Equal(4, padding); - } - - // 4 padding should result in 4 spaces. Where in the previous test (5 spaces) should result in 1 tab. - [Theory] - [InlineData(true, false, 4, 0, 4)] - [InlineData(true, false, 2, 0, 4)] - [InlineData(true, true, 4, 1, 0)] - [InlineData(true, true, 2, 2, 0)] - [InlineData(true, true, 1, 4, 0)] - [InlineData(true, true, 0, 4, 0)] - [InlineData(true, true, 3, 1, 1)] - - // in non design time mode padding falls back to spaces to keep runtime code identical to v2 code. - [InlineData(false, true, 4, 0, 5)] - [InlineData(false, true, 2, 0, 5)] - - [InlineData(false, false, 4, 0, 5)] - [InlineData(false, false, 2, 0, 5)] - public void VerifyPaddingForIfSpanWith4Spaces(bool designTime, bool isIndentingWithTabs, int tabSize, int numTabs, int numSpaces) - { - // Arrange - var host = CreateHost(designTime, isIndentingWithTabs, tabSize); - - // no new lines involved - var spanFlat = GenerateSpan(" @if (true)", SpanKind.Code, 2, "if (true)"); - var spanNewlines = GenerateSpan("\t

" + Environment.NewLine + " @if (true)", SpanKind.Code, 5, "if (true)"); - - var paddingBuilder = new CSharpPaddingBuilder(host); - - // Act - var paddingFlat = paddingBuilder.BuildStatementPadding(spanFlat); - var paddingNewlines = paddingBuilder.BuildStatementPadding(spanNewlines); - - // Assert - var code = " if (true)"; - VerifyPadded(numTabs, numSpaces, code, paddingFlat); - VerifyPadded(numTabs, numSpaces, code, paddingNewlines); - } - - [Theory] - [InlineData(true, false, 4, 0, 8)] - [InlineData(true, false, 2, 0, 4)] - [InlineData(true, true, 4, 2, 0)] - [InlineData(true, true, 2, 2, 0)] - [InlineData(true, true, 1, 2, 0)] - [InlineData(true, true, 0, 2, 0)] - [InlineData(true, true, 3, 2, 0)] - - // in non design time mode padding falls back to spaces to keep runtime code identical to v2 code. - [InlineData(false, true, 4, 0, 9)] - [InlineData(false, true, 2, 0, 5)] - - [InlineData(false, false, 4, 0, 9)] - [InlineData(false, false, 2, 0, 5)] - public void VerifyPaddingForIfSpanWithTwoTabs(bool designTime, bool isIndentingWithTabs, int tabSize, int numTabs, int numSpaces) - { - // Arrange - var host = CreateHost(designTime, isIndentingWithTabs, tabSize); - - // no new lines involved - var spanFlat = GenerateSpan("\t\t@if (true)", SpanKind.Code, 2, "if (true)"); - var spanNewlines = GenerateSpan("\t
" + Environment.NewLine + "\t\t@if (true)", SpanKind.Code, 5, "if (true)"); - - var paddingBuilder = new CSharpPaddingBuilder(host); - - // Act - var paddingFlat = paddingBuilder.BuildStatementPadding(spanFlat); - var paddingNewlines = paddingBuilder.BuildStatementPadding(spanNewlines); - - // Assert - var code = " if (true)"; - VerifyPadded(numTabs, numSpaces, code, paddingFlat); - VerifyPadded(numTabs, numSpaces, code, paddingNewlines); - } - - [Theory] - [InlineData(true, false, 4, 0, 8)] - [InlineData(true, false, 2, 0, 4)] - [InlineData(true, true, 4, 2, 0)] - [InlineData(true, true, 2, 2, 0)] - [InlineData(true, true, 1, 2, 0)] - [InlineData(true, true, 0, 2, 0)] - - // in non design time mode padding falls back to spaces to keep runtime code identical to v2 code. - [InlineData(false, true, 4, 0, 9)] - [InlineData(false, true, 2, 0, 5)] - - [InlineData(false, false, 4, 0, 9)] - [InlineData(false, false, 2, 0, 5)] - public void CalculatePaddingForOpenedIf(bool designTime, bool isIndentingWithTabs, int tabSize, int numTabs, int numSpaces) - { - // Arrange - var host = CreateHost(designTime, isIndentingWithTabs, tabSize); - - var text = string.Format("{0}{0}{0}\t\t@if (true) {{ {0}{0}", Environment.NewLine); - - var code = "if (true) { " + Environment.NewLine; - var span = GenerateSpan(text, SpanKind.Code, 7, code); - - var paddingBuilder = new CSharpPaddingBuilder(host); - - // Act - var padding = paddingBuilder.BuildStatementPadding(span); - - // Assert - VerifyPadded(numTabs, numSpaces, code, padding); - } - - private static void VerifyPadded(int numTabs, int numSpaces, string code, string padding) - { - var padded = padding + code; - var expectedPadding = new string('\t', numTabs) + new string(' ', numSpaces); - - Assert.Equal(expectedPadding, padding); - Assert.Equal(numTabs + numSpaces + code.Length, padded.Length); - Assert.Equal(numSpaces + numTabs, padding.Length); - } - - public static IEnumerable SpacePropertyData - { - get - { - yield return new object[] { true, false, 4 }; - yield return new object[] { true, false, 2 }; - yield return new object[] { false, true, 4 }; - yield return new object[] { false, true, 2 }; - yield return new object[] { false, false, 4 }; - yield return new object[] { false, false, 2 }; - yield return new object[] { true, true, 4 }; - yield return new object[] { true, true, 2 }; - yield return new object[] { true, true, 1 }; - yield return new object[] { true, true, 0 }; - } - } - - private static RazorEngineHost CreateHost(bool designTime, bool isIndentingWithTabs = false, int tabSize = 4) - { - return new RazorEngineHost(new CSharpRazorCodeLanguage()) - { - DesignTimeMode = designTime, - IsIndentingWithTabs = isIndentingWithTabs, - TabSize = tabSize, - }; - } - - private static Span GenerateSpan(string text, SpanKind spanKind, int spanIndex, string spanText) - { - var spans = GenerateSpans(text, spanKind, spanIndex, spanText); - - return spans[spanIndex]; - } - - 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; - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpRazorCodeGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpRazorCodeGeneratorTest.cs deleted file mode 100644 index b437517783..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpRazorCodeGeneratorTest.cs +++ /dev/null @@ -1,636 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.CodeGenerators; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CSharpRazorCodeGeneratorTest : RazorCodeGeneratorTest - { - protected override string FileExtension - { - get { return "cshtml"; } - } - - protected override string LanguageName - { - get { return "CS"; } - } - - protected override string BaselineExtension - { - get { return "cs"; } - } - - private const string TestPhysicalPath = @"C:\Bar.cshtml"; - - [Fact] - public void ConstructorRequiresNonNullClassName() - { - Assert.Throws( - "className", - () => new RazorChunkGenerator(null, TestRootNamespaceName, TestPhysicalPath, CreateHost())); - } - - [Fact] - public void ConstructorRequiresNonEmptyClassName() - { - Assert.Throws( - "className", - () => new RazorChunkGenerator(string.Empty, TestRootNamespaceName, TestPhysicalPath, CreateHost())); - } - - [Fact] - public void ConstructorAllowsEmptyRootNamespaceName() - { - new RazorChunkGenerator("Foo", string.Empty, TestPhysicalPath, CreateHost()); - } - - [Theory] - [InlineData("StringLiterals")] - [InlineData("NestedCSharp")] - [InlineData("NullConditionalExpressions")] - [InlineData("NestedCodeBlocks")] - [InlineData("CodeBlock")] - [InlineData("ExplicitExpression")] - [InlineData("MarkupInCodeBlock")] - [InlineData("Blocks")] - [InlineData("ImplicitExpression")] - [InlineData("Imports")] - [InlineData("ExpressionsInCode")] - [InlineData("FunctionsBlock")] - [InlineData("FunctionsBlock_Tabs")] - [InlineData("Templates")] - [InlineData("Sections")] - [InlineData("RazorComments")] - [InlineData("InlineBlocks")] - [InlineData("ConditionalAttributes")] - [InlineData("Await")] - [InlineData("CodeBlockWithTextElement")] - [InlineData("ExplicitExpressionWithMarkup")] - public void CSharpChunkGeneratorCorrectlyGeneratesRunTimeCode(string testType) - { - RunTest(testType); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesMappingsForNestedCSharp() - { - RunTest( - "NestedCSharp", - "NestedCSharp.DesignTime", - designTimeMode: true, - tabTest: TabTest.NoTabs, - expectedDesignTimePragmas: new List - { - BuildLineMapping( - documentAbsoluteIndex: 2, - documentLineIndex: 0, - generatedAbsoluteIndex: 522, - generatedLineIndex: 22, - characterOffsetIndex: 2, - contentLength: 6), - BuildLineMapping( - documentAbsoluteIndex: 9, - documentLineIndex: 1, - documentCharacterOffsetIndex: 5, - generatedAbsoluteIndex: 598, - generatedLineIndex: 29, - generatedCharacterOffsetIndex: 4, - contentLength: 53), - BuildLineMapping( - documentAbsoluteIndex: 82, - documentLineIndex: 4, - generatedAbsoluteIndex: 730, - generatedLineIndex: 37, - characterOffsetIndex: 13, - contentLength: 16), - BuildLineMapping( - documentAbsoluteIndex: 115, - documentLineIndex: 5, - generatedAbsoluteIndex: 825, - generatedLineIndex: 42, - characterOffsetIndex: 14, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 122, - documentLineIndex: 6, - generatedAbsoluteIndex: 903, - generatedLineIndex: 49, - characterOffsetIndex: 5, - contentLength: 2), - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesMappingsForNullConditionalOperator() - { - RunTest("NullConditionalExpressions", - "NullConditionalExpressions.DesignTime", - designTimeMode: true, - tabTest: TabTest.NoTabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 564, 22, 2, 6), - BuildLineMapping(9, 1, 5, 656, 29, 6, 13), - BuildLineMapping(22, 1, 766, 34, 18, 6), - BuildLineMapping(29, 2, 5, 858, 41, 6, 22), - BuildLineMapping(51, 2, 986, 46, 27, 6), - BuildLineMapping(58, 3, 5, 1078, 53, 6, 26), - BuildLineMapping(84, 3, 1214, 58, 31, 6), - BuildLineMapping(91, 4, 5, 1306, 65, 6, 41), - BuildLineMapping(132, 4, 1472, 70, 46, 2), - BuildLineMapping(140, 7, 1, 1558, 76, 6, 13), - BuildLineMapping(156, 8, 1, 1656, 81, 6, 22), - BuildLineMapping(181, 9, 1, 1764, 86, 6, 26), - BuildLineMapping(210, 10, 1, 1876, 91, 6, 41) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesMappingsForAwait() - { - RunTest("Await", - "Await.DesignTime", - designTimeMode: true, - tabTest: TabTest.Tabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(12, 0, 12, 173, 9, 0, 76), - BuildLineMapping(192, 9, 39, 646, 31, 15, 11), - BuildLineMapping(247, 10, 38, 730, 36, 14, 11), - BuildLineMapping(304, 11, 39, 812, 41, 12, 14), - BuildLineMapping(371, 12, 46, 899, 47, 13, 1), - BuildLineMapping(376, 12, 51, 978, 53, 18, 11), - BuildLineMapping(391, 12, 66, 1066, 58, 18, 1), - BuildLineMapping(448, 13, 49, 1146, 64, 19, 5), - BuildLineMapping(578, 18, 42, 1225, 69, 15, 15), - BuildLineMapping(650, 19, 51, 1317, 74, 18, 19), - BuildLineMapping(716, 20, 41, 1412, 79, 17, 22), - BuildLineMapping(787, 21, 42, 1505, 84, 12, 39), - BuildLineMapping(884, 22, 51, 1619, 90, 15, 21), - BuildLineMapping(961, 23, 49, 1713, 96, 13, 1), - BuildLineMapping(966, 23, 54, 1792, 102, 18, 27), - BuildLineMapping(997, 23, 85, 1900, 107, 22, 1), - BuildLineMapping(1057, 24, 52, 1980, 113, 19, 19) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesMappingsForSimpleUnspacedIf() - { - RunTest("SimpleUnspacedIf", - "SimpleUnspacedIf.DesignTime.Tabs", - designTimeMode: true, - tabTest: TabTest.Tabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(1, 0, 1, 532, 22, 0, 15), - BuildLineMapping(27, 2, 12, 623, 30, 6, 3) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesMappingsForRazorCommentsAtDesignTime() - { - RunTest("RazorComments", "RazorComments.DesignTime", designTimeMode: true, tabTest: TabTest.NoTabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(81, 3, 525, 22, 2, 6), - BuildLineMapping(122, 4, 39, 636, 29, 38, 22), - BuildLineMapping(173, 5, 49, 773, 36, 48, 58), - BuildLineMapping(238, 11, 899, 45, 2, 24), - BuildLineMapping(310, 12, 1036, 51, 45, 3), - BuildLineMapping(323, 14, 2, 1112, 56, 6, 1), - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGenerateMappingForOpenedCurlyIf() - { - OpenedIf(withTabs: true); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGenerateMappingForOpenedCurlyIfSpaces() - { - OpenedIf(withTabs: false); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesImportStatementsAtDesignTime() - { - RunTest("Imports", "Imports.DesignTime", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List() - { - BuildLineMapping(1, 0, 1, 51, 3, 0, 15), - BuildLineMapping(19, 1, 1, 132, 9, 0, 32), - BuildLineMapping(54, 2, 1, 230, 15, 0, 12), - BuildLineMapping(71, 4, 1, 308, 21, 0, 19), - BuildLineMapping(93, 5, 1, 393, 27, 0, 27), - BuildLineMapping(123, 6, 1, 486, 33, 0, 41), - BuildLineMapping(197, 8, 1057, 57, 29, 21), - BuildLineMapping(259, 9, 1174, 62, 35, 20) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesFunctionsBlocksAtDesignTime() - { - RunTest("FunctionsBlock", - "FunctionsBlock.DesignTime", - designTimeMode: true, - tabTest: TabTest.NoTabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(12, 0, 12, 191, 9, 0, 4), - BuildLineMapping(33, 4, 12, 259, 15, 0, 104), - BuildLineMapping(167, 11, 788, 37, 25, 11) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesFunctionsBlocksAtDesignTimeTabs() - { - RunTest("FunctionsBlock", - "FunctionsBlock.DesignTime.Tabs", - designTimeMode: true, - tabTest: TabTest.Tabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(12, 0, 12, 191, 9, 0, 4), - BuildLineMapping(33, 4, 12, 259, 15, 0, 104), - BuildLineMapping(167, 11, 25, 776, 37, 13, 11) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesMinimalFunctionsBlocksAtDesignTimeTabs() - { - RunTest("FunctionsBlockMinimal", - "FunctionsBlockMinimal.DesignTime.Tabs", - designTimeMode: true, - tabTest: TabTest.Tabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(16, 2, 12, 205, 9, 0, 55) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesHiddenSpansWithinCode() - { - RunTest("HiddenSpansInCode", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List - { - BuildLineMapping(2, 0, 537, 22, 2, 6), - BuildLineMapping(9, 1, 619, 29, 5, 5) - }); - } - - [Fact] - public void CSharpChunkGeneratorGeneratesCodeWithParserErrorsInDesignTimeMode() - { - RunTest("ParserError", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 519, 22, 2, 31) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesInheritsAtRuntime() - { - RunTest("Inherits", baselineName: "Inherits.Runtime"); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesInheritsAtDesigntime() - { - RunTest("Inherits", baselineName: "Inherits.Designtime", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List() - { - BuildLineMapping(20, 2, 321, 12, 10, 25), - BuildLineMapping(1, 0, 1, 662, 27, 6, 5) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForUnfinishedExpressionsInCode() - { - RunTest("UnfinishedExpressionInCode", tabTest: TabTest.NoTabs, designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 564, 22, 2, 2), - BuildLineMapping(5, 1, 1, 650, 28, 6, 9), - BuildLineMapping(14, 1, 748, 33, 10, 2) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForUnfinishedExpressionsInCodeTabs() - { - RunTest("UnfinishedExpressionInCode", - "UnfinishedExpressionInCode.Tabs", - tabTest: TabTest.Tabs, - designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 564, 22, 2, 2), - BuildLineMapping(5, 1, 1, 650, 28, 6, 9), - BuildLineMapping(14, 1, 10, 742, 33, 4, 2) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasMarkupAndExpressions() - { - RunTest("DesignTime", - designTimeMode: true, - tabTest: TabTest.NoTabs, - expectedDesignTimePragmas: new List() - { - BuildLineMapping( - documentAbsoluteIndex: 20, - documentLineIndex: 1, - documentCharacterOffsetIndex: 13, - generatedAbsoluteIndex: 526, - generatedLineIndex: 22, - generatedCharacterOffsetIndex: 12, - contentLength: 36), - BuildLineMapping( - documentAbsoluteIndex: 74, - documentLineIndex: 2, - generatedAbsoluteIndex: 648, - generatedLineIndex: 29, - characterOffsetIndex: 22, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 79, - documentLineIndex: 2, - generatedAbsoluteIndex: 739, - generatedLineIndex: 34, - characterOffsetIndex: 27, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 113, - documentLineIndex: 7, - documentCharacterOffsetIndex: 2, - generatedAbsoluteIndex: 824, - generatedLineIndex: 41, - generatedCharacterOffsetIndex: 6, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 129, - documentLineIndex: 8, - documentCharacterOffsetIndex: 1, - generatedAbsoluteIndex: 905, - generatedLineIndex: 46, - generatedCharacterOffsetIndex: 6, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 142, - documentLineIndex: 8, - generatedAbsoluteIndex: 1010, - generatedLineIndex: 48, - characterOffsetIndex: 14, - contentLength: 3), - BuildLineMapping( - documentAbsoluteIndex: 204, - documentLineIndex: 13, - documentCharacterOffsetIndex: 5, - generatedAbsoluteIndex: 1196, - generatedLineIndex: 60, - generatedCharacterOffsetIndex: 6, - contentLength: 3), - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForExplicitExpressionContainingMarkup() - { - RunTest( - "ExplicitExpressionWithMarkup", - "ExplicitExpressionWithMarkup.DesignTime", - designTimeMode: true, - expectedDesignTimePragmas: new List()); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForImplicitExpressionStartedAtEOF() - { - RunTest("ImplicitExpressionAtEOF", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(19, 2, 1, 559, 22, 6, 0) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForExplicitExpressionStartedAtEOF() - { - RunTest("ExplicitExpressionAtEOF", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(20, 2, 2, 559, 22, 6, 0) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForCodeBlockStartedAtEOF() - { - RunTest("CodeBlockAtEOF", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 528, 22, 2, 0) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpression() - { - RunTest("EmptyImplicitExpression", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(19, 2, 1, 559, 22, 6, 0) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpressionInCode() - { - RunTest("EmptyImplicitExpressionInCode", tabTest: TabTest.NoTabs, designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 573, 22, 2, 6), - BuildLineMapping(9, 1, 5, 668, 29, 6, 0), - BuildLineMapping(9, 1, 755, 34, 5, 2) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpressionInCodeTabs() - { - RunTest("EmptyImplicitExpressionInCode", - "EmptyImplicitExpressionInCode.Tabs", - tabTest: TabTest.Tabs, - designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(2, 0, 573, 22, 2, 6), - BuildLineMapping(9, 1, 5, 668, 29, 6, 0), - BuildLineMapping(9, 1, 5, 752, 34, 2, 2) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyExplicitExpression() - { - RunTest("EmptyExplicitExpression", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(20, 2, 2, 559, 22, 6, 0) - }); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyCodeBlock() - { - RunTest("EmptyCodeBlock", designTimeMode: true, expectedDesignTimePragmas: new List() - { - BuildLineMapping(20, 2, 528, 22, 2, 0) - }); - } - - [Fact] - public void CSharpChunkGeneratorDoesNotRenderLinePragmasIfGenerateLinePragmasIsSetToFalse() - { - RunTest("NoLinePragmas", generatePragmas: false); - } - - [Fact] - public void CSharpChunkGeneratorCorrectlyInstrumentsRazorCodeWhenInstrumentationRequested() - { - RunTest("Instrumented", hostConfig: host => - { - host.InstrumentedSourceFilePath = string.Format("~/{0}.cshtml", host.DefaultClassName); - - return host; - }); - } - - [Fact] - public void CSharpChunkGeneratorGeneratesUrlsCorrectlyWithCommentsAndQuotes() - { - RunTest("HtmlCommentWithQuote_Single", - tabTest: TabTest.NoTabs); - - RunTest("HtmlCommentWithQuote_Double", - tabTest: TabTest.NoTabs); - } - - [Fact] - public void CSharpChunkGenerator_CorrectlyGeneratesAttributes_AtDesignTime() - { - var expectedDesignTimePragmas = new[] - { - BuildLineMapping(2, 0, 549, 22, 2, 48), - BuildLineMapping(66, 3, 692, 31, 20, 6), - BuildLineMapping(83, 4, 788, 38, 15, 3), - BuildLineMapping(90, 4, 887, 43, 22, 6), - BuildLineMapping(111, 5, 987, 50, 19, 3), - BuildLineMapping(118, 5, 1090, 55, 26, 6), - BuildLineMapping(135, 6, 1186, 62, 15, 3), - BuildLineMapping(146, 6, 1289, 67, 26, 6), - BuildLineMapping(185, 7, 1407, 74, 37, 2), - BuildLineMapping(191, 7, 1526, 79, 43, 6), - BuildLineMapping(234, 8, 1648, 86, 41, 2), - BuildLineMapping(240, 8, 1771, 91, 47, 6), - BuildLineMapping(257, 9, 15, 1867, 98, 14, 18), - BuildLineMapping(276, 9, 1995, 104, 34, 3), - BuildLineMapping(279, 9, 2110, 109, 37, 2), - BuildLineMapping(285, 9, 2231, 115, 43, 6), - BuildLineMapping(309, 10, 2335, 122, 22, 6), - BuildLineMapping(329, 11, 2435, 129, 18, 44), - BuildLineMapping(407, 11, 2650, 134, 96, 6), - BuildLineMapping(427, 12, 2750, 141, 18, 60), - BuildLineMapping(521, 12, 2997, 146, 112, 6), - BuildLineMapping(638, 13, 3194, 153, 115, 2) - }; - - RunTest("ConditionalAttributes", - baselineName: "ConditionalAttributes.DesignTime", - designTimeMode: true, - tabTest: TabTest.NoTabs, - expectedDesignTimePragmas: expectedDesignTimePragmas); - } - - private void OpenedIf(bool withTabs) - { - var tabOffsetForMapping = 7; - - // where the test is running with tabs, the offset into the CS buffer changes for the whitespace mapping - // with spaces we get 7xspace -> offset of 8 (column = offset+1) - // with tabs we get tab + 3 spaces -> offset of 4 chars + 1 = 5 - if (withTabs) - { - tabOffsetForMapping -= 3; - } - - RunTest("OpenedIf", - "OpenedIf.DesignTime" + (withTabs ? ".Tabs" : ""), - designTimeMode: true, - tabTest: withTabs ? TabTest.Tabs : TabTest.NoTabs, - spans: new TestSpan[] - { - new TestSpan(SpanKind.Markup, 0, 6), - new TestSpan(SpanKind.Markup, 6, 8), - new TestSpan(SpanKind.Markup, 8, 14), - new TestSpan(SpanKind.Markup, 14, 16), - new TestSpan(SpanKind.Transition, 16, 17), - new TestSpan(SpanKind.Code, 17, 31), - new TestSpan(SpanKind.Markup, 31, 38), - new TestSpan(SpanKind.Code, 38, 40), - new TestSpan(SpanKind.Markup, 40, 47), - new TestSpan(SpanKind.Code, 47, 47), - }, - expectedDesignTimePragmas: new List() - { - BuildLineMapping(17, 2, 1, 508, 22, 0, 14), - BuildLineMapping(38, 3, 7, 582 + tabOffsetForMapping, 28, tabOffsetForMapping, 2), - // Multiply the tab offset absolute index by 2 to account for the first mapping - BuildLineMapping(47, 4, 7, 644 + tabOffsetForMapping * 2, 34, tabOffsetForMapping, 0) - }); - } - - protected static LineMapping BuildLineMapping(int documentAbsoluteIndex, - int documentLineIndex, - int generatedAbsoluteIndex, - int generatedLineIndex, - int characterOffsetIndex, - int contentLength) - { - return BuildLineMapping(documentAbsoluteIndex, - documentLineIndex, - characterOffsetIndex, - generatedAbsoluteIndex, - generatedLineIndex, - characterOffsetIndex, - contentLength); - } - - protected static LineMapping BuildLineMapping(int documentAbsoluteIndex, - int documentLineIndex, - int documentCharacterOffsetIndex, - int generatedAbsoluteIndex, - int generatedLineIndex, - int generatedCharacterOffsetIndex, - int contentLength) - { - return new LineMapping( - documentLocation: new MappingLocation( - new SourceLocation(documentAbsoluteIndex, - documentLineIndex, - documentCharacterOffsetIndex), - contentLength), - generatedLocation: new MappingLocation( - new SourceLocation(generatedAbsoluteIndex, - generatedLineIndex, - generatedCharacterOffsetIndex), - contentLength) - ); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingTest.cs deleted file mode 100644 index 9187f84d07..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingTest.cs +++ /dev/null @@ -1,2100 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -#if NETCOREAPP1_1 -using System.Reflection; -#endif -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Testing.xunit; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class CSharpTagHelperRenderingTest : TagHelperTestBase - { - private static IEnumerable DefaultPAndInputTagHelperDescriptors { get; } - = BuildPAndInputTagHelperDescriptors(prefix: string.Empty); - private static IEnumerable PrefixedPAndInputTagHelperDescriptors { get; } - = BuildPAndInputTagHelperDescriptors(prefix: "THS"); - - private static IEnumerable CssSelectorTagHelperDescriptors - { - get - { - var inputTypePropertyInfo = typeof(TestType).GetProperty("Type"); - var inputCheckedPropertyInfo = typeof(TestType).GetProperty("Checked"); - - return new[] - { - new TagHelperDescriptor - { - TagName = "a", - TypeName = "TestNamespace.ATagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "href", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "~/", - ValueComparison = TagHelperRequiredAttributeValueComparison.FullMatch, - } - }, - }, - new TagHelperDescriptor - { - TagName = "a", - TypeName = "TestNamespace.ATagHelperMultipleSelectors", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "href", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "~/", - ValueComparison = TagHelperRequiredAttributeValueComparison.PrefixMatch, - }, - new TagHelperRequiredAttributeDescriptor - { - Name = "href", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "?hello=world", - ValueComparison = TagHelperRequiredAttributeValueComparison.SuffixMatch, - } - }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "type", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "text", - ValueComparison = TagHelperRequiredAttributeValueComparison.FullMatch, - } - }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "ty", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - } - }, - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "href", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "~/", - ValueComparison = TagHelperRequiredAttributeValueComparison.PrefixMatch, - } - }, - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper2", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "type", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - } - }, - } - }; - } - } - - private static IEnumerable EnumTagHelperDescriptors - { - get - { - return new[] - { - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "catch-all", - PropertyName = "CatchAll", - IsEnum = true, - TypeName = typeof(MyEnum).FullName - }, - } - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "value", - PropertyName = "Value", - IsEnum = true, - TypeName = typeof(MyEnum).FullName - }, - } - }, - }; - } - } - - private static IEnumerable SymbolBoundTagHelperDescriptors - { - get - { - return new[] - { - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "[item]", - PropertyName = "ListItems", - TypeName = typeof(List).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "[(item)]", - PropertyName = "ArrayItems", - TypeName = typeof(string[]).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "(click)", - PropertyName = "Event1", - TypeName = typeof(Action).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "(^click)", - PropertyName = "Event2", - TypeName = typeof(Action).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "*something", - PropertyName = "StringProperty1", - TypeName = typeof(string).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "#local", - PropertyName = "StringProperty2", - TypeName = typeof(string).FullName - }, - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "bound" } }, - }, - }; - } - } - - private static IEnumerable MinimizedTagHelpers_Descriptors - { - get - { - return new[] - { - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "catchall-bound-string", - PropertyName = "BoundRequiredString", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "catchall-unbound-required" } - }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "input-bound-required-string", - PropertyName = "BoundRequiredString", - TypeName = typeof(string).FullName, - IsStringProperty = true - }, - new TagHelperAttributeDescriptor - { - Name = "input-bound-string", - PropertyName = "BoundString", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "input-bound-required-string" }, - new TagHelperRequiredAttributeDescriptor { Name = "input-unbound-required" } - }, - } - }; - } - } - - private static IEnumerable DynamicAttributeTagHelpers_Descriptors - { - get - { - return new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "bound", - PropertyName = "Bound", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - } - } - }; - } - } - - private static IEnumerable DuplicateTargetTagHelperDescriptors - { - get - { - var inputTypePropertyInfo = typeof(TestType).GetProperty("Type"); - var inputCheckedPropertyInfo = typeof(TestType).GetProperty("Checked"); - return new[] - { - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", inputCheckedPropertyInfo) - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "type" } }, - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", inputCheckedPropertyInfo) - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "checked" } }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", inputCheckedPropertyInfo) - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "type" } }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", inputCheckedPropertyInfo) - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "checked" } }, - } - }; - } - } - - private static IEnumerable AttributeTargetingTagHelperDescriptors - { - get - { - var inputTypePropertyInfo = typeof(TestType).GetProperty("Type"); - var inputCheckedPropertyInfo = typeof(TestType).GetProperty("Checked"); - return new[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "TestNamespace.PTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "class" } }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo) - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "type" } }, - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", inputCheckedPropertyInfo) - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "type" }, - new TagHelperRequiredAttributeDescriptor { Name = "checked" } - }, - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "TestNamespace.CatchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "catchAll" } }, - } - }; - } - } - - private static IEnumerable PrefixedAttributeTagHelperDescriptors - { - get - { - return new[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper1", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "int-prefix-grabber", - PropertyName = "IntProperty", - TypeName = typeof(int).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "int-dictionary", - PropertyName = "IntDictionaryProperty", - TypeName = typeof(IDictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "string-dictionary", - PropertyName = "StringDictionaryProperty", - TypeName = "Namespace.DictionaryWithoutParameterlessConstructor" - }, - new TagHelperAttributeDescriptor - { - Name = "string-prefix-grabber", - PropertyName = "StringProperty", - TypeName = typeof(string).FullName, - IsStringProperty = true - }, - new TagHelperAttributeDescriptor - { - Name = "int-prefix-", - PropertyName = "IntDictionaryProperty", - TypeName = typeof(int).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "string-prefix-", - PropertyName = "StringDictionaryProperty", - TypeName = typeof(string).FullName, - IsIndexer = true, - IsStringProperty = true - } - } - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "int-dictionary", - PropertyName = "IntDictionaryProperty", - TypeName = typeof(int).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "string-dictionary", - PropertyName = "StringDictionaryProperty", - TypeName = "Namespace.DictionaryWithoutParameterlessConstructor" - }, - new TagHelperAttributeDescriptor - { - Name = "int-prefix-", - PropertyName = "IntDictionaryProperty", - TypeName = typeof(int).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "string-prefix-", - PropertyName = "StringDictionaryProperty", - TypeName = typeof(string).FullName, - IsIndexer = true, - IsStringProperty = true - } - } - } - }; - } - } - - public static TheoryData TagHelperDescriptorFlowTestData - { - get - { - return new TheoryData< - string, // Test name - string, // Baseline name - IEnumerable, // TagHelperDescriptors provided - IEnumerable, // Expected TagHelperDescriptors - bool> // Design time mode. - { - { - "SingleTagHelper", - "SingleTagHelper", - DefaultPAndInputTagHelperDescriptors, - DefaultPAndInputTagHelperDescriptors, - false - }, - { - "SingleTagHelper", - "SingleTagHelper.DesignTime", - DefaultPAndInputTagHelperDescriptors, - DefaultPAndInputTagHelperDescriptors, - true - }, - { - "BasicTagHelpers", - "BasicTagHelpers", - DefaultPAndInputTagHelperDescriptors, - DefaultPAndInputTagHelperDescriptors, - false - }, - { - "DuplicateTargetTagHelper", - "DuplicateTargetTagHelper", - DuplicateTargetTagHelperDescriptors, - DuplicateTargetTagHelperDescriptors, - false - }, - { - "BasicTagHelpers", - "BasicTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - DefaultPAndInputTagHelperDescriptors, - true - }, - { - "BasicTagHelpers.RemoveTagHelper", - "BasicTagHelpers.RemoveTagHelper", - DefaultPAndInputTagHelperDescriptors, - Enumerable.Empty(), - false - }, - { - "BasicTagHelpers.Prefixed", - "BasicTagHelpers.Prefixed", - PrefixedPAndInputTagHelperDescriptors, - PrefixedPAndInputTagHelperDescriptors, - false - }, - { - "BasicTagHelpers.Prefixed", - "BasicTagHelpers.Prefixed.DesignTime", - PrefixedPAndInputTagHelperDescriptors, - PrefixedPAndInputTagHelperDescriptors, - true - }, - { - "ComplexTagHelpers", - "ComplexTagHelpers", - DefaultPAndInputTagHelperDescriptors, - DefaultPAndInputTagHelperDescriptors, - false - }, - { - "ComplexTagHelpers", - "ComplexTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - DefaultPAndInputTagHelperDescriptors, - true - }, - { - "AttributeTargetingTagHelpers", - "AttributeTargetingTagHelpers", - AttributeTargetingTagHelperDescriptors, - AttributeTargetingTagHelperDescriptors, - false - }, - { - "AttributeTargetingTagHelpers", - "AttributeTargetingTagHelpers.DesignTime", - AttributeTargetingTagHelperDescriptors, - AttributeTargetingTagHelperDescriptors, - true - }, - { - "MinimizedTagHelpers", - "MinimizedTagHelpers", - MinimizedTagHelpers_Descriptors, - MinimizedTagHelpers_Descriptors, - false - }, - { - "MinimizedTagHelpers", - "MinimizedTagHelpers.DesignTime", - MinimizedTagHelpers_Descriptors, - MinimizedTagHelpers_Descriptors, - true - } - }; - } - } - - [Theory] - [MemberData(nameof(TagHelperDescriptorFlowTestData))] - public void TagHelpers_RenderingOutputFlowsFoundTagHelperDescriptors( - string testName, - string baselineName, - IEnumerable tagHelperDescriptors, - IEnumerable expectedTagHelperDescriptors, - bool designTimeMode) - { - RunTagHelperTest( - testName, - baseLineName: baselineName, - tagHelperDescriptors: tagHelperDescriptors, - onResults: (results) => - { - Assert.Equal( - expectedTagHelperDescriptors, - results.TagHelperDescriptors, - TagHelperDescriptorComparer.Default); - }, - designTimeMode: designTimeMode); - } - - public static TheoryData DesignTimeTagHelperTestData - { - get - { - // Test resource name, baseline resource name, expected TagHelperDescriptors, expected LineMappings - return new TheoryData, IList> - { - { - "SingleTagHelper", - "SingleTagHelper.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 372, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 61, - documentLineIndex: 2, - documentCharacterOffsetIndex: 28, - generatedAbsoluteIndex: 892, - generatedLineIndex: 27, - generatedCharacterOffsetIndex: 33, - contentLength: 4), - } - }, - { - "BasicTagHelpers", - "BasicTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new[] - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 371, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 47, - contentLength: 17), - BuildLineMapping( - documentAbsoluteIndex: 220, - documentLineIndex: 5, - generatedAbsoluteIndex: 1293, - generatedLineIndex: 31, - characterOffsetIndex: 38, - contentLength: 23), - BuildLineMapping( - documentAbsoluteIndex: 303, - documentLineIndex: 6, - documentCharacterOffsetIndex: 40, - generatedAbsoluteIndex: 1934, - generatedLineIndex: 42, - generatedCharacterOffsetIndex: 42, - contentLength: 4), - } - }, - { - "BasicTagHelpers.Prefixed", - "BasicTagHelpers.Prefixed.DesignTime", - PrefixedPAndInputTagHelperDescriptors, - new[] - { - BuildLineMapping( - documentAbsoluteIndex: 17, - documentLineIndex: 0, - documentCharacterOffsetIndex: 17, - generatedAbsoluteIndex: 380, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 47, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 38, - documentLineIndex: 1, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 436, - generatedLineIndex: 13, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 224, - documentLineIndex: 7, - generatedAbsoluteIndex: 1437, - generatedLineIndex: 33, - characterOffsetIndex: 43, - contentLength: 4), - } - }, - { - "ComplexTagHelpers", - "ComplexTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 374, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 34, - documentLineIndex: 2, - documentCharacterOffsetIndex: 1, - generatedAbsoluteIndex: 958, - generatedLineIndex: 28, - generatedCharacterOffsetIndex: 0, - contentLength: 48), - BuildLineMapping( - documentAbsoluteIndex: 209, - documentLineIndex: 9, - generatedAbsoluteIndex: 1076, - generatedLineIndex: 37, - characterOffsetIndex: 0, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 222, - documentLineIndex: 9, - documentCharacterOffsetIndex: 13, - generatedAbsoluteIndex: 1172, - generatedLineIndex: 43, - generatedCharacterOffsetIndex: 12, - contentLength: 27), - BuildLineMapping( - documentAbsoluteIndex: 350, - documentLineIndex: 12, - generatedAbsoluteIndex: 1720, - generatedLineIndex: 55, - characterOffsetIndex: 0, - contentLength: 48), - BuildLineMapping( - documentAbsoluteIndex: 444, - documentLineIndex: 15, - generatedAbsoluteIndex: 2092, - generatedLineIndex: 65, - characterOffsetIndex: 46, - contentLength: 8), - BuildLineMapping( - documentAbsoluteIndex: 461, - documentLineIndex: 15, - generatedAbsoluteIndex: 2388, - generatedLineIndex: 72, - characterOffsetIndex: 63, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 505, - documentLineIndex: 16, - generatedAbsoluteIndex: 2797, - generatedLineIndex: 80, - characterOffsetIndex: 31, - contentLength: 30), - BuildLineMapping( - documentAbsoluteIndex: 572, - documentLineIndex: 17, - documentCharacterOffsetIndex: 30, - generatedAbsoluteIndex: 3289, - generatedLineIndex: 89, - generatedCharacterOffsetIndex: 29, - contentLength: 10), - BuildLineMapping( - documentAbsoluteIndex: 604, - documentLineIndex: 17, - documentCharacterOffsetIndex: 62, - generatedAbsoluteIndex: 3432, - generatedLineIndex: 95, - generatedCharacterOffsetIndex: 61, - contentLength: 9), - BuildLineMapping( - documentAbsoluteIndex: 635, - documentLineIndex: 17, - documentCharacterOffsetIndex: 93, - generatedAbsoluteIndex: 3604, - generatedLineIndex: 101, - generatedCharacterOffsetIndex: 91, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 641, - documentLineIndex: 18, - generatedAbsoluteIndex: 3832, - generatedLineIndex: 109, - characterOffsetIndex: 0, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 161, - documentLineIndex: 7, - generatedAbsoluteIndex: 4043, - generatedLineIndex: 116, - characterOffsetIndex: 32, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 767, - documentLineIndex: 21, - generatedAbsoluteIndex: 4126, - generatedLineIndex: 121, - characterOffsetIndex: 0, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 781, - documentLineIndex: 21, - generatedAbsoluteIndex: 4224, - generatedLineIndex: 127, - characterOffsetIndex: 14, - contentLength: 21), - BuildLineMapping( - documentAbsoluteIndex: 834, - documentLineIndex: 22, - documentCharacterOffsetIndex: 29, - generatedAbsoluteIndex: 4567, - generatedLineIndex: 135, - generatedCharacterOffsetIndex: 42, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 835, - documentLineIndex: 22, - documentCharacterOffsetIndex: 30, - generatedAbsoluteIndex: 4568, - generatedLineIndex: 135, - generatedCharacterOffsetIndex: 43, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 842, - documentLineIndex: 22, - documentCharacterOffsetIndex: 37, - generatedAbsoluteIndex: 4575, - generatedLineIndex: 135, - generatedCharacterOffsetIndex: 50, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 709, - documentLineIndex: 20, - documentCharacterOffsetIndex: 39, - generatedAbsoluteIndex: 4780, - generatedLineIndex: 141, - generatedCharacterOffsetIndex: 38, - contentLength: 23), - BuildLineMapping( - documentAbsoluteIndex: 732, - documentLineIndex: 20, - documentCharacterOffsetIndex: 62, - generatedAbsoluteIndex: 4803, - generatedLineIndex: 141, - generatedCharacterOffsetIndex: 61, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 974, - documentLineIndex: 25, - documentCharacterOffsetIndex: 61, - generatedAbsoluteIndex: 5149, - generatedLineIndex: 148, - generatedCharacterOffsetIndex: 60, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 975, - documentLineIndex: 25, - documentCharacterOffsetIndex: 62, - generatedAbsoluteIndex: 5150, - generatedLineIndex: 148, - generatedCharacterOffsetIndex: 61, - contentLength: 30), - BuildLineMapping( - documentAbsoluteIndex: 1005, - documentLineIndex: 25, - documentCharacterOffsetIndex: 92, - generatedAbsoluteIndex: 5180, - generatedLineIndex: 148, - generatedCharacterOffsetIndex: 91, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 877, - documentLineIndex: 24, - documentCharacterOffsetIndex: 16, - generatedAbsoluteIndex: 5380, - generatedLineIndex: 154, - generatedCharacterOffsetIndex: 33, - contentLength: 8), - BuildLineMapping( - documentAbsoluteIndex: 885, - documentLineIndex: 24, - documentCharacterOffsetIndex: 24, - generatedAbsoluteIndex: 5388, - generatedLineIndex: 154, - generatedCharacterOffsetIndex: 41, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 886, - documentLineIndex: 24, - documentCharacterOffsetIndex: 25, - generatedAbsoluteIndex: 5389, - generatedLineIndex: 154, - generatedCharacterOffsetIndex: 42, - contentLength: 23), - BuildLineMapping( - documentAbsoluteIndex: 1104, - documentLineIndex: 28, - documentCharacterOffsetIndex: 28, - generatedAbsoluteIndex: 5733, - generatedLineIndex: 161, - generatedCharacterOffsetIndex: 42, - contentLength: 30), - BuildLineMapping( - documentAbsoluteIndex: 1042, - documentLineIndex: 27, - documentCharacterOffsetIndex: 16, - generatedAbsoluteIndex: 5962, - generatedLineIndex: 167, - generatedCharacterOffsetIndex: 33, - contentLength: 30), - BuildLineMapping( - documentAbsoluteIndex: 1232, - documentLineIndex: 31, - documentCharacterOffsetIndex: 28, - generatedAbsoluteIndex: 6313, - generatedLineIndex: 174, - generatedCharacterOffsetIndex: 42, - contentLength: 3), - BuildLineMapping( - documentAbsoluteIndex: 1235, - documentLineIndex: 31, - documentCharacterOffsetIndex: 31, - generatedAbsoluteIndex: 6316, - generatedLineIndex: 174, - generatedCharacterOffsetIndex: 45, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 1237, - documentLineIndex: 31, - documentCharacterOffsetIndex: 33, - generatedAbsoluteIndex: 6318, - generatedLineIndex: 174, - generatedCharacterOffsetIndex: 47, - contentLength: 27), - BuildLineMapping( - documentAbsoluteIndex: 1264, - documentLineIndex: 31, - documentCharacterOffsetIndex: 60, - generatedAbsoluteIndex: 6345, - generatedLineIndex: 174, - generatedCharacterOffsetIndex: 74, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 1265, - documentLineIndex: 31, - documentCharacterOffsetIndex: 61, - generatedAbsoluteIndex: 6346, - generatedLineIndex: 174, - generatedCharacterOffsetIndex: 75, - contentLength: 10), - BuildLineMapping( - documentAbsoluteIndex: 1169, - documentLineIndex: 30, - documentCharacterOffsetIndex: 17, - generatedAbsoluteIndex: 6555, - generatedLineIndex: 180, - generatedCharacterOffsetIndex: 33, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 1170, - documentLineIndex: 30, - documentCharacterOffsetIndex: 18, - generatedAbsoluteIndex: 6556, - generatedLineIndex: 180, - generatedCharacterOffsetIndex: 34, - contentLength: 29), - BuildLineMapping( - documentAbsoluteIndex: 1199, - documentLineIndex: 30, - documentCharacterOffsetIndex: 47, - generatedAbsoluteIndex: 6585, - generatedLineIndex: 180, - generatedCharacterOffsetIndex: 63, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 1304, - documentLineIndex: 33, - generatedAbsoluteIndex: 6666, - generatedLineIndex: 185, - characterOffsetIndex: 9, - contentLength: 11), - BuildLineMapping( - documentAbsoluteIndex: 1359, - documentLineIndex: 33, - documentCharacterOffsetIndex: 64, - generatedAbsoluteIndex: 7027, - generatedLineIndex: 189, - generatedCharacterOffsetIndex: 63, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 1324, - documentLineIndex: 33, - documentCharacterOffsetIndex: 29, - generatedAbsoluteIndex: 7225, - generatedLineIndex: 195, - generatedCharacterOffsetIndex: 33, - contentLength: 3), - BuildLineMapping( - documentAbsoluteIndex: 1388, - documentLineIndex: 35, - generatedAbsoluteIndex: 7340, - generatedLineIndex: 206, - characterOffsetIndex: 0, - contentLength: 1), - } - }, - { - "EmptyAttributeTagHelpers", - "EmptyAttributeTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 381, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 9), - BuildLineMapping( - documentAbsoluteIndex: 60, - documentLineIndex: 3, - documentCharacterOffsetIndex: 26, - generatedAbsoluteIndex: 1367, - generatedLineIndex: 32, - generatedCharacterOffsetIndex: 42, - contentLength: 0), - BuildLineMapping( - documentAbsoluteIndex: 120, - documentLineIndex: 5, - documentCharacterOffsetIndex: 30, - generatedAbsoluteIndex: 1838, - generatedLineIndex: 41, - generatedCharacterOffsetIndex: 42, - contentLength: 0), - BuildLineMapping( - documentAbsoluteIndex: 86, - documentLineIndex: 4, - documentCharacterOffsetIndex: 12, - generatedAbsoluteIndex: 2043, - generatedLineIndex: 47, - generatedCharacterOffsetIndex: 33, - contentLength: 0), - } - }, - { - "EscapedTagHelpers", - "EscapedTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 374, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 9), - BuildLineMapping( - documentAbsoluteIndex: 100, - documentLineIndex: 3, - generatedAbsoluteIndex: 896, - generatedLineIndex: 27, - characterOffsetIndex: 29, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 198, - documentLineIndex: 5, - generatedAbsoluteIndex: 1237, - generatedLineIndex: 34, - characterOffsetIndex: 51, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 221, - documentLineIndex: 5, - generatedAbsoluteIndex: 1547, - generatedLineIndex: 41, - characterOffsetIndex: 74, - contentLength: 4), - } - }, - { - "AttributeTargetingTagHelpers", - "AttributeTargetingTagHelpers.DesignTime", - AttributeTargetingTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 385, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 184, - documentLineIndex: 5, - documentCharacterOffsetIndex: 36, - generatedAbsoluteIndex: 1598, - generatedLineIndex: 34, - generatedCharacterOffsetIndex: 42, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 230, - documentLineIndex: 6, - documentCharacterOffsetIndex: 36, - generatedAbsoluteIndex: 2194, - generatedLineIndex: 44, - generatedCharacterOffsetIndex: 42, - contentLength: 4), - } - }, - { - "PrefixedAttributeTagHelpers", - "PrefixedAttributeTagHelpers.DesignTime", - PrefixedAttributeTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 384, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 35, - documentLineIndex: 2, - generatedAbsoluteIndex: 907, - generatedLineIndex: 27, - characterOffsetIndex: 2, - contentLength: 242), - BuildLineMapping( - documentAbsoluteIndex: 368, - documentLineIndex: 15, - documentCharacterOffsetIndex: 43, - generatedAbsoluteIndex: 1495, - generatedLineIndex: 44, - generatedCharacterOffsetIndex: 56, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 402, - documentLineIndex: 15, - generatedAbsoluteIndex: 1790, - generatedLineIndex: 50, - characterOffsetIndex: 77, - contentLength: 16), - BuildLineMapping( - documentAbsoluteIndex: 466, - documentLineIndex: 16, - documentCharacterOffsetIndex: 43, - generatedAbsoluteIndex: 2283, - generatedLineIndex: 58, - generatedCharacterOffsetIndex: 56, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 500, - documentLineIndex: 16, - generatedAbsoluteIndex: 2578, - generatedLineIndex: 64, - characterOffsetIndex: 77, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 524, - documentLineIndex: 16, - generatedAbsoluteIndex: 2906, - generatedLineIndex: 70, - characterOffsetIndex: 101, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 588, - documentLineIndex: 18, - documentCharacterOffsetIndex: 31, - generatedAbsoluteIndex: 3370, - generatedLineIndex: 78, - generatedCharacterOffsetIndex: 46, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 609, - documentLineIndex: 18, - documentCharacterOffsetIndex: 52, - generatedAbsoluteIndex: 3642, - generatedLineIndex: 84, - generatedCharacterOffsetIndex: 64, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 632, - documentLineIndex: 18, - generatedAbsoluteIndex: 3940, - generatedLineIndex: 90, - characterOffsetIndex: 75, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 781, - documentLineIndex: 20, - generatedAbsoluteIndex: 4665, - generatedLineIndex: 100, - characterOffsetIndex: 42, - contentLength: 8), - BuildLineMapping( - documentAbsoluteIndex: 824, - documentLineIndex: 21, - documentCharacterOffsetIndex: 29, - generatedAbsoluteIndex: 5272, - generatedLineIndex: 109, - generatedCharacterOffsetIndex: 65, - contentLength: 2), - } - }, - { - "DuplicateAttributeTagHelpers", - "DuplicateAttributeTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 385, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 144, - documentLineIndex: 4, - documentCharacterOffsetIndex: 34, - generatedAbsoluteIndex: 1749, - generatedLineIndex: 36, - generatedCharacterOffsetIndex: 42, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 220, - documentLineIndex: 5, - documentCharacterOffsetIndex: 34, - generatedAbsoluteIndex: 2234, - generatedLineIndex: 45, - generatedCharacterOffsetIndex: 42, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 41, - documentLineIndex: 2, - documentCharacterOffsetIndex: 8, - generatedAbsoluteIndex: 2447, - generatedLineIndex: 51, - generatedCharacterOffsetIndex: 33, - contentLength: 1), - } - }, - { - "DynamicAttributeTagHelpers", - "DynamicAttributeTagHelpers.DesignTime", - DynamicAttributeTagHelpers_Descriptors, - new List - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 383, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 57, - documentLineIndex: 2, - generatedAbsoluteIndex: 932, - generatedLineIndex: 27, - characterOffsetIndex: 24, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 94, - documentLineIndex: 4, - documentCharacterOffsetIndex: 17, - generatedAbsoluteIndex: 1142, - generatedLineIndex: 33, - generatedCharacterOffsetIndex: 16, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 107, - documentLineIndex: 4, - generatedAbsoluteIndex: 1264, - generatedLineIndex: 39, - characterOffsetIndex: 30, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 119, - documentLineIndex: 4, - generatedAbsoluteIndex: 1397, - generatedLineIndex: 44, - characterOffsetIndex: 42, - contentLength: 10), - BuildLineMapping( - documentAbsoluteIndex: 130, - documentLineIndex: 4, - generatedAbsoluteIndex: 1540, - generatedLineIndex: 50, - characterOffsetIndex: 53, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 135, - documentLineIndex: 4, - generatedAbsoluteIndex: 1682, - generatedLineIndex: 55, - characterOffsetIndex: 58, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 174, - documentLineIndex: 6, - generatedAbsoluteIndex: 1889, - generatedLineIndex: 62, - characterOffsetIndex: 22, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 212, - documentLineIndex: 6, - generatedAbsoluteIndex: 2106, - generatedLineIndex: 68, - characterOffsetIndex: 60, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 254, - documentLineIndex: 8, - generatedAbsoluteIndex: 2315, - generatedLineIndex: 74, - characterOffsetIndex: 15, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 269, - documentLineIndex: 8, - documentCharacterOffsetIndex: 30, - generatedAbsoluteIndex: 2436, - generatedLineIndex: 79, - generatedCharacterOffsetIndex: 29, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 282, - documentLineIndex: 8, - generatedAbsoluteIndex: 2571, - generatedLineIndex: 85, - characterOffsetIndex: 43, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 294, - documentLineIndex: 8, - generatedAbsoluteIndex: 2717, - generatedLineIndex: 90, - characterOffsetIndex: 55, - contentLength: 10), - BuildLineMapping( - documentAbsoluteIndex: 305, - documentLineIndex: 8, - generatedAbsoluteIndex: 2873, - generatedLineIndex: 96, - characterOffsetIndex: 66, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 310, - documentLineIndex: 8, - generatedAbsoluteIndex: 3028, - generatedLineIndex: 101, - characterOffsetIndex: 71, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 314, - documentLineIndex: 8, - generatedAbsoluteIndex: 3185, - generatedLineIndex: 107, - characterOffsetIndex: 75, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 346, - documentLineIndex: 9, - generatedAbsoluteIndex: 3360, - generatedLineIndex: 113, - characterOffsetIndex: 17, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 361, - documentLineIndex: 9, - documentCharacterOffsetIndex: 32, - generatedAbsoluteIndex: 3484, - generatedLineIndex: 118, - generatedCharacterOffsetIndex: 31, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 374, - documentLineIndex: 9, - generatedAbsoluteIndex: 3622, - generatedLineIndex: 124, - characterOffsetIndex: 45, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 386, - documentLineIndex: 9, - generatedAbsoluteIndex: 3771, - generatedLineIndex: 129, - characterOffsetIndex: 57, - contentLength: 10), - BuildLineMapping( - documentAbsoluteIndex: 397, - documentLineIndex: 9, - generatedAbsoluteIndex: 3930, - generatedLineIndex: 135, - characterOffsetIndex: 68, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 402, - documentLineIndex: 9, - generatedAbsoluteIndex: 4088, - generatedLineIndex: 140, - characterOffsetIndex: 73, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 406, - documentLineIndex: 9, - generatedAbsoluteIndex: 4248, - generatedLineIndex: 146, - characterOffsetIndex: 77, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 443, - documentLineIndex: 11, - generatedAbsoluteIndex: 4460, - generatedLineIndex: 152, - characterOffsetIndex: 17, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 458, - documentLineIndex: 11, - generatedAbsoluteIndex: 4585, - generatedLineIndex: 157, - characterOffsetIndex: 32, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 490, - documentLineIndex: 11, - generatedAbsoluteIndex: 4741, - generatedLineIndex: 162, - characterOffsetIndex: 64, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 527, - documentLineIndex: 13, - documentCharacterOffsetIndex: 17, - generatedAbsoluteIndex: 4952, - generatedLineIndex: 168, - generatedCharacterOffsetIndex: 16, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 540, - documentLineIndex: 13, - generatedAbsoluteIndex: 5075, - generatedLineIndex: 174, - characterOffsetIndex: 30, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 552, - documentLineIndex: 13, - generatedAbsoluteIndex: 5209, - generatedLineIndex: 179, - characterOffsetIndex: 42, - contentLength: 10), - BuildLineMapping( - documentAbsoluteIndex: 563, - documentLineIndex: 13, - generatedAbsoluteIndex: 5353, - generatedLineIndex: 185, - characterOffsetIndex: 53, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 568, - documentLineIndex: 13, - generatedAbsoluteIndex: 5496, - generatedLineIndex: 190, - characterOffsetIndex: 58, - contentLength: 2), - } - }, - { - "TransitionsInTagHelperAttributes", - "TransitionsInTagHelperAttributes.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new[] - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 389, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 33, - documentLineIndex: 1, - generatedAbsoluteIndex: 817, - generatedLineIndex: 26, - characterOffsetIndex: 2, - contentLength: 59), - BuildLineMapping( - documentAbsoluteIndex: 120, - documentLineIndex: 6, - documentCharacterOffsetIndex: 23, - generatedAbsoluteIndex: 1088, - generatedLineIndex: 35, - generatedCharacterOffsetIndex: 33, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 155, - documentLineIndex: 7, - generatedAbsoluteIndex: 1284, - generatedLineIndex: 41, - characterOffsetIndex: 12, - contentLength: 6), - BuildLineMapping( - documentAbsoluteIndex: 169, - documentLineIndex: 7, - documentCharacterOffsetIndex: 26, - generatedAbsoluteIndex: 1408, - generatedLineIndex: 46, - generatedCharacterOffsetIndex: 33, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 200, - documentLineIndex: 8, - documentCharacterOffsetIndex: 21, - generatedAbsoluteIndex: 1623, - generatedLineIndex: 52, - generatedCharacterOffsetIndex: 33, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 205, - documentLineIndex: 8, - documentCharacterOffsetIndex: 26, - generatedAbsoluteIndex: 1628, - generatedLineIndex: 52, - generatedCharacterOffsetIndex: 38, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 206, - documentLineIndex: 8, - documentCharacterOffsetIndex: 27, - generatedAbsoluteIndex: 1629, - generatedLineIndex: 52, - generatedCharacterOffsetIndex: 39, - contentLength: 3), - BuildLineMapping( - documentAbsoluteIndex: 239, - documentLineIndex: 9, - documentCharacterOffsetIndex: 22, - generatedAbsoluteIndex: 1846, - generatedLineIndex: 58, - generatedCharacterOffsetIndex: 33, - contentLength: 3), - BuildLineMapping( - documentAbsoluteIndex: 272, - documentLineIndex: 10, - documentCharacterOffsetIndex: 22, - generatedAbsoluteIndex: 2063, - generatedLineIndex: 64, - generatedCharacterOffsetIndex: 33, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 273, - documentLineIndex: 10, - documentCharacterOffsetIndex: 23, - generatedAbsoluteIndex: 2064, - generatedLineIndex: 64, - generatedCharacterOffsetIndex: 34, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 277, - documentLineIndex: 10, - documentCharacterOffsetIndex: 27, - generatedAbsoluteIndex: 2068, - generatedLineIndex: 64, - generatedCharacterOffsetIndex: 38, - contentLength: 1), - BuildLineMapping( - documentAbsoluteIndex: 305, - documentLineIndex: 11, - generatedAbsoluteIndex: 2269, - generatedLineIndex: 70, - characterOffsetIndex: 19, - contentLength: 6), - BuildLineMapping( - documentAbsoluteIndex: 319, - documentLineIndex: 11, - generatedAbsoluteIndex: 2394, - generatedLineIndex: 75, - characterOffsetIndex: 33, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 323, - documentLineIndex: 11, - generatedAbsoluteIndex: 2398, - generatedLineIndex: 75, - characterOffsetIndex: 37, - contentLength: 2), - BuildLineMapping( - documentAbsoluteIndex: 325, - documentLineIndex: 11, - generatedAbsoluteIndex: 2400, - generatedLineIndex: 75, - characterOffsetIndex: 39, - contentLength: 8), - BuildLineMapping( - documentAbsoluteIndex: 333, - documentLineIndex: 11, - generatedAbsoluteIndex: 2408, - generatedLineIndex: 75, - characterOffsetIndex: 47, - contentLength: 1), - } - }, - { - "NestedScriptTagTagHelpers", - "NestedScriptTagTagHelpers.DesignTime", - DefaultPAndInputTagHelperDescriptors, - new[] - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 382, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 180, - documentLineIndex: 5, - generatedAbsoluteIndex: 982, - generatedLineIndex: 28, - characterOffsetIndex: 0, - contentLength: 12), - BuildLineMapping( - documentAbsoluteIndex: 193, - documentLineIndex: 5, - documentCharacterOffsetIndex: 13, - generatedAbsoluteIndex: 1085, - generatedLineIndex: 34, - generatedCharacterOffsetIndex: 12, - contentLength: 30), - BuildLineMapping( - documentAbsoluteIndex: 337, - documentLineIndex: 7, - generatedAbsoluteIndex: 1450, - generatedLineIndex: 42, - characterOffsetIndex: 50, - contentLength: 23), - BuildLineMapping( - documentAbsoluteIndex: 387, - documentLineIndex: 7, - generatedAbsoluteIndex: 1799, - generatedLineIndex: 49, - characterOffsetIndex: 100, - contentLength: 4), - BuildLineMapping( - documentAbsoluteIndex: 422, - documentLineIndex: 9, - generatedAbsoluteIndex: 1882, - generatedLineIndex: 54, - characterOffsetIndex: 0, - contentLength: 15), - } - }, - { - "SymbolBoundAttributes", - "SymbolBoundAttributes.DesignTime", - SymbolBoundTagHelperDescriptors, - new[] - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 378, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 294, - documentLineIndex: 11, - documentCharacterOffsetIndex: 18, - generatedAbsoluteIndex: 944, - generatedLineIndex: 27, - generatedCharacterOffsetIndex: 46, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 343, - documentLineIndex: 12, - documentCharacterOffsetIndex: 20, - generatedAbsoluteIndex: 1180, - generatedLineIndex: 33, - generatedCharacterOffsetIndex: 47, - contentLength: 5), - BuildLineMapping( - documentAbsoluteIndex: 397, - documentLineIndex: 13, - documentCharacterOffsetIndex: 23, - generatedAbsoluteIndex: 1412, - generatedLineIndex: 39, - generatedCharacterOffsetIndex: 43, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 479, - documentLineIndex: 14, - documentCharacterOffsetIndex: 24, - generatedAbsoluteIndex: 1652, - generatedLineIndex: 45, - generatedCharacterOffsetIndex: 43, - contentLength: 13), - } - }, - { - "EnumTagHelpers", - "EnumTagHelpers.DesignTime", - EnumTagHelperDescriptors, - new[] - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 371, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - BuildLineMapping( - documentAbsoluteIndex: 35, - documentLineIndex: 2, - generatedAbsoluteIndex: 870, - generatedLineIndex: 27, - characterOffsetIndex: 2, - contentLength: 39), - BuildLineMapping( - documentAbsoluteIndex: 94, - documentLineIndex: 6, - documentCharacterOffsetIndex: 15, - generatedAbsoluteIndex: 1226, - generatedLineIndex: 36, - generatedCharacterOffsetIndex: 39, - contentLength: 14), - BuildLineMapping( - documentAbsoluteIndex: 129, - documentLineIndex: 7, - generatedAbsoluteIndex: 1534, - generatedLineIndex: 43, - characterOffsetIndex: 15, - contentLength: 20), - BuildLineMapping( - documentAbsoluteIndex: 169, - documentLineIndex: 8, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 1934, - generatedLineIndex: 50, - generatedCharacterOffsetIndex: 101, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 196, - documentLineIndex: 9, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 2322, - generatedLineIndex: 57, - generatedCharacterOffsetIndex: 101, - contentLength: 13), - BuildLineMapping( - documentAbsoluteIndex: 222, - documentLineIndex: 9, - documentCharacterOffsetIndex: 40, - generatedAbsoluteIndex: 2510, - generatedLineIndex: 62, - generatedCharacterOffsetIndex: 107, - contentLength: 7), - BuildLineMapping( - documentAbsoluteIndex: 249, - documentLineIndex: 10, - documentCharacterOffsetIndex: 15, - generatedAbsoluteIndex: 2836, - generatedLineIndex: 69, - generatedCharacterOffsetIndex: 39, - contentLength: 9), - BuildLineMapping( - documentAbsoluteIndex: 272, - documentLineIndex: 10, - documentCharacterOffsetIndex: 38, - generatedAbsoluteIndex: 2958, - generatedLineIndex: 74, - generatedCharacterOffsetIndex: 45, - contentLength: 9), - } - } - }; - } - } - - [Theory] - [MemberData(nameof(DesignTimeTagHelperTestData))] - public void TagHelpers_GenerateExpectedDesignTimeOutput( - string testName, - string baseLineName, - IEnumerable tagHelperDescriptors, - IList expectedDesignTimePragmas) - { - // Act & Assert - RunTagHelperTest(testName, - baseLineName, - designTimeMode: true, - tagHelperDescriptors: tagHelperDescriptors, - expectedDesignTimePragmas: expectedDesignTimePragmas); - } - - public static TheoryData RuntimeTimeTagHelperTestData - { - get - { - // Test resource name, expected TagHelperDescriptors - // Note: The baseline resource name is equivalent to the test resource name. - return new TheoryData> - { - { "IncompleteTagHelper", null, DefaultPAndInputTagHelperDescriptors }, - { "SingleTagHelper", null, DefaultPAndInputTagHelperDescriptors }, - { "SingleTagHelperWithNewlineBeforeAttributes", null, DefaultPAndInputTagHelperDescriptors }, - { "TagHelpersWithWeirdlySpacedAttributes", null, DefaultPAndInputTagHelperDescriptors }, - { "BasicTagHelpers", null, DefaultPAndInputTagHelperDescriptors }, - { "BasicTagHelpers.RemoveTagHelper", null, DefaultPAndInputTagHelperDescriptors }, - { "BasicTagHelpers.Prefixed", null, PrefixedPAndInputTagHelperDescriptors }, - { "ComplexTagHelpers", null, DefaultPAndInputTagHelperDescriptors }, - { "DuplicateTargetTagHelper", null, DuplicateTargetTagHelperDescriptors }, - { "EmptyAttributeTagHelpers", null, DefaultPAndInputTagHelperDescriptors }, - { "EscapedTagHelpers", null, DefaultPAndInputTagHelperDescriptors }, - { "AttributeTargetingTagHelpers", null, AttributeTargetingTagHelperDescriptors }, - { "PrefixedAttributeTagHelpers", null, PrefixedAttributeTagHelperDescriptors }, - { - "PrefixedAttributeTagHelpers", - "PrefixedAttributeTagHelpers.Reversed", - PrefixedAttributeTagHelperDescriptors.Reverse() - }, - { "DuplicateAttributeTagHelpers", null, DefaultPAndInputTagHelperDescriptors }, - { "DynamicAttributeTagHelpers", null, DynamicAttributeTagHelpers_Descriptors }, - { "TransitionsInTagHelperAttributes", null, DefaultPAndInputTagHelperDescriptors }, - { "NestedScriptTagTagHelpers", null, DefaultPAndInputTagHelperDescriptors }, - { "SymbolBoundAttributes", null, SymbolBoundTagHelperDescriptors }, - { "EnumTagHelpers", null, EnumTagHelperDescriptors }, - }; - } - } - - [Theory] - [MemberData(nameof(RuntimeTimeTagHelperTestData))] - public void TagHelpers_GenerateExpectedRuntimeOutput( - string testName, - string baseLineName, - IEnumerable tagHelperDescriptors) - { - // Arrange & Act & Assert - RunTagHelperTest(testName, baseLineName, tagHelperDescriptors: tagHelperDescriptors); - } - - [ConditionalFact] - [FrameworkSkipCondition(RuntimeFrameworks.Mono)] - public void TagHelpers_CssSelectorTagHelperAttributesGeneratesExpectedOutput() - { - // Arrange & Act & Assert - RunTagHelperTest( - testName: "CssSelectorTagHelperAttributes", - tagHelperDescriptors: CssSelectorTagHelperDescriptors); - } - - [Fact] - public void CSharpChunkGenerator_CorrectlyGeneratesMappings_ForRemoveTagHelperDirective() - { - // Act & Assert - RunTagHelperTest( - "RemoveTagHelperDirective", - designTimeMode: true, - expectedDesignTimePragmas: new List() - { - BuildLineMapping( - documentAbsoluteIndex: 17, - documentLineIndex: 0, - documentCharacterOffsetIndex: 17, - generatedAbsoluteIndex: 381, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - }); - } - - [Fact] - public void CSharpChunkGenerator_CorrectlyGeneratesMappings_ForAddTagHelperDirective() - { - // Act & Assert - RunTagHelperTest( - "AddTagHelperDirective", - designTimeMode: true, - expectedDesignTimePragmas: new List() - { - BuildLineMapping( - documentAbsoluteIndex: 14, - documentLineIndex: 0, - documentCharacterOffsetIndex: 14, - generatedAbsoluteIndex: 378, - generatedLineIndex: 12, - generatedCharacterOffsetIndex: 48, - contentLength: 15), - }); - } - - [Fact] - public void TagHelpers_Directive_GenerateDesignTimeMappings() - { - // Act & Assert - RunTagHelperTest("AddTagHelperDirective", - designTimeMode: true, - tagHelperDescriptors: new[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "TestNamespace.PTagHelper", - AssemblyName = "SomeAssembly" - } - }); - } - - [Fact] - public void TagHelpers_WithinHelpersAndSections_GeneratesExpectedOutput() - { - // Arrange - var propertyInfo = typeof(TestType).GetProperty("BoundProperty"); - var tagHelperDescriptors = new[] - { - new TagHelperDescriptor - { - TagName = "MyTagHelper", - TypeName = "TestNamespace.MyTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new [] - { - new TagHelperAttributeDescriptor("BoundProperty", propertyInfo) - } - }, - new TagHelperDescriptor - { - TagName = "NestedTagHelper", - TypeName = "TestNamespace.NestedTagHelper", - AssemblyName = "SomeAssembly" - } - }; - - // Act & Assert - RunTagHelperTest("TagHelpersInSection", tagHelperDescriptors: tagHelperDescriptors); - } - - private static IEnumerable BuildPAndInputTagHelperDescriptors(string prefix) - { - var pAgePropertyInfo = typeof(TestType).GetProperty("Age"); - var inputTypePropertyInfo = typeof(TestType).GetProperty("Type"); - var checkedPropertyInfo = typeof(TestType).GetProperty("Checked"); - - return new[] - { - new TagHelperDescriptor - { - Prefix = prefix, - TagName = "p", - TypeName = "TestNamespace.PTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("age", pAgePropertyInfo) - }, - TagStructure = TagStructure.NormalOrSelfClosing - }, - new TagHelperDescriptor - { - Prefix = prefix, - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo) - }, - TagStructure = TagStructure.WithoutEndTag - }, - new TagHelperDescriptor - { - Prefix = prefix, - TagName = "input", - TypeName = "TestNamespace.InputTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", checkedPropertyInfo) - }, - } - }; - } - - private class TestType - { - public int Age { get; set; } - - public string Type { get; set; } - - public bool Checked { get; set; } - - public string BoundProperty { get; set; } - } - } - - public enum MyEnum - { - MyValue, - MySecondValue - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingUnitTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingUnitTest.cs deleted file mode 100644 index 3429212490..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CSharpTagHelperRenderingUnitTest.cs +++ /dev/null @@ -1,302 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class CSharpTagHelperRenderingUnitTest - { - [Fact] - public void CreatesAUniqueIdForSingleTagHelperChunk() - { - // Arrange - var chunk = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var codeRenderer = CreateCodeRenderer(); - - // Act - codeRenderer.RenderTagHelper(chunk); - - // Assert - Assert.Equal(1, codeRenderer.GenerateUniqueIdCount); - } - - [Fact] - public void UsesTheSameUniqueIdForTagHelperChunkWithMultipleTagHelpers() - { - // Arrange - var chunk = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - }, - new TagHelperDescriptor - { - TagName = "div", - TypeName = "Div2TagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var codeRenderer = CreateCodeRenderer(); - - // Act - codeRenderer.RenderTagHelper(chunk); - - // Assert - Assert.Equal(1, codeRenderer.GenerateUniqueIdCount); - } - - [Fact] - public void UsesDifferentUniqueIdForMultipleTagHelperChunksForSameTagHelper() - { - // Arrange - var chunk1 = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var chunk2 = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var codeRenderer = CreateCodeRenderer(); - - // Act - codeRenderer.RenderTagHelper(chunk1); - codeRenderer.RenderTagHelper(chunk2); - - // Assert - Assert.Equal(2, codeRenderer.GenerateUniqueIdCount); - } - - [Fact] - public void UsesDifferentUniqueIdForNestedTagHelperChunksForSameTagHelper() - { - // Arrange - var parentChunk = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var childChunk = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - parentChunk.Children.Add(childChunk); - var codeRenderer = CreateCodeRenderer(); - - // Act - codeRenderer.RenderTagHelper(parentChunk); - - // Assert - Assert.Equal(2, codeRenderer.GenerateUniqueIdCount); - } - - [Fact] - public void UsesDifferentUniqueIdForMultipleTagHelperChunksForDifferentTagHelpers() - { - // Arrange - var divChunk = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var spanChunk = CreateTagHelperChunk( - "span", - new[] - { - new TagHelperDescriptor - { - TagName = "span", - TypeName = "SpanTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var codeRenderer = CreateCodeRenderer(); - - // Act - codeRenderer.RenderTagHelper(divChunk); - codeRenderer.RenderTagHelper(spanChunk); - - // Assert - Assert.Equal(2, codeRenderer.GenerateUniqueIdCount); - } - - [Fact] - public void UsesCorrectUniqueIdForMultipleTagHelperChunksSomeWithSameSameTagHelpersSomeWithDifferentTagHelpers() - { - // Arrange - var chunk1 = CreateTagHelperChunk( - "div", - new[] - { - new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "FakeAssemblyName" - }, - new TagHelperDescriptor - { - TagName = "div", - TypeName = "Div2TagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var chunk2 = CreateTagHelperChunk( - "span", - new[] - { - new TagHelperDescriptor - { - TagName = "span", - TypeName = "SpanTagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var chunk3 = CreateTagHelperChunk( - "span", - new[] - { - new TagHelperDescriptor - { - TagName = "span", - TypeName = "SpanTagHelper", - AssemblyName = "FakeAssemblyName" - }, - new TagHelperDescriptor - { - TagName = "span", - TypeName = "Span2TagHelper", - AssemblyName = "FakeAssemblyName" - } - }); - var codeRenderer = CreateCodeRenderer(); - - // Act - codeRenderer.RenderTagHelper(chunk1); - codeRenderer.RenderTagHelper(chunk2); - codeRenderer.RenderTagHelper(chunk3); - - // Assert - Assert.Equal(3, codeRenderer.GenerateUniqueIdCount); - } - - private static TagHelperChunk CreateTagHelperChunk(string tagName, IEnumerable tagHelperDescriptors) - { - return new TagHelperChunk( - tagName, - tagMode: TagMode.StartTagAndEndTag, - attributes: new List(), - descriptors: tagHelperDescriptors) - { - Association = new TagHelperBlock( - new TagHelperBlockBuilder( - tagName, - tagMode: TagMode.StartTagAndEndTag, - attributes: new List(), - children: Enumerable.Empty())), - Children = new List(), - }; - } - - private static TrackingUniqueIdsTagHelperCodeRenderer CreateCodeRenderer() - { - var writer = new CSharpCodeWriter(); - var codeGeneratorContext = CreateContext(); - var visitor = new CSharpCodeVisitor(writer, codeGeneratorContext); - var codeRenderer = new TrackingUniqueIdsTagHelperCodeRenderer( - visitor, - writer, - codeGeneratorContext); - visitor.TagHelperRenderer = codeRenderer; - return codeRenderer; - } - - private static CodeGeneratorContext CreateContext() - { - return new CodeGeneratorContext( - new ChunkGeneratorContext( - new RazorEngineHost(new CSharpRazorCodeLanguage()), - "MyClass", - "MyNamespace", - string.Empty, - shouldGenerateLinePragmas: true), - new ErrorSink()); - } - - private class TrackingUniqueIdsTagHelperCodeRenderer : CSharpTagHelperCodeRenderer - { - public TrackingUniqueIdsTagHelperCodeRenderer( - IChunkVisitor bodyVisitor, - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(bodyVisitor, writer, context) - { - - } - - protected override string GenerateUniqueId() - { - GenerateUniqueIdCount++; - return "test"; - } - - public int GenerateUniqueIdCount { get; private set; } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestCodeGenerator.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestCodeGenerator.cs deleted file mode 100644 index 20b47954ed..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestCodeGenerator.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.CodeGenerators; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class CodeGenTestCodeGenerator : CSharpCodeGenerator - { - public CodeGenTestCodeGenerator(CodeGeneratorContext context) - : base(context) - { - } - - protected override CSharpCodeWriter CreateCodeWriter() - { - return new TestCodeWriter(); - } - - private class TestCodeWriter : CSharpCodeWriter - { - public TestCodeWriter() - { - // We normalize newlines so no matter what platform we're on they're consistent (for code generation - // tests). - NewLine = "\r\n"; - } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestHost.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestHost.cs deleted file mode 100644 index f8f3b6dc47..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeGenTestHost.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.CodeGenerators; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class CodeGenTestHost : RazorEngineHost - { - public CodeGenTestHost(RazorCodeLanguage language) - : base(language) - { - } - - public override CodeGenerator DecorateCodeGenerator(CodeGenerator incomingBuilder, CodeGeneratorContext context) - { - if (incomingBuilder is CodeGenTestCodeGenerator) - { - return incomingBuilder; - } - else - { - return new CodeGenTestCodeGenerator(context); - } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeWriterTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeWriterTest.cs deleted file mode 100644 index 1458e7e1c2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/CodeWriterTest.cs +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class CodeWriterTest - { - // The length of the newline string written by writer.WriteLine. - private static readonly int WriterNewLineLength = Environment.NewLine.Length; - - public static IEnumerable NewLines - { - get - { - return new object[][] - { - new object[] { "\r" }, - new object[] { "\n" }, - new object[] { "\r\n" }, - }; - } - } - - [Fact] - public void CodeWriter_TracksPosition_WithWrite() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234"); - - // Assert - var location = writer.GetCurrentSourceLocation(); - var expected = new SourceLocation(absoluteIndex: 4, lineIndex: 0, characterIndex: 4); - - Assert.Equal(expected, location); - } - - [Fact] - public void CodeWriter_TracksPosition_WithIndent() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.WriteLine(); - writer.Indent(size: 3); - - // Assert - var location = writer.GetCurrentSourceLocation(); - var expected = new SourceLocation(absoluteIndex: 3 + WriterNewLineLength, lineIndex: 1, characterIndex: 3); - - Assert.Equal(expected, location); - } - - [Fact] - public void CodeWriter_TracksPosition_WithWriteLine() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.WriteLine("1234"); - - // Assert - var location = writer.GetCurrentSourceLocation(); - - var expected = new SourceLocation(absoluteIndex: 4 + WriterNewLineLength, lineIndex: 1, characterIndex: 0); - - Assert.Equal(expected, location); - } - - [Theory] - [MemberData("NewLines")] - public void CodeWriter_TracksPosition_WithWriteLine_WithNewLineInContent(string newLine) - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.WriteLine("1234" + newLine + "12"); - - // Assert - var location = writer.GetCurrentSourceLocation(); - - var expected = new SourceLocation( - absoluteIndex: 6 + newLine.Length + WriterNewLineLength, - lineIndex: 2, - characterIndex: 0); - - Assert.Equal(expected, location); - } - - [Theory] - [MemberData("NewLines")] - public void CodeWriter_TracksPosition_WithWrite_WithNewlineInContent(string newLine) - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234" + newLine + "123" + newLine + "12"); - - // Assert - var location = writer.GetCurrentSourceLocation(); - - var expected = new SourceLocation( - absoluteIndex: 9 + newLine.Length + newLine.Length, - lineIndex: 2, - characterIndex: 2); - - Assert.Equal(expected, location); - } - - [Fact] - public void CodeWriter_TracksPosition_WithWrite_WithNewlineInContent_RepeatedN() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234\n\n123"); - - // Assert - var location = writer.GetCurrentSourceLocation(); - - var expected = new SourceLocation( - absoluteIndex: 9, - lineIndex: 2, - characterIndex: 3); - - Assert.Equal(expected, location); - } - - [Fact] - public void CodeWriter_TracksPosition_WithWrite_WithMixedNewlineInContent() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234\r123\r\n12\n1"); - - // Assert - var location = writer.GetCurrentSourceLocation(); - - var expected = new SourceLocation( - absoluteIndex: 14, - lineIndex: 3, - characterIndex: 1); - - Assert.Equal(expected, location); - } - - [Fact] - public void CodeWriter_TracksPosition_WithNewline_SplitAcrossWrites() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234\r"); - var location1 = writer.GetCurrentSourceLocation(); - - writer.Write("\n"); - var location2 = writer.GetCurrentSourceLocation(); - - // Assert - var expected1 = new SourceLocation(absoluteIndex: 5, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected1, location1); - - var expected2 = new SourceLocation(absoluteIndex: 6, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected2, location2); - } - - [Fact] - public void CodeWriter_TracksPosition_WithTwoNewline_SplitAcrossWrites_R() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234\r"); - var location1 = writer.GetCurrentSourceLocation(); - - writer.Write("\r"); - var location2 = writer.GetCurrentSourceLocation(); - - // Assert - var expected1 = new SourceLocation(absoluteIndex: 5, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected1, location1); - - var expected2 = new SourceLocation(absoluteIndex: 6, lineIndex: 2, characterIndex: 0); - Assert.Equal(expected2, location2); - } - - [Fact] - public void CodeWriter_TracksPosition_WithTwoNewline_SplitAcrossWrites_N() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234\n"); - var location1 = writer.GetCurrentSourceLocation(); - - writer.Write("\n"); - var location2 = writer.GetCurrentSourceLocation(); - - // Assert - var expected1 = new SourceLocation(absoluteIndex: 5, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected1, location1); - - var expected2 = new SourceLocation(absoluteIndex: 6, lineIndex: 2, characterIndex: 0); - Assert.Equal(expected2, location2); - } - - [Fact] - public void CodeWriter_TracksPosition_WithTwoNewline_SplitAcrossWrites_Reversed() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("1234\n"); - var location1 = writer.GetCurrentSourceLocation(); - - writer.Write("\r"); - var location2 = writer.GetCurrentSourceLocation(); - - // Assert - var expected1 = new SourceLocation(absoluteIndex: 5, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected1, location1); - - var expected2 = new SourceLocation(absoluteIndex: 6, lineIndex: 2, characterIndex: 0); - Assert.Equal(expected2, location2); - } - - [Fact] - public void CodeWriter_TracksPosition_WithNewline_SplitAcrossWrites_AtBeginning() - { - // Arrange - var writer = new CodeWriter(); - - // Act - writer.Write("\r"); - var location1 = writer.GetCurrentSourceLocation(); - - writer.Write("\n"); - var location2 = writer.GetCurrentSourceLocation(); - - // Assert - var expected1 = new SourceLocation(absoluteIndex: 1, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected1, location1); - - var expected2 = new SourceLocation(absoluteIndex: 2, lineIndex: 1, characterIndex: 0); - Assert.Equal(expected2, location2); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/DynamicAttributeBlockChunkGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/DynamicAttributeBlockChunkGeneratorTest.cs deleted file mode 100644 index f3537499d4..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/DynamicAttributeBlockChunkGeneratorTest.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Chunks.Generators -{ - public class DynamicAttributeBlockChunkGeneratorTest - { - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { - new DynamicAttributeBlockChunkGenerator(prefix: null, offset: 0, line: 0, col: 0), - new DynamicAttributeBlockChunkGenerator(prefix: null, offset: 0, line: 0, col: 0) - }, - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Fred", offset: 0, line: 0, col: 0), - offset: 10, - line: 11, - col: 12), - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Fred", offset: 0, line: 0, col: 0), - offset: 10, - line: 11, - col: 12) - }, - // ValueStart not involved in equality check or hash code calculation. - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12), - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - offset: 100, - line: 11, - col: 12) - }, - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "George", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12), - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "George", offset: 10, line: 11, col: 12), - offset: 10, - line: 110, - col: 12) - }, - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Dean", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12), - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Dean", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 120) - }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { - new DynamicAttributeBlockChunkGenerator(prefix: null, offset: 0, line: 0, col: 0), - null - }, - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Ginger", offset: 0, line: 0, col: 0), - offset: 10, - line: 11, - col: 12), - null - }, - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12), - new object() - }, - { - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "George", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12), - new AttributeBlockChunkGenerator( - name: "Fred", - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - suffix: new LocationTagged(value: "George", offset: 13, line: 14, col: 15)) - }, - { - // Different Prefix. - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "Ginger", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12), - new DynamicAttributeBlockChunkGenerator( - prefix: new LocationTagged(value: "George", offset: 10, line: 11, col: 12), - offset: 10, - line: 11, - col: 12) - }, - }; - } - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected( - DynamicAttributeBlockChunkGenerator leftObject, - DynamicAttributeBlockChunkGenerator rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(DynamicAttributeBlockChunkGenerator leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual( - DynamicAttributeBlockChunkGenerator leftObject, - DynamicAttributeBlockChunkGenerator rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/LineMappingTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/LineMappingTest.cs deleted file mode 100644 index e40f350866..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/LineMappingTest.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class LineMappingTest - { - [Fact] - public void GeneratedCodeMappingsAreEqualIfDataIsEqual() - { - // Arrange - var left = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 8) - ); - var right = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 8) - ); - - // Assert - Assert.True(left == right); - Assert.True(left.Equals(right)); - Assert.True(right.Equals(left)); - Assert.True(Equals(left, right)); - } - - [Fact] - public void GeneratedCodeMappingsAreNotEqualIfCodeLengthIsNotEqual() - { - // Arrange - var left = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 8) - ); - var right = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 5), - new MappingLocation(new SourceLocation(5, 6, 7), 9) - ); - - // Assert - AssertNotEqual(left, right); - } - - [Fact] - public void GeneratedCodeMappingsAreNotEqualIfStartGeneratedColumnIsNotEqual() - { - // Arrange - var left = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 8) - ); - var right = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 8), 8) - ); - - // Assert - AssertNotEqual(left, right); - } - - [Fact] - public void GeneratedCodeMappingsAreNotEqualIfStartColumnIsNotEqual() - { - // Arrange - var left = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 8), 8) - ); - var right = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 8) - ); - - // Assert - AssertNotEqual(left, right); - } - - [Fact] - public void GeneratedCodeMappingsAreNotEqualIfStartLineIsNotEqual() - { - // Arrange - var left = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 5, 7), 8) - ); - var right = new LineMapping( - new MappingLocation(new SourceLocation(1, 1, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 8) - ); - - // Assert - AssertNotEqual(left, right); - } - - [Fact] - public void GeneratedCodeMappingsAreNotEqualIfAbsoluteIndexIsNotEqual() - { - // Arrange - var left = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(4, 6, 7), 8) - ); - var right = new LineMapping( - new MappingLocation(new SourceLocation(1, 2, 3), 4), - new MappingLocation(new SourceLocation(5, 6, 7), 9) - ); - - // Assert - AssertNotEqual(left, right); - } - - private void AssertNotEqual(LineMapping left, LineMapping right) - { - Assert.False(left == right); - Assert.False(left.Equals(right)); - Assert.False(right.Equals(left)); - Assert.False(Equals(left, right)); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/RazorChunkGeneratorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/RazorChunkGeneratorTest.cs deleted file mode 100644 index 87b18e5317..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/RazorChunkGeneratorTest.cs +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Test.Utils; -using Microsoft.AspNetCore.Testing; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public abstract class RazorCodeGeneratorTest - where TLanguage : RazorCodeLanguage, new() - { - protected static readonly string TestRootNamespaceName = "TestOutput"; - - protected abstract string FileExtension { get; } - protected abstract string LanguageName { get; } - protected abstract string BaselineExtension { get; } - - protected RazorEngineHost CreateHost() - { - return new CodeGenTestHost(new TLanguage()); - } - - protected void RunTest( - string name, - string baselineName = null, - bool generatePragmas = true, - bool designTimeMode = false, - IList expectedDesignTimePragmas = null, - TestSpan[] spans = null, - TabTest tabTest = TabTest.Both, - Func hostConfig = null, - Func templateEngineConfig = null, - Action onResults = null) - { - var testRun = false; - - if ((tabTest & TabTest.Tabs) == TabTest.Tabs) - { - using (new CultureReplacer()) - { - RunTestInternal( - name: name, - baselineName: baselineName, - generatePragmas: generatePragmas, - designTimeMode: designTimeMode, - expectedDesignTimePragmas: expectedDesignTimePragmas, - spans: spans, - withTabs: true, - hostConfig: hostConfig, - templateEngineConfig: templateEngineConfig, - onResults: onResults); - } - - testRun = true; - } - - if ((tabTest & TabTest.NoTabs) == TabTest.NoTabs) - { - using (new CultureReplacer()) - { - RunTestInternal( - name: name, - baselineName: baselineName, - generatePragmas: generatePragmas, - designTimeMode: designTimeMode, - expectedDesignTimePragmas: expectedDesignTimePragmas, - spans: spans, - withTabs: false, - hostConfig: hostConfig, - templateEngineConfig: templateEngineConfig, - onResults: onResults); - } - - testRun = true; - } - - Assert.True(testRun, "No test was run because TabTest is not set correctly"); - } - - private Stream NormalizeNewLines(Stream inputStream) - { - if (!inputStream.CanSeek) - { - var memoryStream = new MemoryStream(); - inputStream.CopyTo(memoryStream); - - // We don't have to dispose the input stream since it is owned externally. - inputStream = memoryStream; - } - - inputStream.Position = 0; - var reader = new StreamReader(inputStream); - - // Normalize newlines to be \r\n. This is to ensure when running tests cross plat the final test output - // is compared against test files in a normalized fashion. - var fileContents = reader.ReadToEnd().Replace(Environment.NewLine, "\r\n"); - - // Since this is a test we can normalize to utf8. - inputStream = new MemoryStream(Encoding.UTF8.GetBytes(fileContents)); - - return inputStream; - } - - private void RunTestInternal( - string name, - string baselineName, - bool generatePragmas, - bool designTimeMode, - IList expectedDesignTimePragmas, - TestSpan[] spans, - bool withTabs, - Func hostConfig, - Func templateEngineConfig, - Action onResults = null) - { - // Load the test files - if (baselineName == null) - { - baselineName = name; - } - - var sourceLocation = string.Format("TestFiles/CodeGenerator/Source/{0}.{1}", name, FileExtension); - var testFile = TestFile - .Create(string.Format("TestFiles/CodeGenerator/Output/{0}.{1}", baselineName, BaselineExtension)); - - string expectedOutput; -#if GENERATE_BASELINES - if (testFile.Exists()) - { - expectedOutput = testFile.ReadAllText(); - } - else - { - expectedOutput = null; - } -#else - expectedOutput = testFile.ReadAllText(); -#endif - - // Set up the host and engine - var host = CreateHost(); - host.NamespaceImports.Add("System"); - host.DesignTimeMode = designTimeMode; - host.StaticHelpers = true; - host.DefaultClassName = name; - - // Add support for templates, etc. - host.GeneratedClassContext = new GeneratedClassContext( - GeneratedClassContext.DefaultExecuteMethodName, - GeneratedClassContext.DefaultWriteMethodName, - GeneratedClassContext.DefaultWriteLiteralMethodName, - "WriteTo", - "WriteLiteralTo", - "Template", - "DefineSection", - "Instrumentation.BeginContext", - "Instrumentation.EndContext", - new GeneratedTagHelperContext()); - if (hostConfig != null) - { - host = hostConfig(host); - } - - host.IsIndentingWithTabs = withTabs; - host.EnableInstrumentation = true; - - var engine = new RazorTemplateEngine(host); - - if (templateEngineConfig != null) - { - engine = templateEngineConfig(engine); - } - - // Generate code for the file - GeneratorResults results = null; - using (var source = TestFile.Create(sourceLocation).OpenRead()) - { - var sourceFile = NormalizeNewLines(source); - var sourceFileName = generatePragmas ? string.Format("{0}.{1}", name, FileExtension) : null; - results = engine.GenerateCode( - sourceFile, - className: name, - rootNamespace: TestRootNamespaceName, - sourceFileName: sourceFileName); - } - - var textOutput = results.GeneratedCode; -#if GENERATE_BASELINES - var outputFile = string.Format( - @"test\Microsoft.AspNetCore.Razor.Test\TestFiles\CodeGenerator\Output\{0}.{1}", - baselineName, - BaselineExtension); - - // Update baseline files if files do not already match. - if (!string.Equals(expectedOutput, textOutput, StringComparison.Ordinal)) - { - BaselineWriter.WriteBaseline(outputFile, textOutput); - } -#else - if (onResults != null) - { - onResults(results); - } - - // Verify code against baseline - Assert.Equal(expectedOutput, textOutput); -#endif - - var generatedSpans = results.Document.Flatten(); - - foreach (var span in generatedSpans) - { - VerifyNoBrokenEndOfLines(span.Content); - } - - // Verify design-time pragmas - if (designTimeMode) - { - if (spans != null) - { - Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray()); - } - - if (expectedDesignTimePragmas != null) - { - Assert.NotNull(results.DesignTimeLineMappings); // Guard -#if GENERATE_BASELINES - if (expectedDesignTimePragmas == null || - !Enumerable.SequenceEqual(expectedDesignTimePragmas, results.DesignTimeLineMappings)) - { - var lineMappingFile = Path.ChangeExtension(outputFile, "lineMappings.cs"); - var lineMappingCode = GetDesignTimeLineMappingsCode(results.DesignTimeLineMappings); - BaselineWriter.WriteBaseline(lineMappingFile, lineMappingCode); - } -#else - for (var i = 0; i < expectedDesignTimePragmas.Count && i < results.DesignTimeLineMappings.Count; i++) - { - Assert.Equal(expectedDesignTimePragmas[i], results.DesignTimeLineMappings[i]); - } - - Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count); -#endif - } - } - } - - private static string GetDesignTimeLineMappingsCode(IList designTimeLineMappings) - { - var lineMappings = new StringBuilder(); - lineMappings.AppendLine($"// !!! Do not check in. Instead paste content into test method. !!!"); - lineMappings.AppendLine(); - - var indent = " "; - lineMappings.AppendLine($"{ indent }var expectedLineMappings = new[]"); - lineMappings.AppendLine($"{ indent }{{"); - foreach (var lineMapping in designTimeLineMappings) - { - var innerIndent = indent + " "; - var documentLocation = lineMapping.DocumentLocation; - var generatedLocation = lineMapping.GeneratedLocation; - lineMappings.AppendLine($"{ innerIndent }BuildLineMapping("); - - innerIndent += " "; - lineMappings.AppendLine($"{ innerIndent }documentAbsoluteIndex: { documentLocation.AbsoluteIndex },"); - lineMappings.AppendLine($"{ innerIndent }documentLineIndex: { documentLocation.LineIndex },"); - if (documentLocation.CharacterIndex != generatedLocation.CharacterIndex) - { - lineMappings.AppendLine($"{ innerIndent }documentCharacterOffsetIndex: { documentLocation.CharacterIndex },"); - } - - lineMappings.AppendLine($"{ innerIndent }generatedAbsoluteIndex: { generatedLocation.AbsoluteIndex },"); - lineMappings.AppendLine($"{ innerIndent }generatedLineIndex: { generatedLocation.LineIndex },"); - if (documentLocation.CharacterIndex != generatedLocation.CharacterIndex) - { - lineMappings.AppendLine($"{ innerIndent }generatedCharacterOffsetIndex: { generatedLocation.CharacterIndex },"); - } - else - { - lineMappings.AppendLine($"{ innerIndent }characterOffsetIndex: { generatedLocation.CharacterIndex },"); - } - - lineMappings.AppendLine($"{ innerIndent }contentLength: { generatedLocation.ContentLength }),"); - } - - lineMappings.AppendLine($"{ indent }}};"); - - return lineMappings.ToString(); - } - - private void VerifyNoBrokenEndOfLines(string text) - { - for (int i = 0; i < text.Length; i++) - { - if (text[i] == '\r') - { - Assert.True(text.Length > i + 1); - Assert.Equal('\n', text[i + 1]); - } - else if (text[i] == '\n') - { - Assert.True(i > 0); - Assert.Equal('\r', text[i - 1]); - } - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TabTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TabTest.cs deleted file mode 100644 index 7970743d96..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TabTest.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - [Flags] - public enum TabTest - { - NoTabs = 1, - Tabs = 2, - Both = 3 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperAttributeValueCodeRendererTest.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperAttributeValueCodeRendererTest.cs deleted file mode 100644 index aa66115eee..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperAttributeValueCodeRendererTest.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -#if NETCOREAPP1_1 -using System.Reflection; -#endif -using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Xunit; -using Microsoft.AspNetCore.Razor.Test.CodeGenerators; - -namespace Microsoft.AspNetCore.Razor.CodeGenerators -{ - public class TagHelperAttributeValueCodeRendererTest : TagHelperTestBase - { - [Fact] - public void TagHelpers_CanReplaceAttributeChunkGeneratorLogic() - { - // Arrange - var inputTypePropertyInfo = typeof(TestType).GetProperty("Type"); - var checkedPropertyInfo = typeof(TestType).GetProperty("Checked"); - var tagHelperDescriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "TestNamespace.PTagHelper", - AssemblyName = "SomeAssembly" - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo) - }, - TagStructure = TagStructure.WithoutEndTag - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "TestNamespace.InputTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new TagHelperAttributeDescriptor[] - { - new TagHelperAttributeDescriptor("type", inputTypePropertyInfo), - new TagHelperAttributeDescriptor("checked", checkedPropertyInfo) - } - } - }; - - // Act & Assert - RunTagHelperTest(testName: "BasicTagHelpers", - baseLineName: "BasicTagHelpers.CustomAttributeCodeGenerator", - tagHelperDescriptors: tagHelperDescriptors, - hostConfig: (host) => - { - return new CodeGeneratorReplacingHost(host); - }); - } - - private class CodeGeneratorReplacingHost : CodeGenTestHost - { - public CodeGeneratorReplacingHost(RazorEngineHost originalHost) - : base(new CSharpRazorCodeLanguage()) - { - GeneratedClassContext = originalHost.GeneratedClassContext; - } - - public override CodeGenerator DecorateCodeGenerator( - CodeGenerator incomingBuilder, - CodeGeneratorContext context) - { - return new AttributeChunkGeneratorReplacingCodeGenerator(context); - } - } - - private class AttributeChunkGeneratorReplacingCodeGenerator : TestCSharpCodeGenerator - { - public AttributeChunkGeneratorReplacingCodeGenerator(CodeGeneratorContext context) - : base(context) - { - } - - protected override CSharpCodeVisitor CreateCSharpCodeVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context) - { - var bodyVisitor = base.CreateCSharpCodeVisitor(writer, context); - - bodyVisitor.TagHelperRenderer.AttributeValueCodeRenderer = new CustomTagHelperAttributeCodeRenderer(); - - return bodyVisitor; - } - } - - private class CustomTagHelperAttributeCodeRenderer : TagHelperAttributeValueCodeRenderer - { - public override void RenderAttributeValue( - TagHelperAttributeDescriptor attributeDescriptor, - CSharpCodeWriter writer, - CodeGeneratorContext context, - Action renderAttributeValue, - bool complexValue) - { - writer.Write("**From custom attribute code renderer**: "); - - base.RenderAttributeValue(attributeDescriptor, writer, context, renderAttributeValue, complexValue); - } - } - - private class TestType - { - public string Type { get; set; } - - public bool Checked { get; set; } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperTestBase.cs deleted file mode 100644 index 6e00c9b649..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TagHelperTestBase.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class TagHelperTestBase : CSharpRazorCodeGeneratorTest - { - protected void RunTagHelperTest(string testName, - string baseLineName = null, - bool designTimeMode = false, - IEnumerable tagHelperDescriptors = null, - Func hostConfig = null, - IList expectedDesignTimePragmas = null, - Action onResults = null) - { - RunTest(name: testName, - baselineName: baseLineName, - designTimeMode: designTimeMode, - tabTest: TabTest.NoTabs, - templateEngineConfig: (engine) => - { - return new TagHelperTemplateEngine(engine, tagHelperDescriptors); - }, - onResults: onResults, - hostConfig: hostConfig, - expectedDesignTimePragmas: expectedDesignTimePragmas); - } - - private class CustomTagHelperDescriptorResolver : ITagHelperDescriptorResolver - { - private IEnumerable _tagHelperDescriptors; - - public CustomTagHelperDescriptorResolver(IEnumerable tagHelperDescriptors) - { - _tagHelperDescriptors = tagHelperDescriptors ?? Enumerable.Empty(); - } - - public IEnumerable Resolve(TagHelperDescriptorResolutionContext resolutionContext) - { - IEnumerable descriptors = null; - - foreach (var directiveDescriptor in resolutionContext.DirectiveDescriptors) - { - if (directiveDescriptor.DirectiveType == TagHelperDirectiveType.RemoveTagHelper) - { - // We don't yet support "typeName, assemblyName" for @removeTagHelper in this test class. Will - // add that ability and add the corresponding end-to-end test verification in: - // https://github.com/aspnet/Razor/issues/222 - descriptors = null; - } - else if (directiveDescriptor.DirectiveType == TagHelperDirectiveType.AddTagHelper) - { - descriptors = _tagHelperDescriptors; - } - } - - return descriptors ?? Enumerable.Empty(); - } - } - - private class TagHelperTemplateEngine : RazorTemplateEngine - { - private IEnumerable _tagHelperDescriptors; - - public TagHelperTemplateEngine(RazorTemplateEngine engine, - IEnumerable tagHelperDescriptors) - : base(engine.Host) - { - _tagHelperDescriptors = tagHelperDescriptors; - } - - protected internal override CodeGenerator CreateCodeGenerator(CodeGeneratorContext context) - { - return Host.DecorateCodeGenerator(new TestCSharpCodeGenerator(context), context); - } - - protected internal override RazorParser CreateParser(string sourceFileName) - { - var parser = base.CreateParser(sourceFileName); - - return new RazorParser(parser.CodeParser, - parser.MarkupParser, - new CustomTagHelperDescriptorResolver(_tagHelperDescriptors)); - } - } - - protected class TestCSharpCodeGenerator : CodeGenTestCodeGenerator - { - public TestCSharpCodeGenerator(CodeGeneratorContext context) - : base(context) - { - - } - - protected override CSharpCodeVisitor CreateCSharpCodeVisitor( - CSharpCodeWriter writer, - CodeGeneratorContext context) - { - var visitor = base.CreateCSharpCodeVisitor(writer, context); - visitor.TagHelperRenderer = new NoUniqueIdsTagHelperCodeRenderer(visitor, writer, context); - return visitor; - } - - private class NoUniqueIdsTagHelperCodeRenderer : CSharpTagHelperCodeRenderer - { - public NoUniqueIdsTagHelperCodeRenderer(IChunkVisitor bodyVisitor, - CSharpCodeWriter writer, - CodeGeneratorContext context) - : base(bodyVisitor, writer, context) - { - - } - - protected override string GenerateUniqueId() - { - return "test"; - } - } - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TestSpan.cs b/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TestSpan.cs deleted file mode 100644 index cdb4a62d71..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/CodeGenerators/TestSpan.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.Extensions.Internal; - -namespace Microsoft.AspNetCore.Razor.Test.CodeGenerators -{ - public class TestSpan - { - /// - /// Test span to simplify the generation of the actual Span in test initializer. - /// - /// Span kind - /// Zero indexed start char index in the buffer. - /// End Column, if the text length is zero Start == End. - public TestSpan(SpanKind kind, int start, int end) - { - Kind = kind; - Start = start; - End = end; - } - - public TestSpan(Span span) - : this(span.Kind, - span.Start.AbsoluteIndex, - span.Start.AbsoluteIndex + span.Length) - { - } - - public SpanKind Kind { get; } - - public int Start { get; } - - public int End { get; } - - public override string ToString() - { - return string.Format("{0}: {1}-{2}", Kind, Start, End); - } - - public override bool Equals(object obj) - { - var other = obj as TestSpan; - return other != null && - Kind == other.Kind && - Start == other.Start && - End == other.End; - } - - public override int GetHashCode() - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(Kind); - hashCodeCombiner.Add(Start); - hashCodeCombiner.Add(End); - - return hashCodeCombiner; - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorProviderTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorProviderTest.cs deleted file mode 100644 index 23b4929aa2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorProviderTest.cs +++ /dev/null @@ -1,499 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.TagHelpers.Testing; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - public class TagHelperDescriptorProviderTest - { - public static TheoryData RequiredParentData - { - get - { - var strongPParent = new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly", - RequiredParent = "p", - }; - var strongDivParent = new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly", - RequiredParent = "div", - }; - var catchAllPParent = new TagHelperDescriptor - { - TagName = "*", - TypeName = "CatchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredParent = "p", - }; - - return new TheoryData< - string, // tagName - string, // parentTagName - IEnumerable, // availableDescriptors - IEnumerable> // expectedDescriptors - { - { - "strong", - "p", - new[] { strongPParent, strongDivParent }, - new[] { strongPParent } - }, - { - "strong", - "div", - new[] { strongPParent, strongDivParent, catchAllPParent }, - new[] { strongDivParent } - }, - { - "strong", - "p", - new[] { strongPParent, strongDivParent, catchAllPParent }, - new[] { strongPParent, catchAllPParent } - }, - { - "custom", - "p", - new[] { strongPParent, strongDivParent, catchAllPParent }, - new[] { catchAllPParent } - }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredParentData))] - public void GetDescriptors_ReturnsDescriptorsParentTags( - string tagName, - string parentTagName, - IEnumerable availableDescriptors, - IEnumerable expectedDescriptors) - { - // Arrange - var provider = new TagHelperDescriptorProvider(availableDescriptors); - - // Act - var resolvedDescriptors = provider.GetDescriptors( - tagName, - attributes: Enumerable.Empty>(), - parentTagName: parentTagName); - - // Assert - Assert.Equal(expectedDescriptors, resolvedDescriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - public static TheoryData RequiredAttributeData - { - get - { - var divDescriptor = new TagHelperDescriptor - { - TagName = "div", - TypeName = "DivTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "style" } } - }; - var inputDescriptor = new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - } - }; - var inputWildcardPrefixDescriptor = new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputWildCardAttribute", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "nodashprefix", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - } - } - }; - var catchAllDescriptor = new TagHelperDescriptor - { - TagName = TagHelperDescriptorProvider.ElementCatchAllTarget, - TypeName = "CatchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "class" } } - }; - var catchAllDescriptor2 = new TagHelperDescriptor - { - TagName = TagHelperDescriptorProvider.ElementCatchAllTarget, - TypeName = "CatchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "custom" }, - new TagHelperRequiredAttributeDescriptor { Name = "class" } - } - }; - var catchAllWildcardPrefixDescriptor = new TagHelperDescriptor - { - TagName = TagHelperDescriptorProvider.ElementCatchAllTarget, - TypeName = "CatchAllWildCardAttribute", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "prefix-", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - } - } - }; - var defaultAvailableDescriptors = - new[] { divDescriptor, inputDescriptor, catchAllDescriptor, catchAllDescriptor2 }; - var defaultWildcardDescriptors = - new[] { inputWildcardPrefixDescriptor, catchAllWildcardPrefixDescriptor }; - Func> kvp = - (name) => new KeyValuePair(name, "test value"); - - return new TheoryData< - string, // tagName - IEnumerable>, // providedAttributes - IEnumerable, // availableDescriptors - IEnumerable> // expectedDescriptors - { - { - "div", - new[] { kvp("custom") }, - defaultAvailableDescriptors, - Enumerable.Empty() - }, - { "div", new[] { kvp("style") }, defaultAvailableDescriptors, new[] { divDescriptor } }, - { "div", new[] { kvp("class") }, defaultAvailableDescriptors, new[] { catchAllDescriptor } }, - { - "div", - new[] { kvp("class"), kvp("style") }, - defaultAvailableDescriptors, - new[] { divDescriptor, catchAllDescriptor } - }, - { - "div", - new[] { kvp("class"), kvp("style"), kvp("custom") }, - defaultAvailableDescriptors, - new[] { divDescriptor, catchAllDescriptor, catchAllDescriptor2 } - }, - { - "input", - new[] { kvp("class"), kvp("style") }, - defaultAvailableDescriptors, - new[] { inputDescriptor, catchAllDescriptor } - }, - { - "input", - new[] { kvp("nodashprefixA") }, - defaultWildcardDescriptors, - new[] { inputWildcardPrefixDescriptor } - }, - { - "input", - new[] { kvp("nodashprefix-ABC-DEF"), kvp("random") }, - defaultWildcardDescriptors, - new[] { inputWildcardPrefixDescriptor } - }, - { - "input", - new[] { kvp("prefixABCnodashprefix") }, - defaultWildcardDescriptors, - Enumerable.Empty() - }, - { - "input", - new[] { kvp("prefix-") }, - defaultWildcardDescriptors, - Enumerable.Empty() - }, - { - "input", - new[] { kvp("nodashprefix") }, - defaultWildcardDescriptors, - Enumerable.Empty() - }, - { - "input", - new[] { kvp("prefix-A") }, - defaultWildcardDescriptors, - new[] { catchAllWildcardPrefixDescriptor } - }, - { - "input", - new[] { kvp("prefix-ABC-DEF"), kvp("random") }, - defaultWildcardDescriptors, - new[] { catchAllWildcardPrefixDescriptor } - }, - { - "input", - new[] { kvp("prefix-abc"), kvp("nodashprefix-def") }, - defaultWildcardDescriptors, - new[] { inputWildcardPrefixDescriptor, catchAllWildcardPrefixDescriptor } - }, - { - "input", - new[] { kvp("class"), kvp("prefix-abc"), kvp("onclick"), kvp("nodashprefix-def"), kvp("style") }, - defaultWildcardDescriptors, - new[] { inputWildcardPrefixDescriptor, catchAllWildcardPrefixDescriptor } - }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredAttributeData))] - public void GetDescriptors_ReturnsDescriptorsWithRequiredAttributes( - string tagName, - IEnumerable> providedAttributes, - IEnumerable availableDescriptors, - IEnumerable expectedDescriptors) - { - // Arrange - var provider = new TagHelperDescriptorProvider(availableDescriptors); - - // Act - var resolvedDescriptors = provider.GetDescriptors(tagName, providedAttributes, parentTagName: "p"); - - // Assert - Assert.Equal(expectedDescriptors, resolvedDescriptors, CaseSensitiveTagHelperDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_ReturnsEmptyDescriptorsWithPrefixAsTagName() - { - // Arrange - var catchAllDescriptor = CreatePrefixedDescriptor( - "th", - TagHelperDescriptorProvider.ElementCatchAllTarget, - "foo1"); - var descriptors = new[] { catchAllDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var resolvedDescriptors = provider.GetDescriptors( - tagName: "th", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - Assert.Empty(resolvedDescriptors); - } - - [Fact] - public void GetDescriptors_OnlyUnderstandsSinglePrefix() - { - // Arrange - var divDescriptor = CreatePrefixedDescriptor("th:", "div", "foo1"); - var spanDescriptor = CreatePrefixedDescriptor("th2:", "span", "foo2"); - var descriptors = new[] { divDescriptor, spanDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var retrievedDescriptorsDiv = provider.GetDescriptors( - tagName: "th:div", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - var retrievedDescriptorsSpan = provider.GetDescriptors( - tagName: "th2:span", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - var descriptor = Assert.Single(retrievedDescriptorsDiv); - Assert.Same(divDescriptor, descriptor); - Assert.Empty(retrievedDescriptorsSpan); - } - - [Fact] - public void GetDescriptors_ReturnsCatchAllDescriptorsForPrefixedTags() - { - // Arrange - var catchAllDescriptor = CreatePrefixedDescriptor("th:", TagHelperDescriptorProvider.ElementCatchAllTarget, "foo1"); - var descriptors = new[] { catchAllDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var retrievedDescriptorsDiv = provider.GetDescriptors( - tagName: "th:div", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - var retrievedDescriptorsSpan = provider.GetDescriptors( - tagName: "th:span", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - var descriptor = Assert.Single(retrievedDescriptorsDiv); - Assert.Same(catchAllDescriptor, descriptor); - descriptor = Assert.Single(retrievedDescriptorsSpan); - Assert.Same(catchAllDescriptor, descriptor); - } - - [Fact] - public void GetDescriptors_ReturnsDescriptorsForPrefixedTags() - { - // Arrange - var divDescriptor = CreatePrefixedDescriptor("th:", "div", "foo1"); - var descriptors = new[] { divDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var retrievedDescriptors = provider.GetDescriptors( - tagName: "th:div", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - var descriptor = Assert.Single(retrievedDescriptors); - Assert.Same(divDescriptor, descriptor); - } - - [Theory] - [InlineData("*")] - [InlineData("div")] - public void GetDescriptors_ReturnsNothingForUnprefixedTags(string tagName) - { - // Arrange - var divDescriptor = CreatePrefixedDescriptor("th:", tagName, "foo1"); - var descriptors = new[] { divDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var retrievedDescriptorsDiv = provider.GetDescriptors( - tagName: "div", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - Assert.Empty(retrievedDescriptorsDiv); - } - - [Fact] - public void GetDescriptors_ReturnsNothingForUnregisteredTags() - { - // Arrange - var divDescriptor = new TagHelperDescriptor - { - TagName = "div", - TypeName = "foo1", - AssemblyName = "SomeAssembly", - }; - var spanDescriptor = new TagHelperDescriptor - { - TagName = "span", - TypeName = "foo2", - AssemblyName = "SomeAssembly", - }; - var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var retrievedDescriptors = provider.GetDescriptors( - tagName: "foo", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - Assert.Empty(retrievedDescriptors); - } - - [Fact] - public void GetDescriptors_ReturnsCatchAllsWithEveryTagName() - { - // Arrange - var divDescriptor = new TagHelperDescriptor - { - TagName = "div", - TypeName = "foo1", - AssemblyName = "SomeAssembly", - }; - var spanDescriptor = new TagHelperDescriptor - { - TagName = "span", - TypeName = "foo2", - AssemblyName = "SomeAssembly", - }; - var catchAllDescriptor = new TagHelperDescriptor - { - TagName = TagHelperDescriptorProvider.ElementCatchAllTarget, - TypeName = "foo3", - AssemblyName = "SomeAssembly", - }; - var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor, catchAllDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var divDescriptors = provider.GetDescriptors( - tagName: "div", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - var spanDescriptors = provider.GetDescriptors( - tagName: "span", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - // For divs - Assert.Equal(2, divDescriptors.Count()); - Assert.Contains(divDescriptor, divDescriptors); - Assert.Contains(catchAllDescriptor, divDescriptors); - - // For spans - Assert.Equal(2, spanDescriptors.Count()); - Assert.Contains(spanDescriptor, spanDescriptors); - Assert.Contains(catchAllDescriptor, spanDescriptors); - } - - [Fact] - public void GetDescriptors_DuplicateDescriptorsAreNotPartOfTagHelperDescriptorPool() - { - // Arrange - var divDescriptor = new TagHelperDescriptor - { - TagName = "div", - TypeName = "foo1", - AssemblyName = "SomeAssembly", - }; - var descriptors = new TagHelperDescriptor[] { divDescriptor, divDescriptor }; - var provider = new TagHelperDescriptorProvider(descriptors); - - // Act - var retrievedDescriptors = provider.GetDescriptors( - tagName: "div", - attributes: Enumerable.Empty>(), - parentTagName: "p"); - - // Assert - var descriptor = Assert.Single(retrievedDescriptors); - Assert.Same(divDescriptor, descriptor); - } - - private static TagHelperDescriptor CreatePrefixedDescriptor(string prefix, string tagName, string typeName) - { - return new TagHelperDescriptor - { - Prefix = prefix, - TagName = tagName, - TypeName = typeName, - AssemblyName = "SomeAssembly" - }; - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorTest.cs deleted file mode 100644 index f115f14d3e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperDescriptorTest.cs +++ /dev/null @@ -1,558 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers.Testing; -using Newtonsoft.Json; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - public class TagHelperDescriptorTest - { - [Fact] - public void Constructor_CorrectlyCreatesCopy() - { - // Arrange - var descriptor = new TagHelperDescriptor - { - Prefix = "prefix", - TagName = "tag-name", - TypeName = "TypeName", - AssemblyName = "AsssemblyName", - Attributes = new List - { - new TagHelperAttributeDescriptor - { - Name = "test-attribute", - PropertyName = "TestAttribute", - TypeName = "string" - } - }, - RequiredAttributes = new List - { - new TagHelperRequiredAttributeDescriptor - { - Name = "test-required-attribute" - } - }, - AllowedChildren = new[] { "child" }, - RequiredParent = "required parent", - TagStructure = TagStructure.NormalOrSelfClosing, - DesignTimeDescriptor = new TagHelperDesignTimeDescriptor() - }; - - descriptor.PropertyBag.Add("foo", "bar"); - - // Act - var copyDescriptor = new TagHelperDescriptor(descriptor); - - // Assert - Assert.Equal(descriptor, copyDescriptor, CaseSensitiveTagHelperDescriptorComparer.Default); - Assert.Same(descriptor.Attributes, copyDescriptor.Attributes); - Assert.Same(descriptor.RequiredAttributes, copyDescriptor.RequiredAttributes); - } - - [Fact] - public void TagHelperDescriptor_CanBeSerialized() - { - // Arrange - var descriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "required attribute one", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch - }, - new TagHelperRequiredAttributeDescriptor - { - Name = "required attribute two", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "something", - ValueComparison = TagHelperRequiredAttributeValueComparison.PrefixMatch, - } - }, - AllowedChildren = new[] { "allowed child one" }, - RequiredParent = "parent name", - DesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - Summary = "usage summary", - Remarks = "usage remarks", - OutputElementHint = "some-tag" - }, - }; - - var expectedSerializedDescriptor = - $"{{\"{ nameof(TagHelperDescriptor.Prefix) }\":\"prefix:\"," + - $"\"{ nameof(TagHelperDescriptor.TagName) }\":\"tag name\"," + - $"\"{ nameof(TagHelperDescriptor.FullTagName) }\":\"prefix:tag name\"," + - $"\"{ nameof(TagHelperDescriptor.TypeName) }\":\"type name\"," + - $"\"{ nameof(TagHelperDescriptor.AssemblyName) }\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.Attributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":" + - $"[{{\"{ nameof(TagHelperRequiredAttributeDescriptor.Name)}\":\"required attribute one\"," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.NameComparison) }\":1," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.Value) }\":null," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.ValueComparison) }\":0}}," + - $"{{\"{ nameof(TagHelperRequiredAttributeDescriptor.Name)}\":\"required attribute two\"," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.NameComparison) }\":0," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.Value) }\":\"something\"," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.ValueComparison) }\":2}}]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":[\"allowed child one\"]," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":\"parent name\"," + - $"\"{ nameof(TagHelperDescriptor.TagStructure) }\":0," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":{{" + - $"\"{ nameof(TagHelperDesignTimeDescriptor.Summary) }\":\"usage summary\"," + - $"\"{ nameof(TagHelperDesignTimeDescriptor.Remarks) }\":\"usage remarks\"," + - $"\"{ nameof(TagHelperDesignTimeDescriptor.OutputElementHint) }\":\"some-tag\"}}," + - $"\"{ nameof(TagHelperDescriptor.PropertyBag) }\":{{}}}}"; - - // Act - var serializedDescriptor = JsonConvert.SerializeObject(descriptor); - - // Assert - Assert.Equal(expectedSerializedDescriptor, serializedDescriptor, StringComparer.Ordinal); - } - - [Fact] - public void TagHelperDescriptor_WithAttributes_CanBeSerialized() - { - // Arrange - var descriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "attribute one", - PropertyName = "property name", - TypeName = "property type name", - IsEnum = true, - }, - new TagHelperAttributeDescriptor - { - Name = "attribute two", - PropertyName = "property name", - TypeName = typeof(string).FullName, - IsStringProperty = true - }, - }, - TagStructure = TagStructure.NormalOrSelfClosing - }; - - var expectedSerializedDescriptor = - $"{{\"{ nameof(TagHelperDescriptor.Prefix) }\":\"prefix:\"," + - $"\"{ nameof(TagHelperDescriptor.TagName) }\":\"tag name\"," + - $"\"{ nameof(TagHelperDescriptor.FullTagName) }\":\"prefix:tag name\"," + - $"\"{ nameof(TagHelperDescriptor.TypeName) }\":\"type name\"," + - $"\"{ nameof(TagHelperDescriptor.AssemblyName) }\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.Attributes) }\":[" + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute one\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"property type name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}," + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute two\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"{ typeof(string).FullName }\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":null," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":null," + - $"\"{ nameof(TagHelperDescriptor.TagStructure) }\":1," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":null," + - $"\"{ nameof(TagHelperDescriptor.PropertyBag) }\":{{}}}}"; - - // Act - var serializedDescriptor = JsonConvert.SerializeObject(descriptor); - - // Assert - Assert.Equal(expectedSerializedDescriptor, serializedDescriptor, StringComparer.Ordinal); - } - - [Fact] - public void TagHelperDescriptor_WithIndexerAttributes_CanBeSerialized() - { - // Arrange - var descriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "attribute one", - PropertyName = "property name", - TypeName = "property type name", - IsIndexer = true, - IsEnum = true, - }, - new TagHelperAttributeDescriptor - { - Name = "attribute two", - PropertyName = "property name", - TypeName = typeof(string).FullName, - IsIndexer = true, - IsEnum = false, - IsStringProperty = true - }, - }, - AllowedChildren = new[] { "allowed child one", "allowed child two" }, - RequiredParent = "parent name" - }; - - var expectedSerializedDescriptor = - $"{{\"{ nameof(TagHelperDescriptor.Prefix) }\":\"prefix:\"," + - $"\"{ nameof(TagHelperDescriptor.TagName) }\":\"tag name\"," + - $"\"{ nameof(TagHelperDescriptor.FullTagName) }\":\"prefix:tag name\"," + - $"\"{ nameof(TagHelperDescriptor.TypeName) }\":\"type name\"," + - $"\"{ nameof(TagHelperDescriptor.AssemblyName) }\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.Attributes) }\":[" + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute one\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"property type name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}," + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute two\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"{ typeof(string).FullName }\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":[\"allowed child one\",\"allowed child two\"]," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":\"parent name\"," + - $"\"{ nameof(TagHelperDescriptor.TagStructure) }\":0," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":null," + - $"\"{ nameof(TagHelperDescriptor.PropertyBag) }\":{{}}}}"; - - // Act - var serializedDescriptor = JsonConvert.SerializeObject(descriptor); - - // Assert - Assert.Equal(expectedSerializedDescriptor, serializedDescriptor, StringComparer.Ordinal); - } - - [Fact] - public void TagHelperDescriptor_WithPropertyBagElements_CanBeSerialized() - { - // Arrange - var descriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name" - }; - - descriptor.PropertyBag.Add("key one", "value one"); - descriptor.PropertyBag.Add("key two", "value two"); - - var expectedSerializedDescriptor = - $"{{\"{ nameof(TagHelperDescriptor.Prefix) }\":\"prefix:\"," + - $"\"{ nameof(TagHelperDescriptor.TagName) }\":\"tag name\"," + - $"\"{ nameof(TagHelperDescriptor.FullTagName) }\":\"prefix:tag name\"," + - $"\"{ nameof(TagHelperDescriptor.TypeName) }\":\"type name\"," + - $"\"{ nameof(TagHelperDescriptor.AssemblyName) }\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.Attributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":null," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":null," + - $"\"{ nameof(TagHelperDescriptor.TagStructure) }\":0," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":null," + - $"\"{ nameof(TagHelperDescriptor.PropertyBag) }\":" + - "{\"key one\":\"value one\",\"key two\":\"value two\"}}"; - - // Act - var serializedDescriptor = JsonConvert.SerializeObject(descriptor); - - // Assert - Assert.Equal(expectedSerializedDescriptor, serializedDescriptor); - } - - [Fact] - public void TagHelperDescriptor_CanBeDeserialized() - { - // Arrange - var serializedDescriptor = - $"{{\"{nameof(TagHelperDescriptor.Prefix)}\":\"prefix:\"," + - $"\"{nameof(TagHelperDescriptor.TagName)}\":\"tag name\"," + - $"\"{nameof(TagHelperDescriptor.FullTagName)}\":\"prefix:tag name\"," + - $"\"{nameof(TagHelperDescriptor.TypeName)}\":\"type name\"," + - $"\"{nameof(TagHelperDescriptor.AssemblyName)}\":\"assembly name\"," + - $"\"{nameof(TagHelperDescriptor.Attributes)}\":[]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":" + - $"[{{\"{ nameof(TagHelperRequiredAttributeDescriptor.Name)}\":\"required attribute one\"," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.NameComparison) }\":1," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.Value) }\":null," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.ValueComparison) }\":0}}," + - $"{{\"{ nameof(TagHelperRequiredAttributeDescriptor.Name)}\":\"required attribute two\"," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.NameComparison) }\":0," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.Value) }\":\"something\"," + - $"\"{ nameof(TagHelperRequiredAttributeDescriptor.ValueComparison) }\":2}}]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":[\"allowed child one\",\"allowed child two\"]," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":\"parent name\"," + - $"\"{nameof(TagHelperDescriptor.TagStructure)}\":2," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":{{" + - $"\"{ nameof(TagHelperDesignTimeDescriptor.Summary) }\":\"usage summary\"," + - $"\"{ nameof(TagHelperDesignTimeDescriptor.Remarks) }\":\"usage remarks\"," + - $"\"{ nameof(TagHelperDesignTimeDescriptor.OutputElementHint) }\":\"some-tag\"}}}}"; - var expectedDescriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor - { - Name = "required attribute one", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch - }, - new TagHelperRequiredAttributeDescriptor - { - Name = "required attribute two", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "something", - ValueComparison = TagHelperRequiredAttributeValueComparison.PrefixMatch, - } - }, - AllowedChildren = new[] { "allowed child one", "allowed child two" }, - RequiredParent = "parent name", - DesignTimeDescriptor = new TagHelperDesignTimeDescriptor - { - Summary = "usage summary", - Remarks = "usage remarks", - OutputElementHint = "some-tag" - } - }; - - // Act - var descriptor = JsonConvert.DeserializeObject(serializedDescriptor); - - // Assert - Assert.NotNull(descriptor); - Assert.Equal(expectedDescriptor.Prefix, descriptor.Prefix, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TagName, descriptor.TagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.FullTagName, descriptor.FullTagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TypeName, descriptor.TypeName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.AssemblyName, descriptor.AssemblyName, StringComparer.Ordinal); - Assert.Empty(descriptor.Attributes); - Assert.Equal(expectedDescriptor.RequiredAttributes, descriptor.RequiredAttributes, TagHelperRequiredAttributeDescriptorComparer.Default); - Assert.Equal( - expectedDescriptor.DesignTimeDescriptor, - descriptor.DesignTimeDescriptor, - TagHelperDesignTimeDescriptorComparer.Default); - Assert.Empty(descriptor.PropertyBag); - } - - [Fact] - public void TagHelperDescriptor_WithAttributes_CanBeDeserialized() - { - // Arrange - var serializedDescriptor = - $"{{\"{ nameof(TagHelperDescriptor.Prefix) }\":\"prefix:\"," + - $"\"{ nameof(TagHelperDescriptor.TagName) }\":\"tag name\"," + - $"\"{ nameof(TagHelperDescriptor.FullTagName) }\":\"prefix:tag name\"," + - $"\"{ nameof(TagHelperDescriptor.TypeName) }\":\"type name\"," + - $"\"{ nameof(TagHelperDescriptor.AssemblyName) }\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.Attributes) }\":[" + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute one\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"property type name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}," + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute two\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"{ typeof(string).FullName }\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":null," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":null," + - $"\"{nameof(TagHelperDescriptor.TagStructure)}\":0," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":null}}"; - var expectedDescriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "attribute one", - PropertyName = "property name", - TypeName = "property type name", - IsEnum = true, - }, - new TagHelperAttributeDescriptor - { - Name = "attribute two", - PropertyName = "property name", - TypeName = typeof(string).FullName, - IsEnum = false, - IsStringProperty = true - }, - }, - AllowedChildren = new[] { "allowed child one", "allowed child two" } - }; - - // Act - var descriptor = JsonConvert.DeserializeObject(serializedDescriptor); - - // Assert - Assert.NotNull(descriptor); - Assert.Equal(expectedDescriptor.Prefix, descriptor.Prefix, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TagName, descriptor.TagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.FullTagName, descriptor.FullTagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TypeName, descriptor.TypeName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.AssemblyName, descriptor.AssemblyName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.Attributes, descriptor.Attributes, TagHelperAttributeDescriptorComparer.Default); - Assert.Empty(descriptor.RequiredAttributes); - Assert.Empty(descriptor.PropertyBag); - } - - [Fact] - public void TagHelperDescriptor_WithIndexerAttributes_CanBeDeserialized() - { - // Arrange - var serializedDescriptor = - $"{{\"{ nameof(TagHelperDescriptor.Prefix) }\":\"prefix:\"," + - $"\"{ nameof(TagHelperDescriptor.TagName) }\":\"tag name\"," + - $"\"{ nameof(TagHelperDescriptor.FullTagName) }\":\"prefix:tag name\"," + - $"\"{ nameof(TagHelperDescriptor.TypeName) }\":\"type name\"," + - $"\"{ nameof(TagHelperDescriptor.AssemblyName) }\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.Attributes) }\":[" + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute one\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"property type name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}," + - $"{{\"{ nameof(TagHelperAttributeDescriptor.IsIndexer) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsEnum) }\":false," + - $"\"{ nameof(TagHelperAttributeDescriptor.IsStringProperty) }\":true," + - $"\"{ nameof(TagHelperAttributeDescriptor.Name) }\":\"attribute two\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.PropertyName) }\":\"property name\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.TypeName) }\":\"{ typeof(string).FullName }\"," + - $"\"{ nameof(TagHelperAttributeDescriptor.DesignTimeDescriptor) }\":null}}]," + - $"\"{ nameof(TagHelperDescriptor.RequiredAttributes) }\":[]," + - $"\"{ nameof(TagHelperDescriptor.AllowedChildren) }\":null," + - $"\"{ nameof(TagHelperDescriptor.RequiredParent) }\":null," + - $"\"{nameof(TagHelperDescriptor.TagStructure)}\":1," + - $"\"{ nameof(TagHelperDescriptor.DesignTimeDescriptor) }\":null," + - $"\"{ nameof(TagHelperDescriptor.PropertyBag) }\":{{}}}}"; - - var expectedDescriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "attribute one", - PropertyName = "property name", - TypeName = "property type name", - IsIndexer = true, - IsEnum = true, - }, - new TagHelperAttributeDescriptor - { - Name = "attribute two", - PropertyName = "property name", - TypeName = typeof(string).FullName, - IsIndexer = true, - IsEnum = false, - IsStringProperty = true - } - }, - TagStructure = TagStructure.NormalOrSelfClosing - }; - - // Act - var descriptor = JsonConvert.DeserializeObject(serializedDescriptor); - - // Assert - Assert.NotNull(descriptor); - Assert.Equal(expectedDescriptor.Prefix, descriptor.Prefix, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TagName, descriptor.TagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.FullTagName, descriptor.FullTagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TypeName, descriptor.TypeName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.AssemblyName, descriptor.AssemblyName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.Attributes, descriptor.Attributes, TagHelperAttributeDescriptorComparer.Default); - Assert.Empty(descriptor.RequiredAttributes); - Assert.Empty(descriptor.PropertyBag); - } - - [Fact] - public void TagHelperDescriptor_WithPropertyBagElements_CanBeDeserialized() - { - // Arrange - var serializedDescriptor = - $"{{\"{nameof(TagHelperDescriptor.Prefix)}\":\"prefix:\"," + - $"\"{nameof(TagHelperDescriptor.TagName)}\":\"tag name\"," + - $"\"{nameof(TagHelperDescriptor.TypeName)}\":\"type name\"," + - $"\"{nameof(TagHelperDescriptor.AssemblyName)}\":\"assembly name\"," + - $"\"{ nameof(TagHelperDescriptor.PropertyBag) }\":" + - "{\"key one\":\"value one\",\"key two\":\"value two\"}}"; - var expectedDescriptor = new TagHelperDescriptor - { - Prefix = "prefix:", - TagName = "tag name", - TypeName = "type name", - AssemblyName = "assembly name" - }; - - expectedDescriptor.PropertyBag.Add("key one", "value one"); - expectedDescriptor.PropertyBag.Add("key two", "value two"); - - // Act - var descriptor = JsonConvert.DeserializeObject(serializedDescriptor); - - // Assert - Assert.NotNull(descriptor); - Assert.Equal(expectedDescriptor.Prefix, descriptor.Prefix, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TagName, descriptor.TagName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.TypeName, descriptor.TypeName, StringComparer.Ordinal); - Assert.Equal(expectedDescriptor.AssemblyName, descriptor.AssemblyName, StringComparer.Ordinal); - Assert.Empty(descriptor.Attributes); - Assert.Empty(descriptor.RequiredAttributes); - Assert.Equal(expectedDescriptor.PropertyBag["key one"], descriptor.PropertyBag["key one"]); - Assert.Equal(expectedDescriptor.PropertyBag["key two"], descriptor.PropertyBag["key two"]); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorTest.cs deleted file mode 100644 index eca127af6a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Compilation/TagHelpers/TagHelperRequiredAttributeDescriptorTest.cs +++ /dev/null @@ -1,173 +0,0 @@ -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Compilation.TagHelpers -{ - public class TagHelperRequiredAttributeDescriptorTest - { - public static TheoryData RequiredAttributeDescriptorData - { - get - { - // requiredAttributeDescriptor, attributeName, attributeValue, expectedResult - return new TheoryData - { - { - new TagHelperRequiredAttributeDescriptor - { - Name = "key" - }, - "KeY", - "value", - true - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "key" - }, - "keys", - "value", - false - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "route-", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - }, - "ROUTE-area", - "manage", - true - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "route-", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - }, - "routearea", - "manage", - false - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "route-", - NameComparison = TagHelperRequiredAttributeNameComparison.PrefixMatch, - }, - "route-", - "manage", - false - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "key", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - }, - "KeY", - "value", - true - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "key", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - }, - "keys", - "value", - false - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "key", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "value", - ValueComparison = TagHelperRequiredAttributeValueComparison.FullMatch, - }, - "key", - "value", - true - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "key", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "value", - ValueComparison = TagHelperRequiredAttributeValueComparison.FullMatch, - }, - "key", - "Value", - false - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "class", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "btn", - ValueComparison = TagHelperRequiredAttributeValueComparison.PrefixMatch, - }, - "class", - "btn btn-success", - true - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "class", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "btn", - ValueComparison = TagHelperRequiredAttributeValueComparison.PrefixMatch, - }, - "class", - "BTN btn-success", - false - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "href", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "#navigate", - ValueComparison = TagHelperRequiredAttributeValueComparison.SuffixMatch, - }, - "href", - "/home/index#navigate", - true - }, - { - new TagHelperRequiredAttributeDescriptor - { - Name = "href", - NameComparison = TagHelperRequiredAttributeNameComparison.FullMatch, - Value = "#navigate", - ValueComparison = TagHelperRequiredAttributeValueComparison.SuffixMatch, - }, - "href", - "/home/index#NAVigate", - false - }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredAttributeDescriptorData))] - public void Matches_ReturnsExpectedResult( - TagHelperRequiredAttributeDescriptor requiredAttributeDescriptor, - string attributeName, - string attributeValue, - bool expectedResult) - { - // Act - var result = requiredAttributeDescriptor.IsMatch(attributeName, attributeValue); - - // Assert - Assert.Equal(expectedResult, result); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Editor/AutoCompleteEditHandlerTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Editor/AutoCompleteEditHandlerTest.cs deleted file mode 100644 index 892ec81b3e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Editor/AutoCompleteEditHandlerTest.cs +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class AutoCompleteEditHandlerTest - { -#pragma warning disable 618 // Ignore obsolete warning for EditorHints - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - AutoCompleteString = "one string", - EditorHints = EditorHints.VirtualPath, - }, - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - AutoCompleteString = "one string", - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Tokenizer not involved in equality check or hash code calculation. - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - AutoCompleteString = "two string", - EditorHints = EditorHints.None, - }, - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - AutoCompleteString = "two string", - EditorHints = EditorHints.None, - } - }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - AutoCompleteString = "three string", - EditorHints = EditorHints.VirtualPath, - }, - null - }, - { - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - AutoCompleteString = "three string", - EditorHints = EditorHints.VirtualPath, - }, - new object() - }, - { - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - AutoCompleteString = "three string", - EditorHints = EditorHints.VirtualPath, - }, - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - }, - { - // Different AcceptedCharacters. - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - AutoCompleteString = "three string", - EditorHints = EditorHints.VirtualPath, - }, - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - AutoCompleteString = "three string", - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different AutoCompleteAtEndOfSpan. - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - AutoCompleteString = "four string", - EditorHints = EditorHints.None, - }, - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - AutoCompleteString = "four string", - EditorHints = EditorHints.None, - } - }, - { - // Different AutoCompleteString. - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.NewLine, - AutoCompleteString = "some string", - EditorHints = EditorHints.None, - }, - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.NewLine, - AutoCompleteString = "different string", - EditorHints = EditorHints.None, - } - }, - { - // Different AutoCompleteString (case sensitive). - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.None, - AutoCompleteString = "some string", - EditorHints = EditorHints.VirtualPath, - }, - new AutoCompleteEditHandler(tokenizer: null, autoCompleteAtEndOfSpan: false) - { - AcceptedCharacters = AcceptedCharacters.None, - AutoCompleteString = "Some String", - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different EditorHints. - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace, - AutoCompleteString = "five string", - EditorHints = EditorHints.VirtualPath, - }, - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace, - AutoCompleteString = "five string", - EditorHints = EditorHints.None, - } - }, - }; - } - } -#pragma warning restore 618 // Ignore obsolete warning for EditorHints - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected(AutoCompleteEditHandler leftObject, AutoCompleteEditHandler rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(AutoCompleteEditHandler leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual( - AutoCompleteEditHandler leftObject, - AutoCompleteEditHandler rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Editor/ImplicitExpressionEditHandlerTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Editor/ImplicitExpressionEditHandlerTest.cs deleted file mode 100644 index b0cb4dd719..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Editor/ImplicitExpressionEditHandlerTest.cs +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class ImplicitExpressionEditHandlerTest - { -#pragma warning disable 618 // Ignore obsolete warning for EditorHints - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { - new ImplicitExpressionEditHandler( - tokenizer: null, - keywords: new HashSet(), - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new ImplicitExpressionEditHandler( - tokenizer: null, - keywords: new HashSet(), - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Tokenizer not involved in equality check or hash code calculation. - new ImplicitExpressionEditHandler( - tokenizer: null, - keywords: new HashSet { "keyword 1" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 1" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - } - }, - { - // Only comparers are different (HashSet's comparer does not affect GetHashCode of entries). - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 2", "keyword 3" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet(StringComparer.OrdinalIgnoreCase) { "keyword 2", "keyword 3" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - } - }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet { "keyword 4" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.WhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - null - }, - { - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet { "keyword 4" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.WhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new object() - }, - { - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet { "keyword 4" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.WhiteSpace, - EditorHints = EditorHints.None, - }, - new SpanEditHandler( tokenizer: _ => null) - }, - { - // Different AcceptedCharacters. - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 5" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 5" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different AcceptTrailingDot. - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet { "keyword 6" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - EditorHints = EditorHints.VirtualPath, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet { "keyword 6" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different Keywords. - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 7" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.NewLine, - EditorHints = EditorHints.None, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 8" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.NewLine, - EditorHints = EditorHints.None, - } - }, - { - // Different Keywords comparers (Equals uses left comparer). - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet { "keyword 9" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.None, - EditorHints = EditorHints.VirtualPath, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => null, - keywords: new HashSet(StringComparer.OrdinalIgnoreCase) { "KEYWORD 9" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.None, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different Keywords (count). - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 10" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace, - EditorHints = EditorHints.None, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 10", "keyword 11" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace, - EditorHints = EditorHints.None, - } - }, - { - // Different Keywords (count). - new ImplicitExpressionEditHandler( - tokenizer: null, - keywords: new HashSet { "keyword 12" }, - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.WhiteSpace, - EditorHints = EditorHints.None, - }, - new ImplicitExpressionEditHandler( - tokenizer: null, - keywords: new HashSet(), - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.WhiteSpace, - EditorHints = EditorHints.None, - } - }, - { - // Different EditorHints. - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 13" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new ImplicitExpressionEditHandler( - tokenizer: _ => Enumerable.Empty(), - keywords: new HashSet { "keyword 13" }, - acceptTrailingDot: true) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.None, - } - }, - }; - } - } -#pragma warning restore 618 // Ignore obsolete warning for EditorHints - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected( - ImplicitExpressionEditHandler leftObject, - ImplicitExpressionEditHandler rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(ImplicitExpressionEditHandler leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual( - ImplicitExpressionEditHandler leftObject, - ImplicitExpressionEditHandler rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Editor/SpanEditHandlerTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Editor/SpanEditHandlerTest.cs deleted file mode 100644 index eb21188b47..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Editor/SpanEditHandlerTest.cs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Editor -{ - public class SpanEditHandlerTest - { -#pragma warning disable 618 // Ignore obsolete warning for EditorHints - public static TheoryData MatchingTestDataSet - { - get - { - return new TheoryData - { - { - new SpanEditHandler(tokenizer: null) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new SpanEditHandler(tokenizer: null) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Tokenizer not involved in equality check or hash code calculation. - new SpanEditHandler(tokenizer: null) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - }, - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - } - }, - }; - } - } - - public static TheoryData NonMatchingTestDataSet - { - get - { - return new TheoryData - { - { - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - null - }, - { - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new object() - }, - { - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.Any, - EditorHints = EditorHints.None, - }, - new AutoCompleteEditHandler( - tokenizer: _ => Enumerable.Empty(), - autoCompleteAtEndOfSpan: true) - { - AcceptedCharacters = AcceptedCharacters.Any, - AutoCompleteString = "two string", - EditorHints = EditorHints.None, - } - }, - { - new SpanEditHandler(tokenizer: null) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - EditorHints = EditorHints.VirtualPath, - }, - new ImplicitExpressionEditHandler( - tokenizer: null, - keywords: new HashSet(), - acceptTrailingDot: false) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different AcceptedCharacters. - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.AllWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.AnyExceptNewline, - EditorHints = EditorHints.VirtualPath, - } - }, - { - // Different EditorHints. - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace, - EditorHints = EditorHints.VirtualPath, - }, - new SpanEditHandler(tokenizer: _ => Enumerable.Empty()) - { - AcceptedCharacters = AcceptedCharacters.NonWhiteSpace, - EditorHints = EditorHints.None, - } - }, - }; - } - } -#pragma warning restore 618 // Ignore obsolete warning for EditorHints - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void Equals_True_WhenExpected(SpanEditHandler leftObject, SpanEditHandler rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.True(result); - } - - [Theory] - [MemberData(nameof(NonMatchingTestDataSet))] - public void Equals_False_WhenExpected(SpanEditHandler leftObject, object rightObject) - { - // Arrange & Act - var result = leftObject.Equals(rightObject); - - // Assert - Assert.False(result); - } - - [Theory] - [MemberData(nameof(MatchingTestDataSet))] - public void GetHashCode_ReturnsSameValue_WhenEqual(SpanEditHandler leftObject, SpanEditHandler rightObject) - { - // Arrange & Act - var leftResult = leftObject.GetHashCode(); - var rightResult = rightObject.GetHashCode(); - - // Assert - Assert.Equal(leftResult, rightResult); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockExtensions.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockExtensions.cs deleted file mode 100644 index b756173f4b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public static class BlockExtensions - { - public static void LinkNodes(this Block self) - { - Span first = null; - Span previous = null; - foreach (Span span in self.Flatten()) - { - if (first == null) - { - first = span; - } - span.Previous = previous; - - if (previous != null) - { - previous.Next = span; - } - previous = span; - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockFactory.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockFactory.cs deleted file mode 100644 index 8d65d4dbfe..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockFactory.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public class BlockFactory - { - private SpanFactory _factory; - - public BlockFactory(SpanFactory factory) - { - _factory = factory; - } - - public Block EscapedMarkupTagBlock(string prefix, string suffix) - { - return EscapedMarkupTagBlock(prefix, suffix, AcceptedCharacters.Any); - } - - public Block EscapedMarkupTagBlock(string prefix, string suffix, params SyntaxTreeNode[] children) - { - return EscapedMarkupTagBlock(prefix, suffix, AcceptedCharacters.Any, children); - } - - public Block EscapedMarkupTagBlock( - string prefix, - string suffix, - AcceptedCharacters acceptedCharacters, - params SyntaxTreeNode[] children) - { - var newChildren = new List( - new SyntaxTreeNode[] - { - _factory.Markup(prefix), - _factory.BangEscape(), - _factory.Markup(suffix).Accepts(acceptedCharacters) - }); - - newChildren.AddRange(children); - - return new MarkupTagBlock(newChildren.ToArray()); - } - - public Block MarkupTagBlock(string content) - { - return MarkupTagBlock(content, AcceptedCharacters.Any); - } - - public Block MarkupTagBlock(string content, AcceptedCharacters acceptedCharacters) - { - return new MarkupTagBlock( - _factory.Markup(content).Accepts(acceptedCharacters) - ); - } - - public Block TagHelperBlock( - string tagName, - TagMode tagMode, - SourceLocation start, - Block startTag, - SyntaxTreeNode[] children, - Block endTag) - { - var builder = new TagHelperBlockBuilder( - tagName, - tagMode, - attributes: new List(), - children: children) - { - Start = start, - SourceStartTag = startTag, - SourceEndTag = endTag - }; - - return builder.Build(); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockTypes.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockTypes.cs deleted file mode 100644 index c64aeffd5c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/BlockTypes.cs +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - // The product code doesn't need this, but having subclasses for the block types makes tests much cleaner :) - - public class StatementBlock : Block - { - private const BlockType ThisBlockType = BlockType.Statement; - - public StatementBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public StatementBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public StatementBlock(params SyntaxTreeNode[] children) - : this(ParentChunkGenerator.Null, children) - { - } - } - - public class DirectiveBlock : Block - { - private const BlockType ThisBlockType = BlockType.Directive; - - public DirectiveBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public DirectiveBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public DirectiveBlock(params SyntaxTreeNode[] children) - : this(ParentChunkGenerator.Null, children) - { - } - } - - public class FunctionsBlock : Block - { - private const BlockType ThisBlockType = BlockType.Functions; - - public FunctionsBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public FunctionsBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public FunctionsBlock(params SyntaxTreeNode[] children) - : this(ParentChunkGenerator.Null, children) - { - } - } - - public class ExpressionBlock : Block - { - private const BlockType ThisBlockType = BlockType.Expression; - - public ExpressionBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public ExpressionBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public ExpressionBlock(params SyntaxTreeNode[] children) - : this(new ExpressionChunkGenerator(), children) - { - } - } - - public class MarkupTagBlock : Block - { - private const BlockType ThisBlockType = BlockType.Tag; - - public MarkupTagBlock(params SyntaxTreeNode[] children) - : base(ThisBlockType, children, ParentChunkGenerator.Null) - { - } - } - - public class MarkupBlock : Block - { - private const BlockType ThisBlockType = BlockType.Markup; - - public MarkupBlock( - BlockType blockType, - IParentChunkGenerator chunkGenerator, - IReadOnlyList children) - : base(blockType, children, chunkGenerator) - { - } - - public MarkupBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : this(ThisBlockType, chunkGenerator, children) - { - } - - public MarkupBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public MarkupBlock(params SyntaxTreeNode[] children) - : this(ParentChunkGenerator.Null, children) - { - } - } - - public class MarkupTagHelperBlock : TagHelperBlock - { - public MarkupTagHelperBlock(string tagName) - : this(tagName, tagMode: TagMode.StartTagAndEndTag, attributes: new List()) - { - } - - public MarkupTagHelperBlock(string tagName, TagMode tagMode) - : this(tagName, tagMode, new List()) - { - } - - public MarkupTagHelperBlock( - string tagName, - IList attributes) - : this(tagName, TagMode.StartTagAndEndTag, attributes, children: new SyntaxTreeNode[0]) - { - } - - public MarkupTagHelperBlock( - string tagName, - TagMode tagMode, - IList attributes) - : this(tagName, tagMode, attributes, new SyntaxTreeNode[0]) - { - } - - public MarkupTagHelperBlock(string tagName, params SyntaxTreeNode[] children) - : this( - tagName, - TagMode.StartTagAndEndTag, - attributes: new List(), - children: children) - { - } - - public MarkupTagHelperBlock(string tagName, TagMode tagMode, params SyntaxTreeNode[] children) - : this(tagName, tagMode, new List(), children) - { - } - - public MarkupTagHelperBlock( - string tagName, - IList attributes, - params SyntaxTreeNode[] children) - : base(new TagHelperBlockBuilder( - tagName, - TagMode.StartTagAndEndTag, - attributes: attributes, - children: children)) - { - } - - public MarkupTagHelperBlock( - string tagName, - TagMode tagMode, - IList attributes, - params SyntaxTreeNode[] children) - : base(new TagHelperBlockBuilder(tagName, tagMode, attributes, children)) - { - } - } - - public class SectionBlock : Block - { - private const BlockType ThisBlockType = BlockType.Section; - - public SectionBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public SectionBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public SectionBlock(params SyntaxTreeNode[] children) - : this(ParentChunkGenerator.Null, children) - { - } - - public SectionBlock(IReadOnlyList children) - : this(ParentChunkGenerator.Null, children) - { - } - } - - public class TemplateBlock : Block - { - private const BlockType ThisBlockType = BlockType.Template; - - public TemplateBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public TemplateBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public TemplateBlock(params SyntaxTreeNode[] children) - : this(new TemplateBlockChunkGenerator(), children) - { - } - - public TemplateBlock(IReadOnlyList children) - : this(new TemplateBlockChunkGenerator(), children) - { - } - } - - public class CommentBlock : Block - { - private const BlockType ThisBlockType = BlockType.Comment; - - public CommentBlock(IParentChunkGenerator chunkGenerator, IReadOnlyList children) - : base(ThisBlockType, children, chunkGenerator) - { - } - - public CommentBlock(IParentChunkGenerator chunkGenerator, params SyntaxTreeNode[] children) - : this(chunkGenerator, (IReadOnlyList)children) - { - } - - public CommentBlock(params SyntaxTreeNode[] children) - : this(new RazorCommentChunkGenerator(), children) - { - } - - public CommentBlock(IReadOnlyList children) - : this(new RazorCommentChunkGenerator(), children) - { - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/CodeParserTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/CodeParserTestBase.cs deleted file mode 100644 index b332618e4b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/CodeParserTestBase.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public abstract class CodeParserTestBase : ParserTestBase - { - protected abstract ISet KeywordSet { get; } - - protected override ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser) - { - return codeParser; - } - - protected void ImplicitExpressionTest(string input, params RazorError[] errors) - { - ImplicitExpressionTest(input, AcceptedCharacters.NonWhiteSpace, errors); - } - - protected void ImplicitExpressionTest(string input, AcceptedCharacters acceptedCharacters, params RazorError[] errors) - { - ImplicitExpressionTest(input, input, acceptedCharacters, errors); - } - - protected void ImplicitExpressionTest(string input, string expected, params RazorError[] errors) - { - ImplicitExpressionTest(input, expected, AcceptedCharacters.NonWhiteSpace, errors); - } - - protected override void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - SingleSpanBlockTest(document, blockType, spanType, acceptedCharacters, expectedError: null); - } - - protected override void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - SingleSpanBlockTest(document, spanContent, blockType, spanType, acceptedCharacters, expectedErrors: null); - } - - protected override void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, params RazorError[] expectedError) - { - SingleSpanBlockTest(document, document, blockType, spanType, expectedError); - } - - protected override void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, params RazorError[] expectedErrors) - { - SingleSpanBlockTest(document, spanContent, blockType, spanType, AcceptedCharacters.Any, expectedErrors ?? new RazorError[0]); - } - - protected override void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedError) - { - SingleSpanBlockTest(document, document, blockType, spanType, acceptedCharacters, expectedError); - } - - protected override void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedErrors) - { - var b = CreateSimpleBlockAndSpan(spanContent, blockType, spanType, acceptedCharacters); - ParseBlockTest(document, b, expectedErrors ?? new RazorError[0]); - } - - protected void ImplicitExpressionTest(string input, string expected, AcceptedCharacters acceptedCharacters, params RazorError[] errors) - { - var factory = CreateSpanFactory(); - ParseBlockTest(SyntaxConstants.TransitionString + input, - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(expected) - .AsImplicitExpression(KeywordSet) - .Accepts(acceptedCharacters)), - errors); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlCodeParserTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlCodeParserTestBase.cs deleted file mode 100644 index 8f30fe7b87..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlCodeParserTestBase.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.Internal; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public abstract class CsHtmlCodeParserTestBase : CodeParserTestBase - { - protected override ISet KeywordSet - { - get { return CSharpCodeParser.DefaultKeywords; } - } - - protected override BlockFactory CreateBlockFactory() - { - return new BlockFactory(Factory ?? CreateSpanFactory()); - } - - protected override SpanFactory CreateSpanFactory() - { - return SpanFactory.CreateCsHtml(); - } - - public override ParserBase CreateMarkupParser() - { - return new HtmlMarkupParser(); - } - - public override ParserBase CreateCodeParser() - { - return new CSharpCodeParser(); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlMarkupParserTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlMarkupParserTestBase.cs deleted file mode 100644 index 4576949324..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/CsHtmlMarkupParserTestBase.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.Internal; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public abstract class CsHtmlMarkupParserTestBase : MarkupParserTestBase - { - protected override ISet KeywordSet - { - get { return CSharpCodeParser.DefaultKeywords; } - } - - protected override BlockFactory CreateBlockFactory() - { - return new BlockFactory(Factory ?? CreateSpanFactory()); - } - - protected override SpanFactory CreateSpanFactory() - { - return SpanFactory.CreateCsHtml(); - } - - public override ParserBase CreateMarkupParser() - { - return new HtmlMarkupParser(); - } - - public override ParserBase CreateCodeParser() - { - return new CSharpCodeParser(); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/ErrorCollector.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/ErrorCollector.cs deleted file mode 100644 index 57413774a4..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/ErrorCollector.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Text; -using Microsoft.AspNetCore.Razor.Parser; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public class ErrorCollector - { - private StringBuilder _message = new StringBuilder(); - private int _indent = 0; - - public bool Success { get; private set; } - - public string Message - { - get { return _message.ToString(); } - } - - public ErrorCollector() - { - Success = true; - } - - public void AddError(string msg, params object[] args) - { - Append("F", msg, args); - Success = false; - } - - public void AddMessage(string msg, params object[] args) - { - Append("P", msg, args); - } - - public IDisposable Indent() - { - _indent++; - return new DisposableAction(Unindent); - } - - public void Unindent() - { - _indent--; - } - - private void Append(string prefix, string msg, object[] args) - { - _message.Append(prefix); - _message.Append(":"); - _message.Append(new String('\t', _indent)); - _message.AppendFormat(msg, args); - _message.AppendLine(); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/MarkupParserTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/MarkupParserTestBase.cs deleted file mode 100644 index 19c69d91ca..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/MarkupParserTestBase.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public abstract class MarkupParserTestBase : CodeParserTestBase - { - protected override ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser) - { - return markupParser; - } - - protected virtual void SingleSpanDocumentTest(string document, BlockType blockType, SpanKind spanType) - { - var b = CreateSimpleBlockAndSpan(document, blockType, spanType); - ParseDocumentTest(document, b); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/ParserTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/ParserTestBase.cs deleted file mode 100644 index 5d22d33a4f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/ParserTestBase.cs +++ /dev/null @@ -1,543 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public abstract class ParserTestBase - { - protected static Block IgnoreOutput = new IgnoreOutputBlock(); - - public SpanFactory Factory { get; private set; } - public BlockFactory BlockFactory { get; private set; } - - protected ParserTestBase() - { - Factory = CreateSpanFactory(); - BlockFactory = CreateBlockFactory(); - } - - public abstract ParserBase CreateMarkupParser(); - public abstract ParserBase CreateCodeParser(); - - protected abstract ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser); - - public virtual ParserContext CreateParserContext(ITextDocument input, - ParserBase codeParser, - ParserBase markupParser, - ErrorSink errorSink) - { - return new ParserContext(input, - codeParser, - markupParser, - SelectActiveParser(codeParser, markupParser), - errorSink); - } - - protected abstract SpanFactory CreateSpanFactory(); - protected abstract BlockFactory CreateBlockFactory(); - - protected virtual void ParseBlockTest(string document) - { - ParseBlockTest(document, null, false, new RazorError[0]); - } - - protected virtual void ParseBlockTest(string document, bool designTimeParser) - { - ParseBlockTest(document, null, designTimeParser, new RazorError[0]); - } - - protected virtual void ParseBlockTest(string document, params RazorError[] expectedErrors) - { - ParseBlockTest(document, false, expectedErrors); - } - - protected virtual void ParseBlockTest(string document, bool designTimeParser, params RazorError[] expectedErrors) - { - ParseBlockTest(document, null, designTimeParser, expectedErrors); - } - - protected virtual void ParseBlockTest(string document, Block expectedRoot) - { - ParseBlockTest(document, expectedRoot, false, null); - } - - protected virtual void ParseBlockTest(string document, Block expectedRoot, bool designTimeParser) - { - ParseBlockTest(document, expectedRoot, designTimeParser, null); - } - - protected virtual void ParseBlockTest(string document, Block expectedRoot, params RazorError[] expectedErrors) - { - ParseBlockTest(document, expectedRoot, false, expectedErrors); - } - - protected virtual void ParseBlockTest(string document, Block expectedRoot, bool designTimeParser, params RazorError[] expectedErrors) - { - RunParseTest(document, parser => parser.ParseBlock, expectedRoot, (expectedErrors ?? new RazorError[0]).ToList(), designTimeParser); - } - - protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - SingleSpanBlockTest(document, blockType, spanType, acceptedCharacters, expectedError: null); - } - - protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - SingleSpanBlockTest(document, spanContent, blockType, spanType, acceptedCharacters, expectedErrors: null); - } - - protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, params RazorError[] expectedError) - { - SingleSpanBlockTest(document, document, blockType, spanType, expectedError); - } - - protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, params RazorError[] expectedErrors) - { - SingleSpanBlockTest(document, spanContent, blockType, spanType, AcceptedCharacters.Any, expectedErrors ?? new RazorError[0]); - } - - protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedError) - { - SingleSpanBlockTest(document, document, blockType, spanType, acceptedCharacters, expectedError); - } - - protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedErrors) - { - var builder = new BlockBuilder(); - builder.Type = blockType; - ParseBlockTest( - document, - ConfigureAndAddSpanToBlock( - builder, - Factory.Span(spanType, spanContent, spanType == SpanKind.Markup) - .Accepts(acceptedCharacters)), - expectedErrors ?? new RazorError[0]); - } - - protected virtual void ParseDocumentTest(string document) - { - ParseDocumentTest(document, null, false); - } - - protected virtual void ParseDocumentTest(string document, Block expectedRoot) - { - ParseDocumentTest(document, expectedRoot, false, null); - } - - protected virtual void ParseDocumentTest(string document, Block expectedRoot, params RazorError[] expectedErrors) - { - ParseDocumentTest(document, expectedRoot, false, expectedErrors); - } - - protected virtual void ParseDocumentTest(string document, bool designTimeParser) - { - ParseDocumentTest(document, null, designTimeParser); - } - - protected virtual void ParseDocumentTest(string document, Block expectedRoot, bool designTimeParser) - { - ParseDocumentTest(document, expectedRoot, designTimeParser, null); - } - - protected virtual void ParseDocumentTest(string document, Block expectedRoot, bool designTimeParser, params RazorError[] expectedErrors) - { - RunParseTest(document, parser => parser.ParseDocument, expectedRoot, expectedErrors, designTimeParser, parserSelector: c => c.MarkupParser); - } - - protected virtual ParserResults ParseDocument(string document) - { - return ParseDocument(document, designTimeParser: false, errorSink: null); - } - - protected virtual ParserResults ParseDocument(string document, ErrorSink errorSink) - { - return ParseDocument(document, designTimeParser: false, errorSink: errorSink); - } - - protected virtual ParserResults ParseDocument(string document, - bool designTimeParser, - ErrorSink errorSink) - { - return RunParse(document, - parser => parser.ParseDocument, - designTimeParser, - parserSelector: c => c.MarkupParser, - errorSink: errorSink); - } - - protected virtual ParserResults ParseBlock(string document) - { - return ParseBlock(document, designTimeParser: false); - } - - protected virtual ParserResults ParseBlock(string document, bool designTimeParser) - { - return RunParse(document, parser => parser.ParseBlock, designTimeParser); - } - - protected virtual ParserResults RunParse(string document, - Func parserActionSelector, - bool designTimeParser, - Func parserSelector = null, - ErrorSink errorSink = null) - { - parserSelector = parserSelector ?? (c => c.ActiveParser); - errorSink = errorSink ?? new ErrorSink(); - - // Create the source - ParserResults results = null; - using (var reader = new SeekableTextReader(document)) - { - try - { - var codeParser = CreateCodeParser(); - var markupParser = CreateMarkupParser(); - var context = CreateParserContext(reader, codeParser, markupParser, errorSink); - context.DesignTimeMode = designTimeParser; - - codeParser.Context = context; - markupParser.Context = context; - - // Run the parser - parserActionSelector(parserSelector(context))(); - results = context.CompleteParse(); - } - finally - { - if (results != null && results.Document != null) - { - WriteTraceLine(string.Empty); - WriteTraceLine("Actual Parse Tree:"); - WriteNode(0, results.Document); - } - } - } - return results; - } - - protected virtual void RunParseTest(string document, Func parserActionSelector, Block expectedRoot, IList expectedErrors, bool designTimeParser, Func parserSelector = null) - { - // Create the source - var results = RunParse(document, parserActionSelector, designTimeParser, parserSelector); - - // Evaluate the results - if (!ReferenceEquals(expectedRoot, IgnoreOutput)) - { - EvaluateResults(results, expectedRoot, expectedErrors); - } - } - - [Conditional("PARSER_TRACE")] - private void WriteNode(int indent, SyntaxTreeNode node) - { - var content = node.ToString().Replace("\r", "\\r") - .Replace("\n", "\\n") - .Replace("{", "{{") - .Replace("}", "}}"); - if (indent > 0) - { - content = new String('.', indent * 2) + content; - } - WriteTraceLine(content); - var block = node as Block; - if (block != null) - { - foreach (SyntaxTreeNode child in block.Children) - { - WriteNode(indent + 1, child); - } - } - } - - public static void EvaluateResults(ParserResults results, Block expectedRoot) - { - EvaluateResults(results, expectedRoot, null); - } - - public static void EvaluateResults(ParserResults results, Block expectedRoot, IList expectedErrors) - { - EvaluateParseTree(results.Document, expectedRoot); - EvaluateRazorErrors(results.ParserErrors, expectedErrors); - } - - public static void EvaluateParseTree(Block actualRoot, Block expectedRoot) - { - // Evaluate the result - var collector = new ErrorCollector(); - - if (expectedRoot == null) - { - Assert.Null(actualRoot); - } - else - { - // Link all the nodes - expectedRoot.LinkNodes(); - Assert.NotNull(actualRoot); - EvaluateSyntaxTreeNode(collector, actualRoot, expectedRoot); - if (collector.Success) - { - WriteTraceLine("Parse Tree Validation Succeeded:" + Environment.NewLine + collector.Message); - } - else - { - Assert.True(false, Environment.NewLine + collector.Message); - } - } - } - - private static void EvaluateSyntaxTreeNode(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected) - { - if (actual == null) - { - AddNullActualError(collector, actual, expected); - return; - } - - if (actual.IsBlock != expected.IsBlock) - { - AddMismatchError(collector, actual, expected); - } - else - { - if (expected.IsBlock) - { - EvaluateBlock(collector, (Block)actual, (Block)expected); - } - else - { - EvaluateSpan(collector, (Span)actual, (Span)expected); - } - } - } - - private static void EvaluateTagHelperAttribute( - ErrorCollector collector, - TagHelperAttributeNode actual, - TagHelperAttributeNode expected) - { - if (actual.Name != expected.Name) - { - collector.AddError("{0} - FAILED :: Attribute names do not match", expected.Name); - } - else - { - collector.AddMessage("{0} - PASSED :: Attribute names match", expected.Name); - } - - if (actual.ValueStyle != expected.ValueStyle) - { - collector.AddError("{0} - FAILED :: Attribute value styles do not match", expected.ValueStyle.ToString()); - } - else - { - collector.AddMessage("{0} - PASSED :: Attribute value style match", expected.ValueStyle); - } - - if (actual.ValueStyle != HtmlAttributeValueStyle.Minimized) - { - EvaluateSyntaxTreeNode(collector, actual.Value, expected.Value); - } - } - - private static void EvaluateSpan(ErrorCollector collector, Span actual, Span expected) - { - if (!Equals(expected, actual)) - { - AddMismatchError(collector, actual, expected); - } - else - { - AddPassedMessage(collector, expected); - } - } - - private static void EvaluateBlock(ErrorCollector collector, Block actual, Block expected) - { - if (actual.Type != expected.Type || !expected.ChunkGenerator.Equals(actual.ChunkGenerator)) - { - AddMismatchError(collector, actual, expected); - } - else - { - if (actual is TagHelperBlock) - { - EvaluateTagHelperBlock(collector, actual as TagHelperBlock, expected as TagHelperBlock); - } - - AddPassedMessage(collector, expected); - using (collector.Indent()) - { - var expectedNodes = expected.Children.GetEnumerator(); - var actualNodes = actual.Children.GetEnumerator(); - while (expectedNodes.MoveNext()) - { - if (!actualNodes.MoveNext()) - { - collector.AddError("{0} - FAILED :: No more elements at this node", expectedNodes.Current); - } - else - { - EvaluateSyntaxTreeNode(collector, actualNodes.Current, expectedNodes.Current); - } - } - while (actualNodes.MoveNext()) - { - collector.AddError("End of Node - FAILED :: Found Node: {0}", actualNodes.Current); - } - } - } - } - - private static void EvaluateTagHelperBlock(ErrorCollector collector, TagHelperBlock actual, TagHelperBlock expected) - { - if (expected == null) - { - AddMismatchError(collector, actual, expected); - } - else - { - if (!string.Equals(expected.TagName, actual.TagName, StringComparison.Ordinal)) - { - collector.AddError( - "{0} - FAILED :: TagName mismatch for TagHelperBlock :: ACTUAL: {1}", - expected.TagName, - actual.TagName); - } - - if (expected.TagMode != actual.TagMode) - { - collector.AddError( - $"{expected.TagMode} - FAILED :: {nameof(TagMode)} for {nameof(TagHelperBlock)} " + - $"{actual.TagName} :: ACTUAL: {actual.TagMode}"); - } - - var expectedAttributes = expected.Attributes.GetEnumerator(); - var actualAttributes = actual.Attributes.GetEnumerator(); - - while (expectedAttributes.MoveNext()) - { - if (!actualAttributes.MoveNext()) - { - collector.AddError("{0} - FAILED :: No more attributes on this node", expectedAttributes.Current); - } - else - { - EvaluateTagHelperAttribute(collector, actualAttributes.Current, expectedAttributes.Current); - } - } - while (actualAttributes.MoveNext()) - { - collector.AddError("End of Attributes - FAILED :: Found Attribute: {0}", actualAttributes.Current.Name); - } - } - } - - private static void AddPassedMessage(ErrorCollector collector, SyntaxTreeNode expected) - { - collector.AddMessage("{0} - PASSED", expected); - } - - private static void AddMismatchError(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected) - { - collector.AddError("{0} - FAILED :: Actual: {1}", expected, actual); - } - - private static void AddNullActualError(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected) - { - collector.AddError("{0} - FAILED :: Actual: << Null >>", expected); - } - - public static void EvaluateRazorErrors(IEnumerable actualErrors, IList expectedErrors) - { - var realCount = actualErrors.Count(); - - // Evaluate the errors - if (expectedErrors == null || expectedErrors.Count == 0) - { - Assert.True( - realCount == 0, - "Expected that no errors would be raised, but the following errors were:" + Environment.NewLine + FormatErrors(actualErrors)); - } - else - { - Assert.True( - expectedErrors.Count == realCount, - $"Expected that {expectedErrors.Count} errors would be raised, but {realCount} errors were." + - $"{Environment.NewLine}Expected Errors: {Environment.NewLine}{FormatErrors(expectedErrors)}" + - $"{Environment.NewLine}Actual Errors: {Environment.NewLine}{FormatErrors(actualErrors)}"); - Assert.Equal(expectedErrors, actualErrors); - } - WriteTraceLine("Expected Errors were raised:" + Environment.NewLine + FormatErrors(expectedErrors)); - } - - public static string FormatErrors(IEnumerable errors) - { - if (errors == null) - { - return "\t<< No Errors >>"; - } - - var builder = new StringBuilder(); - foreach (var error in errors) - { - builder.AppendFormat("\t{0}", error); - builder.AppendLine(); - } - return builder.ToString(); - } - - [Conditional("PARSER_TRACE")] - private static void WriteTraceLine(string format, params object[] args) - { - Trace.WriteLine(string.Format(format, args)); - } - - protected virtual Block CreateSimpleBlockAndSpan(string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - var span = Factory.Span(spanType, spanContent, spanType == SpanKind.Markup).Accepts(acceptedCharacters); - var b = new BlockBuilder() - { - Type = blockType - }; - return ConfigureAndAddSpanToBlock(b, span); - } - - protected virtual Block ConfigureAndAddSpanToBlock(BlockBuilder block, SpanConstructor span) - { - switch (block.Type) - { - case BlockType.Markup: - span.With(new MarkupChunkGenerator()); - break; - case BlockType.Statement: - span.With(new StatementChunkGenerator()); - break; - case BlockType.Expression: - block.ChunkGenerator = new ExpressionChunkGenerator(); - span.With(new ExpressionChunkGenerator()); - break; - } - block.Children.Add(span); - return block.Build(); - } - - private class IgnoreOutputBlock : Block - { - public IgnoreOutputBlock() : base(BlockType.Template, new SyntaxTreeNode[0], null) { } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/RawTextSymbol.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/RawTextSymbol.cs deleted file mode 100644 index 1392005df0..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/RawTextSymbol.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Globalization; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public class RawTextSymbol : ISymbol - { - public SourceLocation Start { get; private set; } - public string Content { get; } - - public RawTextSymbol(SourceLocation start, string content) - { - Start = start; - Content = content; - } - - public override bool Equals(object obj) - { - var other = obj as RawTextSymbol; - return other != null && Equals(Start, other.Start) && Equals(Content, other.Content); - } - - internal bool EquivalentTo(ISymbol sym) - { - return Equals(Start, sym.Start) && Equals(Content, sym.Content); - } - - public override int GetHashCode() - { - // Hash code should include only immutable properties. - return Content == null ? 0 : Content.GetHashCode(); - } - - public void OffsetStart(SourceLocation documentStart) - { - Start = documentStart + Start; - } - - public void ChangeStart(SourceLocation newStart) - { - Start = newStart; - } - - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "{0} RAW - [{1}]", Start, Content); - } - - internal void CalculateStart(Span prev) - { - if (prev == null) - { - Start = SourceLocation.Zero; - } - else - { - Start = new SourceLocationTracker(prev.Start).UpdateLocation(prev.Content).CurrentLocation; - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Framework/TestSpanBuilder.cs b/test/Microsoft.AspNetCore.Razor.Test/Framework/TestSpanBuilder.cs deleted file mode 100644 index be919eff97..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Framework/TestSpanBuilder.cs +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Test.Framework -{ - public static class SpanFactoryExtensions - { - public static UnclassifiedCodeSpanConstructor EmptyCSharp(this SpanFactory self) - { - return new UnclassifiedCodeSpanConstructor( - self.Span( - SpanKind.Code, - new CSharpSymbol(self.LocationTracker.CurrentLocation, string.Empty, CSharpSymbolType.Unknown))); - } - - public static SpanConstructor EmptyHtml(this SpanFactory self) - { - return self - .Span( - SpanKind.Markup, - new HtmlSymbol(self.LocationTracker.CurrentLocation, string.Empty, HtmlSymbolType.Unknown)) - .With(new MarkupChunkGenerator()); - } - - public static UnclassifiedCodeSpanConstructor Code(this SpanFactory self, string content) - { - return new UnclassifiedCodeSpanConstructor( - self.Span(SpanKind.Code, content, markup: false)); - } - - public static SpanConstructor CodeTransition(this SpanFactory self) - { - return self - .Span(SpanKind.Transition, SyntaxConstants.TransitionString, markup: false) - .Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor CodeTransition(this SpanFactory self, string content) - { - return self.Span(SpanKind.Transition, content, markup: false).Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor CodeTransition(this SpanFactory self, CSharpSymbolType type) - { - return self - .Span(SpanKind.Transition, SyntaxConstants.TransitionString, type) - .Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor CodeTransition(this SpanFactory self, string content, CSharpSymbolType type) - { - return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor MarkupTransition(this SpanFactory self) - { - return self - .Span(SpanKind.Transition, SyntaxConstants.TransitionString, markup: true) - .Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor MarkupTransition(this SpanFactory self, string content) - { - return self.Span(SpanKind.Transition, content, markup: true).Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor MarkupTransition(this SpanFactory self, HtmlSymbolType type) - { - return self - .Span(SpanKind.Transition, SyntaxConstants.TransitionString, type) - .Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor MarkupTransition(this SpanFactory self, string content, HtmlSymbolType type) - { - return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor MetaCode(this SpanFactory self, string content) - { - return self.Span(SpanKind.MetaCode, content, markup: false); - } - - public static SpanConstructor MetaCode(this SpanFactory self, string content, CSharpSymbolType type) - { - return self.Span(SpanKind.MetaCode, content, type); - } - - public static SpanConstructor MetaMarkup(this SpanFactory self, string content) - { - return self.Span(SpanKind.MetaCode, content, markup: true); - } - - public static SpanConstructor MetaMarkup(this SpanFactory self, string content, HtmlSymbolType type) - { - return self.Span(SpanKind.MetaCode, content, type); - } - - public static SpanConstructor Comment(this SpanFactory self, string content, CSharpSymbolType type) - { - return self.Span(SpanKind.Comment, content, type); - } - - public static SpanConstructor Comment(this SpanFactory self, string content, HtmlSymbolType type) - { - return self.Span(SpanKind.Comment, content, type); - } - - public static SpanConstructor BangEscape(this SpanFactory self) - { - return self - .Span(SpanKind.MetaCode, "!", markup: true) - .With(SpanChunkGenerator.Null) - .Accepts(AcceptedCharacters.None); - } - - public static SpanConstructor Markup(this SpanFactory self, string content) - { - return self.Span(SpanKind.Markup, content, markup: true).With(new MarkupChunkGenerator()); - } - - public static SpanConstructor Markup(this SpanFactory self, params string[] content) - { - return self.Span(SpanKind.Markup, content, markup: true).With(new MarkupChunkGenerator()); - } - - public static SpanConstructor CodeMarkup(this SpanFactory self, params string[] content) - { - return self - .Span(SpanKind.Code, content, markup: true) - .AsCodeMarkup(); - } - - public static SpanConstructor CSharpCodeMarkup(this SpanFactory self, string content) - { - return self.Code(content) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .AsCodeMarkup(); - } - - public static SpanConstructor AsCodeMarkup(this SpanConstructor self) - { - return self - .With(new ImplicitExpressionEditHandler( - SpanConstructor.TestTokenizer, - CSharpCodeParser.DefaultKeywords, - acceptTrailingDot: true)) - .With(new MarkupChunkGenerator()) - .Accepts(AcceptedCharacters.AnyExceptNewline); - } - - public static SourceLocation GetLocationAndAdvance(this SourceLocationTracker self, string content) - { - var ret = self.CurrentLocation; - self.UpdateLocation(content); - return ret; - } - } - - public class SpanFactory - { - public Func MarkupTokenizerFactory { get; set; } - public Func CodeTokenizerFactory { get; set; } - public SourceLocationTracker LocationTracker { get; private set; } - - public static SpanFactory CreateCsHtml() - { - return new SpanFactory() - { - MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), - CodeTokenizerFactory = doc => new CSharpTokenizer(doc) - }; - } - - public SpanFactory() - { - LocationTracker = new SourceLocationTracker(); - } - - public SpanConstructor Span(SpanKind kind, string content, CSharpSymbolType type) - { - return CreateSymbolSpan(kind, content, st => new CSharpSymbol(st, content, type)); - } - - public SpanConstructor Span(SpanKind kind, string content, HtmlSymbolType type) - { - return CreateSymbolSpan(kind, content, st => new HtmlSymbol(st, content, type)); - } - - public SpanConstructor Span(SpanKind kind, string content, bool markup) - { - return new SpanConstructor(kind, Tokenize(new[] { content }, markup)); - } - - public SpanConstructor Span(SpanKind kind, string[] content, bool markup) - { - return new SpanConstructor(kind, Tokenize(content, markup)); - } - - public SpanConstructor Span(SpanKind kind, params ISymbol[] symbols) - { - return new SpanConstructor(kind, symbols); - } - - private SpanConstructor CreateSymbolSpan(SpanKind kind, string content, Func ctor) - { - var start = LocationTracker.CurrentLocation; - LocationTracker.UpdateLocation(content); - return new SpanConstructor(kind, new[] { ctor(start) }); - } - - public void Reset() - { - LocationTracker.CurrentLocation = SourceLocation.Zero; - } - - private IEnumerable Tokenize(IEnumerable contentFragments, bool markup) - { - return contentFragments.SelectMany(fragment => Tokenize(fragment, markup)); - } - - private IEnumerable Tokenize(string content, bool markup) - { - var tok = MakeTokenizer(markup, new SeekableTextReader(content)); - ISymbol sym; - ISymbol last = null; - while ((sym = tok.NextSymbol()) != null) - { - OffsetStart(sym, LocationTracker.CurrentLocation); - last = sym; - yield return sym; - } - LocationTracker.UpdateLocation(content); - } - - private ITokenizer MakeTokenizer(bool markup, SeekableTextReader seekableTextReader) - { - if (markup) - { - return MarkupTokenizerFactory(seekableTextReader); - } - else - { - return CodeTokenizerFactory(seekableTextReader); - } - } - - private void OffsetStart(ISymbol sym, SourceLocation sourceLocation) - { - sym.OffsetStart(sourceLocation); - } - } - - public static class SpanConstructorExtensions - { - public static SpanConstructor Accepts(this SpanConstructor self, AcceptedCharacters accepted) - { - return self.With(eh => eh.AcceptedCharacters = accepted); - } - - public static SpanConstructor AutoCompleteWith(this SpanConstructor self, string autoCompleteString) - { - return AutoCompleteWith(self, autoCompleteString, atEndOfSpan: false); - } - - public static SpanConstructor AutoCompleteWith( - this SpanConstructor self, - string autoCompleteString, - bool atEndOfSpan) - { - return self.With(new AutoCompleteEditHandler( - SpanConstructor.TestTokenizer, - autoCompleteAtEndOfSpan: atEndOfSpan) - { - AutoCompleteString = autoCompleteString - }); - } - -#pragma warning disable 618 // Ignore obsolete warning for EditorHints - public static SpanConstructor WithEditorHints(this SpanConstructor self, EditorHints hints) - { - return self.With(eh => eh.EditorHints = hints); - } -#pragma warning restore 618 // Ignore obsolete warning for EditorHints - } - - public class UnclassifiedCodeSpanConstructor - { - SpanConstructor _self; - - public UnclassifiedCodeSpanConstructor(SpanConstructor self) - { - _self = self; - } - - public SpanConstructor AsMetaCode() - { - _self.Builder.Kind = SpanKind.MetaCode; - return _self; - } - - public SpanConstructor AsStatement() - { - return _self.With(new StatementChunkGenerator()); - } - - public SpanConstructor AsExpression() - { - return _self.With(new ExpressionChunkGenerator()); - } - - public SpanConstructor AsImplicitExpression(ISet keywords) - { - return AsImplicitExpression(keywords, acceptTrailingDot: false); - } - - public SpanConstructor AsImplicitExpression(ISet keywords, bool acceptTrailingDot) - { - return _self - .With(new ImplicitExpressionEditHandler(SpanConstructor.TestTokenizer, keywords, acceptTrailingDot)) - .With(new ExpressionChunkGenerator()); - } - - public SpanConstructor AsFunctionsBody() - { - return _self.With(new TypeMemberChunkGenerator()); - } - - public SpanConstructor AsNamespaceImport(string ns) - { - return _self.With(new AddImportChunkGenerator(ns)); - } - - public SpanConstructor Hidden() - { - return _self.With(SpanChunkGenerator.Null); - } - - public SpanConstructor AsBaseType(string baseType) - { - return _self - .With(new SetBaseTypeChunkGenerator(baseType)) - .Accepts(AcceptedCharacters.AnyExceptNewline); - } - - public SpanConstructor AsAddTagHelper(string lookupText) - { - return _self - .With(new AddTagHelperChunkGenerator(lookupText)) - .Accepts(AcceptedCharacters.AnyExceptNewline); - } - - public SpanConstructor AsRemoveTagHelper(string lookupText) - { - return _self - .With(new RemoveTagHelperChunkGenerator(lookupText)) - .Accepts(AcceptedCharacters.AnyExceptNewline); - } - - public SpanConstructor AsTagHelperPrefixDirective(string prefix) - { - return _self - .With(new TagHelperPrefixDirectiveChunkGenerator(prefix)) - .Accepts(AcceptedCharacters.AnyExceptNewline); - } - - public SpanConstructor As(ISpanChunkGenerator chunkGenerator) - { - return _self.With(chunkGenerator); - } - } - - public class SpanConstructor - { - public SpanBuilder Builder { get; private set; } - - internal static IEnumerable TestTokenizer(string str) - { - yield return new RawTextSymbol(SourceLocation.Zero, str); - } - - public SpanConstructor(SpanKind kind, IEnumerable symbols) - { - Builder = new SpanBuilder(); - Builder.Kind = kind; - Builder.EditHandler = SpanEditHandler.CreateDefault(TestTokenizer); - foreach (ISymbol sym in symbols) - { - Builder.Accept(sym); - } - } - - private Span Build() - { - return Builder.Build(); - } - - public SpanConstructor As(SpanKind spanKind) - { - Builder.Kind = spanKind; - return this; - } - - public SpanConstructor With(ISpanChunkGenerator generator) - { - Builder.ChunkGenerator = generator; - return this; - } - - public SpanConstructor With(SpanEditHandler handler) - { - Builder.EditHandler = handler; - return this; - } - - public SpanConstructor With(Action generatorConfigurer) - { - generatorConfigurer(Builder.ChunkGenerator); - return this; - } - - public SpanConstructor With(Action handlerConfigurer) - { - handlerConfigurer(Builder.EditHandler); - return this; - } - - public static implicit operator Span(SpanConstructor self) - { - return self.Build(); - } - - public SpanConstructor Hidden() - { - Builder.ChunkGenerator = SpanChunkGenerator.Null; - return this; - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Microsoft.AspNetCore.Razor.Test.csproj b/test/Microsoft.AspNetCore.Razor.Test/Microsoft.AspNetCore.Razor.Test.csproj deleted file mode 100644 index fb036a1d43..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Microsoft.AspNetCore.Razor.Test.csproj +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - netcoreapp1.1;net452 - netcoreapp1.1 - $(DefineConstants);__RemoveThisBitTo__GENERATE_BASELINES - $(DefaultItemExcludes);TestFiles\**\* - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpAutoCompleteTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpAutoCompleteTest.cs deleted file mode 100644 index c4e5ef2a49..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpAutoCompleteTest.cs +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpAutoCompleteTest : CsHtmlCodeParserTestBase - { - [Fact] - public void FunctionsDirectiveAutoCompleteAtEOF() - { - ParseBlockTest( - "@functions{", - new FunctionsBlock( - Factory.CodeTransition("@") - .Accepts(AcceptedCharacters.None), - Factory.MetaCode("functions{") - .Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsFunctionsBody() - .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) - { - AutoCompleteString = "}" - })), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("functions", "}", "{"), - new SourceLocation(10, 0, 10), - length: 1)); - } - - [Fact] - public void SectionDirectiveAutoCompleteAtEOF() - { - ParseBlockTest("@section Header {", - new SectionBlock(new SectionChunkGenerator("Header"), - Factory.CodeTransition(), - Factory.MetaCode("section Header {") - .AutoCompleteWith("}", atEndOfSpan: true) - .Accepts(AcceptedCharacters.Any), - new MarkupBlock()), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("section", "}", "{"), - new SourceLocation(16, 0, 16), - length: 1)); - } - - [Fact] - public void VerbatimBlockAutoCompleteAtEOF() - { - ParseBlockTest("@{", - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = "}" }) - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF( - RazorResources.BlockName_Code, "}", "{"), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void FunctionsDirectiveAutoCompleteAtStartOfFile() - { - ParseBlockTest("@functions{" + Environment.NewLine - + "foo", - new FunctionsBlock( - Factory.CodeTransition("@") - .Accepts(AcceptedCharacters.None), - Factory.MetaCode("functions{") - .Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + "foo") - .AsFunctionsBody() - .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) - { - AutoCompleteString = "}" - })), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("functions", "}", "{"), - new SourceLocation(10, 0, 10), - length: 1)); - } - - [Fact] - public void SectionDirectiveAutoCompleteAtStartOfFile() - { - ParseBlockTest("@section Header {" + Environment.NewLine - + "

Foo

", - new SectionBlock(new SectionChunkGenerator("Header"), - Factory.CodeTransition(), - Factory.MetaCode("section Header {") - .AutoCompleteWith("}", atEndOfSpan: true) - .Accepts(AcceptedCharacters.Any), - new MarkupBlock( - Factory.Markup(Environment.NewLine), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")))), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("section", "}", "{"), - new SourceLocation(16, 0, 16), - length: 1)); - } - - [Fact] - public void VerbatimBlockAutoCompleteAtStartOfFile() - { - ParseBlockTest("@{" + Environment.NewLine - + "

", - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine) - .AsStatement() - .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = "}" }), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None))), - Factory.Span(SpanKind.Code, new CSharpSymbol(Factory.LocationTracker.CurrentLocation, string.Empty, CSharpSymbolType.Unknown)) - .With(new StatementChunkGenerator()) - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF( - RazorResources.BlockName_Code, "}", "{"), - new SourceLocation(1, 0, 1), - length: 1)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpBlockTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpBlockTest.cs deleted file mode 100644 index 4d7b6f3344..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpBlockTest.cs +++ /dev/null @@ -1,1284 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpBlockTest : CsHtmlCodeParserTestBase - { - [Fact] - public void ParseBlock_NestedCodeBlockWithCSharpAt() - { - ParseBlockTest("{ if (true) { var val = @x; if (val != 3) { } } }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory - .Code(" if (true) { var val = @x; if (val != 3) { } } ") - .AsStatement() - .Accepts(AcceptedCharacters.Any) - .AutoCompleteWith(autoCompleteString: null, atEndOfSpan: false), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlock_NestedCodeBlockWithMarkupSetsDotAsMarkup() - { - ParseBlockTest("if (true) { @if(false) {
@something.
} }", - new StatementBlock( - Factory.Code("if (true) { ").AsStatement(), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(false) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("
", AcceptedCharacters.None), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("something") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Markup("."), - BlockFactory.MarkupTagBlock("
", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - Factory.Code("}").AsStatement()), - Factory.Code(" }").AsStatement())); - } - - [Fact] - public void ParseBlockMethodThrowsArgNullExceptionOnNullContext() - { - // Arrange - var parser = new CSharpCodeParser(); - - // Act and Assert - var exception = Assert.Throws(() => parser.ParseBlock()); - Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); - } - - [Fact] - public void BalancingBracketsIgnoresStringLiteralCharactersAndBracketsInsideSingleLineComments() - { - SingleSpanBlockTest(@"if(foo) { - // bar } "" baz ' - zoop(); -}", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void NestedCodeBlockWithAtDoesntCauseError() - { - ParseBlockTest("if (true) { @if(false) { } }", - new StatementBlock( - Factory.Code("if (true) { ").AsStatement(), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(false) { }").AsStatement() - ), - Factory.Code(" }").AsStatement())); - } - - [Fact] - public void BalancingBracketsIgnoresStringLiteralCharactersAndBracketsInsideBlockComments() - { - SingleSpanBlockTest( - @"if(foo) { - /* bar } "" */ ' baz } ' - zoop(); -}", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsForKeyword() - { - SingleSpanBlockTest( - "for(int i = 0; i < 10; new Foo { Bar = \"baz\" }) { Debug.WriteLine(@\"foo } bar\"); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsForeachKeyword() - { - SingleSpanBlockTest( - "foreach(int i = 0; i < 10; new Foo { Bar = \"baz\" }) { Debug.WriteLine(@\"foo } bar\"); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsWhileKeyword() - { - SingleSpanBlockTest( - "while(int i = 0; i < 10; new Foo { Bar = \"baz\" }) { Debug.WriteLine(@\"foo } bar\"); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsUsingKeywordFollowedByParen() - { - SingleSpanBlockTest( - "using(int i = 0; i < 10; new Foo { Bar = \"baz\" }) { Debug.WriteLine(@\"foo } bar\"); }", - BlockType.Statement, - SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsUsingsNestedWithinOtherBlocks() - { - SingleSpanBlockTest( - "if(foo) { using(int i = 0; i < 10; new Foo { Bar = \"baz\" }) { Debug.WriteLine(@\"foo } bar\"); } }", - BlockType.Statement, - SpanKind.Code); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsIfKeywordWithNoElseBranches() - { - SingleSpanBlockTest( - "if(int i = 0; i < 10; new Foo { Bar = \"baz\" }) { Debug.WriteLine(@\"foo } bar\"); }", - BlockType.Statement, - SpanKind.Code); - } - - [Fact] - public void ParseBlockAllowsEmptyBlockStatement() - { - SingleSpanBlockTest("if(false) { }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockTerminatesParenBalancingAtEOF() - { - ImplicitExpressionTest( - "Html.En(code()", "Html.En(code()", - AcceptedCharacters.Any, - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(8, 0, 8), - length: 1)); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenIfAndElseClause() - { - SingleSpanBlockTest( - "if(foo) { bar(); } /* Foo */ /* Bar */ else { baz(); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenIfAndElseClause() - { - RunRazorCommentBetweenClausesTest( - "if(foo) { bar(); } ", " else { baz(); }", - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenElseIfAndElseClause() - { - SingleSpanBlockTest( - "if(foo) { bar(); } else if(bar) { baz(); } /* Foo */ /* Bar */ else { biz(); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenElseIfAndElseClause() - { - RunRazorCommentBetweenClausesTest( - "if(foo) { bar(); } else if(bar) { baz(); } ", " else { baz(); }", - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenIfAndElseIfClause() - { - SingleSpanBlockTest( - "if(foo) { bar(); } /* Foo */ /* Bar */ else if(bar) { baz(); }", - BlockType.Statement, - SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenIfAndElseIfClause() - { - RunRazorCommentBetweenClausesTest("if(foo) { bar(); } ", " else if(bar) { baz(); }"); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenIfAndElseClause() - { - SingleSpanBlockTest(@"if(foo) { bar(); } -// Foo -// Bar -else { baz(); }", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenElseIfAndElseClause() - { - SingleSpanBlockTest(@"if(foo) { bar(); } else if(bar) { baz(); } -// Foo -// Bar -else { biz(); }", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenIfAndElseIfClause() - { - SingleSpanBlockTest(@"if(foo) { bar(); } -// Foo -// Bar -else if(bar) { baz(); }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockParsesElseIfBranchesOfIfStatement() - { - const string ifStatement = @"if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""foo } bar""); -}"; - const string elseIfBranch = @" else if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""bar } baz""); -}"; - const string document = ifStatement + elseIfBranch; - - SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockParsesMultipleElseIfBranchesOfIfStatement() - { - const string ifStatement = @"if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""foo } bar""); -}"; - const string elseIfBranch = @" else if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""bar } baz""); -}"; - const string document = ifStatement + elseIfBranch + elseIfBranch + elseIfBranch + elseIfBranch; - SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockParsesMultipleElseIfBranchesOfIfStatementFollowedByOneElseBranch() - { - const string ifStatement = @"if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""foo } bar""); -}"; - const string elseIfBranch = @" else if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""bar } baz""); -}"; - const string elseBranch = @" else { Debug.WriteLine(@""bar } baz""); }"; - const string document = ifStatement + elseIfBranch + elseIfBranch + elseBranch; - - SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockStopsParsingCodeAfterElseBranch() - { - const string ifStatement = @"if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""foo } bar""); -}"; - const string elseIfBranch = @" else if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""bar } baz""); -}"; - const string elseBranch = @" else { Debug.WriteLine(@""bar } baz""); }"; - const string document = ifStatement + elseIfBranch + elseBranch + elseIfBranch; - const string expected = ifStatement + elseIfBranch + elseBranch; - - ParseBlockTest( - document, - new StatementBlock(Factory.Code(expected).AsStatement().Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockStopsParsingIfIfStatementNotFollowedByElse() - { - const string document = @"if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""foo } bar""); -}"; - - SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockAcceptsElseIfWithNoCondition() - { - // We don't want to be a full C# parser - If the else if is missing it's condition, the C# compiler - // can handle that, we have all the info we need to keep parsing - const string ifBranch = @"if(int i = 0; i < 10; new Foo { Bar = ""baz"" }) { - Debug.WriteLine(@""foo } bar""); -}"; - const string elseIfBranch = @" else if { foo(); }"; - const string document = ifBranch + elseIfBranch; - - SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockCorrectlyParsesDoWhileBlock() - { - SingleSpanBlockTest( - "do { var foo = bar; } while(foo != bar);", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockCorrectlyParsesDoWhileBlockMissingSemicolon() - { - SingleSpanBlockTest("do { var foo = bar; } while(foo != bar)", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockCorrectlyParsesDoWhileBlockMissingWhileCondition() - { - SingleSpanBlockTest("do { var foo = bar; } while", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockCorrectlyParsesDoWhileBlockMissingWhileConditionWithSemicolon() - { - SingleSpanBlockTest( - "do { var foo = bar; } while;", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockCorrectlyParsesDoWhileBlockMissingWhileClauseEntirely() - { - SingleSpanBlockTest("do { var foo = bar; } narf;", "do { var foo = bar; }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenDoAndWhileClause() - { - SingleSpanBlockTest( - "do { var foo = bar; } /* Foo */ /* Bar */ while(true);", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenDoAndWhileClause() - { - SingleSpanBlockTest(@"do { var foo = bar; } -// Foo -// Bar -while(true);", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenDoAndWhileClause() - { - RunRazorCommentBetweenClausesTest( - "do { var foo = bar; } ", " while(true);", - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockCorrectlyParsesMarkupInDoWhileBlock() - { - ParseBlockTest("@do { var foo = bar;

Foo

foo++; } while (foo);", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("do { var foo = bar;").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("foo++; } while (foo);").AsStatement().Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsSwitchKeyword() - { - SingleSpanBlockTest(@"switch(foo) { - case 0: - break; - case 1: - { - break; - } - case 2: - return; - default: - return; -}", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsLockKeyword() - { - SingleSpanBlockTest( - "lock(foo) { Debug.WriteLine(@\"foo } bar\"); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockHasErrorsIfNamespaceImportMissingSemicolon() - { - NamespaceImportTest( - "using Foo.Bar.Baz", - " Foo.Bar.Baz", - acceptedCharacters: AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace, - location: new SourceLocation(17, 0, 17)); - } - - [Fact] - public void ParseBlockHasErrorsIfNamespaceAliasMissingSemicolon() - { - NamespaceImportTest( - "using Foo.Bar.Baz = FooBarBaz", - " Foo.Bar.Baz = FooBarBaz", - acceptedCharacters: AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace, - location: new SourceLocation(29, 0, 29)); - } - - [Fact] - public void ParseBlockParsesNamespaceImportWithSemicolonForUsingKeywordIfIsInValidFormat() - { - NamespaceImportTest( - "using Foo.Bar.Baz;", - " Foo.Bar.Baz", - AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace); - } - - [Fact] - public void ParseBlockDoesntCaptureWhitespaceAfterUsing() - { - ParseBlockTest("using Foo ", - new DirectiveBlock( - Factory.Code("using Foo") - .AsNamespaceImport(" Foo") - .Accepts(AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace))); - } - - [Fact] - public void ParseBlockParsesNamespaceAliasWithSemicolonForUsingKeywordIfIsInValidFormat() - { - NamespaceImportTest( - "using FooBarBaz = FooBarBaz;", - " FooBarBaz = FooBarBaz", - AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace); - } - - [Fact] - public void ParseBlockTerminatesUsingKeywordAtEOFAndOutputsFileCodeBlock() - { - SingleSpanBlockTest("using ", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockTerminatesSingleLineCommentAtEndOfFile() - { - const string document = "foreach(var f in Foo) { // foo bar baz"; - SingleSpanBlockTest( - document, - document, - BlockType.Statement, - SpanKind.Code, - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("foreach", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesBlockCommentAtEndOfFile() - { - const string document = "foreach(var f in Foo) { /* foo bar baz"; - SingleSpanBlockTest( - document, - document, - BlockType.Statement, - SpanKind.Code, - new RazorError( - RazorResources.ParseError_BlockComment_Not_Terminated, - new SourceLocation(24, 0, 24), - length: 1), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("foreach", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesSingleSlashAtEndOfFile() - { - const string document = "foreach(var f in Foo) { / foo bar baz"; - SingleSpanBlockTest( - document, - document, - BlockType.Statement, - SpanKind.Code, - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("foreach", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenTryAndFinallyClause() - { - SingleSpanBlockTest("try { bar(); } /* Foo */ /* Bar */ finally { baz(); }", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenTryAndFinallyClause() - { - RunRazorCommentBetweenClausesTest("try { bar(); } ", " finally { biz(); }", acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenCatchAndFinallyClause() - { - SingleSpanBlockTest( - "try { bar(); } catch(bar) { baz(); } /* Foo */ /* Bar */ finally { biz(); }", - BlockType.Statement, - SpanKind.Code, - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenCatchAndFinallyClause() - { - RunRazorCommentBetweenClausesTest( - "try { bar(); } catch(bar) { baz(); } ", " finally { biz(); }", - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsBlockCommentBetweenTryAndCatchClause() - { - SingleSpanBlockTest("try { bar(); } /* Foo */ /* Bar */ catch(bar) { baz(); }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsRazorCommentBetweenTryAndCatchClause() - { - RunRazorCommentBetweenClausesTest("try { bar(); }", " catch(bar) { baz(); }"); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenTryAndFinallyClause() - { - SingleSpanBlockTest(@"try { bar(); } -// Foo -// Bar -finally { baz(); }", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenCatchAndFinallyClause() - { - SingleSpanBlockTest(@"try { bar(); } catch(bar) { baz(); } -// Foo -// Bar -finally { biz(); }", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsLineCommentBetweenTryAndCatchClause() - { - SingleSpanBlockTest(@"try { bar(); } -// Foo -// Bar -catch(bar) { baz(); }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsTryStatementWithNoAdditionalClauses() - { - SingleSpanBlockTest("try { var foo = new { } }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsMarkupWithinTryClause() - { - RunSimpleWrappedMarkupTest( - prefix: "try {", - markup: "

Foo

", - suffix: "}", - expectedMarkup: new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockSupportsTryStatementWithOneCatchClause() - { - SingleSpanBlockTest("try { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsMarkupWithinCatchClause() - { - RunSimpleWrappedMarkupTest( - prefix: "try { var foo = new { } } catch(Foo Bar Baz) {", - markup: "

Foo

", - suffix: "}", - expectedMarkup: new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockSupportsTryStatementWithMultipleCatchClause() - { - SingleSpanBlockTest( - "try { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } } catch(Foo Bar Baz) " + - "{ var foo = new { } } catch(Foo Bar Baz) { var foo = new { } }", - BlockType.Statement, - SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsExceptionLessCatchClauses() - { - SingleSpanBlockTest("try { var foo = new { } } catch { var foo = new { } }", BlockType.Statement, SpanKind.Code); - } - - [Fact] - public void ParseBlockSupportsMarkupWithinAdditionalCatchClauses() - { - RunSimpleWrappedMarkupTest( - prefix: "try { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } } catch(Foo Bar Baz) " + - "{ var foo = new { } } catch(Foo Bar Baz) {", - markup: "

Foo

", - suffix: "}", - expectedMarkup: new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockSupportsTryStatementWithFinallyClause() - { - SingleSpanBlockTest("try { var foo = new { } } finally { var foo = new { } }", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsMarkupWithinFinallyClause() - { - RunSimpleWrappedMarkupTest( - prefix: "try { var foo = new { } } finally {", - markup: "

Foo

", - suffix: "}", - expectedMarkup: new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockStopsParsingCatchClausesAfterFinallyBlock() - { - var expectedContent = "try { var foo = new { } } finally { var foo = new { } }"; - SingleSpanBlockTest(expectedContent + " catch(Foo Bar Baz) { }", expectedContent, BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockDoesNotAllowMultipleFinallyBlocks() - { - var expectedContent = "try { var foo = new { } } finally { var foo = new { } }"; - SingleSpanBlockTest(expectedContent + " finally { }", expectedContent, BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockAcceptsTrailingDotIntoImplicitExpressionWhenEmbeddedInCode() - { - // Arrange - ParseBlockTest(@"if(foo) { @foo. }", - new StatementBlock( - Factory.Code("if(foo) { ").AsStatement(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - Factory.Code(" }").AsStatement() - )); - } - - [Fact] - public void ParseBlockParsesExpressionOnSwitchCharacterFollowedByOpenParen() - { - // Arrange - ParseBlockTest(@"if(foo) { @(foo + bar) }", - new StatementBlock( - Factory.Code("if(foo) { ").AsStatement(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("foo + bar").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - ), - Factory.Code(" }").AsStatement() - )); - } - - [Fact] - public void ParseBlockParsesExpressionOnSwitchCharacterFollowedByIdentifierStart() - { - // Arrange - ParseBlockTest(@"if(foo) { @foo[4].bar() }", - new StatementBlock( - Factory.Code("if(foo) { ").AsStatement(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo[4].bar()") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - Factory.Code(" }").AsStatement() - )); - } - - [Fact] - public void ParseBlockTreatsDoubleAtSignAsEscapeSequenceIfAtStatementStart() - { - // Arrange - ParseBlockTest(@"if(foo) { @@class.Foo() }", - new StatementBlock( - Factory.Code("if(foo) { ").AsStatement(), - Factory.Code("@").Hidden(), - Factory.Code("@class.Foo() }").AsStatement() - )); - } - - [Fact] - public void ParseBlockTreatsAtSignsAfterFirstPairAsPartOfCSharpStatement() - { - // Arrange - ParseBlockTest(@"if(foo) { @@@@class.Foo() }", - new StatementBlock( - Factory.Code("if(foo) { ").AsStatement(), - Factory.Code("@").Hidden(), - Factory.Code("@@@class.Foo() }").AsStatement() - )); - } - - [Fact] - public void ParseBlockDoesNotParseMarkupStatementOrExpressionOnSwitchCharacterNotFollowedByOpenAngleOrColon() - { - // Arrange - ParseBlockTest("if(foo) { @\"Foo\".ToString(); }", - new StatementBlock( - Factory.Code("if(foo) { @\"Foo\".ToString(); }").AsStatement())); - } - - [Fact] - public void ParsersCanNestRecursively() - { - // Arrange - ParseBlockTest("foreach(var c in db.Categories) {" + Environment.NewLine - + "
" + Environment.NewLine - + " }", - new StatementBlock( - Factory.Code("foreach(var c in db.Categories) {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("
", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine + " "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("c.Name") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine + " "), - BlockFactory.MarkupTagBlock("
    ", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine), - new StatementBlock( - Factory.Code(@" ").AsStatement(), - Factory.CodeTransition(), - Factory.Code("foreach(var p in c.Products) {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("
  • ", AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("(" href=\"", 183 + Environment.NewLine.Length * 5, 5, 30), - new LocationTagged("\"", 246 + Environment.NewLine.Length * 5, 5, 93)), - Factory.Markup(" href=\"").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged(string.Empty, 190 + Environment.NewLine.Length * 5, 5, 37), 190 + Environment.NewLine.Length * 5, 5, 37), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("Html.ActionUrl(\"Products\", \"Detail\", new { id = p.Id })") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(">").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("p.Name") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - BlockFactory.MarkupTagBlock("", AcceptedCharacters.None), - BlockFactory.MarkupTagBlock("
  • ", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code(" }" + Environment.NewLine).AsStatement().Accepts(AcceptedCharacters.None)), - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("
", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine + " "), - BlockFactory.MarkupTagBlock("
", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code(" }").AsStatement().Accepts(AcceptedCharacters.None))); - } - - public static TheoryData BlockWithEscapedTransitionData - { - get - { - var factory = CreateDefaultSpanFactory(); - var datetimeBlock = new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)); - - return new TheoryData - { - { - // Double transition in attribute value - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 14, 0, 14)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("@", 12, 0, 12))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - // Double transition at the end of attribute value - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 17, 0, 17)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - factory.Markup("abc").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("abc", 12, 0, 12))), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 15, 0, 15), new LocationTagged("@", 15, 0, 15))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - // Double transition at the beginning attribute value - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 17, 0, 17)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("@", 12, 0, 12))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("def").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 14, 0, 14), new LocationTagged("def", 14, 0, 14))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - // Double transition in between attribute value - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 22, 0, 22)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - factory.Markup("abc").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("abc", 12, 0, 12))), - new MarkupBlock( - factory.Markup(" @").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 15, 0, 15), new LocationTagged("@", 16, 0, 16))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup(" def").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 18, 0, 18), new LocationTagged("def", 19, 0, 19))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - // Double transition with expression block - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 27, 0, 27)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("@", 12, 0, 12))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 14, 0, 14), 14, 0, 14), - factory.EmptyHtml().With(SpanChunkGenerator.Null), - datetimeBlock), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 28, 0, 28)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), 12, 0, 12), - datetimeBlock), - new MarkupBlock( - factory.Markup(" @").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 25, 0, 25), new LocationTagged("@", 26, 0, 26))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 27, 0, 27)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), 12, 0, 12), - datetimeBlock), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 25, 0, 25), new LocationTagged("@", 25, 0, 25))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 33, 0, 33)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), 12, 0, 12), - new ExpressionBlock( - factory.CodeTransition(), - factory.MetaCode("(").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None), - factory.Code("2+3").AsExpression(), - factory.MetaCode(")").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None))), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 18, 0, 18), new LocationTagged("@", 18, 0, 18))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 20, 0, 20), 20, 0, 20), - factory.EmptyHtml().With(SpanChunkGenerator.Null), - datetimeBlock), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 20, 0, 20)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("@", 12, 0, 12))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 14, 0, 14), 14, 0, 14), - factory.EmptyHtml().With(SpanChunkGenerator.Null), - new ExpressionBlock( - factory.CodeTransition(), - factory.MetaCode("(").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None), - factory.Code("2+3").AsExpression(), - factory.MetaCode(")").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - // Double transition with email in attribute value - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 26, 0, 26)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - factory.Markup("abc@def.com").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("abc@def.com", 12, 0, 12))), - new MarkupBlock( - factory.Markup(" @").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 23, 0, 23), new LocationTagged("@", 24, 0, 24))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - "{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 6, 0, 6), new LocationTagged("'", 27, 0, 27)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - factory.Markup("abc").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("abc", 12, 0, 12))), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 15, 0, 15), new LocationTagged("@", 15, 0, 15))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("def.com").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 17, 0, 17), new LocationTagged("def.com", 17, 0, 17))), - new MarkupBlock( - factory.Markup(" @").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 24, 0, 24), new LocationTagged("@", 25, 0, 25))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - { - // Double transition in complex regex in attribute value - @"{}", - CreateStatementBlock( - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo=\"", 6, 0, 6), new LocationTagged("\"", 112, 0, 112)), - factory.Markup(" foo=\"").With(SpanChunkGenerator.Null), - factory.Markup(@"/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged(@"/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+", 12, 0, 12))), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 44, 0, 44), new LocationTagged("@", 44, 0, 44))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup(@"[a-z0-9]([a-z0-9-]*[a-z0-9])?\.([a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 46, 0, 46), new LocationTagged(@"[a-z0-9]([a-z0-9-]*[a-z0-9])?\.([a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i", 46, 0, 46))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(" />").Accepts(AcceptedCharacters.None)))) - }, - }; - } - } - - [Theory] - [MemberData(nameof(BlockWithEscapedTransitionData))] - public void ParseBlock_WithDoubleTransition_DoesNotThrow(string input, Block expected) - { - // Act & Assert - ParseBlockTest(input, expected); - } - - [Fact] - public void ParseBlock_WithDoubleTransition_EndOfFile_Throws() - { - // Arrange - var expected = new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" foo='", 6, 0, 6), new LocationTagged(string.Empty, 14, 0, 14)), - Factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - Factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), new LocationTagged("@", 12, 0, 12))).Accepts(AcceptedCharacters.None), - Factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)))), - Factory.EmptyHtml())); - var expectedErrors = new RazorError[] - { - new RazorError( - @"End of file or an unexpected character was reached before the ""span"" tag could be parsed. Elements inside markup blocks must be complete. They must either be self-closing (""
"") or have matching end tags (""

Hello

""). If you intended to display a ""<"" character, use the ""<"" HTML entity.", - new SourceLocation(2, 0, 2), - length: 4), - new RazorError( - @"The code block is missing a closing ""}"" character. Make sure you have a matching ""}"" character for all the ""{"" characters within this block, and that none of the ""}"" characters are being interpreted as markup.", - SourceLocation.Zero, - length: 1), - }; - - // Act & Assert - ParseBlockTest("{("'", 15, 0, 15)), - Factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 12, 0, 12), 12, 0, 12), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp().AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace))), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(" ", 13, 0, 13), 13, 0, 13), - Factory.Markup(" ").With(SpanChunkGenerator.Null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp().AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None))), - Factory.EmptyCSharp().AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)); - 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(13, 0, 13), - length: 1), - new RazorError( - @"""' />}"" is not valid at the start of a code block. Only identifiers, keywords, comments, ""("" and ""{"" are valid.", - new SourceLocation(15, 0, 15), - length: 5), - }; - - // Act & Assert - ParseBlockTest("{}", expected, expectedErrors); - } - - private void RunRazorCommentBetweenClausesTest(string preComment, string postComment, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - ParseBlockTest(preComment + "@* Foo *@ @* Bar *@" + postComment, - new StatementBlock( - Factory.Code(preComment).AsStatement(), - new CommentBlock( - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None), - Factory.Comment(" Foo ", CSharpSymbolType.RazorComment), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None), - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition) - ), - Factory.Code(" ").AsStatement(), - new CommentBlock( - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None), - Factory.Comment(" Bar ", CSharpSymbolType.RazorComment), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None), - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition) - ), - Factory.Code(postComment).AsStatement().Accepts(acceptedCharacters))); - } - - private void RunSimpleWrappedMarkupTest(string prefix, string markup, string suffix, MarkupBlock expectedMarkup, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any) - { - ParseBlockTest(prefix + markup + suffix, - new StatementBlock( - Factory.Code(prefix).AsStatement(), - expectedMarkup, - Factory.Code(suffix).AsStatement().Accepts(acceptedCharacters) - )); - } - - 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, length: 1) - }; - } - ParseBlockTest(content, - new DirectiveBlock( - Factory.Code(content) - .AsNamespaceImport(expectedNS) - .Accepts(acceptedCharacters)), - errors); - } - - private static SpanFactory CreateDefaultSpanFactory() - { - return new SpanFactory - { - MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), - CodeTokenizerFactory = doc => new CSharpTokenizer(doc) - }; - } - - private static StatementBlock CreateStatementBlock(MarkupBlock block) - { - var factory = CreateDefaultSpanFactory(); - return new StatementBlock( - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - block, - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpDirectivesTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpDirectivesTest.cs deleted file mode 100644 index 783d9f5c20..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpDirectivesTest.cs +++ /dev/null @@ -1,429 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpDirectivesTest : CsHtmlCodeParserTestBase - { - [Fact] - public void TagHelperPrefixDirective_NoValueSucceeds() - { - ParseBlockTest("@tagHelperPrefix \"\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"\"") - .AsTagHelperPrefixDirective(string.Empty))); - } - - [Fact] - public void TagHelperPrefixDirective_Succeeds() - { - ParseBlockTest("@tagHelperPrefix Foo", - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo") - .AsTagHelperPrefixDirective("Foo"))); - } - - [Fact] - public void TagHelperPrefixDirective_WithQuotes_Succeeds() - { - ParseBlockTest("@tagHelperPrefix \"Foo\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"Foo\"") - .AsTagHelperPrefixDirective("Foo"))); - } - - [Fact] - public void TagHelperPrefixDirective_RequiresValue() - { - ParseBlockTest("@tagHelperPrefix ", - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsTagHelperPrefixDirective(string.Empty) - .Accepts(AcceptedCharacters.AnyExceptNewline)), - new RazorError( - RazorResources.FormatParseError_DirectiveMustHaveValue( - SyntaxConstants.CSharp.TagHelperPrefixKeyword), - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 15)); - } - - [Fact] - public void TagHelperPrefixDirective_StartQuoteRequiresDoubleQuotesAroundValue() - { - ParseBlockTest("@tagHelperPrefix \"Foo", - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"Foo") - .AsTagHelperPrefixDirective("\"Foo")), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 1), - new RazorError( - RazorResources.FormatParseError_IncompleteQuotesAroundDirective( - SyntaxConstants.CSharp.TagHelperPrefixKeyword), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 4)); - } - - [Fact] - public void TagHelperPrefixDirective_EndQuoteRequiresDoubleQuotesAroundValue() - { - ParseBlockTest("@tagHelperPrefix Foo \"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo \"") - .AsTagHelperPrefixDirective("Foo \"")), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 23, lineIndex: 0, columnIndex: 23, length: 1), - new RazorError( - RazorResources.FormatParseError_IncompleteQuotesAroundDirective( - SyntaxConstants.CSharp.TagHelperPrefixKeyword), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 7)); - } - - [Fact] - public void RemoveTagHelperDirective_NoValue_Succeeds() - { - ParseBlockTest("@removeTagHelper \"\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"\"") - .AsRemoveTagHelper(string.Empty))); - } - - [Fact] - public void RemoveTagHelperDirective_Succeeds() - { - ParseBlockTest("@removeTagHelper Foo", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo") - .AsRemoveTagHelper("Foo"))); - } - - [Fact] - public void RemoveTagHelperDirective_WithQuotes_Succeeds() - { - ParseBlockTest("@removeTagHelper \"Foo\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"Foo\"") - .AsRemoveTagHelper("Foo"))); - } - - [Fact] - public void RemoveTagHelperDirective_SupportsSpaces() - { - ParseBlockTest("@removeTagHelper Foo, Bar ", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo, Bar ") - .AsRemoveTagHelper("Foo, Bar") - .Accepts(AcceptedCharacters.AnyExceptNewline))); - } - - [Fact] - public void RemoveTagHelperDirective_RequiresValue() - { - ParseBlockTest("@removeTagHelper ", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsRemoveTagHelper(string.Empty) - .Accepts(AcceptedCharacters.AnyExceptNewline)), - new RazorError( - RazorResources.FormatParseError_DirectiveMustHaveValue( - SyntaxConstants.CSharp.RemoveTagHelperKeyword), - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 15)); - } - - [Fact] - public void RemoveTagHelperDirective_StartQuoteRequiresDoubleQuotesAroundValue() - { - ParseBlockTest("@removeTagHelper \"Foo", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"Foo") - .AsRemoveTagHelper("\"Foo")), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 1), - new RazorError( - RazorResources.FormatParseError_IncompleteQuotesAroundDirective( - SyntaxConstants.CSharp.RemoveTagHelperKeyword), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 4)); - } - - [Fact] - public void RemoveTagHelperDirective_EndQuoteRequiresDoubleQuotesAroundValue() - { - ParseBlockTest("@removeTagHelper Foo\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo\"") - .AsRemoveTagHelper("Foo\"") - .Accepts(AcceptedCharacters.AnyExceptNewline)), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 20, lineIndex: 0, columnIndex: 20, length: 1), - new RazorError( - RazorResources.FormatParseError_IncompleteQuotesAroundDirective( - SyntaxConstants.CSharp.RemoveTagHelperKeyword), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 4)); - } - - [Fact] - public void AddTagHelperDirective_NoValue_Succeeds() - { - ParseBlockTest("@addTagHelper \"\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"\"") - .AsAddTagHelper(string.Empty))); - } - - [Fact] - public void AddTagHelperDirective_Succeeds() - { - ParseBlockTest("@addTagHelper Foo", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo") - .AsAddTagHelper("Foo"))); - } - - [Fact] - public void AddTagHelperDirective_WithQuotes_Succeeds() - { - ParseBlockTest("@addTagHelper \"Foo\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"Foo\"") - .AsAddTagHelper("Foo"))); - } - - [Fact] - public void AddTagHelperDirectiveSupportsSpaces() - { - ParseBlockTest("@addTagHelper Foo, Bar ", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo, Bar ") - .AsAddTagHelper("Foo, Bar"))); - } - - [Fact] - public void AddTagHelperDirectiveRequiresValue() - { - ParseBlockTest("@addTagHelper ", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsAddTagHelper(string.Empty) - .Accepts(AcceptedCharacters.AnyExceptNewline)), - new RazorError( - RazorResources.FormatParseError_DirectiveMustHaveValue(SyntaxConstants.CSharp.AddTagHelperKeyword), - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 12)); - } - - [Fact] - public void AddTagHelperDirective_StartQuoteRequiresDoubleQuotesAroundValue() - { - ParseBlockTest("@addTagHelper \"Foo", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("\"Foo") - .AsAddTagHelper("\"Foo")), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 14, lineIndex: 0, columnIndex: 14, length: 1), - new RazorError( - RazorResources.FormatParseError_IncompleteQuotesAroundDirective( - SyntaxConstants.CSharp.AddTagHelperKeyword), - absoluteIndex: 14, lineIndex: 0, columnIndex: 14, length: 4)); - } - - [Fact] - public void AddTagHelperDirective_EndQuoteRequiresDoubleQuotesAroundValue() - { - ParseBlockTest("@addTagHelper Foo\"", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.AddTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("Foo\"") - .AsAddTagHelper("Foo\"") - .Accepts(AcceptedCharacters.AnyExceptNewline)), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 1), - new RazorError( - RazorResources.FormatParseError_IncompleteQuotesAroundDirective( - SyntaxConstants.CSharp.AddTagHelperKeyword), - absoluteIndex: 14, lineIndex: 0, columnIndex: 14, length: 4)); - } - - [Fact] - public void InheritsDirective() - { - ParseBlockTest("@inherits System.Web.WebPages.WebPage", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("System.Web.WebPages.WebPage") - .AsBaseType("System.Web.WebPages.WebPage"))); - } - - [Fact] - public void InheritsDirectiveSupportsArrays() - { - ParseBlockTest("@inherits string[[]][]", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("string[[]][]") - .AsBaseType("string[[]][]"))); - } - - [Fact] - public void InheritsDirectiveSupportsNestedGenerics() - { - ParseBlockTest("@inherits System.Web.Mvc.WebViewPage>", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("System.Web.Mvc.WebViewPage>") - .AsBaseType("System.Web.Mvc.WebViewPage>"))); - } - - [Fact] - public void InheritsDirectiveSupportsTypeKeywords() - { - ParseBlockTest("@inherits string", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("string") - .AsBaseType("string"))); - } - - [Fact] - public void InheritsDirectiveSupportsVSTemplateTokens() - { - ParseBlockTest("@inherits $rootnamespace$.MyBase", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("$rootnamespace$.MyBase") - .AsBaseType("$rootnamespace$.MyBase"))); - } - - [Fact] - public void FunctionsDirective() - { - ParseBlockTest("@functions { foo(); bar(); }", - new FunctionsBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.FunctionsKeyword + " {") - .Accepts(AcceptedCharacters.None), - Factory.Code(" foo(); bar(); ") - .AsFunctionsBody() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}") - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void EmptyFunctionsDirective() - { - ParseBlockTest("@functions { }", - new FunctionsBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.FunctionsKeyword + " {") - .Accepts(AcceptedCharacters.None), - Factory.Code(" ") - .AsFunctionsBody() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}") - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void SectionDirective() - { - ParseBlockTest("@section Header {

F{o}o

}", - new SectionBlock(new SectionChunkGenerator("Header"), - Factory.CodeTransition(), - Factory.MetaCode("section Header {") - .AutoCompleteWith(null, atEndOfSpan: true) - .Accepts(AcceptedCharacters.Any), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("F", "{", "o", "}", "o"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(" ")), - Factory.MetaCode("}") - .Accepts(AcceptedCharacters.None))); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpErrorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpErrorTest.cs deleted file mode 100644 index cbf910ad3f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpErrorTest.cs +++ /dev/null @@ -1,698 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpErrorTest : CsHtmlCodeParserTestBase - { - [Fact] - public void ParseBlockHandlesQuotesAfterTransition() - { - ParseBlockTest("@\"", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(KeywordSet) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS('"'), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockWithHelperDirectiveProducesError() - { - ParseBlockTest("@helper fooHelper { }", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("helper") - .AsImplicitExpression(KeywordSet) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new RazorError( - RazorResources.FormatParseError_HelperDirectiveNotAvailable(SyntaxConstants.CSharp.HelperKeyword), - new SourceLocation(1, 0, 1), - length: 6)); - } - - [Fact] - public void ParseBlockCapturesWhitespaceToEndOfLineInInvalidUsingStatementAndTreatsAsFileCode() - { - ParseBlockTest("using " + Environment.NewLine - + Environment.NewLine, - new StatementBlock( - Factory.Code("using " + Environment.NewLine).AsStatement() - )); - } - - [Fact] - public void ParseBlockMethodOutputsOpenCurlyAsCodeSpanIfEofFoundAfterOpenCurlyBrace() - { - ParseBlockTest("{", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = "}" }) - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(RazorResources.BlockName_Code, "}", "{"), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockMethodOutputsZeroLengthCodeSpanIfStatementBlockEmpty() - { - ParseBlockTest("{}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockMethodProducesErrorIfNewlineFollowsTransition() - { - ParseBlockTest("@" + Environment.NewLine, - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new RazorError( - RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, - new SourceLocation(1, 0, 1), - Environment.NewLine.Length)); - } - - [Fact] - public void ParseBlockMethodProducesErrorIfWhitespaceBetweenTransitionAndBlockStartInEmbeddedExpression() - { - ParseBlockTest("{" + Environment.NewLine - + " @ {}" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Code(" {}" + Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), - new RazorError( - RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, - new SourceLocation(6 + Environment.NewLine.Length, 1, 5), - length: 3)); - } - - [Fact] - public void ParseBlockMethodProducesErrorIfEOFAfterTransitionInEmbeddedExpression() - { - ParseBlockTest("{" + Environment.NewLine - + " @", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith("}"), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.EmptyCSharp().AsStatement() - ), - new RazorError( - RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, - 6 + Environment.NewLine.Length, 1, 5, length: 1), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(RazorResources.BlockName_Code, "}", "{"), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockMethodParsesNothingIfFirstCharacterIsNotIdentifierStartOrParenOrBrace() - { - ParseBlockTest("@!!!", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS("!"), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockShouldReportErrorAndTerminateAtEOFIfIfParenInExplicitExpressionUnclosed() - { - ParseBlockTest("(foo bar" + Environment.NewLine - + "baz", - new ExpressionBlock( - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code($"foo bar{Environment.NewLine}baz").AsExpression() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(RazorResources.BlockName_ExplicitExpression, ')', '('), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockShouldReportErrorAndTerminateAtMarkupIfIfParenInExplicitExpressionUnclosed() - { - ParseBlockTest("(foo bar" + Environment.NewLine - + "" + Environment.NewLine - + "baz" + Environment.NewLine - + "@Html.Foo(Bar);" + Environment.NewLine, - new ExpressionBlock( - Factory.Code("Href(" + Environment.NewLine) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(4, 0, 4), - length: 1)); - } - - [Fact] - // Test for fix to Dev10 884975 - Incorrect Error Messaging - public void ParseBlockShouldReportErrorAndTerminateAtEOFIfParenInImplicitExpressionUnclosed() - { - ParseBlockTest("Foo(Bar(Baz)" + Environment.NewLine - + "Biz" + Environment.NewLine - + "Boz", - new ExpressionBlock( - Factory.Code($"Foo(Bar(Baz){Environment.NewLine}Biz{Environment.NewLine}Boz") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(3, 0, 3), - length: 1)); - } - - [Fact] - // Test for fix to Dev10 884975 - Incorrect Error Messaging - public void ParseBlockShouldReportErrorAndTerminateAtMarkupIfParenInImplicitExpressionUnclosed() - { - ParseBlockTest("Foo(Bar(Baz)" + Environment.NewLine - + "Biz" + Environment.NewLine - + "" + Environment.NewLine - + "Boz" + Environment.NewLine - + "", - new ExpressionBlock( - Factory.Code($"Foo(Bar(Baz){Environment.NewLine}Biz{Environment.NewLine}") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(3, 0, 3), - length: 1)); - } - - [Fact] - // Test for fix to Dev10 884975 - Incorrect Error Messaging - public void ParseBlockShouldReportErrorAndTerminateAtEOFIfBracketInImplicitExpressionUnclosed() - { - ParseBlockTest("Foo[Bar[Baz]" + Environment.NewLine - + "Biz" + Environment.NewLine - + "Boz", - new ExpressionBlock( - Factory.Code($"Foo[Bar[Baz]{Environment.NewLine}Biz{Environment.NewLine}Boz") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("[", "]"), - new SourceLocation(3, 0, 3), - length: 1)); - } - - [Fact] - // Test for fix to Dev10 884975 - Incorrect Error Messaging - public void ParseBlockShouldReportErrorAndTerminateAtMarkupIfBracketInImplicitExpressionUnclosed() - { - ParseBlockTest("Foo[Bar[Baz]" + Environment.NewLine - + "Biz" + Environment.NewLine - + "" + Environment.NewLine - + "Boz" + Environment.NewLine - + "", - new ExpressionBlock( - Factory.Code($"Foo[Bar[Baz]{Environment.NewLine}Biz{Environment.NewLine}") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("[", "]"), - new SourceLocation(3, 0, 3), - length: 1)); - } - - // Simple EOF handling errors: - [Fact] - public void ParseBlockReportsErrorIfExplicitCodeBlockUnterminatedAtEOF() - { - ParseBlockTest("{ var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = bar; if(foo != null) { bar(); } ") - .AsStatement() - .AutoCompleteWith("}")), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF( - RazorResources.BlockName_Code, '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfClassBlockUnterminatedAtEOF() - { - ParseBlockTest("functions { var foo = bar; if(foo != null) { bar(); } ", - new FunctionsBlock( - Factory.MetaCode("functions {").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = bar; if(foo != null) { bar(); } ") - .AsFunctionsBody() - .AutoCompleteWith("}")), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("functions", '}', '{'), - new SourceLocation(10, 0, 10), - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfIfBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("if"); - } - - [Fact] - public void ParseBlockReportsErrorIfElseBlockUnterminatedAtEOF() - { - ParseBlockTest("if(foo) { baz(); } else { var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.Code("if(foo) { baz(); } else { var foo = bar; if(foo != null) { bar(); } ").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("else", '}', '{'), - new SourceLocation(19, 0, 19), - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfElseIfBlockUnterminatedAtEOF() - { - ParseBlockTest("if(foo) { baz(); } else if { var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.Code("if(foo) { baz(); } else if { var foo = bar; if(foo != null) { bar(); } ").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("else if", '}', '{'), - new SourceLocation(19, 0, 19), - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfDoBlockUnterminatedAtEOF() - { - ParseBlockTest("do { var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.Code("do { var foo = bar; if(foo != null) { bar(); } ").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("do", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfTryBlockUnterminatedAtEOF() - { - ParseBlockTest("try { var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.Code("try { var foo = bar; if(foo != null) { bar(); } ").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("try", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfCatchBlockUnterminatedAtEOF() - { - ParseBlockTest("try { baz(); } catch(Foo) { var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.Code("try { baz(); } catch(Foo) { var foo = bar; if(foo != null) { bar(); } ").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("catch", '}', '{'), - new SourceLocation(15, 0, 15), - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfFinallyBlockUnterminatedAtEOF() - { - ParseBlockTest("try { baz(); } finally { var foo = bar; if(foo != null) { bar(); } ", - new StatementBlock( - Factory.Code("try { baz(); } finally { var foo = bar; if(foo != null) { bar(); } ").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("finally", '}', '{'), - new SourceLocation(15, 0, 15), - length: 1)); - } - - [Fact] - public void ParseBlockReportsErrorIfForBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("for"); - } - - [Fact] - public void ParseBlockReportsErrorIfForeachBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("foreach"); - } - - [Fact] - public void ParseBlockReportsErrorIfWhileBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("while"); - } - - [Fact] - public void ParseBlockReportsErrorIfSwitchBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("switch"); - } - - [Fact] - public void ParseBlockReportsErrorIfLockBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("lock"); - } - - [Fact] - public void ParseBlockReportsErrorIfUsingBlockUnterminatedAtEOF() - { - RunUnterminatedSimpleKeywordBlock("using"); - } - - [Fact] - public void ParseBlockRequiresControlFlowStatementsToHaveBraces() - { - var expectedMessage = RazorResources.FormatParseError_SingleLine_ControlFlowStatements_Not_Allowed("{", "<"); - ParseBlockTest("if(foo)

Bar

else if(bar)

Baz

else

Boz

", - new StatementBlock( - Factory.Code("if(foo) ").AsStatement(), - new MarkupBlock( - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Bar"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - Factory.Code("else if(bar) ").AsStatement(), - new MarkupBlock( - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Baz"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - Factory.Code("else ").AsStatement(), - new MarkupBlock( - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Boz"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None)), - Factory.EmptyCSharp().AsStatement() - ), - new RazorError(expectedMessage, 8, 0, 8, 1), - new RazorError(expectedMessage, 32, 0, 32, 1), - new RazorError(expectedMessage, 48, 0, 48, 1)); - } - - [Fact] - public void ParseBlockIncludesUnexpectedCharacterInSingleStatementControlFlowStatementError() - { - ParseBlockTest("if(foo)) { var bar = foo; }", - new StatementBlock( - Factory.Code("if(foo)) { var bar = foo; }").AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_SingleLine_ControlFlowStatements_Not_Allowed("{", ")"), - new SourceLocation(7, 0, 7), - length: 1)); - } - - [Fact] - public void ParseBlockOutputsErrorIfAtSignFollowedByLessThanSignAtStatementStart() - { - ParseBlockTest("if(foo) { @

Bar

}", - new StatementBlock( - Factory.Code("if(foo) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Bar"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - Factory.Code("}").AsStatement() - ), - new RazorError( - RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start, - new SourceLocation(10, 0, 10), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesIfBlockAtEOLWhenRecoveringFromMissingCloseParen() - { - ParseBlockTest("if(foo bar" + Environment.NewLine - + "baz", - new StatementBlock( - Factory.Code("if(foo bar" + Environment.NewLine).AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(2, 0, 2), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesForeachBlockAtEOLWhenRecoveringFromMissingCloseParen() - { - ParseBlockTest("foreach(foo bar" + Environment.NewLine - + "baz", - new StatementBlock( - Factory.Code("foreach(foo bar" + Environment.NewLine).AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(7, 0, 7), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesWhileClauseInDoStatementAtEOLWhenRecoveringFromMissingCloseParen() - { - ParseBlockTest("do { } while(foo bar" + Environment.NewLine - + "baz", - new StatementBlock( - Factory.Code("do { } while(foo bar" + Environment.NewLine).AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(12, 0, 12), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesUsingBlockAtEOLWhenRecoveringFromMissingCloseParen() - { - ParseBlockTest("using(foo bar" + Environment.NewLine - + "baz", - new StatementBlock( - Factory.Code("using(foo bar" + Environment.NewLine).AsStatement() - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(5, 0, 5), - length: 1)); - } - - [Fact] - public void ParseBlockResumesIfStatementAfterOpenParen() - { - ParseBlockTest("if(" + Environment.NewLine - + "else {

Foo

}", - new StatementBlock( - Factory.Code($"if({Environment.NewLine}else {{").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None) - ), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(2, 0, 2), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesNormalCSharpStringsAtEOLIfEndQuoteMissing() - { - SingleSpanBlockTest("if(foo) {" + Environment.NewLine - + " var p = \"foo bar baz" + Environment.NewLine - + ";" + Environment.NewLine - + "}", - BlockType.Statement, SpanKind.Code, - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - new SourceLocation(21 + Environment.NewLine.Length, 1, 12), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesNormalStringAtEndOfFile() - { - SingleSpanBlockTest("if(foo) { var foo = \"blah blah blah blah blah", BlockType.Statement, SpanKind.Code, - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - new SourceLocation(20, 0, 20), - length: 1), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("if", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesVerbatimStringAtEndOfFile() - { - SingleSpanBlockTest("if(foo) { var foo = @\"blah " + Environment.NewLine - + "blah; " + Environment.NewLine - + "

Foo

" + Environment.NewLine - + "blah " + Environment.NewLine - + "blah", - BlockType.Statement, SpanKind.Code, - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - new SourceLocation(20, 0, 20), - length: 1), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("if", '}', '{'), - SourceLocation.Zero, - length: 1)); - } - - [Fact] - public void ParseBlockCorrectlyParsesMarkupIncorrectyAssumedToBeWithinAStatement() - { - ParseBlockTest("if(foo) {" + Environment.NewLine - + " var foo = \"foo bar baz" + Environment.NewLine - + "

Foo is @foo

" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code($"if(foo) {{{Environment.NewLine} var foo = \"foo bar baz{Environment.NewLine} ").AsStatement(), - new MarkupBlock( - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Foo is "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code("}").AsStatement() - ), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - new SourceLocation(23 + Environment.NewLine.Length, 1, 14), - length: 1)); - } - - [Fact] - public void ParseBlockCorrectlyParsesAtSignInDelimitedBlock() - { - ParseBlockTest("(Request[\"description\"] ?? @photo.Description)", - new ExpressionBlock( - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("Request[\"description\"] ?? @photo.Description").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockCorrectlyRecoversFromMissingCloseParenInExpressionWithinCode() - { - ParseBlockTest(@"{string.Format(}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code("string.Format(") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - BlockFactory.MarkupTagBlock("", AcceptedCharacters.None), - BlockFactory.MarkupTagBlock("", AcceptedCharacters.None)), - Factory.EmptyCSharp().AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - expectedErrors: new[] - { - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(14, 0, 14), - length: 1) - }); - - } - - private void RunUnterminatedSimpleKeywordBlock(string keyword) - { - SingleSpanBlockTest( - keyword + " (foo) { var foo = bar; if(foo != null) { bar(); } ", - BlockType.Statement, - SpanKind.Code, - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF(keyword, '}', '{'), - SourceLocation.Zero, - length: 1)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpExplicitExpressionTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpExplicitExpressionTest.cs deleted file mode 100644 index 6e83ef8f62..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpExplicitExpressionTest.cs +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpExplicitExpressionTest : CsHtmlCodeParserTestBase - { - [Fact] - public void ParseBlockShouldOutputZeroLengthCodeSpanIfExplicitExpressionIsEmpty() - { - ParseBlockTest("@()", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp().AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldOutputZeroLengthCodeSpanIfEOFOccursAfterStartOfExplicitExpression() - { - ParseBlockTest("@(", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp().AsExpression() - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF( - RazorResources.BlockName_ExplicitExpression, ")", "("), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockShouldAcceptEscapedQuoteInNonVerbatimStrings() - { - ParseBlockTest("@(\"\\\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("\"\\\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptEscapedQuoteInVerbatimStrings() - { - ParseBlockTest("@(@\"\"\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("@\"\"\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptMultipleRepeatedEscapedQuoteInVerbatimStrings() - { - ParseBlockTest("@(@\"\"\"\"\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("@\"\"\"\"\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptMultiLineVerbatimStrings() - { - ParseBlockTest(@"@(@""" + Environment.NewLine - + @"Foo" + Environment.NewLine - + @"Bar" + Environment.NewLine - + @"Baz" + Environment.NewLine - + @""")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code($"@\"{Environment.NewLine}Foo{Environment.NewLine}Bar{Environment.NewLine}Baz{Environment.NewLine}\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptMultipleEscapedQuotesInNonVerbatimStrings() - { - ParseBlockTest("@(\"\\\"hello, world\\\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("\"\\\"hello, world\\\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptMultipleEscapedQuotesInVerbatimStrings() - { - ParseBlockTest("@(@\"\"\"hello, world\"\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("@\"\"\"hello, world\"\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptConsecutiveEscapedQuotesInNonVerbatimStrings() - { - ParseBlockTest("@(\"\\\"\\\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("\"\\\"\\\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockShouldAcceptConsecutiveEscapedQuotesInVerbatimStrings() - { - ParseBlockTest("@(@\"\"\"\"\"\")", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("@\"\"\"\"\"\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpImplicitExpressionTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpImplicitExpressionTest.cs deleted file mode 100644 index 9de808cd63..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpImplicitExpressionTest.cs +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpImplicitExpressionTest : CsHtmlCodeParserTestBase - { - private const string TestExtraKeyword = "model"; - - public override ParserBase CreateCodeParser() - { - return new CSharpCodeParser(); - } - - public static TheoryData NullConditionalOperatorData_Bracket - { - get - { - var noErrors = new RazorError[0]; - Func missingEndParenError = (index) => - new RazorError[1] - { - new RazorError( - "An opening \"(\" is missing the corresponding closing \")\".", - new SourceLocation(index, 0, index), - length: 1) - }; - Func missingEndBracketError = (index) => - new RazorError[1] - { - new RazorError( - "An opening \"[\" is missing the corresponding closing \"]\".", - new SourceLocation(index, 0, index), - length: 1) - }; - - // implicitExpression, expectedImplicitExpression, acceptedCharacters, expectedErrors - return new TheoryData - { - { "val??[", "val", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val??[0", "val", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[", "val?[", AcceptedCharacters.Any, missingEndBracketError(5) }, - { "val?(", "val", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[more", "val?[more", AcceptedCharacters.Any, missingEndBracketError(5) }, - { "val?[0]", "val?[0]", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[

", "val?[", AcceptedCharacters.Any, missingEndBracketError(5) }, - { "val?[more.

", "val?[more.", AcceptedCharacters.Any, missingEndBracketError(5) }, - { "val??[more

", "val", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[-1]?", "val?[-1]", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[abc]?[def", "val?[abc]?[def", AcceptedCharacters.Any, missingEndBracketError(11) }, - { "val?[abc]?[2]", "val?[abc]?[2]", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[abc]?.more?[def]", "val?[abc]?.more?[def]", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[abc]?.more?.abc", "val?[abc]?.more?.abc", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[null ?? true]", "val?[null ?? true]", AcceptedCharacters.NonWhiteSpace, noErrors }, - { "val?[abc?.gef?[-1]]", "val?[abc?.gef?[-1]]", AcceptedCharacters.NonWhiteSpace, noErrors }, - }; - } - } - - [Theory] - [MemberData(nameof(NullConditionalOperatorData_Bracket))] - public void ParseBlockMethodParsesNullConditionalOperatorImplicitExpression_Bracket( - string implicitExpresison, - string expectedImplicitExpression, - AcceptedCharacters acceptedCharacters, - RazorError[] expectedErrors) - { - // Act & Assert - ImplicitExpressionTest( - implicitExpresison, - expectedImplicitExpression, - acceptedCharacters, - expectedErrors); - } - - public static TheoryData NullConditionalOperatorData_Dot - { - get - { - // implicitExpression, expectedImplicitExpression - return new TheoryData - { - { "val?", "val" }, - { "val??", "val" }, - { "val??more", "val" }, - { "val?!", "val" }, - { "val?.", "val?." }, - { "val??.", "val" }, - { "val?.(abc)", "val?." }, - { "val?.

", "val?." }, - { "val?.more", "val?.more" }, - { "val?.more

", "val?.more" }, - { "val??.more

", "val" }, - { "val?.more(false)?.

", "val?.more(false)?." }, - { "val?.more(false)?.abc", "val?.more(false)?.abc" }, - { "val?.more(null ?? true)?.abc", "val?.more(null ?? true)?.abc" }, - }; - } - } - - [Theory] - [MemberData(nameof(NullConditionalOperatorData_Dot))] - public void ParseBlockMethodParsesNullConditionalOperatorImplicitExpression_Dot( - string implicitExpresison, - string expectedImplicitExpression) - { - // Act & Assert - ImplicitExpressionTest(implicitExpresison, expectedImplicitExpression); - } - - [Fact] - public void NestedImplicitExpression() - { - ParseBlockTest("if (true) { @foo }", - new StatementBlock( - Factory.Code("if (true) { ").AsStatement(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Code(" }").AsStatement())); - } - - [Fact] - public void ParseBlockAcceptsNonEnglishCharactersThatAreValidIdentifiers() - { - ImplicitExpressionTest("हळूँजद॔.", "हळूँजद॔"); - } - - [Fact] - public void ParseBlockOutputsZeroLengthCodeSpanIfInvalidCharacterFollowsTransition() - { - ParseBlockTest("@/", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(KeywordSet) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS("/"), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockOutputsZeroLengthCodeSpanIfEOFOccursAfterTransition() - { - ParseBlockTest("@", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(KeywordSet) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new RazorError( - RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockSupportsSlashesWithinComplexImplicitExpressions() - { - ImplicitExpressionTest("DataGridColumn.Template(\"Years of Service\", e => (int)Math.Round((DateTime.Now - dt).TotalDays / 365))"); - } - - [Fact] - public void ParseBlockMethodParsesSingleIdentifierAsImplicitExpression() - { - ImplicitExpressionTest("foo"); - } - - [Fact] - public void ParseBlockMethodDoesNotAcceptSemicolonIfExpressionTerminatedByWhitespace() - { - ImplicitExpressionTest("foo ;", "foo"); - } - - [Fact] - public void ParseBlockMethodIgnoresSemicolonAtEndOfSimpleImplicitExpression() - { - RunTrailingSemicolonTest("foo"); - } - - [Fact] - public void ParseBlockMethodParsesDottedIdentifiersAsImplicitExpression() - { - ImplicitExpressionTest("foo.bar.baz"); - } - - [Fact] - public void ParseBlockMethodIgnoresSemicolonAtEndOfDottedIdentifiers() - { - RunTrailingSemicolonTest("foo.bar.baz"); - } - - [Fact] - public void ParseBlockMethodDoesNotIncludeDotAtEOFInImplicitExpression() - { - ImplicitExpressionTest("foo.bar.", "foo.bar"); - } - - [Fact] - public void ParseBlockMethodDoesNotIncludeDotFollowedByInvalidIdentifierCharacterInImplicitExpression() - { - ImplicitExpressionTest("foo.bar.0", "foo.bar"); - ImplicitExpressionTest("foo.bar.

", "foo.bar"); - } - - [Fact] - public void ParseBlockMethodDoesNotIncludeSemicolonAfterDot() - { - ImplicitExpressionTest("foo.bar.;", "foo.bar"); - } - - [Fact] - public void ParseBlockMethodTerminatesAfterIdentifierUnlessFollowedByDotOrParenInImplicitExpression() - { - ImplicitExpressionTest("foo.bar

", "foo.bar"); - } - - [Fact] - public void ParseBlockProperlyParsesParenthesesAndBalancesThemInImplicitExpression() - { - ImplicitExpressionTest(@"foo().bar(""bi\""z"", 4)(""chained method; call"").baz(@""bo""""z"", '\'', () => { return 4; }, (4+5+new { foo = bar[4] }))"); - } - - [Fact] - public void ParseBlockProperlyParsesBracketsAndBalancesThemInImplicitExpression() - { - ImplicitExpressionTest(@"foo.bar[4 * (8 + 7)][""fo\""o""].baz"); - } - - [Fact] - public void ParseBlockTerminatesImplicitExpressionAtHtmlEndTag() - { - ImplicitExpressionTest("foo().bar.baz

zoop", "foo().bar.baz"); - } - - [Fact] - public void ParseBlockTerminatesImplicitExpressionAtHtmlStartTag() - { - ImplicitExpressionTest("foo().bar.baz

zoop", "foo().bar.baz"); - } - - [Fact] - public void ParseBlockTerminatesImplicitExpressionBeforeDotIfDotNotFollowedByIdentifierStartCharacter() - { - ImplicitExpressionTest("foo().bar.baz.42", "foo().bar.baz"); - } - - [Fact] - public void ParseBlockStopsBalancingParenthesesAtEOF() - { - ImplicitExpressionTest( - "foo(()", "foo(()", - acceptedCharacters: AcceptedCharacters.Any, - errors: new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(4, 0, 4), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesImplicitExpressionIfCloseParenFollowedByAnyWhiteSpace() - { - ImplicitExpressionTest("foo.bar() (baz)", "foo.bar()"); - } - - [Fact] - public void ParseBlockTerminatesImplicitExpressionIfIdentifierFollowedByAnyWhiteSpace() - { - ImplicitExpressionTest("foo .bar() (baz)", "foo"); - } - - [Fact] - public void ParseBlockTerminatesImplicitExpressionAtLastValidPointIfDotFollowedByWhitespace() - { - ImplicitExpressionTest("foo. bar() (baz)", "foo"); - } - - [Fact] - public void ParseBlockOutputExpressionIfModuleTokenNotFollowedByBrace() - { - ImplicitExpressionTest("module.foo()"); - } - - private void RunTrailingSemicolonTest(string expr) - { - ParseBlockTest(SyntaxConstants.TransitionString + expr + ";", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code(expr) - .AsImplicitExpression(KeywordSet) - .Accepts(AcceptedCharacters.NonWhiteSpace) - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpLanguageCharacteristicsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpLanguageCharacteristicsTest.cs deleted file mode 100644 index fe905f65c3..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpLanguageCharacteristicsTest.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpLanguageCharacteristicsTest - { - [Fact] - public void GetSymbolSample_RightShiftAssign_ReturnsCorrectSymbol() - { - // Arrange & Act - var symbol = CSharpLanguageCharacteristics.GetSymbolSample(CSharpSymbolType.RightShiftAssign); - - // Assert - Assert.Equal(">>=", symbol); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpNestedStatementsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpNestedStatementsTest.cs deleted file mode 100644 index 74b7cb306f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpNestedStatementsTest.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpNestedStatementsTest : CsHtmlCodeParserTestBase - { - [Fact] - public void NestedSimpleStatement() - { - ParseBlockTest("@while(true) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void NestedKeywordStatement() - { - ParseBlockTest("@while(true) { for(int i = 0; i < 10; i++) { foo(); } }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) { for(int i = 0; i < 10; i++) { foo(); } }") - .AsStatement() - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void NestedCodeBlock() - { - ParseBlockTest("@while(true) { { { { foo(); } } } }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) { { { { foo(); } } } }") - .AsStatement() - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void NestedImplicitExpression() - { - ParseBlockTest("@while(true) { @foo }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) { ") - .AsStatement(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Code(" }") - .AsStatement() - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void NestedExplicitExpression() - { - ParseBlockTest("@while(true) { @(foo) }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) { ") - .AsStatement(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(") - .Accepts(AcceptedCharacters.None), - Factory.Code("foo") - .AsExpression(), - Factory.MetaCode(")") - .Accepts(AcceptedCharacters.None)), - Factory.Code(" }") - .AsStatement() - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void NestedMarkupBlock() - { - ParseBlockTest("@while(true) {

Hello

}", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) {") - .AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Hello"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("}") - .AsStatement() - .Accepts(AcceptedCharacters.None))); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpRazorCommentsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpRazorCommentsTest.cs deleted file mode 100644 index 76e20cd585..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpRazorCommentsTest.cs +++ /dev/null @@ -1,428 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpRazorCommentsTest : CsHtmlMarkupParserTestBase - { - [Fact] - public void UnterminatedRazorComment() - { - ParseDocumentTest("@*", - new MarkupBlock( - Factory.EmptyHtml(), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any))), - new RazorError( - RazorResources.ParseError_RazorComment_Not_Terminated, - SourceLocation.Zero, - length: 2)); - } - - [Fact] - public void EmptyRazorComment() - { - ParseDocumentTest("@**@", - new MarkupBlock( - Factory.EmptyHtml(), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void RazorCommentInImplicitExpressionMethodCall() - { - ParseDocumentTest("@foo(" + Environment.NewLine - + "@**@" + Environment.NewLine, - new MarkupBlock( - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo(" + Environment.NewLine) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - new CommentBlock( - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new CSharpSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - CSharpSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Code(Environment.NewLine) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords))), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(4, 0, 4), - length: 1)); - } - - [Fact] - public void UnterminatedRazorCommentInImplicitExpressionMethodCall() - { - ParseDocumentTest("@foo(@*", - new MarkupBlock( - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo(") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - new CommentBlock( - Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaCode("*", CSharpSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new CSharpSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - CSharpSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any)))), - new RazorError( - RazorResources.ParseError_RazorComment_Not_Terminated, - new SourceLocation(5, 0, 5), - length: 2), - new RazorError( - RazorResources.FormatParseError_Expected_CloseBracket_Before_EOF("(", ")"), - new SourceLocation(4, 0, 4), - length: 1)); - } - - [Fact] - public void RazorCommentInVerbatimBlock() - { - ParseDocumentTest("@{" + Environment.NewLine - + " " + Environment.NewLine - + "@**@" + Environment.NewLine - + "

", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(Environment.NewLine), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).With(SpanChunkGenerator.Null), - new MarkupTagBlock( - Factory.Markup("

")) - )); - } - - [Fact] - public void MultipleRazorCommentInMarkup() - { - ParseDocumentTest( - "

" + Environment.NewLine - + " @**@ " + Environment.NewLine - + "@**@" + Environment.NewLine - + "

", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(Environment.NewLine), - Factory.Markup(" ").With(SpanChunkGenerator.Null), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(" " + Environment.NewLine).With(SpanChunkGenerator.Null), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).With(SpanChunkGenerator.Null), - new MarkupTagBlock( - Factory.Markup("

")) - )); - } - - [Fact] - public void MultipleRazorCommentsInSameLineInMarkup() - { - ParseDocumentTest( - "

" + Environment.NewLine - + "@**@ @**@" + Environment.NewLine - + "

", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(Environment.NewLine), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml(), - Factory.Markup(" ").With(SpanChunkGenerator.Null), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - string.Empty, - HtmlSymbolType.Unknown)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).With(SpanChunkGenerator.Null), - new MarkupTagBlock( - Factory.Markup("

")) - )); - } - - [Fact] - public void RazorCommentsSurroundingMarkup() - { - ParseDocumentTest( - "

" + Environment.NewLine - + "@* hello *@ content @* world *@" + Environment.NewLine - + "

", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(Environment.NewLine), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - " hello ", - HtmlSymbolType.RazorComment)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(" content "), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - " world ", - HtmlSymbolType.RazorComment)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine), - new MarkupTagBlock( - Factory.Markup("

")) - )); - } - - [Fact] - public void RazorCommentWithExtraNewLineInMarkup() - { - ParseDocumentTest( - "

" + Environment.NewLine + Environment.NewLine - + "@* content *@" + Environment.NewLine - + "@*" + Environment.NewLine - + "content" + Environment.NewLine - + "*@" + Environment.NewLine + Environment.NewLine - + "

", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(Environment.NewLine + Environment.NewLine), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - " content ", - HtmlSymbolType.RazorComment)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).With(SpanChunkGenerator.Null), - new CommentBlock( - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.Span(SpanKind.Comment, new HtmlSymbol( - Factory.LocationTracker.CurrentLocation, - Environment.NewLine + "content" + Environment.NewLine, - HtmlSymbolType.RazorComment)) - .Accepts(AcceptedCharacters.Any), - Factory.MetaMarkup("*", HtmlSymbolType.RazorCommentStar) - .Accepts(AcceptedCharacters.None), - Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition) - .Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).With(SpanChunkGenerator.Null), - Factory.Markup(Environment.NewLine), - new MarkupTagBlock( - Factory.Markup("

")) - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpReservedWordsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpReservedWordsTest.cs deleted file mode 100644 index 3a979b8bc6..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpReservedWordsTest.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class CSharpReservedWordsTest : CsHtmlCodeParserTestBase - { - [Theory] - [InlineData("namespace")] - [InlineData("class")] - public void ReservedWords(string word) - { - ParseBlockTest(word, - new DirectiveBlock( - Factory.MetaCode(word).Accepts(AcceptedCharacters.None) - ), - new RazorError( - RazorResources.FormatParseError_ReservedWord(word), - SourceLocation.Zero, - word.Length)); - } - - [Theory] - [InlineData("Namespace")] - [InlineData("Class")] - [InlineData("NAMESPACE")] - [InlineData("CLASS")] - [InlineData("nameSpace")] - [InlineData("NameSpace")] - private void ReservedWordsAreCaseSensitive(string word) - { - ParseBlockTest(word, - new ExpressionBlock( - Factory.Code(word) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSectionTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSectionTest.cs deleted file mode 100644 index cf5eef4440..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSectionTest.cs +++ /dev/null @@ -1,602 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class CSharpSectionTest : CsHtmlMarkupParserTestBase - { - [Fact] - public void ParseSectionBlockCapturesNewlineImmediatelyFollowing() - { - ParseDocumentTest("@section" + Environment.NewLine, - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator(string.Empty), - Factory.CodeTransition(), - Factory.MetaCode("section" + Environment.NewLine))), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Section_Name_Start( - RazorResources.ErrorComponent_EndOfFile), - new SourceLocation(8 + Environment.NewLine.Length, 1, 0), - length: 1)); - } - - [Fact] - public void ParseSectionBlockCapturesWhitespaceToEndOfLineInSectionStatementMissingOpenBrace() - { - ParseDocumentTest("@section Foo " + Environment.NewLine - + " ", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Foo"), - Factory.CodeTransition(), - Factory.MetaCode("section Foo " + Environment.NewLine)), - Factory.Markup(" ")), - new RazorError( - RazorResources.ParseError_MissingOpenBraceAfterSection, - new SourceLocation(12, 0, 12), - length: 1)); - } - - [Fact] - public void ParseSectionBlockCapturesWhitespaceToEndOfLineInSectionStatementMissingName() - { - ParseDocumentTest("@section " + Environment.NewLine - + " ", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator(string.Empty), - Factory.CodeTransition(), - Factory.MetaCode("section " + Environment.NewLine)), - Factory.Markup(" ")), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Section_Name_Start( - RazorResources.ErrorComponent_EndOfFile), - new SourceLocation(21 + Environment.NewLine.Length, 1, 4), - length: 1)); - } - - [Fact] - public void ParseSectionBlockIgnoresSectionUnlessAllLowerCase() - { - ParseDocumentTest("@Section foo", - new MarkupBlock( - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("Section") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Markup(" foo"))); - } - - [Fact] - public void ParseSectionBlockReportsErrorAndTerminatesSectionBlockIfKeywordNotFollowedByIdentifierStartCharacter() - { - ParseDocumentTest("@section 9 {

Foo

}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator(string.Empty), - Factory.CodeTransition(), - Factory.MetaCode("section ")), - Factory.Markup("9 { "), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(" }")), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Section_Name_Start( - RazorResources.FormatErrorComponent_Character("9")), - new SourceLocation(9, 0, 9), - length: 1)); - } - - [Fact] - public void ParseSectionBlockReportsErrorAndTerminatesSectionBlockIfNameNotFollowedByOpenBrace() - { - ParseDocumentTest("@section foo-bar {

Foo

}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo")), - Factory.Markup("-bar { "), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(" }")), - new RazorError( - RazorResources.ParseError_MissingOpenBraceAfterSection, - new SourceLocation(12, 0, 12), - length: 1)); - } - - [Fact] - public void ParserOutputsErrorOnNestedSections() - { - ParseDocumentTest("@section foo { @section bar {

Foo

} }", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new SectionBlock(new SectionChunkGenerator("bar"), - Factory.CodeTransition(), - Factory.MetaCode("section bar {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml()), - new RazorError( - RazorResources.FormatParseError_Sections_Cannot_Be_Nested(RazorResources.SectionExample_CS), - new SourceLocation(16, 0, 16), - 7)); - } - - [Fact] - public void ParseSectionBlockHandlesEOFAfterOpenBrace() - { - ParseDocumentTest("@section foo {", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith("}", atEndOfSpan: true), - new MarkupBlock())), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("section", "}", "{"), - new SourceLocation(13, 0, 13), - length: 1)); - } - - [Theory] - [InlineData(" ")] - [InlineData("\n")] - [InlineData(" abc")] - [InlineData(" \n abc")] - public void ParseSectionBlockHandlesEOFAfterOpenContent(string postStartBrace) - { - ParseDocumentTest("@section foo {" + postStartBrace, - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith("}", atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(postStartBrace)))), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("section", "}", "{"), - new SourceLocation(13, 0, 13), - length: 1)); - } - - [Fact] - public void ParseSectionBlockHandlesUnterminatedSection() - { - ParseDocumentTest("@section foo {

Foo{}

", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith("}", atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

")), - // Need to provide the markup span as fragments, since the parser will split the {} into separate symbols. - Factory.Markup("Foo", "{", "}"), - new MarkupTagBlock( - Factory.Markup("

"))))), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("section", "}", "{"), - new SourceLocation(13, 0, 13), - length: 1)); - } - - [Fact] - public void ParseSectionBlockHandlesUnterminatedSectionWithNestedIf() - { - var newLine = Environment.NewLine; - var spaces = " "; - ParseDocumentTest( - string.Format( - "@section Test{0}{{{0}{1}@if(true){0}{1}{{{0}{1}{1}

Hello World

{0}{1}}}", - newLine, - spaces), - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Test"), - Factory.CodeTransition(), - Factory.MetaCode($"section Test{newLine}{{") - .AutoCompleteWith("}", atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(newLine), - new StatementBlock( - Factory.Code(spaces).AsStatement(), - Factory.CodeTransition(), - Factory.Code($"if(true){newLine}{spaces}{{{newLine}").AsStatement(), - new MarkupBlock( - Factory.Markup($"{spaces}{spaces}"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup("Hello World"), - BlockFactory.MarkupTagBlock("

", AcceptedCharacters.None), - Factory.Markup(newLine).Accepts(AcceptedCharacters.None)), - Factory.Code($"{spaces}}}").AsStatement())))), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("section", "}", "{"), - new SourceLocation(13 + newLine.Length, 1, 0), - length: 1)); - } - - [Fact] - public void ParseSectionBlockReportsErrorAndAcceptsWhitespaceToEndOfLineIfSectionNotFollowedByOpenBrace() - { - ParseDocumentTest("@section foo " + Environment.NewLine, - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo " + Environment.NewLine))), - new RazorError( - RazorResources.ParseError_MissingOpenBraceAfterSection, - new SourceLocation(12, 0, 12), - length: 1)); - } - - [Fact] - public void ParseSectionBlockAcceptsOpenBraceMultipleLinesBelowSectionName() - { - ParseDocumentTest("@section foo " + Environment.NewLine - + Environment.NewLine - + Environment.NewLine - + Environment.NewLine - + Environment.NewLine - + Environment.NewLine - + "{" + Environment.NewLine - + "

Foo

" + Environment.NewLine - + "}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode(string.Format("section foo {0}{0}{0}{0}{0}{0}{{", Environment.NewLine)) - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(Environment.NewLine), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(Environment.NewLine)), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockParsesNamedSectionCorrectly() - { - ParseDocumentTest("@section foo {

Foo

}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockDoesNotRequireSpaceBetweenSectionNameAndOpenBrace() - { - ParseDocumentTest("@section foo{

Foo

}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo{") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

")), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockBalancesBraces() - { - ParseDocumentTest("@section foo { }", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("")), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockAllowsBracesInCSharpExpression() - { - ParseDocumentTest("@section foo { I really want to render a close brace, so here I go: @(\"}\") }", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" I really want to render a close brace, so here I go: "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("\"}\"").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void SectionIsCorrectlyTerminatedWhenCloseBraceImmediatelyFollowsCodeBlock() - { - ParseDocumentTest("@section Foo {" + Environment.NewLine - + "@if(true) {" + Environment.NewLine - + "}" + Environment.NewLine - + "}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Foo"), - Factory.CodeTransition(), - Factory.MetaCode("section Foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(Environment.NewLine), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code($"if(true) {{{Environment.NewLine}}}{Environment.NewLine}").AsStatement() - )), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void SectionIsCorrectlyTerminatedWhenCloseBraceImmediatelyFollowsCodeBlockNoWhitespace() - { - ParseDocumentTest("@section Foo {" + Environment.NewLine - + "@if(true) {" + Environment.NewLine - + "}}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Foo"), - Factory.CodeTransition(), - Factory.MetaCode("section Foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(Environment.NewLine), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code($"if(true) {{{Environment.NewLine}}}").AsStatement() - )), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockCorrectlyTerminatesWhenCloseBraceImmediatelyFollowsMarkup() - { - ParseDocumentTest("@section foo {something}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup("something")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockParsesComment() - { - ParseDocumentTest("@section s {}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("s"), - Factory.CodeTransition(), - Factory.MetaCode("section s {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup("")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - // This was a user reported bug (codeplex #710), the section parser wasn't handling - // comments. - [Fact] - public void ParseSectionBlockParsesCommentWithDelimiters() - { - ParseDocumentTest("@section s {}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("s"), - Factory.CodeTransition(), - Factory.MetaCode("section s {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup("")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockCommentRecoversFromUnclosedTag() - { - ParseDocumentTest( - "@section s {" + Environment.NewLine + " \" '-->}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("s"), - Factory.CodeTransition(), - Factory.MetaCode("section s {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(Environment.NewLine), - new MarkupTagBlock( - Factory.Markup(" \" '-->")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseSectionBlockParsesXmlProcessingInstruction() - { - ParseDocumentTest( - "@section s { }", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("s"), - Factory.CodeTransition(), - Factory.MetaCode("section s {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - public static TheoryData SectionWithEscapedTransitionData - { - get - { - var factory = CreateDefaultSpanFactory(); - - return new TheoryData - { - { - "@section s {}", - new MarkupBlock( - factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("s"), - factory.CodeTransition(), - factory.MetaCode("section s {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 17, 0, 17), new LocationTagged("'", 25, 0, 25)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 23, 0, 23), new LocationTagged("@", 23, 0, 23))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />"))), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()) - }, - { - "@section s {}", - new MarkupBlock( - factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("s"), - factory.CodeTransition(), - factory.MetaCode("section s {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" foo='", 17, 0, 17), new LocationTagged("'", 39, 0, 39)), - factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 23, 0, 23), 23, 0, 23), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - new MarkupBlock( - factory.Markup(" @").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 36, 0, 36), new LocationTagged("@", 37, 0, 37))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(" />"))), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()) - }, - }; - } - } - - [Theory] - [MemberData(nameof(SectionWithEscapedTransitionData))] - public void ParseSectionBlock_WithDoubleTransition_DoesNotThrow(string input, Block expected) - { - ParseDocumentTest(input, expected); - } - - private static SpanFactory CreateDefaultSpanFactory() - { - return new SpanFactory - { - MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), - CodeTokenizerFactory = doc => new CSharpTokenizer(doc) - }; - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSpecialBlockTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSpecialBlockTest.cs deleted file mode 100644 index 4e1eb88cff..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpSpecialBlockTest.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class CSharpSpecialBlockTest : CsHtmlCodeParserTestBase - { - [Fact] - public void ParseInheritsStatementMarksInheritsSpanAsCanGrowIfMissingTrailingSpace() - { - ParseBlockTest("inherits", - new DirectiveBlock( - Factory.MetaCode("inherits").Accepts(AcceptedCharacters.Any) - ), - new RazorError( - RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName, - new SourceLocation(0, 0, 0), 8)); - } - - [Fact] - public void InheritsBlockAcceptsMultipleGenericArguments() - { - ParseBlockTest("inherits Foo.Bar, string, int>.Baz", - new DirectiveBlock( - Factory.MetaCode("inherits ").Accepts(AcceptedCharacters.None), - Factory.Code("Foo.Bar, string, int>.Baz") - .AsBaseType("Foo.Bar, string, int>.Baz") - )); - } - - [Fact] - public void InheritsBlockOutputsErrorIfInheritsNotFollowedByTypeButAcceptsEntireLineAsCode() - { - ParseBlockTest("inherits " + Environment.NewLine - + "foo", - new DirectiveBlock( - Factory.MetaCode("inherits ").Accepts(AcceptedCharacters.None), - Factory.Code(" " + Environment.NewLine) - .AsBaseType(string.Empty) - ), - new RazorError(RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName, 0, 0, 0, 8)); - } - - [Fact] - public void NamespaceImportInsideCodeBlockCausesError() - { - ParseBlockTest("{ using Foo.Bar.Baz; var foo = bar; }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" using Foo.Bar.Baz; var foo = bar; ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), - new RazorError( - RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock, - new SourceLocation(2, 0, 2), - length: 5)); - } - - [Fact] - public void TypeAliasInsideCodeBlockIsNotHandledSpecially() - { - ParseBlockTest("{ using Foo = Bar.Baz; var foo = bar; }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" using Foo = Bar.Baz; var foo = bar; ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), - new RazorError( - RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock, - new SourceLocation(2, 0, 2), - length: 5)); - } - - [Fact] - public void Plan9FunctionsKeywordInsideCodeBlockIsNotHandledSpecially() - { - ParseBlockTest("{ functions Foo; }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" functions Foo; ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void NonKeywordStatementInCodeBlockIsHandledCorrectly() - { - ParseBlockTest("{" + Environment.NewLine - + " List photos = gallery.Photo.ToList();" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code($"{Environment.NewLine} List photos = gallery.Photo.ToList();{Environment.NewLine}") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockBalancesBracesOutsideStringsIfFirstCharacterIsBraceAndReturnsSpanOfTypeCode() - { - // Arrange - const string code = "foo\"b}ar\" if(condition) { string.Format(\"{0}\"); } "; - - // Act/Assert - ParseBlockTest("{" + code + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(code) - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockBalancesParensOutsideStringsIfFirstCharacterIsParenAndReturnsSpanOfTypeExpression() - { - // Arrange - const string code = "foo\"b)ar\" if(condition) { string.Format(\"{0}\"); } "; - - // Act/Assert - ParseBlockTest("(" + code + ")", - new ExpressionBlock( - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code(code).AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockBalancesBracesAndOutputsContentAsClassLevelCodeSpanIfFirstIdentifierIsFunctionsKeyword() - { - const string code = " foo(); \"bar}baz\" "; - ParseBlockTest("functions {" + code + "} zoop", - new FunctionsBlock( - Factory.MetaCode("functions {").Accepts(AcceptedCharacters.None), - Factory.Code(code) - .AsFunctionsBody() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockDoesNoErrorRecoveryForFunctionsBlock() - { - ParseBlockTest("functions { { { { { } zoop", - new FunctionsBlock( - Factory.MetaCode("functions {").Accepts(AcceptedCharacters.None), - Factory.Code(" { { { { } zoop") - .AsFunctionsBody() - .AutoCompleteWith("}") - ), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("functions", "}", "{"), - new SourceLocation(10, 0, 10), - length: 1)); - } - - [Fact] - public void ParseBlockIgnoresFunctionsUnlessAllLowerCase() - { - ParseBlockTest("Functions { foo() }", - new ExpressionBlock( - Factory.Code("Functions") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))); - } - - [Fact] - public void ParseBlockIgnoresSingleSlashAtStart() - { - ParseBlockTest("@/ foo", - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS("/"), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockTerminatesSingleLineCommentAtEndOfLine() - { - ParseBlockTest("if(!false) {" + Environment.NewLine - + " // Foo" + Environment.NewLine - + "\t

A real tag!

" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code($"if(!false) {{{Environment.NewLine} // Foo{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup("\t"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("A real tag!"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code("}").AsStatement() - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpStatementTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpStatementTest.cs deleted file mode 100644 index ea59a08fd7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpStatementTest.cs +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - // Basic Tests for C# Statements: - // * Basic case for each statement - // * Basic case for ALL clauses - - // This class DOES NOT contain - // * Error cases - // * Tests for various types of nested statements - // * Comment tests - - public class CSharpStatementTest : CsHtmlCodeParserTestBase - { - [Fact] - public void ForStatement() - { - ParseBlockTest("@for(int i = 0; i++; i < length) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("for(int i = 0; i++; i < length) { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ForEachStatement() - { - ParseBlockTest("@foreach(var foo in bar) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("foreach(var foo in bar) { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void WhileStatement() - { - ParseBlockTest("@while(true) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("while(true) { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void SwitchStatement() - { - ParseBlockTest("@switch(foo) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("switch(foo) { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void LockStatement() - { - ParseBlockTest("@lock(baz) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("lock(baz) { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void IfStatement() - { - ParseBlockTest("@if(true) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(true) { foo(); }") - .AsStatement() - )); - } - - [Fact] - public void ElseIfClause() - { - ParseBlockTest("@if(true) { foo(); } else if(false) { foo(); } else if(!false) { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(true) { foo(); } else if(false) { foo(); } else if(!false) { foo(); }") - .AsStatement() - )); - } - - [Fact] - public void ElseClause() - { - ParseBlockTest("@if(true) { foo(); } else { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(true) { foo(); } else { foo(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void TryStatement() - { - ParseBlockTest("@try { foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("try { foo(); }") - .AsStatement() - )); - } - - [Fact] - public void CatchClause() - { - ParseBlockTest("@try { foo(); } catch(IOException ioex) { handleIO(); } catch(Exception ex) { handleOther(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("try { foo(); } catch(IOException ioex) { handleIO(); } catch(Exception ex) { handleOther(); }") - .AsStatement() - )); - } - - public static TheoryData ExceptionFilterData - { - get - { - var factory = SpanFactory.CreateCsHtml(); - - // document, expectedStatement - return new TheoryData - { - { - "@try { someMethod(); } catch(Exception) when (true) { handleIO(); }", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when (true) { handleIO(); }") - .AsStatement()) - }, - { - "@try { A(); } catch(Exception) when (true) { B(); } finally { C(); }", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { A(); } catch(Exception) when (true) { B(); } finally { C(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None)) - }, - { - "@try { A(); } catch(Exception) when (true) { B(); } catch(IOException) when (false) { C(); }", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { A(); } catch(Exception) when (true) { B(); } catch(IOException) " + - "when (false) { C(); }") - .AsStatement()) - }, - { - string.Format("@try{0}{{{0} A();{0}}}{0}catch(Exception) when (true)", Environment.NewLine) + - string.Format("{0}{{{0} B();{0}}}{0}catch(IOException) when (false)", Environment.NewLine) + - string.Format("{0}{{{0} C();{0}}}", Environment.NewLine), - new StatementBlock( - factory.CodeTransition(), - factory - .Code( - string.Format("try{0}{{{0} A();{0}}}{0}catch(Exception) ", Environment.NewLine) + - string.Format("when (true){0}{{{0} B();{0}}}{0}", Environment.NewLine) + - string.Format("catch(IOException) when (false){0}{{{0} ", Environment.NewLine) + - string.Format("C();{0}}}", Environment.NewLine)) - .AsStatement()) - }, - - // Wrapped in @{ block. - { - "@{try { someMethod(); } catch(Exception) when (true) { handleIO(); }}", - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory - .Code("try { someMethod(); } catch(Exception) when (true) { handleIO(); }") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)) - }, - - // Partial exception filter data - { - "@try { someMethod(); } catch(Exception) when", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when") - .AsStatement()) - }, - { - "@try { someMethod(); } when", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); }") - .AsStatement()) - }, - { - "@try { someMethod(); } catch(Exception) when { anotherMethod(); }", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when { anotherMethod(); }") - .AsStatement()) - }, - { - "@try { someMethod(); } catch(Exception) when (true)", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when (true)") - .AsStatement()) - }, - }; - } - } - - [Theory] - [MemberData(nameof(ExceptionFilterData))] - public void ExceptionFilters(string document, StatementBlock expectedStatement) - { - // Act & Assert - ParseBlockTest(document, expectedStatement); - } - - public static TheoryData ExceptionFilterErrorData - { - get - { - var factory = SpanFactory.CreateCsHtml(); - var unbalancedParenErrorString = "An opening \"(\" is missing the corresponding closing \")\"."; - var unbalancedBracketCatchErrorString = "The catch block is missing a closing \"}\" character. " + - "Make sure you have a matching \"}\" character for all the \"{\" characters within this block, " + - "and that none of the \"}\" characters are being interpreted as markup."; - - // document, expectedStatement, expectedErrors - return new TheoryData - { - { - "@try { someMethod(); } catch(Exception) when (", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when (") - .AsStatement()), - new[] { new RazorError(unbalancedParenErrorString, 45, 0, 45, 1) } - }, - { - "@try { someMethod(); } catch(Exception) when (someMethod(", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when (someMethod(") - .AsStatement()), - new[] { new RazorError(unbalancedParenErrorString, 45, 0, 45, 1) } - }, - { - "@try { someMethod(); } catch(Exception) when (true) {", - new StatementBlock( - factory.CodeTransition(), - factory - .Code("try { someMethod(); } catch(Exception) when (true) {") - .AsStatement()), - new[] { new RazorError(unbalancedBracketCatchErrorString, 23, 0, 23, 1) } - }, - }; - } - } - - [Theory] - [MemberData(nameof(ExceptionFilterErrorData))] - public void ExceptionFilterErrors( - string document, - StatementBlock expectedStatement, - RazorError[] expectedErrors) - { - // Act & Assert - ParseBlockTest(document, expectedStatement, expectedErrors); - } - - [Fact] - public void FinallyClause() - { - ParseBlockTest("@try { foo(); } finally { Dispose(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("try { foo(); } finally { Dispose(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - public static TheoryData StaticUsingData - { - get - { - var factory = SpanFactory.CreateCsHtml(); - Func createUsing = (code, import) => - new DirectiveBlock( - factory.CodeTransition(), - factory.Code(code) - .AsNamespaceImport(import) - .Accepts(AcceptedCharacters.AnyExceptNewline)); - - // document, expectedResult - return new TheoryData - { - { "@using static", createUsing("using static", " static") }, - { "@using static ", createUsing("using static ", " static ") }, - { "@using static ", createUsing("using static ", " static ") }, - { "@using static System", createUsing("using static System", " static System") }, - { - "@using static System", - createUsing("using static System", " static System") - }, - { - "@using static System.Console", - createUsing("using static System.Console", " static System.Console") - }, - { - "@using static global::System.Console", - createUsing("using static global::System.Console", " static global::System.Console") - }, - { - "@using static global::System.Console ", - createUsing("using static global::System.Console", " static global::System.Console") - }, - }; - } - } - - [Theory] - [MemberData(nameof(StaticUsingData))] - public void StaticUsingImport(string document, DirectiveBlock expectedResult) - { - // Act & Assert - ParseBlockTest(document, expectedResult); - } - - [Fact] - public void UsingStatement() - { - ParseBlockTest("@using(var foo = new Foo()) { foo.Bar(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("using(var foo = new Foo()) { foo.Bar(); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void UsingTypeAlias() - { - ParseBlockTest("@using StringDictionary = System.Collections.Generic.Dictionary", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.Code("using StringDictionary = System.Collections.Generic.Dictionary") - .AsNamespaceImport(" StringDictionary = System.Collections.Generic.Dictionary") - .Accepts(AcceptedCharacters.AnyExceptNewline) - )); - } - - [Fact] - public void UsingNamespaceImport() - { - ParseBlockTest("@using System.Text.Encoding.ASCIIEncoding", - new DirectiveBlock( - Factory.CodeTransition(), - Factory.Code("using System.Text.Encoding.ASCIIEncoding") - .AsNamespaceImport(" System.Text.Encoding.ASCIIEncoding") - .Accepts(AcceptedCharacters.AnyExceptNewline) - )); - } - - [Fact] - public void DoStatement() - { - ParseBlockTest("@do { foo(); } while(true);", - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("do { foo(); } while(true);") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void NonBlockKeywordTreatedAsImplicitExpression() - { - ParseBlockTest("@is foo", - new ExpressionBlock(new ExpressionChunkGenerator(), - Factory.CodeTransition(), - Factory.Code("is") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpTemplateTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpTemplateTest.cs deleted file mode 100644 index 149cff548c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpTemplateTest.cs +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class CSharpTemplateTest : CsHtmlCodeParserTestBase - { - private const string TestTemplateCode = " @

Foo #@item

"; - - private TemplateBlock TestTemplate() - { - return new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo #"), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("item") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ) - ); - } - - private const string TestNestedTemplateCode = " @

Foo #@Html.Repeat(10, @

@item

)

"; - - private TemplateBlock TestNestedTemplate() - { - return new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo #"), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("Html.Repeat(10, ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("item") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ) - ), - Factory.Code(")") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ) - ); - } - - [Fact] - public void ParseBlockHandlesSingleLineTemplate() - { - ParseBlockTest("{ var foo = @: bar" + Environment.NewLine - + "; }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup(" bar" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)) - .Accepts(AcceptedCharacters.None) - ) - ), - Factory.Code("; ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockHandlesSingleLineImmediatelyFollowingStatementChar() - { - ParseBlockTest("{i@: bar" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code("i") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup(" bar" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)) - .Accepts(AcceptedCharacters.None) - ) - ), - Factory.EmptyCSharp().AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockHandlesSimpleTemplateInExplicitExpressionParens() - { - ParseBlockTest("(Html.Repeat(10," + TestTemplateCode + "))", - new ExpressionBlock( - Factory.MetaCode("(").Accepts(AcceptedCharacters.None), - Factory.Code("Html.Repeat(10, ").AsExpression(), - TestTemplate(), - Factory.Code(")").AsExpression(), - Factory.MetaCode(")").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockHandlesSimpleTemplateInImplicitExpressionParens() - { - ParseBlockTest("Html.Repeat(10," + TestTemplateCode + ")", - new ExpressionBlock( - Factory.Code("Html.Repeat(10, ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - TestTemplate(), - Factory.Code(")") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - )); - } - - [Fact] - public void ParseBlockHandlesTwoTemplatesInImplicitExpressionParens() - { - ParseBlockTest("Html.Repeat(10," + TestTemplateCode + "," + TestTemplateCode + ")", - new ExpressionBlock( - Factory.Code("Html.Repeat(10, ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - TestTemplate(), - Factory.Code(", ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - TestTemplate(), - Factory.Code(")") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace) - )); - } - - [Fact] - public void ParseBlockProducesErrorButCorrectlyParsesNestedTemplateInImplicitExpressionParens() - { - ParseBlockTest("Html.Repeat(10," + TestNestedTemplateCode + ")", - new ExpressionBlock( - Factory.Code("Html.Repeat(10, ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - TestNestedTemplate(), - Factory.Code(")") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - GetNestedTemplateError(42)); - } - - [Fact] - public void ParseBlockHandlesSimpleTemplateInStatementWithinCodeBlock() - { - ParseBlockTest("foreach(foo in Bar) { Html.ExecuteTemplate(foo," + TestTemplateCode + "); }", - new StatementBlock( - Factory.Code("foreach(foo in Bar) { Html.ExecuteTemplate(foo, ").AsStatement(), - TestTemplate(), - Factory.Code("); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockHandlesTwoTemplatesInStatementWithinCodeBlock() - { - ParseBlockTest("foreach(foo in Bar) { Html.ExecuteTemplate(foo," + TestTemplateCode + "," + TestTemplateCode + "); }", - new StatementBlock( - Factory.Code("foreach(foo in Bar) { Html.ExecuteTemplate(foo, ").AsStatement(), - TestTemplate(), - Factory.Code(", ").AsStatement(), - TestTemplate(), - Factory.Code("); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockProducesErrorButCorrectlyParsesNestedTemplateInStatementWithinCodeBlock() - { - ParseBlockTest("foreach(foo in Bar) { Html.ExecuteTemplate(foo," + TestNestedTemplateCode + "); }", - new StatementBlock( - Factory.Code("foreach(foo in Bar) { Html.ExecuteTemplate(foo, ") - .AsStatement(), - TestNestedTemplate(), - Factory.Code("); }") - .AsStatement() - .Accepts(AcceptedCharacters.None) - ), - GetNestedTemplateError(74)); - } - - [Fact] - public void ParseBlockHandlesSimpleTemplateInStatementWithinStatementBlock() - { - ParseBlockTest("{ var foo = bar; Html.ExecuteTemplate(foo," + TestTemplateCode + "); }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = bar; Html.ExecuteTemplate(foo, ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - TestTemplate(), - Factory.Code("); ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockHandlessTwoTemplatesInStatementWithinStatementBlock() - { - ParseBlockTest("{ var foo = bar; Html.ExecuteTemplate(foo," + TestTemplateCode + "," + TestTemplateCode + "); }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = bar; Html.ExecuteTemplate(foo, ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - TestTemplate(), - Factory.Code(", ").AsStatement(), - TestTemplate(), - Factory.Code("); ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockProducesErrorButCorrectlyParsesNestedTemplateInStatementWithinStatementBlock() - { - ParseBlockTest("{ var foo = bar; Html.ExecuteTemplate(foo," + TestNestedTemplateCode + "); }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = bar; Html.ExecuteTemplate(foo, ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - TestNestedTemplate(), - Factory.Code("); ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), - GetNestedTemplateError(69)); - } - - [Fact] - public void ParseBlock_WithDoubleTransition_DoesNotThrow() - { - // Arrange - var testTemplateWithDoubleTransitionCode = " @

Foo #@item

"; - var testTemplateWithDoubleTransition = new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - new MarkupTagBlock( - Factory.Markup("(" foo='", 46, 0, 46), new LocationTagged("'", 54, 0, 54)), - Factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - Factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 52, 0, 52), new LocationTagged("@", 52, 0, 52))).Accepts(AcceptedCharacters.None), - Factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(">").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo #"), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("item") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ) - ); - - var expected = new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" var foo = bar; Html.ExecuteTemplate(foo, ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - testTemplateWithDoubleTransition, - Factory.Code("); ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)); - - // Act & Assert - ParseBlockTest("{ var foo = bar; Html.ExecuteTemplate(foo," + testTemplateWithDoubleTransitionCode + "); }", expected); - } - - private static RazorError GetNestedTemplateError(int characterIndex) - { - return new RazorError( - RazorResources.ParseError_InlineMarkup_Blocks_Cannot_Be_Nested, - new SourceLocation(characterIndex, 0, characterIndex), - length: 1); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpToMarkupSwitchTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpToMarkupSwitchTest.cs deleted file mode 100644 index a1f68fe0ab..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpToMarkupSwitchTest.cs +++ /dev/null @@ -1,697 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpToMarkupSwitchTest : CsHtmlCodeParserTestBase - { - [Fact] - public void SingleAngleBracketDoesNotCauseSwitchIfOuterBlockIsTerminated() - { - ParseBlockTest("{ List< }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" List< ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockGivesSpacesToCodeOnAtTagTemplateTransitionInDesignTimeMode() - { - ParseBlockTest("Foo( @

Foo

)", - new ExpressionBlock( - Factory.Code("Foo( ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.Any), - new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ) - ), - Factory.Code(" )") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), designTimeParser: true); - } - - [Fact] - public void ParseBlockGivesSpacesToCodeOnAtColonTemplateTransitionInDesignTimeMode() - { - ParseBlockTest("Foo( " + Environment.NewLine - + "@:

Foo

" + Environment.NewLine - + ")", - new ExpressionBlock( - Factory.Code("Foo( " + Environment.NewLine).AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("

Foo

" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ) - ), - Factory.Code(")") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - ), designTimeParser: true); - } - - [Fact] - public void ParseBlockGivesSpacesToCodeOnTagTransitionInDesignTimeMode() - { - ParseBlockTest("{" + Environment.NewLine - + "

Foo

" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ), - Factory.Code(" " + Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), designTimeParser: true); - } - - [Fact] - public void ParseBlockGivesSpacesToCodeOnInvalidAtTagTransitionInDesignTimeMode() - { - ParseBlockTest("{" + Environment.NewLine - + " @

Foo

" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.MarkupTransition(), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)) - ), - Factory.Code(" " + Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), true, - new RazorError( - RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start, - new SourceLocation(5 + Environment.NewLine.Length, 1, 4), - length: 1)); - } - - [Fact] - public void ParseBlockGivesSpacesToCodeOnAtColonTransitionInDesignTimeMode() - { - ParseBlockTest("{" + Environment.NewLine - + " @:

Foo

" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("

Foo

" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.EmptyCSharp().AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), designTimeParser: true); - } - - [Fact] - public void ParseBlockShouldSupportSingleLineMarkupContainingStatementBlock() - { - ParseBlockTest("Repeat(10," + Environment.NewLine - + " @: @{}" + Environment.NewLine - + ")", - new ExpressionBlock( - Factory.Code($"Repeat(10,{Environment.NewLine} ") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords), - new TemplateBlock( - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup(" ") - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)), - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - ), - Factory.Markup(Environment.NewLine) - .Accepts(AcceptedCharacters.None) - ) - ), - Factory.Code(")") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace) - )); - } - - [Fact] - public void ParseBlockShouldSupportMarkupWithoutPreceedingWhitespace() - { - ParseBlockTest("foreach(var file in files){" + Environment.NewLine - + Environment.NewLine - + Environment.NewLine - + "@:Baz" + Environment.NewLine - + "
" + Environment.NewLine - + "Foo" + Environment.NewLine - + "@:Bar" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code(string.Format("foreach(var file in files){{{0}{0}{0}", Environment.NewLine)).AsStatement(), - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("Baz" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("
").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("Bar" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockGivesAllWhitespaceOnSameLineExcludingPreceedingNewlineButIncludingTrailingNewLineToMarkup() - { - ParseBlockTest("if(foo) {" + Environment.NewLine - + " var foo = \"After this statement there are 10 spaces\"; " + Environment.NewLine - + "

" + Environment.NewLine - + " Foo" + Environment.NewLine - + " @bar" + Environment.NewLine - + "

" + Environment.NewLine - + " @:Hello!" + Environment.NewLine - + " var biz = boz;" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code( - $"if(foo) {{{Environment.NewLine} var foo = \"After this statement there are " + - "10 spaces\"; " + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup($"{Environment.NewLine} Foo{Environment.NewLine}"), - new ExpressionBlock( - Factory.Code(" ").AsStatement(), - Factory.CodeTransition(), - Factory.Code("bar").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace) - ), - Factory.Markup(Environment.NewLine + " "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("Hello!" + Environment.NewLine).With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code($" var biz = boz;{Environment.NewLine}}}").AsStatement())); - } - - [Fact] - public void ParseBlockAllowsMarkupInIfBodyWithBraces() - { - ParseBlockTest("if(foo) {

Bar

} else if(bar) {

Baz

} else {

Boz

}", - new StatementBlock( - Factory.Code("if(foo) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Bar"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("} else if(bar) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Baz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("} else {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Boz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockAllowsMarkupInIfBodyWithBracesWithinCodeBlock() - { - ParseBlockTest("{ if(foo) {

Bar

} else if(bar) {

Baz

} else {

Boz

} }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" if(foo) {") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Bar"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("} else if(bar) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Baz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("} else {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Boz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("} ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockSupportsMarkupInCaseAndDefaultBranchesOfSwitch() - { - // Arrange - ParseBlockTest("switch(foo) {" + Environment.NewLine - + " case 0:" + Environment.NewLine - + "

Foo

" + Environment.NewLine - + " break;" + Environment.NewLine - + " case 1:" + Environment.NewLine - + "

Bar

" + Environment.NewLine - + " return;" + Environment.NewLine - + " case 2:" + Environment.NewLine - + " {" + Environment.NewLine - + "

Baz

" + Environment.NewLine - + "

Boz

" + Environment.NewLine - + " }" + Environment.NewLine - + " default:" + Environment.NewLine - + "

Biz

" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code($"switch(foo) {{{Environment.NewLine} case 0:{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code($" break;{Environment.NewLine} case 1:{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Bar"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code( - $" return;{Environment.NewLine} case 2:{Environment.NewLine}" + - " {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Baz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Boz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code($" }}{Environment.NewLine} default:{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Biz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockSupportsMarkupInCaseAndDefaultBranchesOfSwitchInCodeBlock() - { - // Arrange - ParseBlockTest("{ switch(foo) {" + Environment.NewLine - + " case 0:" + Environment.NewLine - + "

Foo

" + Environment.NewLine - + " break;" + Environment.NewLine - + " case 1:" + Environment.NewLine - + "

Bar

" + Environment.NewLine - + " return;" + Environment.NewLine - + " case 2:" + Environment.NewLine - + " {" + Environment.NewLine - + "

Baz

" + Environment.NewLine - + "

Boz

" + Environment.NewLine - + " }" + Environment.NewLine - + " default:" + Environment.NewLine - + "

Biz

" + Environment.NewLine - + "} }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code($" switch(foo) {{{Environment.NewLine} case 0:{Environment.NewLine}") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code($" break;{Environment.NewLine} case 1:{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Bar"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code( - $" return;{Environment.NewLine} case 2:{Environment.NewLine}" + - " {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Baz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Boz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code($" }}{Environment.NewLine} default:{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Biz"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code("} ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockParsesMarkupStatementOnOpenAngleBracket() - { - ParseBlockTest("for(int i = 0; i < 10; i++) {

Foo

}", - new StatementBlock( - Factory.Code("for(int i = 0; i < 10; i++) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("}").AsStatement().Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void ParseBlockParsesMarkupStatementOnOpenAngleBracketInCodeBlock() - { - ParseBlockTest("{ for(int i = 0; i < 10; i++) {

Foo

} }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" for(int i = 0; i < 10; i++) {") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(" ").Accepts(AcceptedCharacters.None) - ), - Factory.Code("} ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByColon() - { - // Arrange - ParseBlockTest("if(foo) { @:Bar" + Environment.NewLine - + "} zoop", - new StatementBlock( - Factory.Code("if(foo) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("Bar" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code("}").AsStatement())); - } - - [Fact] - public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByDoubleColon() - { - // Arrange - ParseBlockTest("if(foo) { @::Sometext" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code("if(foo) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup(":Sometext" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code("}").AsStatement())); - } - - - [Fact] - public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByTripleColon() - { - // Arrange - ParseBlockTest("if(foo) { @:::Sometext" + Environment.NewLine - + "}", - new StatementBlock( - Factory.Code("if(foo) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("::Sometext" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code("}").AsStatement())); - } - - [Fact] - public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByColonInCodeBlock() - { - // Arrange - ParseBlockTest("{ if(foo) { @:Bar" + Environment.NewLine - + "} } zoop", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" if(foo) {") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("Bar" + Environment.NewLine).Accepts(AcceptedCharacters.None) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code("} ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockCorrectlyReturnsFromMarkupBlockWithPseudoTag() - { - ParseBlockTest("if (i > 0) { ; }", - new StatementBlock( - Factory.Code("if (i > 0) {").AsStatement(), - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("").Accepts(AcceptedCharacters.None)), - Factory.Markup(";").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.MarkupTransition("").Accepts(AcceptedCharacters.None))), - Factory.Code(" }").AsStatement())); - } - - [Fact] - public void ParseBlockCorrectlyReturnsFromMarkupBlockWithPseudoTagInCodeBlock() - { - ParseBlockTest("{ if (i > 0) { ; } }", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(" if (i > 0) {") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("").Accepts(AcceptedCharacters.None)), - Factory.Markup(";").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.MarkupTransition("").Accepts(AcceptedCharacters.None))), - Factory.Code(" } ").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockSupportsAllKindsOfImplicitMarkupInCodeBlock() - { - ParseBlockTest("{" + Environment.NewLine - + " if(true) {" + Environment.NewLine - + " @:Single Line Markup" + Environment.NewLine - + " }" + Environment.NewLine - + " foreach (var p in Enumerable.Range(1, 10)) {" + Environment.NewLine - + " The number is @p" + Environment.NewLine - + " }" + Environment.NewLine - + " if(!false) {" + Environment.NewLine - + "

A real tag!

" + Environment.NewLine - + " }" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code($"{Environment.NewLine} if(true) {{{Environment.NewLine}") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new MarkupBlock( - Factory.Markup(" "), - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("Single Line Markup" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - ), - Factory.Code($" }}{Environment.NewLine} foreach (var p in Enumerable.Range(1, 10)) {{{Environment.NewLine}").AsStatement(), - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("").Accepts(AcceptedCharacters.None)), - Factory.Markup("The number is ").Accepts(AcceptedCharacters.None), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("p").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace) - ), - new MarkupTagBlock( - Factory.MarkupTransition("").Accepts(AcceptedCharacters.None))), - Factory.Code($"{Environment.NewLine} }}{Environment.NewLine} if(!false) {{{Environment.NewLine}").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("A real tag!"), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None) - ), - Factory.Code(" }" + Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpVerbatimBlockTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpVerbatimBlockTest.cs deleted file mode 100644 index 6e75ce3c4b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpVerbatimBlockTest.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpVerbatimBlockTest : CsHtmlCodeParserTestBase - { - private const string TestExtraKeyword = "model"; - - [Fact] - public void VerbatimBlock() - { - ParseBlockTest("@{ foo(); }", - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{") - .Accepts(AcceptedCharacters.None), - Factory.Code(" foo(); ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - Factory.MetaCode("}") - .Accepts(AcceptedCharacters.None) - )); - } - - [Fact] - public void InnerImplicitExpressionWithOnlySingleAtOutputsZeroLengthCodeSpan() - { - ParseBlockTest("{@}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp().AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace) - ), - Factory.EmptyCSharp().AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - designTimeParser: true, - expectedErrors: new[] - { - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS("}"), - new SourceLocation(2, 0, 2), - length: 1) - }); - } - - [Fact] - public void InnerImplicitExpressionDoesNotAcceptDotAfterAt() - { - ParseBlockTest("{@.}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp().AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace) - ), - Factory.Code(".").AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - designTimeParser: true, - expectedErrors: new[] - { - new RazorError( - RazorResources.FormatParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS("."), - new SourceLocation(2, 0, 2), - length: 1) - }); - } - - [Fact] - public void InnerImplicitExpressionWithOnlySingleAtAcceptsSingleSpaceOrNewlineAtDesignTime() - { - ParseBlockTest("{" + Environment.NewLine - + " @" + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp().AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace) - ), - Factory.Code(Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - /* designTimeParser */ true, - new RazorError( - RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, - new SourceLocation(6 + Environment.NewLine.Length, 1, 5), - Environment.NewLine.Length)); - } - - [Fact] - public void InnerImplicitExpressionDoesNotAcceptTrailingNewlineInRunTimeMode() - { - ParseBlockTest("{@foo." + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo.").AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Code(Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void InnerImplicitExpressionAcceptsTrailingNewlineInDesignTimeMode() - { - ParseBlockTest("{@foo." + Environment.NewLine - + "}", - new StatementBlock( - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo.").AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Code(Environment.NewLine).AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - designTimeParser: true); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpWhitespaceHandlingTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpWhitespaceHandlingTest.cs deleted file mode 100644 index f1ab422059..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/CSharpWhitespaceHandlingTest.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class CSharpWhitespaceHandlingTest : CsHtmlMarkupParserTestBase - { - [Fact] - public void StatementBlockDoesNotAcceptTrailingNewlineIfNewlinesAreSignificantToAncestor() - { - ParseBlockTest("@: @if (true) { }" + Environment.NewLine - + "}", - new MarkupBlock( - Factory.MarkupTransition() - .Accepts(AcceptedCharacters.None), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup(" ") - .With(new SingleLineMarkupEditHandler( - CSharpLanguageCharacteristics.Instance.TokenizeString, - AcceptedCharacters.Any)), - new StatementBlock( - Factory.CodeTransition() - .Accepts(AcceptedCharacters.None), - Factory.Code("if (true) { }") - .AsStatement() - ), - Factory.Markup(Environment.NewLine) - .Accepts(AcceptedCharacters.None))); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/DisposableActionTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/DisposableActionTest.cs deleted file mode 100644 index b0693f9f1c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/DisposableActionTest.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class DisposableActionTest - { - [Fact] - public void ActionIsExecutedOnDispose() - { - // Arrange - var called = false; - var action = new DisposableAction(() => { called = true; }); - - // Act - action.Dispose(); - - // Assert - Assert.True(called, "The action was not run when the DisposableAction was disposed"); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/HtmlToCodeSwitchTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/HtmlToCodeSwitchTest.cs deleted file mode 100644 index 72ab8560bc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/HtmlToCodeSwitchTest.cs +++ /dev/null @@ -1,441 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Test.Parser.Internal; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class HtmlToCodeSwitchTest : CsHtmlMarkupParserTestBase - { - [Fact] - public void ParseBlockSwitchesWhenCharacterBeforeSwapIsNonAlphanumeric() - { - ParseBlockTest("

foo#@i

", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)), - Factory.Markup("foo#"), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("i").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("

").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSwitchesToCodeWhenSwapCharacterEncounteredMidTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSwitchesToCodeWhenSwapCharacterEncounteredInAttributeValue() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" bar=\"", 4, 0, 4), new LocationTagged("\"", 14, 0, 14)), - Factory.Markup(" bar=\"").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 10, 0, 10), 10, 0, 10), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("baz") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSwitchesToCodeWhenSwapCharacterEncounteredInTagContent() - { - ParseBlockTest("@bar@boz", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("bar") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("boz") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockParsesCodeWithinSingleLineMarkup() - { - // TODO: Fix at a later date, HTML should be a tag block: https://github.com/aspnet/Razor/issues/101 - ParseBlockTest("@:
  • Foo @Bar Baz" + Environment.NewLine - + "bork", - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("
  • Foo ").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("Bar") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Markup(" Baz" + Environment.NewLine) - .Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ParseBlockSupportsCodeWithinComment() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSupportsCodeWithinSGMLDeclaration() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSupportsCodeWithinCDataDeclaration() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSupportsCodeWithinXMLProcessingInstruction() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockDoesNotSwitchToCodeOnEmailAddressInText() - { - ParseBlockTest("anurse@microsoft.com", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("anurse@microsoft.com"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockDoesNotSwitchToCodeOnEmailAddressInAttribute() - { - ParseBlockTest("Email me", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href=\"", 2, 0, 2), new LocationTagged("\"", 36, 0, 36)), - Factory.Markup(" href=\"").With(SpanChunkGenerator.Null), - Factory.Markup("mailto:anurse@microsoft.com") - .With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 9, 0, 9), new LocationTagged("mailto:anurse@microsoft.com", 9, 0, 9))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(">").Accepts(AcceptedCharacters.None)), - Factory.Markup("Email me"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockGivesWhitespacePreceedingAtToCodeIfThereIsNoMarkupOnThatLine() - { - ParseBlockTest("
      " + Environment.NewLine - + " @foreach(var p in Products) {" + Environment.NewLine - + "
    • Product: @p.Name
    • " + Environment.NewLine - + " }" + Environment.NewLine - + "
    ", - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
      ").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine), - new StatementBlock( - Factory.Code(" ").AsStatement(), - Factory.CodeTransition(), - Factory.Code("foreach(var p in Products) {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup("Product: "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("p.Name") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code(" }" + Environment.NewLine).AsStatement().Accepts(AcceptedCharacters.None)), - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
    ").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseDocumentGivesWhitespacePreceedingAtToCodeIfThereIsNoMarkupOnThatLine() - { - ParseDocumentTest("
      " + Environment.NewLine - + " @foreach(var p in Products) {" + Environment.NewLine - + "
    • Product: @p.Name
    • " + Environment.NewLine - + " }" + Environment.NewLine - + "
    ", - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
      ")), - Factory.Markup(Environment.NewLine), - new StatementBlock( - Factory.Code(" ").AsStatement(), - Factory.CodeTransition(), - Factory.Code("foreach(var p in Products) {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup("Product: "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("p.Name") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code(" }" + Environment.NewLine).AsStatement().Accepts(AcceptedCharacters.None)), - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
    ")))); - } - - [Fact] - public void SectionContextGivesWhitespacePreceedingAtToCodeIfThereIsNoMarkupOnThatLine() - { - ParseDocumentTest("@section foo {" + Environment.NewLine - + "
      " + Environment.NewLine - + " @foreach(var p in Products) {" + Environment.NewLine - + "
    • Product: @p.Name
    • " + Environment.NewLine - + " }" + Environment.NewLine - + "
    " + Environment.NewLine - + "}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("foo"), - Factory.CodeTransition(), - Factory.MetaCode("section foo {").AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(Environment.NewLine + " "), - new MarkupTagBlock( - Factory.Markup("
      ")), - Factory.Markup(Environment.NewLine), - new StatementBlock( - Factory.Code(" ").AsStatement(), - Factory.CodeTransition(), - Factory.Code("foreach(var p in Products) {" + Environment.NewLine).AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup("Product: "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("p.Name") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine).Accepts(AcceptedCharacters.None)), - Factory.Code(" }" + Environment.NewLine).AsStatement().Accepts(AcceptedCharacters.None)), - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
    ")), - Factory.Markup(Environment.NewLine)), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void CSharpCodeParserDoesNotAcceptLeadingOrTrailingWhitespaceInDesignMode() - { - ParseBlockTest("
      " + Environment.NewLine - + " @foreach(var p in Products) {" + Environment.NewLine - + "
    • Product: @p.Name
    • " + Environment.NewLine - + " }" + Environment.NewLine - + "
    ", - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("
      ").Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine + " "), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code($"foreach(var p in Products) {{{Environment.NewLine} ").AsStatement(), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None)), - Factory.Markup("Product: "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("p.Name").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("
    • ").Accepts(AcceptedCharacters.None))), - Factory.Code(Environment.NewLine + " }").AsStatement().Accepts(AcceptedCharacters.None)), - Factory.Markup(Environment.NewLine + " "), - new MarkupTagBlock( - Factory.Markup("
    ").Accepts(AcceptedCharacters.None))), - designTimeParser: true); - } - - // Tests for "@@" escape sequence: - [Fact] - public void ParseBlockTreatsTwoAtSignsAsEscapeSequence() - { - HtmlParserTestUtils.RunSingleAtEscapeTest(ParseBlockTest); - } - - [Fact] - public void ParseBlockTreatsPairsOfAtSignsAsEscapeSequence() - { - HtmlParserTestUtils.RunMultiAtEscapeTest(ParseBlockTest); - } - - [Fact] - public void ParseDocumentTreatsTwoAtSignsAsEscapeSequence() - { - HtmlParserTestUtils.RunSingleAtEscapeTest(ParseDocumentTest, lastSpanAcceptedCharacters: AcceptedCharacters.Any); - } - - [Fact] - public void ParseDocumentTreatsPairsOfAtSignsAsEscapeSequence() - { - HtmlParserTestUtils.RunMultiAtEscapeTest(ParseDocumentTest, lastSpanAcceptedCharacters: AcceptedCharacters.Any); - } - - [Fact] - public void SectionBodyTreatsTwoAtSignsAsEscapeSequence() - { - ParseDocumentTest("@section Foo { @@bar }", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Foo"), - Factory.CodeTransition(), - Factory.MetaCode("section Foo {").AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("")), - Factory.Markup("@").Hidden(), - Factory.Markup("@bar"), - new MarkupTagBlock( - Factory.Markup("")), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void SectionBodyTreatsPairsOfAtSignsAsEscapeSequence() - { - ParseDocumentTest("@section Foo { @@@@@bar }", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Foo"), - Factory.CodeTransition(), - Factory.MetaCode("section Foo {").AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(" "), - new MarkupTagBlock( - Factory.Markup("")), - Factory.Markup("@").Hidden(), - Factory.Markup("@"), - Factory.Markup("@").Hidden(), - Factory.Markup("@"), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("bar") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - new MarkupTagBlock( - Factory.Markup("")), - Factory.Markup(" ")), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/CallbackVisitorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/CallbackVisitorTest.cs deleted file mode 100644 index 55c6ccc37c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/CallbackVisitorTest.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class CallbackVisitorTest - { - [Fact] - public void ListenerConstructedWithSpanCallbackCallsCallbackOnEndSpan() - { - RunOnEndSpanTest(callback => new CallbackVisitor(callback)); - } - - [Fact] - public void ListenerConstructedWithSpanCallbackDoesNotThrowOnStartBlockEndBlockOrError() - { - // Arrange - Action spanCallback = _ => { }; - var listener = new CallbackVisitor(spanCallback); - - // Act/Assert - listener.VisitStartBlock(new FunctionsBlock()); - listener.VisitError(new RazorError("Error", SourceLocation.Zero, length: 1)); - listener.VisitEndBlock(new FunctionsBlock()); - } - - [Fact] - public void ListenerConstructedWithSpanAndErrorCallbackCallsCallbackOnEndSpan() - { - RunOnEndSpanTest(spanCallback => new CallbackVisitor(spanCallback, _ => { })); - } - - [Fact] - public void ListenerConstructedWithSpanAndErrorCallbackCallsCallbackOnError() - { - RunOnErrorTest(errorCallback => new CallbackVisitor(_ => { }, errorCallback)); - } - - [Fact] - public void ListenerConstructedWithAllCallbacksCallsCallbackOnEndSpan() - { - RunOnEndSpanTest(spanCallback => new CallbackVisitor(spanCallback, _ => { }, _ => { }, _ => { })); - } - - [Fact] - public void ListenerConstructedWithAllCallbacksCallsCallbackOnError() - { - RunOnErrorTest(errorCallback => new CallbackVisitor(_ => { }, errorCallback, _ => { }, _ => { })); - } - - [Fact] - public void ListenerConstructedWithAllCallbacksCallsCallbackOnStartBlock() - { - RunOnStartBlockTest(startBlockCallback => new CallbackVisitor(_ => { }, _ => { }, startBlockCallback, _ => { })); - } - - [Fact] - public void ListenerConstructedWithAllCallbacksCallsCallbackOnEndBlock() - { - RunOnEndBlockTest(endBlockCallback => new CallbackVisitor(_ => { }, _ => { }, _ => { }, endBlockCallback)); - } - - [Fact] - public void ListenerCallsOnEndSpanCallbackUsingSynchronizationContextIfSpecified() - { - RunSyncContextTest(new SpanBuilder().Build(), - spanCallback => new CallbackVisitor(spanCallback, _ => { }, _ => { }, _ => { }), - (listener, expected) => listener.VisitSpan(expected)); - } - - [Fact] - public void ListenerCallsOnStartBlockCallbackUsingSynchronizationContextIfSpecified() - { - RunSyncContextTest(BlockType.Template, - startBlockCallback => new CallbackVisitor(_ => { }, _ => { }, startBlockCallback, _ => { }), - (listener, expected) => listener.VisitStartBlock(new BlockBuilder() { Type = expected }.Build())); - } - - [Fact] - public void ListenerCallsOnEndBlockCallbackUsingSynchronizationContextIfSpecified() - { - RunSyncContextTest(BlockType.Template, - endBlockCallback => new CallbackVisitor(_ => { }, _ => { }, _ => { }, endBlockCallback), - (listener, expected) => listener.VisitEndBlock(new BlockBuilder() { Type = expected }.Build())); - } - - [Fact] - public void ListenerCallsOnErrorCallbackUsingSynchronizationContextIfSpecified() - { - RunSyncContextTest( - new RazorError("Bar", new SourceLocation(42, 42, 42), length: 3), - errorCallback => new CallbackVisitor(_ => { }, errorCallback, _ => { }, _ => { }), - (listener, expected) => listener.VisitError(expected)); - } - - private static void RunSyncContextTest(T expected, Func, CallbackVisitor> ctor, Action call) - { - // Arrange - var mockContext = new Mock(); - mockContext.Setup(c => c.Post(It.IsAny(), It.IsAny())) - .Callback((callback, state) => { callback(expected); }); - - // Act/Assert - RunCallbackTest(default(T), callback => - { - var listener = ctor(callback); - listener.SynchronizationContext = mockContext.Object; - return listener; - }, call, (original, actual) => - { - Assert.NotEqual(original, actual); - Assert.Equal(expected, actual); - }); - } - - private static void RunOnStartBlockTest(Func, CallbackVisitor> ctor, Action verifyResults = null) - { - RunCallbackTest(BlockType.Markup, ctor, (listener, expected) => listener.VisitStartBlock(new BlockBuilder() { Type = expected }.Build()), verifyResults); - } - - private static void RunOnEndBlockTest(Func, CallbackVisitor> ctor, Action verifyResults = null) - { - RunCallbackTest(BlockType.Markup, ctor, (listener, expected) => listener.VisitEndBlock(new BlockBuilder() { Type = expected }.Build()), verifyResults); - } - - private static void RunOnErrorTest(Func, CallbackVisitor> ctor, Action verifyResults = null) - { - RunCallbackTest( - new RazorError("Foo", SourceLocation.Zero, length: 3), - ctor, - (listener, expected) => listener.VisitError(expected), verifyResults); - } - - private static void RunOnEndSpanTest(Func, CallbackVisitor> ctor, Action verifyResults = null) - { - RunCallbackTest(new SpanBuilder().Build(), ctor, (listener, expected) => listener.VisitSpan(expected), verifyResults); - } - - private static void RunCallbackTest(T expected, Func, CallbackVisitor> ctor, Action call, Action verifyResults = null) - { - // Arrange - object actual = null; - Action callback = t => actual = t; - - var listener = ctor(callback); - - // Act - call(listener, expected); - - // Assert - if (verifyResults == null) - { - Assert.Equal(expected, actual); - } - else - { - verifyResults(expected, (T)actual); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlAttributeTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlAttributeTest.cs deleted file mode 100644 index dce5d1be23..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlAttributeTest.cs +++ /dev/null @@ -1,649 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class HtmlAttributeTest : CsHtmlMarkupParserTestBase - { - public static TheoryData SymbolBoundAttributeNames - { - get - { - return new TheoryData - { - "[item]", - "[(item,", - "(click)", - "(^click)", - "*something", - "#local", - }; - } - } - - [Theory] - [MemberData(nameof(SymbolBoundAttributeNames))] - public void SymbolBoundAttributes_BeforeEqualWhitespace(string attributeName) - { - // Arrange - var attributeNameLength = attributeName.Length; - var newlineLength = Environment.NewLine.Length; - var prefixLocation1 = new SourceLocation( - absoluteIndex: 2, - lineIndex: 0, - characterIndex: 2); - var suffixLocation1 = new SourceLocation( - absoluteIndex: 8 + newlineLength + attributeNameLength, - lineIndex: 1, - characterIndex: 5 + attributeNameLength); - var valueLocation1 = new SourceLocation( - absoluteIndex: 5 + attributeNameLength + newlineLength, - lineIndex: 1, - characterIndex: 2 + attributeNameLength); - var prefixLocation2 = SourceLocation.Advance(suffixLocation1, "'"); - var suffixLocation2 = new SourceLocation( - absoluteIndex: 15 + attributeNameLength * 2 + newlineLength * 2, - lineIndex: 2, - characterIndex: 4); - var valueLocation2 = new SourceLocation( - absoluteIndex: 12 + attributeNameLength * 2 + newlineLength * 2, - lineIndex: 2, - characterIndex: 1); - - // Act & Assert - ParseBlockTest( - $"", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("( - $" {attributeName}{Environment.NewLine}='", prefixLocation1), - suffix: new LocationTagged("'", suffixLocation1)), - Factory.Markup($" {attributeName}{Environment.NewLine}='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, valueLocation1), - value: new LocationTagged("Foo", valueLocation1))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - attributeName, - prefix: new LocationTagged( - $"\t{attributeName}={Environment.NewLine}'", prefixLocation2), - suffix: new LocationTagged("'", suffixLocation2)), - Factory.Markup($"\t{attributeName}={Environment.NewLine}'").With(SpanChunkGenerator.Null), - Factory.Markup("Bar").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, valueLocation2), - value: new LocationTagged("Bar", valueLocation2))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Theory] - [MemberData(nameof(SymbolBoundAttributeNames))] - public void SymbolBoundAttributes_Whitespace(string attributeName) - { - // Arrange - var attributeNameLength = attributeName.Length; - var newlineLength = Environment.NewLine.Length; - var prefixLocation1 = new SourceLocation( - absoluteIndex: 2, - lineIndex: 0, - characterIndex: 2); - var suffixLocation1 = new SourceLocation( - absoluteIndex: 10 + newlineLength + attributeNameLength, - lineIndex: 1, - characterIndex: 5 + attributeNameLength + newlineLength); - var valueLocation1 = new SourceLocation( - absoluteIndex: 7 + attributeNameLength + newlineLength, - lineIndex: 1, - characterIndex: 4 + attributeNameLength); - var prefixLocation2 = SourceLocation.Advance(suffixLocation1, "'"); - var suffixLocation2 = new SourceLocation( - absoluteIndex: 17 + attributeNameLength * 2 + newlineLength * 2, - lineIndex: 2, - characterIndex: 5 + attributeNameLength); - var valueLocation2 = new SourceLocation( - absoluteIndex: 14 + attributeNameLength * 2 + newlineLength * 2, - lineIndex: 2, - characterIndex: 2 + attributeNameLength); - - // Act & Assert - ParseBlockTest( - $"", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("( - $" {Environment.NewLine} {attributeName}='", prefixLocation1), - suffix: new LocationTagged("'", suffixLocation1)), - Factory.Markup($" {Environment.NewLine} {attributeName}='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, valueLocation1), - value: new LocationTagged("Foo", valueLocation1))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - attributeName, - prefix: new LocationTagged( - $"\t{Environment.NewLine}{attributeName}='", prefixLocation2), - suffix: new LocationTagged("'", suffixLocation2)), - Factory.Markup($"\t{Environment.NewLine}{attributeName}='").With(SpanChunkGenerator.Null), - Factory.Markup("Bar").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, valueLocation2), - value: new LocationTagged("Bar", valueLocation2))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Theory] - [MemberData(nameof(SymbolBoundAttributeNames))] - public void SymbolBoundAttributes(string attributeName) - { - // Arrange - var attributeNameLength = attributeName.Length; - var suffixLocation = 8 + attributeNameLength; - var valueLocation = 5 + attributeNameLength; - - // Act & Assert - ParseBlockTest($"", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("($" {attributeName}='", 2, 0, 2), - suffix: new LocationTagged("'", suffixLocation, 0, suffixLocation)), - Factory.Markup($" {attributeName}='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, valueLocation, 0, valueLocation), - value: new LocationTagged("Foo", valueLocation, 0, valueLocation))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void SimpleLiteralAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href='", 2, 0, 2), suffix: new LocationTagged("'", 12, 0, 12)), - Factory.Markup(" href='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 9, 0, 9), value: new LocationTagged("Foo", 9, 0, 9))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void SimpleLiteralAttributeWithWhitespaceSurroundingEquals() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href \f\r\n= \t\n'", 2, 0, 2), - suffix: new LocationTagged("'", 19, 2, 4)), - Factory.Markup(" href \f\r\n= \t\n'").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 2, 1), value: new LocationTagged("Foo", 16, 2, 1))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void DynamicAttributeWithWhitespaceSurroundingEquals() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href \n= \r\n'", 2, 0, 2), - suffix: new LocationTagged("'", 18, 2, 5)), - Factory.Markup(" href \n= \r\n'").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 14, 2, 1), 14, 2, 1), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("Foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void MultiPartLiteralAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href='", 2, 0, 2), suffix: new LocationTagged("'", 20, 0, 20)), - Factory.Markup(" href='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(string.Empty, 9, 0, 9), value: new LocationTagged("Foo", 9, 0, 9))), - Factory.Markup(" Bar").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(" ", 12, 0, 12), value: new LocationTagged("Bar", 13, 0, 13))), - Factory.Markup(" Baz").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(" ", 16, 0, 16), value: new LocationTagged("Baz", 17, 0, 17))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void DoubleQuotedLiteralAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href=\"", 2, 0, 2), suffix: new LocationTagged("\"", 20, 0, 20)), - Factory.Markup(" href=\"").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(string.Empty, 9, 0, 9), value: new LocationTagged("Foo", 9, 0, 9))), - Factory.Markup(" Bar").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(" ", 12, 0, 12), value: new LocationTagged("Bar", 13, 0, 13))), - Factory.Markup(" Baz").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(" ", 16, 0, 16), value: new LocationTagged("Baz", 17, 0, 17))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void NewLinePrecedingAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("("\r\nhref='", 2, 0, 2), - suffix: new LocationTagged("'", 13, 1, 9)), - Factory.Markup("\r\nhref='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 10, 1, 6), - value: new LocationTagged("Foo", 10, 1, 6))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void NewLineBetweenAttributes() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("("\nhref='", 2, 0, 2), - suffix: new LocationTagged("'", 12, 1, 9)), - Factory.Markup("\nhref='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 9, 1, 6), - value: new LocationTagged("Foo", 9, 1, 6))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "abcd", - prefix: new LocationTagged("\r\nabcd='", 13, 1, 10), - suffix: new LocationTagged("'", 24, 2, 9)), - Factory.Markup("\r\nabcd='").With(SpanChunkGenerator.Null), - Factory.Markup("Bar").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 21, 2, 6), - value: new LocationTagged("Bar", 21, 2, 6))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void WhitespaceAndNewLinePrecedingAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" \t\r\nhref='", 2, 0, 2), - suffix: new LocationTagged("'", 15, 1, 9)), - Factory.Markup(" \t\r\nhref='").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 12, 1, 6), - value: new LocationTagged("Foo", 12, 1, 6))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void UnquotedLiteralAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href=", 2, 0, 2), suffix: new LocationTagged(string.Empty, 11, 0, 11)), - Factory.Markup(" href=").With(SpanChunkGenerator.Null), - Factory.Markup("Foo").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(string.Empty, 8, 0, 8), value: new LocationTagged("Foo", 8, 0, 8)))), - new MarkupBlock(Factory.Markup(" Bar")), - new MarkupBlock(Factory.Markup(" Baz")), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void SimpleExpressionAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href='", 2, 0, 2), suffix: new LocationTagged("'", 13, 0, 13)), - Factory.Markup(" href='").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 9, 0, 9), 9, 0, 9), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void MultiValueExpressionAttribute() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href='", 2, 0, 2), suffix: new LocationTagged("'", 22, 0, 22)), - Factory.Markup(" href='").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 9, 0, 9), 9, 0, 9), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup(" bar").With(new LiteralAttributeChunkGenerator(new LocationTagged(" ", 13, 0, 13), new LocationTagged("bar", 14, 0, 14))), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(" ", 17, 0, 17), 18, 0, 18), - Factory.Markup(" ").With(SpanChunkGenerator.Null), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("baz") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void VirtualPathAttributesWorkWithConditionalAttributes() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href='", 2, 0, 2), suffix: new LocationTagged("'", 23, 0, 23)), - Factory.Markup(" href='").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 9, 0, 9), 9, 0, 9), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - Factory.Markup(" ~/Foo/Bar") - .With(new LiteralAttributeChunkGenerator( - new LocationTagged(" ", 13, 0, 13), - new LocationTagged("~/Foo/Bar", 14, 0, 14))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void UnquotedAttributeWithCodeWithSpacesInBlock() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" value=", 6, 0, 6), suffix: new LocationTagged(string.Empty, 17, 0, 17)), - Factory.Markup(" value=").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 13, 0, 13), 13, 0, 13), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void UnquotedAttributeWithCodeWithSpacesInDocument() - { - ParseDocumentTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" value=", 6, 0, 6), suffix: new LocationTagged(string.Empty, 17, 0, 17)), - Factory.Markup(" value=").With(SpanChunkGenerator.Null), - new MarkupBlock(new DynamicAttributeBlockChunkGenerator(new LocationTagged(string.Empty, 13, 0, 13), 13, 0, 13), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))), - Factory.Markup(" />")))); - } - - [Fact] - public void ConditionalAttributeCollapserDoesNotRewriteEscapedTransitions() - { - // Act - var results = ParseDocument(""); - var rewritingContext = new RewritingContext(results.Document, new ErrorSink()); - new ConditionalAttributeCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritingContext); - var rewritten = rewritingContext.SyntaxTree; - - // Assert - Assert.Equal(0, results.ParserErrors.Count()); - EvaluateParseTree(rewritten, - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" foo='", 5, 0, 5), new LocationTagged("'", 13, 0, 13)), - Factory.Markup(" foo='").With(SpanChunkGenerator.Null), - new MarkupBlock( - Factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 11, 0, 11), new LocationTagged("@", 11, 0, 11))).Accepts(AcceptedCharacters.None), - Factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />")))); - } - - [Fact] - public void ConditionalAttributesDoNotCreateExtraDataForEntirelyLiteralAttribute() - { - // Arrange - const string code = - @"
    -

    Title

    -

    - As the author, you can edit - or remove this photo. -

    -
    -
    Description
    -
    - The uploader did not provide a description for this photo. -
    -
    Uploaded by
    -
    user.DisplayName
    -
    Upload date
    -
    photo.UploadDate
    -
    Gallery
    -
    gallery.Name
    -
    Tags
    -
    -
      -
    • This photo has no tags.
    • -
    - edit tags -
    -
    - -

    - Download full photo ((photo.FileSize / 1024) KB) -

    -
    -
    - -

    Nobody has commented on this photo

    -
      -
    1. -

      - comment.DisplayName commented at comment.CommentDate: -

      -

      comment.CommentText

      -
    2. -
    - -
    -
    - Post new comment -
      -
    1. - - -
    2. -
    -

    - -

    -
    -
    -
    "; - - // Act - var results = ParseDocument(code); - var rewritingContext = new RewritingContext(results.Document, new ErrorSink()); - new ConditionalAttributeCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritingContext); - new MarkupCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritingContext); - var rewritten = rewritingContext.SyntaxTree; - - // Assert - Assert.Equal(0, results.ParserErrors.Count()); - Assert.Equal(rewritten.Children.Count(), results.Document.Children.Count()); - } - - [Fact] - public void ConditionalAttributesAreDisabledForDataAttributesInBlock() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ConditionalAttributesWithWeirdSpacingAreDisabledForDataAttributesInBlock() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ConditionalAttributesAreDisabledForDataAttributesInDocument() - { - ParseDocumentTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("")), - new MarkupTagBlock( - Factory.Markup("")))); - } - - [Fact] - public void ConditionalAttributesWithWeirdSpacingAreDisabledForDataAttributesInDocument() - { - ParseDocumentTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("")), - new MarkupTagBlock( - Factory.Markup("")))); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlBlockTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlBlockTest.cs deleted file mode 100644 index 9016339ad7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlBlockTest.cs +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class HtmlBlockTest : CsHtmlMarkupParserTestBase - { - [Fact] - public void ParseBlockMethodThrowsArgNullExceptionOnNullContext() - { - // Arrange - var parser = new HtmlMarkupParser(); - - // Act and Assert - var exception = Assert.Throws(() => parser.ParseBlock()); - Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); - } - - [Fact] - public void ParseBlockHandlesOpenAngleAtEof() - { - ParseDocumentTest("@{" + Environment.NewLine - + "<", - new MarkupBlock( - Factory.EmptyHtml(), - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine) - .AsStatement() - .AutoCompleteWith("}"), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("<"))))), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF( - RazorResources.BlockName_Code, "}", "{"), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockHandlesOpenAngleWithProperTagFollowingIt() - { - ParseDocumentTest("@{" + Environment.NewLine - + "<" + Environment.NewLine - + "", - new MarkupBlock( - Factory.EmptyHtml(), - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - Factory.Code(Environment.NewLine) - .AsStatement() - .AutoCompleteWith("}"), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("<" + Environment.NewLine)) - ), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - ), - Factory.EmptyCSharp().AsStatement() - ) - ), - designTimeParser: true, - expectedErrors: new[] - { - new RazorError( - RazorResources.FormatParseError_UnexpectedEndTag("html"), - new SourceLocation(5 + Environment.NewLine.Length * 2, 2, 2), - length: 4), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("code", "}", "{"), - new SourceLocation(1, 0, 1), - length: 1) - }); - } - - [Fact] - public void TagWithoutCloseAngleDoesNotTerminateBlock() - { - ParseBlockTest("< " + Environment.NewLine - + " ", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup($"< {Environment.NewLine} "))), - designTimeParser: true, - expectedErrors: new RazorError( - RazorResources.FormatParseError_UnfinishedTag(string.Empty), - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseBlockAllowsStartAndEndTagsToDifferInCase() - { - ParseBlockTest("
  • Foo

  • ", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("
  • ").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("

    ").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo"), - new MarkupTagBlock( - Factory.Markup("

    ").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("
  • ").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockReadsToEndOfLineIfFirstCharacterAfterTransitionIsColon() - { - ParseBlockTest("@:
  • Foo Bar Baz" + Environment.NewLine - + "bork", - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup("
  • Foo Bar Baz" + Environment.NewLine) - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockStopsParsingSingleLineBlockAtEOFIfNoEOLReached() - { - ParseBlockTest("@:foo bar", - new MarkupBlock( - Factory.MarkupTransition(), - Factory.MetaMarkup(":", HtmlSymbolType.Colon), - Factory.Markup(@"foo bar") - .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)) - )); - } - - [Fact] - public void ParseBlockStopsAtMatchingCloseTagToStartTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockParsesUntilMatchingEndTagIfFirstNonWhitespaceCharacterIsStartTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockAllowsUnclosedTagsAsLongAsItCanRecoverToAnExpectedEndTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockWithSelfClosingTagJustEmitsTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockCanHandleSelfClosingTagsWithinBlock() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockSupportsTagsWithAttributes() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" bar=\"", 4, 0, 4), new LocationTagged("\"", 13, 0, 13)), - Factory.Markup(" bar=\"").With(SpanChunkGenerator.Null), - Factory.Markup("baz").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 10, 0, 10), new LocationTagged("baz", 10, 0, 10))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(">").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("(" zoop=", 24, 0, 24), new LocationTagged(string.Empty, 34, 0, 34)), - Factory.Markup(" zoop=").With(SpanChunkGenerator.Null), - Factory.Markup("zork").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 30, 0, 30), new LocationTagged("zork", 30, 0, 30)))), - Factory.Markup("/>").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockAllowsCloseAngleBracketInAttributeValueIfDoubleQuoted() - { - ParseBlockTest("\" />", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("(" baz=\"", 9, 0, 9), new LocationTagged("\"", 16, 0, 16)), - Factory.Markup(" baz=\"").With(SpanChunkGenerator.Null), - Factory.Markup(">").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 15, 0, 15), new LocationTagged(">", 15, 0, 15))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockAllowsCloseAngleBracketInAttributeValueIfSingleQuoted() - { - ParseBlockTest("\' />", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("(" baz='", 9, 0, 9), new LocationTagged("'", 16, 0, 16)), - Factory.Markup(" baz='").With(SpanChunkGenerator.Null), - Factory.Markup(">").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 15, 0, 15), new LocationTagged(">", 15, 0, 15))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(" />").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockAllowsSlashInAttributeValueIfDoubleQuoted() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("(" baz=\"", 9, 0, 9), new LocationTagged("\"", 16, 0, 16)), - Factory.Markup(" baz=\"").With(SpanChunkGenerator.Null), - Factory.Markup("/").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 15, 0, 15), new LocationTagged("/", 15, 0, 15))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(">").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockAllowsSlashInAttributeValueIfSingleQuoted() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("(" baz='", 9, 0, 9), new LocationTagged("'", 16, 0, 16)), - Factory.Markup(" baz='").With(SpanChunkGenerator.Null), - Factory.Markup("/").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 15, 0, 15), new LocationTagged("/", 15, 0, 15))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(">").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockTerminatesAtEOF() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None))), - new RazorError( - RazorResources.FormatParseError_MissingEndTag("foo"), - new SourceLocation(1, 0, 1), - length: 3)); - } - - [Fact] - public void ParseBlockSupportsCommentAsBlock() - { - SingleSpanBlockTest("", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockSupportsCommentWithinBlock() - { - ParseBlockTest("barbaz", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("bar"), - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup("baz"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - public static TheoryData HtmlCommentSupportsMultipleDashesData - { - get - { - var factory = new SpanFactory - { - MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), - CodeTokenizerFactory = doc => new CSharpTokenizer(doc) - }; - - return new TheoryData - { - { - "
    ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None)), - factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None))) - }, - { - "
    ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None)), - factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None))) - }, - { - "
    ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None)), - factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None))) - }, - { - "
    ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None)), - factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - factory.Markup("
    ").Accepts(AcceptedCharacters.None))) - }, - }; - } - } - - [Theory] - [MemberData(nameof(HtmlCommentSupportsMultipleDashesData))] - public void HtmlCommentSupportsMultipleDashes(string documentContent, MarkupBlock expectedOutput) - { - ParseBlockTest(documentContent, expectedOutput); - } - - - [Fact] - public void ParseBlockProperlyBalancesCommentStartAndEndTags() - { - SingleSpanBlockTest("", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockTerminatesAtEOFWhenParsingComment() - { - SingleSpanBlockTest("", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); - } - - [Fact] - public void ParseBlockTerminatesCommentAtFirstOccurrenceOfEndSequence() - { - ParseBlockTest("-->", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup("-->"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockTreatsMalformedTagsAsContent() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None))), - new RazorError( - RazorResources.FormatParseError_MissingEndTag("foo"), - new SourceLocation(1, 0, 1), - length: 3)); - } - - - [Fact] - public void ParseBlockParsesSGMLDeclarationAsEmptyTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockTerminatesSGMLDeclarationAtFirstCloseAngle() - { - ParseBlockTest(" baz>", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup(" baz>"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockParsesXMLProcessingInstructionAsEmptyTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockTerminatesXMLProcessingInstructionAtQuestionMarkCloseAnglePair() - { - ParseBlockTest(" baz", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup(" baz"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockDoesNotTerminateXMLProcessingInstructionAtCloseAngleUnlessPreceededByQuestionMark() - { - ParseBlockTest(" baz?>", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup(" baz?>").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSupportsScriptTagsWithLessThanSignsInThem() - { - ParseBlockTest(@"", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockSupportsScriptTagsWithSpacedLessThanSignsInThem() - { - ParseBlockTest(@"", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockAcceptsEmptyTextTag() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("")) - )); - } - - [Fact] - public void ParseBlockAcceptsTextTagAsOuterTagButDoesNotRender() - { - ParseBlockTest("Foo Bar Baz zoop", - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("")), - Factory.Markup("Foo Bar ").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup(" Baz"), - new MarkupTagBlock( - Factory.MarkupTransition("")))); - } - - [Fact] - public void ParseBlockRendersLiteralTextTagIfDoubled() - { - ParseBlockTest("Foo Bar Baz zoop", - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("")), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo Bar "), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - Factory.Markup(" Baz"), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.MarkupTransition("")))); - } - - [Fact] - public void ParseBlockDoesNotConsiderPsuedoTagWithinMarkupBlock() - { - ParseBlockTest("", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)), - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)) - )); - } - - [Fact] - public void ParseBlockStopsParsingMidEmptyTagIfEOFReached() - { - ParseBlockTest("
    Foo @if(true) {} Bar", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("
    ").Accepts(AcceptedCharacters.None)), - Factory.Markup("Foo "), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(true) {}").AsStatement()), - Factory.Markup(" Bar"), - new MarkupTagBlock( - Factory.Markup("
    ").Accepts(AcceptedCharacters.None)))); - } - - [Fact] - public void ParseBlockIgnoresTagsInContentsOfScriptTag() - { - ParseBlockTest(@"", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None)))); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlDocumentTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlDocumentTest.cs deleted file mode 100644 index 08b677326a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/Internal/HtmlDocumentTest.cs +++ /dev/null @@ -1,831 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Test.Utils; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.Internal -{ - public class HtmlDocumentTest : CsHtmlMarkupParserTestBase - { - private static readonly TestFile Nested1000 = TestFile.Create("TestFiles/nested-1000.html"); - - [Fact] - public void ParseDocument_NestedCodeBlockWithMarkupSetsDotAsMarkup() - { - ParseDocumentTest("@if (true) { @if(false) {
    @something.
    } }", - new MarkupBlock( - Factory.EmptyHtml(), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if (true) { ").AsStatement(), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(false) {").AsStatement(), - new MarkupBlock( - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("
    ", AcceptedCharacters.None), - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("something") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Markup("."), - BlockFactory.MarkupTagBlock("
    ", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None)), - Factory.Code("}").AsStatement()), - Factory.Code(" }").AsStatement()))); - } - - [Fact] - public void ParseDocumentMethodThrowsArgNullExceptionOnNullContext() - { - // Arrange - var parser = new HtmlMarkupParser(); - - // Act and Assert - var exception = Assert.Throws(() => parser.ParseDocument()); - Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); - } - - [Fact] - public void ParseSectionMethodThrowsArgNullExceptionOnNullContext() - { - // Arrange - var parser = new HtmlMarkupParser(); - - // Act and Assert - var exception = Assert.Throws(() => parser.ParseSection(null, true)); - Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); - } - - [Fact] - public void ParseDocumentOutputsEmptyBlockWithEmptyMarkupSpanIfContentIsEmptyString() - { - ParseDocumentTest(string.Empty, new MarkupBlock(Factory.EmptyHtml())); - } - - [Fact] - public void ParseDocumentOutputsWhitespaceOnlyContentAsSingleWhitespaceMarkupSpan() - { - SingleSpanDocumentTest(" ", BlockType.Markup, SpanKind.Markup); - } - - [Fact] - public void ParseDocumentAcceptsSwapTokenAtEndOfFileAndOutputsZeroLengthCodeSpan() - { - ParseDocumentTest("@", - new MarkupBlock( - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.EmptyHtml()), - new RazorError( - RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, - new SourceLocation(1, 0, 1), - length: 1)); - } - - [Fact] - public void ParseDocumentCorrectlyHandlesOddlySpacedHTMLElements() - { - ParseDocumentTest("

    Foo

    ", - new MarkupBlock( - BlockFactory.MarkupTagBlock("
    "), - new MarkupTagBlock( - Factory.Markup("(" class = '", 8, 0, 8), suffix: new LocationTagged("'", 21, 0, 21)), - Factory.Markup(" class = '").With(SpanChunkGenerator.Null), - Factory.Markup("bar").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(string.Empty, 18, 0, 18), value: new LocationTagged("bar", 18, 0, 18))), - Factory.Markup("'").With(SpanChunkGenerator.Null)), - Factory.Markup(">")), - Factory.Markup(" Foo "), - BlockFactory.MarkupTagBlock("

    "), - BlockFactory.MarkupTagBlock("
    "))); - } - - [Fact] - public void ParseDocumentCorrectlyHandlesSingleLineOfMarkupWithEmbeddedStatement() - { - ParseDocumentTest("
    Foo @if(true) {} Bar
    ", - new MarkupBlock( - BlockFactory.MarkupTagBlock("
    "), - Factory.Markup("Foo "), - new StatementBlock( - Factory.CodeTransition(), - Factory.Code("if(true) {}").AsStatement()), - Factory.Markup(" Bar"), - BlockFactory.MarkupTagBlock("
    "))); - } - - [Fact] - public void ParseDocumentWithinSectionDoesNotCreateDocumentLevelSpan() - { - ParseDocumentTest("@section Foo {" + Environment.NewLine - + " " + Environment.NewLine - + "}", - new MarkupBlock( - Factory.EmptyHtml(), - new SectionBlock(new SectionChunkGenerator("Foo"), - Factory.CodeTransition(), - Factory.MetaCode("section Foo {") - .AutoCompleteWith(null, atEndOfSpan: true), - new MarkupBlock( - Factory.Markup(Environment.NewLine + " "), - BlockFactory.MarkupTagBlock(""), - BlockFactory.MarkupTagBlock(""), - Factory.Markup(Environment.NewLine)), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseDocumentParsesWholeContentAsOneSpanIfNoSwapCharacterEncountered() - { - SingleSpanDocumentTest("foo baz", BlockType.Markup, SpanKind.Markup); - } - - [Fact] - public void ParseDocumentHandsParsingOverToCodeParserWhenAtSignEncounteredAndEmitsOutput() - { - ParseDocumentTest("foo @bar baz", - new MarkupBlock( - Factory.Markup("foo "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("bar") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.Markup(" baz"))); - } - - [Fact] - public void ParseDocumentEmitsAtSignAsMarkupIfAtEndOfFile() - { - ParseDocumentTest("foo @", - new MarkupBlock( - Factory.Markup("foo "), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.EmptyCSharp() - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.EmptyHtml()), - new RazorError( - RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, - new SourceLocation(5, 0, 5), - length: 1)); - } - - [Fact] - public void ParseDocumentEmitsCodeBlockIfFirstCharacterIsSwapCharacter() - { - ParseDocumentTest("@bar", - new MarkupBlock( - Factory.EmptyHtml(), - new ExpressionBlock( - Factory.CodeTransition(), - Factory.Code("bar") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - Factory.EmptyHtml())); - } - - [Fact] - public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInText() - { - SingleSpanDocumentTest("anurse@microsoft.com", BlockType.Markup, SpanKind.Markup); - } - - [Fact] - public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInAttribute() - { - ParseDocumentTest("Email me", - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("(" href=\"", 2, 0, 2), new LocationTagged("\"", 36, 0, 36)), - Factory.Markup(" href=\"").With(SpanChunkGenerator.Null), - Factory.Markup("mailto:anurse@microsoft.com") - .With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 9, 0, 9), new LocationTagged("mailto:anurse@microsoft.com", 9, 0, 9))), - Factory.Markup("\"").With(SpanChunkGenerator.Null)), - Factory.Markup(">")), - Factory.Markup("Email me"), - BlockFactory.MarkupTagBlock(""))); - } - - [Fact] - public void ParseDocumentDoesNotReturnErrorOnMismatchedTags() - { - ParseDocumentTest("Foo

    Baz", - new MarkupBlock( - Factory.Markup("Foo "), - BlockFactory.MarkupTagBlock("
    "), - BlockFactory.MarkupTagBlock("

    "), - BlockFactory.MarkupTagBlock("

    "), - BlockFactory.MarkupTagBlock("

    "), - Factory.Markup(" Baz"))); - } - - [Fact] - public void ParseDocumentReturnsOneMarkupSegmentIfNoCodeBlocksEncountered() - { - SingleSpanDocumentTest("Foo BazBar Bar", - new MarkupBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void DocTypeTag() - { - ParseBlockTest(" foo", - new MarkupBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ProcessingInstructionTag() - { - ParseBlockTest(" foo", - new MarkupBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ElementTags() - { - ParseBlockTest("

    Foo

    Bar", - new MarkupBlock( - BlockFactory.MarkupTagBlock("

    ", AcceptedCharacters.None), - Factory.Markup("Foo"), - BlockFactory.MarkupTagBlock("

    ", AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void TextTags() - { - ParseBlockTest("Foo}", - new MarkupBlock( - new MarkupTagBlock( - Factory.MarkupTransition("")), - Factory.Markup("Foo").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - Factory.MarkupTransition("")))); - } - - [Fact] - public void CDataTag() - { - ParseBlockTest(" Bar", - new MarkupBlock( - Factory.Markup("").Accepts(AcceptedCharacters.None), - Factory.Markup(" ").Accepts(AcceptedCharacters.None))); - } - - [Fact] - public void ScriptTag() - { - ParseDocumentTest("", - new MarkupBlock( - BlockFactory.MarkupTagBlock(""))); - } - - [Fact] - public void ScriptTag_WithNestedMalformedTag() - { - ParseDocumentTest("", - new MarkupBlock( - BlockFactory.MarkupTagBlock(""))); - } - - [Fact] - public void ScriptTag_WithNestedEndTag() - { - ParseDocumentTest("", - new MarkupBlock( - BlockFactory.MarkupTagBlock(""))); - } - - [Fact] - public void ScriptTag_WithNestedBeginTag() - { - ParseDocumentTest("", - new MarkupBlock( - BlockFactory.MarkupTagBlock(""))); - } - - [Fact] - public void ScriptTag_WithNestedTag() - { - ParseDocumentTest("", - new MarkupBlock( - BlockFactory.MarkupTagBlock(""))); - } - - [Theory] - [MemberData("VoidElementNames")] - public void VoidElementFollowedByContent(string tagName) - { - ParseBlockTest("<" + tagName + ">foo", - new MarkupBlock( - BlockFactory.MarkupTagBlock("<" + tagName + ">", AcceptedCharacters.None))); - } - - [Theory] - [MemberData("VoidElementNames")] - public void VoidElementFollowedByOtherTag(string tagName) - { - ParseBlockTest("<" + tagName + ">foo", - new MarkupBlock( - BlockFactory.MarkupTagBlock("<" + tagName + ">", AcceptedCharacters.None))); - } - - [Theory] - [MemberData("VoidElementNames")] - public void VoidElementFollowedByCloseTag(string tagName) - { - ParseBlockTest("<" + tagName + "> foo", - new MarkupBlock( - BlockFactory.MarkupTagBlock("<" + tagName + ">", AcceptedCharacters.None), - Factory.Markup(" "), - BlockFactory.MarkupTagBlock("", AcceptedCharacters.None))); - } - - [Theory] - [MemberData("VoidElementNames")] - public void IncompleteVoidElementEndTag(string tagName) - { - ParseBlockTest("<" + tagName + ">", AcceptedCharacters.None), - BlockFactory.MarkupTagBlock("(parameterName, - () => new ParserContext( - source: new SeekableTextReader(TextReader.Null), - codeParser: new CSharpCodeParser(), - markupParser: new HtmlMarkupParser(), - activeParser: new CSharpCodeParser(), - errorSink: new ErrorSink())); - ExceptionHelpers.ValidateArgumentException(parameterName, RazorResources.ActiveParser_Must_Be_Code_Or_Markup_Parser, exception); - } - - [Fact] - public void ConstructorAcceptsActiveParserIfIsSameAsEitherCodeOrMarkupParser() - { - var codeParser = new CSharpCodeParser(); - var markupParser = new HtmlMarkupParser(); - var errorSink = new ErrorSink(); - new ParserContext( - new SeekableTextReader(TextReader.Null), codeParser, markupParser, codeParser, errorSink); - new ParserContext( - new SeekableTextReader(TextReader.Null), codeParser, markupParser, markupParser, errorSink); - } - - [Fact] - public void ConstructorInitializesProperties() - { - // Arrange - var expectedBuffer = new SeekableTextReader(TextReader.Null); - var expectedCodeParser = new CSharpCodeParser(); - var expectedMarkupParser = new HtmlMarkupParser(); - - // Act - var context = new ParserContext(expectedBuffer, - expectedCodeParser, - expectedMarkupParser, - expectedCodeParser, - new ErrorSink()); - - // Assert - Assert.NotNull(context.Source); - Assert.Same(expectedCodeParser, context.CodeParser); - Assert.Same(expectedMarkupParser, context.MarkupParser); - Assert.Same(expectedCodeParser, context.ActiveParser); - } - - [Fact] - public void CurrentCharacterReturnsCurrentCharacterInTextBuffer() - { - // Arrange - var context = SetupTestContext("bar", b => b.Read()); - - // Act - var actual = context.CurrentCharacter; - - // Assert - Assert.Equal('a', actual); - } - - [Fact] - public void CurrentCharacterReturnsNulCharacterIfTextBufferAtEOF() - { - // Arrange - var context = SetupTestContext("bar", b => b.ReadToEnd()); - - // Act - var actual = context.CurrentCharacter; - - // Assert - Assert.Equal('\0', actual); - } - - [Fact] - public void EndOfFileReturnsFalseIfTextBufferNotAtEOF() - { - // Arrange - var context = SetupTestContext("bar"); - - // Act/Assert - Assert.False(context.EndOfFile); - } - - [Fact] - public void EndOfFileReturnsTrueIfTextBufferAtEOF() - { - // Arrange - var context = SetupTestContext("bar", b => b.ReadToEnd()); - - // Act/Assert - Assert.True(context.EndOfFile); - } - - [Fact] - public void StartBlockCreatesNewBlock() - { - // Arrange - var context = SetupTestContext("phoo"); - - // Act - context.StartBlock(BlockType.Expression); - - // Assert - Assert.Equal(1, context.BlockStack.Count); - Assert.Equal(BlockType.Expression, context.BlockStack.Peek().Type); - } - - [Fact] - public void EndBlockAddsCurrentBlockToParentBlock() - { - // Arrange - var mockListener = new Mock(); - var context = SetupTestContext("phoo"); - - // Act - context.StartBlock(BlockType.Expression); - context.StartBlock(BlockType.Statement); - context.EndBlock(); - - // Assert - Assert.Equal(1, context.BlockStack.Count); - Assert.Equal(BlockType.Expression, context.BlockStack.Peek().Type); - Assert.Equal(1, context.BlockStack.Peek().Children.Count); - Assert.Equal(BlockType.Statement, ((Block)context.BlockStack.Peek().Children[0]).Type); - } - - [Fact] - public void AddSpanAddsSpanToCurrentBlockBuilder() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var mockListener = new Mock(); - var context = SetupTestContext("phoo"); - - var builder = new SpanBuilder() - { - Kind = SpanKind.Code - }; - builder.Accept(new CSharpSymbol(1, 0, 1, "foo", CSharpSymbolType.Identifier)); - var added = builder.Build(); - - using (context.StartBlock(BlockType.Functions)) - { - context.AddSpan(added); - } - - var expected = new BlockBuilder() - { - Type = BlockType.Functions, - }; - expected.Children.Add(added); - - // Assert - ParserTestBase.EvaluateResults(context.CompleteParse(), expected.Build()); - } - - [Fact] - public void SwitchActiveParserSetsMarkupParserAsActiveIfCodeParserCurrentlyActive() - { - // Arrange - var codeParser = new CSharpCodeParser(); - var markupParser = new HtmlMarkupParser(); - var context = SetupTestContext("barbazbiz", b => b.Read(), codeParser, markupParser, codeParser); - Assert.Same(codeParser, context.ActiveParser); - - // Act - context.SwitchActiveParser(); - - // Assert - Assert.Same(markupParser, context.ActiveParser); - } - - [Fact] - public void SwitchActiveParserSetsCodeParserAsActiveIfMarkupParserCurrentlyActive() - { - // Arrange - var codeParser = new CSharpCodeParser(); - var markupParser = new HtmlMarkupParser(); - var context = SetupTestContext("barbazbiz", b => b.Read(), codeParser, markupParser, markupParser); - Assert.Same(markupParser, context.ActiveParser); - - // Act - context.SwitchActiveParser(); - - // Assert - Assert.Same(codeParser, context.ActiveParser); - } - - private ParserContext SetupTestContext(string document) - { - var codeParser = new CSharpCodeParser(); - var markupParser = new HtmlMarkupParser(); - return SetupTestContext(document, b => { }, codeParser, markupParser, codeParser); - } - - private ParserContext SetupTestContext(string document, Action positioningAction) - { - var codeParser = new CSharpCodeParser(); - var markupParser = new HtmlMarkupParser(); - return SetupTestContext(document, positioningAction, codeParser, markupParser, codeParser); - } - - private ParserContext SetupTestContext(string document, - Action positioningAction, - ParserBase codeParser, - ParserBase markupParser, - ParserBase activeParser) - { - var context = new ParserContext( - new SeekableTextReader(new StringReader(document)), - codeParser, - markupParser, - activeParser, - new ErrorSink()); - - positioningAction(context.Source); - return context; - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/ParserVisitorExtensionsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/ParserVisitorExtensionsTest.cs deleted file mode 100644 index 3e57cb94a5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/ParserVisitorExtensionsTest.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class ParserVisitorExtensionsTest - { - [Fact] - public void VisitSendsDocumentToVisitor() - { - // Arrange - var targetMock = new Mock(); - var root = new BlockBuilder() { Type = BlockType.Comment }.Build(); - var errorSink = new ErrorSink(); - var results = new ParserResults(root, - Enumerable.Empty(), - errorSink); - - // Act - targetMock.Object.Visit(results); - - // Assert - targetMock.Verify(v => v.VisitBlock(root)); - } - - [Fact] - public void VisitSendsErrorsToVisitor() - { - // Arrange - var targetMock = new Mock(); - var root = new BlockBuilder() { Type = BlockType.Comment }.Build(); - var errorSink = new ErrorSink(); - var errors = new List - { - new RazorError("Foo", new SourceLocation(1, 0, 1), length: 3), - new RazorError("Bar", new SourceLocation(2, 0, 2), length: 3), - }; - foreach (var error in errors) - { - errorSink.OnError(error); - } - var results = new ParserResults(root, Enumerable.Empty(), errorSink); - - // Act - targetMock.Object.Visit(results); - - // Assert - targetMock.Verify(v => v.VisitError(errors[0])); - targetMock.Verify(v => v.VisitError(errors[1])); - } - - [Fact] - public void VisitCallsOnCompleteWhenAllNodesHaveBeenVisited() - { - // Arrange - var targetMock = new Mock(); - var root = new BlockBuilder() { Type = BlockType.Comment }.Build(); - var errorSink = new ErrorSink(); - errorSink.OnError(new RazorError("Foo", new SourceLocation(1, 0, 1), length: 3)); - errorSink.OnError(new RazorError("Bar", new SourceLocation(2, 0, 2), length: 3)); - var results = new ParserResults(root, Enumerable.Empty(), errorSink); - - // Act - targetMock.Object.Visit(results); - - // Assert - targetMock.Verify(v => v.OnComplete()); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/RazorParserTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/RazorParserTest.cs deleted file mode 100644 index 2615c55e5f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/RazorParserTest.cs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Moq; -using Moq.Protected; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class RazorParserTest - { - [Fact] - 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"))); - } - - [Fact] - 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"))); - } - - [Fact] - public void GetTagHelperDescriptors_IsInvokedToLocateTagHelperDescriptors() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var parser = new Mock( - new CSharpCodeParser(), - new HtmlMarkupParser(), - Mock.Of()); - parser.CallBase = true; - parser - .Protected() - .Setup>("GetTagHelperDescriptors", ItExpr.IsAny(), ItExpr.IsAny()) - .Returns(Enumerable.Empty()) - .Verifiable(); - - // Act - parser.Object.Parse(new StringReader("

    Hello world. The time is @DateTime.UtcNow

    ")); - - // Assert - parser.Verify(); - } - - [Fact] - public void ParseMethodSetsUpRunWithSpecifiedCodeParserMarkupParserAndListenerAndPassesToMarkupParser() - { - RunParseWithListenerTest((parser, reader) => parser.Parse(reader)); - } - - private static void RunParseWithListenerTest(Action 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); - } - - private class MockMarkupParser : ParserBase - { - public override bool IsMarkupParser - { - get - { - return true; - } - } - - public override void ParseDocument() - { - using (Context.StartBlock(BlockType.Markup)) - { - } - } - - public override void ParseSection(Tuple nestingSequences, bool caseSensitive = true) - { - using (Context.StartBlock(BlockType.Markup)) - { - } - } - - public override void ParseBlock() - { - using (Context.StartBlock(BlockType.Markup)) - { - } - } - - protected override ParserBase OtherParser - { - get { return Context.CodeParser; } - } - - public override void BuildSpan(SpanBuilder span, SourceLocation start, string content) - { - throw new NotImplementedException(); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/SyntaxTree/BlockTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/SyntaxTree/BlockTest.cs deleted file mode 100644 index c89e213782..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/SyntaxTree/BlockTest.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using System.Web.WebPages.TestUtils; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.SyntaxTree -{ - public class BlockTest - { - [Fact] - public void ConstructorWithBlockBuilderSetsParent() - { - // Arrange - var builder = new BlockBuilder() { Type = BlockType.Comment }; - var span = new SpanBuilder() { Kind = SpanKind.Code }.Build(); - builder.Children.Add(span); - - // Act - var block = builder.Build(); - - // Assert - Assert.Same(block, span.Parent); - } - - [Fact] - public void ConstructorTransfersInstanceOfChunkGeneratorFromBlockBuilder() - { - // Arrange - var expected = new ExpressionChunkGenerator(); - var builder = new BlockBuilder() - { - Type = BlockType.Helper, - ChunkGenerator = expected - }; - - // Act - var actual = builder.Build(); - - // Assert - Assert.Same(expected, actual.ChunkGenerator); - } - - [Fact] - public void ConstructorTransfersChildrenFromBlockBuilder() - { - // Arrange - var expected = new SpanBuilder() { Kind = SpanKind.Code }.Build(); - var builder = new BlockBuilder() - { - Type = BlockType.Functions - }; - builder.Children.Add(expected); - - // Act - var block = builder.Build(); - - // Assert - Assert.Same(expected, block.Children.Single()); - } - - [Fact] - public void LocateOwnerReturnsNullIfNoSpanReturnsTrueForOwnsSpan() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var block = new MarkupBlock( - factory.Markup("Foo "), - new StatementBlock( - factory.CodeTransition(), - factory.Code("bar").AsStatement()), - factory.Markup(" Baz")); - var change = new TextChange(128, 1, new StringTextBuffer("Foo @bar Baz"), 1, new StringTextBuffer("Foo @bor Baz")); - - // Act - var actual = block.LocateOwner(change); - - // Assert - Assert.Null(actual); - } - - [Fact] - public void LocateOwnerReturnsNullIfChangeCrossesMultipleSpans() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var block = new MarkupBlock( - factory.Markup("Foo "), - new StatementBlock( - factory.CodeTransition(), - factory.Code("bar").AsStatement()), - factory.Markup(" Baz")); - var change = new TextChange(4, 10, new StringTextBuffer("Foo @bar Baz"), 10, new StringTextBuffer("Foo @bor Baz")); - - // Act - var actual = block.LocateOwner(change); - - // Assert - Assert.Null(actual); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperBlockRewriterTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperBlockRewriterTest.cs deleted file mode 100644 index 2ceea3d89a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperBlockRewriterTest.cs +++ /dev/null @@ -1,4046 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Test.Parser.TagHelpers.Internal; -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.TagHelpers.Internal -{ - public class TagHelperBlockRewriterTest : TagHelperRewritingTestBase - { - public static TheoryData SymbolBoundAttributeData - { - get - { - var factory = CreateDefaultSpanFactory(); - - return new TheoryData - { - { - "
      ", - new MarkupBlock( - new MarkupTagHelperBlock("ul", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("[item]", factory.CodeMarkup("items"), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagHelperBlock("ul", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("[(item)]", factory.CodeMarkup("items"), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("button", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode( - "(click)", - factory.CodeMarkup("doSomething()"), - HtmlAttributeValueStyle.SingleQuotes) - }, - children: factory.Markup("Click Me"))) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("button", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode( - "(^click)", - factory.CodeMarkup("doSomething()"), - HtmlAttributeValueStyle.SingleQuotes) - }, - children: factory.Markup("Click Me"))) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("template", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode( - "*something", - factory.Markup("value"), - HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagHelperBlock("div", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("#localminimized", null, HtmlAttributeValueStyle.Minimized) - })) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagHelperBlock("div", - attributes: new List - { - new TagHelperAttributeNode("bound", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("#local", factory.Markup("value"), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - }; - } - } - - [Theory] - [MemberData(nameof(SymbolBoundAttributeData))] - public void Rewrite_CanHandleSymbolBoundAttributes(string documentContent, MarkupBlock expectedOutput) - { - // Arrange - var descriptors = new[] - { - new TagHelperDescriptor - { - TagName = "*", - TypeName = "CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "[item]", - PropertyName = "ListItems", - TypeName = typeof(List).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "[(item)]", - PropertyName = "ArrayItems", - TypeName = typeof(string[]).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "(click)", - PropertyName = "Event1", - TypeName = typeof(Action).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "(^click)", - PropertyName = "Event2", - TypeName = typeof(Action).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "*something", - PropertyName = "StringProperty1", - TypeName = typeof(string).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "#local", - PropertyName = "StringProperty2", - TypeName = typeof(string).FullName - }, - }, - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "bound" } }, - }, - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - public static TheoryData WithoutEndTagElementData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - // documentContent, expectedOutput - return new TheoryData - { - { - "", - new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.StartTagOnly)) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.StartTagOnly, - attributes: new List - { - new TagHelperAttributeNode("type", factory.Markup("text"), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - new MarkupTagHelperBlock("input", TagMode.StartTagOnly)) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.StartTagOnly, - attributes: new List - { - new TagHelperAttributeNode("type", factory.Markup("text"), HtmlAttributeValueStyle.SingleQuotes) - }), - new MarkupTagHelperBlock("input", TagMode.StartTagOnly)) - }, - { - "
        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("
        "), - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - blockFactory.MarkupTagBlock("
        ")) - }, - }; - } - } - - [Theory] - [MemberData(nameof(WithoutEndTagElementData))] - public void Rewrite_CanHandleWithoutEndTagTagStructure(string documentContent, MarkupBlock expectedOutput) - { - // Arrange - 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 RazorError[0]); - } - - public static TheoryData TagStructureCompatibilityData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - // documentContent, structure1, structure2, expectedOutput - return new TheoryData - { - { - "", - TagStructure.Unspecified, - TagStructure.Unspecified, - new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.StartTagAndEndTag)) - }, - { - "", - TagStructure.Unspecified, - TagStructure.Unspecified, - new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.SelfClosing)) - }, - { - "", - TagStructure.Unspecified, - TagStructure.WithoutEndTag, - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.StartTagOnly, - attributes: new List - { - new TagHelperAttributeNode("type", factory.Markup("text"), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "", - TagStructure.WithoutEndTag, - TagStructure.WithoutEndTag, - new MarkupBlock( - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - new MarkupTagHelperBlock("input", TagMode.StartTagOnly)) - }, - { - "", - TagStructure.Unspecified, - TagStructure.NormalOrSelfClosing, - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.StartTagAndEndTag, - attributes: new List - { - new TagHelperAttributeNode("type", factory.Markup("text"), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "", - TagStructure.Unspecified, - TagStructure.WithoutEndTag, - new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.SelfClosing)) - }, - - { - "", - TagStructure.NormalOrSelfClosing, - TagStructure.Unspecified, - new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.SelfClosing)) - }, - }; - } - } - - [Theory] - [MemberData(nameof(TagStructureCompatibilityData))] - public void Rewrite_AllowsCompatibleTagStructures( - string documentContent, - TagStructure structure1, - TagStructure structure2, - MarkupBlock expectedOutput) - { - // Arrange - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper1", - AssemblyName = "SomeAssembly", - TagStructure = structure1 - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper2", - AssemblyName = "SomeAssembly", - TagStructure = structure2 - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - public static TheoryData MalformedTagHelperAttributeBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatUnclosed = "Found a malformed '{0}' tag helper. Tag helpers must have a start and " + - "end tag or be self closing."; - var errorFormatNoCloseAngle = "Missing close angle for tag helper '{0}'."; - var errorFormatNoCSharp = "The tag helper '{0}' must not have C# in the element's attribute " + - "declaration area."; - Func createInvalidDoBlock = extraCode => - { - return new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(10, 0, 10)), - new SourceLocation(10, 0, 10)), - new StatementBlock( - factory.CodeTransition(), - factory.Code("do {" + extraCode).AsStatement()))); - }; - - return new TheoryData - { - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "bar", - new MarkupBlock(factory.Markup("false"), factory.Markup(" ")), - HtmlAttributeValueStyle.SingleQuotes) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        - { - new TagHelperAttributeNode( - "bar", - new MarkupBlock( - factory.Markup("false"), - factory.Markup(" - { - new TagHelperAttributeNode( - "bar", - factory.Markup("false"), - HtmlAttributeValueStyle.DoubleQuotes) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - "TagHelper attributes must be well-formed.", - new SourceLocation(12, 0, 12), - length: 1) - } - }, - { - "

        - { - new TagHelperAttributeNode( - "bar", - factory.Markup("false'")) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "bar", - new MarkupBlock( - factory.Markup("false'"), - factory.Markup(" >

        "))) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("foo", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bar", null, HtmlAttributeValueStyle.Minimized) - }, - new MarkupTagHelperBlock("strong"))), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "strong"), - new SourceLocation(11, 0, 11), - length: 6) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "class", - new MarkupBlock(factory.Markup("btn"), factory.Markup(" bar="))), - new TagHelperAttributeNode("foo", null, HtmlAttributeValueStyle.Minimized) - }, - new MarkupTagHelperBlock("strong"))), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "strong"), - new SourceLocation(24, 0, 24), - length: 6) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "class", - new MarkupBlock(factory.Markup("btn"), factory.Markup(" bar="))), - new TagHelperAttributeNode("foo", null, HtmlAttributeValueStyle.Minimized), - })), - new RazorError[0] - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p")), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCSharp, "p"), - absoluteIndex: 3, lineIndex: 0 , columnIndex: 3, length: 13) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p")), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCSharp, "p"), - absoluteIndex: 3, lineIndex: 0 , columnIndex: 3, length: 13) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "class", - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(9, 0, 9)), - new SourceLocation(9, 0, 9)), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))), - HtmlAttributeValueStyle.DoubleQuotes) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        - { - new TagHelperAttributeNode( - "class", - createInvalidDoBlock(string.Empty)) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("do", "}", "{"), - absoluteIndex: 11, lineIndex: 0, columnIndex: 11, length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", createInvalidDoBlock("\">

        ")) - })), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("do", "}", "{"), - absoluteIndex: 11, lineIndex: 0, columnIndex: 11, length: 1), - new RazorError( - RazorResources.ParseError_Unterminated_String_Literal, - absoluteIndex: 15, lineIndex: 0, columnIndex: 15, length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p")), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCSharp, "p"), - absoluteIndex: 3, lineIndex: 0 , columnIndex: 3, length: 30), - new RazorError( - RazorResources.FormatParseError_Expected_EndOfBlock_Before_EOF("do", "}", "{"), - absoluteIndex: 4, lineIndex: 0, columnIndex: 4, length: 1), - new RazorError( - RazorResources.FormatParseError_UnexpectedEndTag("p"), - absoluteIndex: 31, lineIndex: 0, columnIndex: 31, length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("some")) - })), - new [] - { - new RazorError( - "TagHelper attributes must be well-formed.", - new SourceLocation(13, 0, 13), - length: 13) - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(MalformedTagHelperAttributeBlockData))] - public void Rewrite_CreatesErrorForMalformedTagHelpersWithAttributes( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p"); - } - - public static TheoryData MalformedTagHelperBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatUnclosed = "Found a malformed '{0}' tag helper. Tag helpers must have a start and " + - "end tag or be self closing."; - var errorFormatNoCloseAngle = "Missing close angle for tag helper '{0}'."; - - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("strong", - new MarkupTagHelperBlock("p"))), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "strong"), - new SourceLocation(1, 0, 1), - length: 6), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "strong"), - new SourceLocation(1, 0, 1), - length: 6), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(9, 0, 9), - length: 1) - } - }, - { - " <

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - blockFactory.MarkupTagBlock("<"), - blockFactory.MarkupTagBlock(""), - factory.Markup(" "), - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("p")), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "strong"), - new SourceLocation(4, 0, 4), - length: 6), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(14, 0, 14), - length: 1) - } - }, - { - "<<> <<>>", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("strong", - factory.Markup("> "), - blockFactory.MarkupTagBlock("<"), - blockFactory.MarkupTagBlock("<>"), - factory.Markup(">"))), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "strong"), - new SourceLocation(3, 0, 3), - length: 6) - } - }, - { - "

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock(""))), - new [] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(14, 0, 14), - length: 1) - } - } - }; - } - } - - [Theory] - [MemberData(nameof(MalformedTagHelperBlockData))] - public void Rewrite_CreatesErrorForMalformedTagHelper( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p"); - } - - public static TheoryData CodeTagHelperAttributesData - { - get - { - var factory = CreateDefaultSpanFactory(); - var dateTimeNow = new MarkupBlock( - factory.Markup(" "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))); - - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("age", factory.CodeMarkup("12")) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "birthday", - factory.CodeMarkup("DateTime.Now")) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "age", - new MarkupBlock( - new MarkupBlock( - new ExpressionBlock( - factory.CodeTransition(), - factory - .CSharpCodeMarkup("DateTime.Now.Year") - .With(new ExpressionChunkGenerator()))))) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "age", - new MarkupBlock( - new MarkupBlock( - factory.CodeMarkup(" "), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory - .CSharpCodeMarkup("DateTime.Now.Year") - .With(new ExpressionChunkGenerator()))))) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("name", factory.Markup("John")) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "name", - new MarkupBlock(factory.Markup("Time:"), dateTimeNow)) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "age", - new MarkupBlock( - factory.CodeMarkup("1"), - factory.CodeMarkup(" +"), - new MarkupBlock( - factory.CodeMarkup(" "), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory.CSharpCodeMarkup("value") - .With(new ExpressionChunkGenerator()))), - factory.CodeMarkup(" +"), - factory.CodeMarkup(" 2"))), - new TagHelperAttributeNode( - "birthday", - new MarkupBlock( - factory.CodeMarkup("(bool)"), - new MarkupBlock( - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory - .CSharpCodeMarkup("Bag[\"val\"]") - .With(new ExpressionChunkGenerator()))), - factory.CodeMarkup(" ?"), - new MarkupBlock( - factory.CodeMarkup(" @") - .As(SpanKind.Code), - factory.CodeMarkup("@") - .As(SpanKind.Code) - .With(SpanChunkGenerator.Null)), - factory.CodeMarkup("DateTime"), - factory.CodeMarkup(" :"), - new MarkupBlock( - factory.CodeMarkup(" "), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory - .CSharpCodeMarkup("DateTime.Now") - .With(new ExpressionChunkGenerator())))), - HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("age", factory.CodeMarkup("12")), - new TagHelperAttributeNode( - "birthday", - factory.CodeMarkup("DateTime.Now")), - new TagHelperAttributeNode( - "name", - new MarkupBlock(factory.Markup("Time:"), dateTimeNow)) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("age", factory.CodeMarkup("12")), - new TagHelperAttributeNode( - "birthday", - factory.CodeMarkup("DateTime.Now")), - new TagHelperAttributeNode( - "name", - new MarkupBlock( - factory.Markup("Time:"), - new MarkupBlock( - factory.Markup(" @").Accepts(AcceptedCharacters.None), - factory.Markup("@") - .With(SpanChunkGenerator.Null) - .Accepts(AcceptedCharacters.None)), - dateTimeNow)) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("age", factory.CodeMarkup("12")), - new TagHelperAttributeNode( - "birthday", - factory.CodeMarkup("DateTime.Now")), - new TagHelperAttributeNode( - "name", - new MarkupBlock( - new MarkupBlock( - factory.Markup("@").Accepts(AcceptedCharacters.None), - factory.Markup("@") - .With(SpanChunkGenerator.Null) - .Accepts(AcceptedCharacters.None)), - factory.Markup("BoundStringAttribute"))) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("person", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "age", - new MarkupBlock( - new MarkupBlock( - factory.CodeMarkup("@"), - factory.CodeMarkup("@") - .With(SpanChunkGenerator.Null)), - new MarkupBlock( - factory.EmptyHtml() - .AsCodeMarkup() - .As(SpanKind.Code), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory.CSharpCodeMarkup("("), - factory.CSharpCodeMarkup("11+1") - .With(new ExpressionChunkGenerator()), - factory.CSharpCodeMarkup(")"))))), - new TagHelperAttributeNode( - "birthday", - factory.CodeMarkup("DateTime.Now")), - new TagHelperAttributeNode( - "name", - new MarkupBlock(factory.Markup("Time:"), dateTimeNow)) - })) - }, - }; - } - } - - [Theory] - [MemberData(nameof(CodeTagHelperAttributesData))] - public void TagHelperParseTreeRewriter_CreatesMarkupCodeSpansForNonStringTagHelperAttributes( - string documentContent, - MarkupBlock expectedOutput) - { - // Arrange - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "person", - TypeName = "PersonTagHelper", - AssemblyName = "personAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "age", - PropertyName = "Age", - TypeName = typeof(int).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "birthday", - PropertyName = "BirthDay", - TypeName = typeof(DateTime).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "name", - PropertyName = "Name", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - } - } - }; - var providerContext = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(providerContext, - documentContent, - expectedOutput, - expectedErrors: Enumerable.Empty()); - } - - public static IEnumerable IncompleteHelperBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var malformedErrorFormat = "Found a malformed '{0}' tag helper. Tag helpers must have a start and " + - "end tag or be self closing."; - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode( - "dynamic", - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(21, 0, 21)), - new SourceLocation(21, 0, 21)), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))), - HtmlAttributeValueStyle.DoubleQuotes), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - new MarkupTagHelperBlock("strong")), - blockFactory.MarkupTagBlock("
        ")), - new RazorError[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, malformedErrorFormat, "strong"), - absoluteIndex: 53, lineIndex: 0, columnIndex: 53, length: 6), - new RazorError( - string.Format(CultureInfo.InvariantCulture, malformedErrorFormat, "strong"), - absoluteIndex: 66, lineIndex: 0, columnIndex: 66, length: 6) - } - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("
        "), - new MarkupTagHelperBlock("p", - factory.Markup("Hello "), - new MarkupTagHelperBlock("strong", - factory.Markup("World")), - blockFactory.MarkupTagBlock("
        "))), - new RazorError[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, malformedErrorFormat, "p"), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 1) - } - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("
        "), - new MarkupTagHelperBlock("p", - factory.Markup("Hello "), - new MarkupTagHelperBlock("strong", - factory.Markup("World"), - blockFactory.MarkupTagBlock("
        ")))), - new RazorError[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, malformedErrorFormat, "p"), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, malformedErrorFormat, "strong"), - absoluteIndex: 15, lineIndex: 0, columnIndex: 15, length: 6) - } - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")) - }, - factory.Markup("Hello "), - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - factory.Markup("World")))), - new RazorError[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, malformedErrorFormat, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }; - } - } - - [Theory] - [MemberData(nameof(IncompleteHelperBlockData))] - public void TagHelperParseTreeRewriter_CreatesErrorForIncompleteTagHelper( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p"); - } - - - public static IEnumerable OddlySpacedBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup(" foo")), - new TagHelperAttributeNode( - "style", - new MarkupBlock( - factory.Markup(" color"), - factory.Markup(" :"), - factory.Markup(" red"), - factory.Markup(" ;"), - factory.Markup(" "))) - })) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup(" foo")), - new TagHelperAttributeNode( - "style", - new MarkupBlock( - factory.Markup(" color"), - factory.Markup(" :"), - factory.Markup(" red"), - factory.Markup(" ;"), - factory.Markup(" "))) - }, - factory.Markup("Hello World"))) - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "class", - new MarkupBlock(factory.Markup(" foo"), factory.Markup(" "))) - }, - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode( - "style", - new MarkupBlock(factory.Markup(" color:red;"), factory.Markup(" "))) - }, - factory.Markup("World"))) - }; - } - } - - [Theory] - [MemberData(nameof(OddlySpacedBlockData))] - public void TagHelperParseTreeRewriter_RewritesOddlySpacedTagHelperTagBlocks( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static IEnumerable ComplexAttributeTagHelperBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var dateTimeNowString = "@DateTime.Now"; - var dateTimeNow = new Func(index => - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(index, 0, index)), - new SourceLocation(index, 0, index)), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))))); - var doWhileString = "@do { var foo = bar; Foo foo++; } while (foo);"; - var doWhile = new Func(index => - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(index, 0, index)), - new SourceLocation(index, 0, index)), - new StatementBlock( - factory.CodeTransition(), - factory.Code("do { var foo = bar;").AsStatement(), - new MarkupBlock( - new MarkupTagBlock( - factory.MarkupTransition("")), - factory.Markup("Foo").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - factory.MarkupTransition(""))), - factory - .Code(" foo++; } while (foo);") - .AsStatement() - .Accepts(AcceptedCharacters.None))))); - - var currentFormattedString = "

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", dateTimeNow(10)), - new TagHelperAttributeNode("style", dateTimeNow(32), HtmlAttributeValueStyle.SingleQuotes) - })) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", doWhile(10)), - new TagHelperAttributeNode("style", doWhile(83), HtmlAttributeValueStyle.SingleQuotes) - })) - }; - - currentFormattedString = "

        Hello World

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", dateTimeNow(10)), - new TagHelperAttributeNode("style", dateTimeNow(32), HtmlAttributeValueStyle.SingleQuotes) - }, - factory.Markup("Hello World"))) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", doWhile(10)), - new TagHelperAttributeNode("style", doWhile(83), HtmlAttributeValueStyle.SingleQuotes) - }, - factory.Markup("Hello World"))) - }; - - currentFormattedString = "

        Hello

        World

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", dateTimeNow(10)) - }, - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("style", dateTimeNow(45), HtmlAttributeValueStyle.SingleQuotes) - }, - factory.Markup("World"))) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", doWhile(10)) - }, - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("style", doWhile(96), HtmlAttributeValueStyle.SingleQuotes) - }, - factory.Markup("World"))) - }; - - currentFormattedString = - "

        Hello World inside of strong tag

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", dateTimeNow(10)), - new TagHelperAttributeNode("style", dateTimeNow(32), HtmlAttributeValueStyle.SingleQuotes) - }, - factory.Markup("Hello World "), - new MarkupTagBlock( - factory.Markup("(" class=\"", 66, 0, 66), - suffix: new LocationTagged("\"", 87, 0, 87)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged(string.Empty, 74, 0, 74), 74, 0, 74), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup("inside of strong tag"), - blockFactory.MarkupTagBlock("
        "))) - }; - } - } - - [Theory] - [MemberData(nameof(ComplexAttributeTagHelperBlockData))] - public void TagHelperParseTreeRewriter_RewritesComplexAttributeTagHelperTagBlocks( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static IEnumerable ComplexTagHelperBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var dateTimeNowString = "@DateTime.Now"; - var dateTimeNow = new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)); - var doWhileString = "@do { var foo = bar;

        Foo

        foo++; } while (foo);"; - var doWhile = new StatementBlock( - factory.CodeTransition(), - factory.Code("do { var foo = bar;").AsStatement(), - new MarkupBlock( - factory.Markup(" "), - new MarkupTagHelperBlock("p", - factory.Markup("Foo")), - factory.Markup(" ").Accepts(AcceptedCharacters.None)), - factory.Code("foo++; } while (foo);") - .AsStatement() - .Accepts(AcceptedCharacters.None)); - - var currentFormattedString = "

        {0}

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", dateTimeNow)) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", doWhile)) - }; - - currentFormattedString = "

        Hello World {0}

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello World "), - dateTimeNow)) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello World "), - doWhile)) - }; - - currentFormattedString = "

        {0}

        {0}

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", dateTimeNow), - factory.Markup(" "), - new MarkupTagHelperBlock("p", dateTimeNow)) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", doWhile), - factory.Markup(" "), - new MarkupTagHelperBlock("p", doWhile)) - }; - - currentFormattedString = "

        Hello {0}inside of {0} strong tag

        "; - yield return new object[] - { - string.Format(currentFormattedString, dateTimeNowString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello "), - dateTimeNow, - blockFactory.MarkupTagBlock(""), - factory.Markup("inside of "), - dateTimeNow, - factory.Markup(" strong tag"), - blockFactory.MarkupTagBlock(""))) - }; - yield return new object[] - { - string.Format(currentFormattedString, doWhileString), - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello "), - doWhile, - blockFactory.MarkupTagBlock(""), - factory.Markup("inside of "), - doWhile, - factory.Markup(" strong tag"), - blockFactory.MarkupTagBlock(""))) - }; - } - } - - [Theory] - [MemberData(nameof(ComplexTagHelperBlockData))] - public void TagHelperParseTreeRewriter_RewritesComplexTagHelperTagBlocks( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - - public static TheoryData InvalidHtmlBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var dateTimeNow = new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)); - - return new TheoryData - { - { - "<<

        >>

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("p", - factory.Markup(">>"))) - }, - { - "<

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("p", TagMode.SelfClosing)) - }, - { - "< p />", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - new MarkupBlock( - factory.Markup(" p")), - factory.Markup(" />"))) - }, - { - "", - new MarkupBlock( - blockFactory.MarkupTagBlock("", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 1, 0, 1), - suffix: new LocationTagged("\"", 12, 0, 12)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("foo").With(new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 9, 0, 9), - value: new LocationTagged("foo", 9, 0, 9))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(" ")), - new MarkupTagHelperBlock("p", TagMode.SelfClosing)) - }, - { - "/>

        >", - new MarkupBlock( - blockFactory.MarkupTagBlock("")), - factory.Markup(">")) - }, - { - "/>

        >", - new MarkupBlock( - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")), - factory.Markup(">")) - }, - { - "@DateTime.Now/>

        >", - new MarkupBlock( - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")), - factory.Markup(">")) - }, - { - "

        @DateTime.Now / >

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock(""), - new MarkupTagHelperBlock("p", - dateTimeNow, - factory.Markup(" / >"), - blockFactory.MarkupTagBlock("")), - blockFactory.MarkupTagBlock("")) - }, - { - "

        < @DateTime.Now >

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagBlock( - factory.Markup("< "), - dateTimeNow, - factory.Markup(" >")), - blockFactory.MarkupTagBlock(""))) - } - }; - } - } - - [Theory] - [MemberData(nameof(InvalidHtmlBlockData))] - public void TagHelperParseTreeRewriter_AllowsInvalidHtml(string documentContent, MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static TheoryData EmptyAttributeTagHelperData - { - get - { - var factory = CreateDefaultSpanFactory(); - - // documentContent, expectedOutput - return new TheoryData - { - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", new MarkupBlock()) - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes) - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - // We expected a markup node here because attribute values without quotes can only ever - // be a single item, hence don't need to be enclosed by a block. - new TagHelperAttributeNode( - "class", - factory.Markup("").With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class1", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode( - "class2", - factory.Markup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - new TagHelperAttributeNode("class3", new MarkupBlock()), - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class1", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("class2", new MarkupBlock()), - new TagHelperAttributeNode( - "class3", - factory.Markup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - })) - }, - }; - } - } - - [Theory] - [MemberData(nameof(EmptyAttributeTagHelperData))] - public void Rewrite_UnderstandsEmptyAttributeTagHelpers(string documentContent, MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, new RazorError[0], "p"); - } - - public static TheoryData EmptyTagHelperBoundAttributeData - { - get - { - var factory = CreateDefaultSpanFactory(); - var emptyAttributeError = - "Attribute '{0}' on tag helper element '{1}' requires a value. Tag helper bound attributes of " + - "type '{2}' cannot be empty or contain only whitespace."; - var boolTypeName = typeof(bool).FullName; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", factory.CodeMarkup(" true"), HtmlAttributeValueStyle.SingleQuotes) - })), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", factory.CodeMarkup(" "), HtmlAttributeValueStyle.SingleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound", new MarkupBlock()) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5), - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 16, lineIndex: 0, columnIndex: 16, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", factory.CodeMarkup(" "), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound", factory.CodeMarkup(" ")) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5), - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", factory.CodeMarkup("true"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode( - "bound", - factory.CodeMarkup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 19, lineIndex: 0, columnIndex: 19, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "bound", - factory.CodeMarkup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - new TagHelperAttributeNode("name", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "bound", - factory.CodeMarkup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - new TagHelperAttributeNode("name", factory.Markup(" "), HtmlAttributeValueStyle.SingleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("bound", factory.CodeMarkup("true"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("name", factory.Markup("john"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode( - "bound", - factory.CodeMarkup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - new TagHelperAttributeNode( - "name", - factory.Markup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "bound", "myth", boolTypeName), - absoluteIndex: 31, lineIndex: 0, columnIndex: 31, length: 5), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("BouND", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "BouND", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("BOUND", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bOUnd", new MarkupBlock()) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "BOUND", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5), - new RazorError( - string.Format(emptyAttributeError, "bOUnd", "myth", boolTypeName), - absoluteIndex: 18, lineIndex: 0, columnIndex: 18, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - new List - { - new TagHelperAttributeNode( - "BOUND", - factory.CodeMarkup(string.Empty).With(SpanChunkGenerator.Null), - HtmlAttributeValueStyle.DoubleQuotes), - new TagHelperAttributeNode("nAMe", factory.Markup("john"), HtmlAttributeValueStyle.SingleQuotes) - })), - new[] - { - new RazorError( - string.Format(emptyAttributeError, "BOUND", "myth", boolTypeName), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 5) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - { - new TagHelperAttributeNode( - "bound", - new MarkupBlock( - new MarkupBlock( - factory.CodeMarkup(" "), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory.CSharpCodeMarkup("true") - .With(new ExpressionChunkGenerator()))), - factory.CodeMarkup(" ")), - HtmlAttributeValueStyle.SingleQuotes) - } - })), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "myth", - TagMode.SelfClosing, - attributes: new List - { - { - new TagHelperAttributeNode( - "bound", - new MarkupBlock( - new MarkupBlock( - factory.CodeMarkup(" "), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory.CSharpCodeMarkup("("), - factory.CSharpCodeMarkup("true") - .With(new ExpressionChunkGenerator()), - factory.CSharpCodeMarkup(")"))), - factory.CodeMarkup(" ")), - HtmlAttributeValueStyle.SingleQuotes) - } - })), - new RazorError[0] - }, - }; - } - } - - [Theory] - [MemberData(nameof(EmptyTagHelperBoundAttributeData))] - 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 - }, - new TagHelperAttributeDescriptor - { - Name = "name", - PropertyName = "Name", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - } - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors); - } - - public static IEnumerable ScriptBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("script", - factory.Markup("", - new MarkupBlock( - new MarkupTagHelperBlock("script", - factory.Markup("Hello World

        "))) - }; - yield return new object[] - { - "

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("script", - factory.Markup("Hel

        lo

        ")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("div", - factory.Markup("World")))) - }; - yield return new object[] - { - " ", - new MarkupBlock( - new MarkupTagHelperBlock("script", - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("script", - factory.Markup("World"))) - }; - yield return new object[] - { - " World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello "), - new MarkupTagHelperBlock("script", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }), - factory.Markup(" World"))) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello "), - new MarkupTagHelperBlock("script", - new List - { - new TagHelperAttributeNode( - "class", - new MarkupBlock( - new MarkupBlock( - factory.Markup("@").Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("foo@bar.com"))), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }), - factory.Markup(" World"))) - }; - } - } - - [Theory] - [MemberData(nameof(ScriptBlockData))] - public void TagHelperParseTreeRewriter_RewritesScriptTagHelpers( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p", "div", "script"); - } - - public static IEnumerable SelfClosingBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - })) - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - children: new SyntaxTreeNode[] - { - factory.Markup("Hello "), - new MarkupTagHelperBlock( - "p", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode( - "style", - factory.Markup("color:red;")) - }), - factory.Markup(" World") - })) - }; - yield return new object[] - { - "Hello

        World", - new MarkupBlock( - factory.Markup("Hello"), - new MarkupTagHelperBlock("p", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")) - }), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }), - factory.Markup("World")) - }; - } - } - - [Theory] - [MemberData(nameof(SelfClosingBlockData))] - public void TagHelperParseTreeRewriter_RewritesSelfClosingTagHelpers( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static IEnumerable QuotelessAttributeBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var dateTimeNow = new Func(index => - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(index, 0, index)), - new SourceLocation(index, 0, index)), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))))); - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("dynamic", dateTimeNow(21)), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - })) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("dynamic", dateTimeNow(21)), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - factory.Markup("Hello World"))) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("dynamic", dateTimeNow(21)), - new TagHelperAttributeNode( - "style", - new MarkupBlock( - factory.Markup("color"), - new MarkupBlock( - factory.Markup("@").Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup(":red;")), - HtmlAttributeValueStyle.DoubleQuotes) - }, - factory.Markup("Hello World"))) - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("dynamic", dateTimeNow(21)) - }, - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("style", factory.Markup("color:red;")), - new TagHelperAttributeNode("dynamic", dateTimeNow(73)) - }, - factory.Markup("World"))) - }; - yield return new object[] - { - "

        Hello World inside of strong tag

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("dynamic", dateTimeNow(21)), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - factory.Markup("Hello World "), - new MarkupTagBlock( - factory.Markup("(" class=\"", 71, 0, 71), - suffix: new LocationTagged("\"", 82, 0, 82)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("foo").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(string.Empty, 79, 0, 79), - value: new LocationTagged("foo", 79, 0, 79))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup("inside of strong tag"), - blockFactory.MarkupTagBlock("
        "))) - }; - } - } - - [Theory] - [MemberData(nameof(QuotelessAttributeBlockData))] - public void TagHelperParseTreeRewriter_RewritesTagHelpersWithQuotelessAttributes( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static IEnumerable PlainAttributeBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - })) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - factory.Markup("Hello World"))) - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")) - }, - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - factory.Markup("World"))) - }; - yield return new object[] - { - "

        Hello World inside of strong tag

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new List - { - new TagHelperAttributeNode("class", factory.Markup("foo")), - new TagHelperAttributeNode("style", factory.Markup("color:red;")) - }, - factory.Markup("Hello World "), - new MarkupTagBlock( - factory.Markup("(" class=\"", 53, 0, 53), - suffix: new LocationTagged("\"", 64, 0, 64)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("foo").With(new LiteralAttributeChunkGenerator(prefix: new LocationTagged(string.Empty, 61, 0, 61), - value: new LocationTagged("foo", 61, 0, 61))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup("inside of strong tag"), - blockFactory.MarkupTagBlock("
        "))) - }; - } - } - - [Theory] - [MemberData(nameof(PlainAttributeBlockData))] - public void TagHelperParseTreeRewriter_RewritesTagHelpersWithPlainAttributes( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static IEnumerable PlainBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p")) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello World"))) - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - factory.Markup("World"))) - }; - yield return new object[] - { - "

        Hello World inside of strong tag

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello World "), - blockFactory.MarkupTagBlock(""), - factory.Markup("inside of strong tag"), - blockFactory.MarkupTagBlock(""))) - }; - } - } - - [Theory] - [MemberData(nameof(PlainBlockData))] - public void TagHelperParseTreeRewriter_RewritesPlainTagHelperTagBlocks( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p"); - } - - public static TheoryData DataDashAttributeData_Document - { - get - { - var factory = CreateDefaultSpanFactory(); - var dateTimeNowString = "@DateTime.Now"; - var dateTimeNow = new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)); - - // documentContent, expectedOutput - return new TheoryData - { - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode( - "data-required", - new MarkupBlock(dateTimeNow), - HtmlAttributeValueStyle.SingleQuotes), - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("data-required", factory.Markup("value"), HtmlAttributeValueStyle.SingleQuotes), - })) - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode( - "data-required", - new MarkupBlock(factory.Markup("prefix "), dateTimeNow), - HtmlAttributeValueStyle.SingleQuotes), - })) - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode( - "data-required", - new MarkupBlock(dateTimeNow, factory.Markup(" suffix")), - HtmlAttributeValueStyle.SingleQuotes), - })) - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode( - "data-required", - new MarkupBlock( - factory.Markup("prefix "), - dateTimeNow, - factory.Markup(" suffix")), - HtmlAttributeValueStyle.SingleQuotes), - })) - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("pre-attribute", value: null, valueStyle: HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode( - "data-required", - new MarkupBlock( - factory.Markup("prefix "), - dateTimeNow, - factory.Markup(" suffix")), - HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("post-attribute", value: null, valueStyle: HtmlAttributeValueStyle.Minimized), - })) - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode( - "data-required", - new MarkupBlock( - dateTimeNow, - factory.Markup(" middle "), - dateTimeNow), - HtmlAttributeValueStyle.SingleQuotes), - })) - }, - }; - } - } - - public static TheoryData DataDashAttributeData_CSharpBlock - { - get - { - var factory = CreateDefaultSpanFactory(); - var documentData = DataDashAttributeData_Document; - Func, MarkupBlock> buildStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder(), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()); - }; - - foreach (var data in documentData) - { - data[0] = $"@{{{data[0]}}}"; - data[1] = buildStatementBlock(() => data[1] as MarkupBlock); - } - - return documentData; - } - } - - [Theory] - [MemberData(nameof(DataDashAttributeData_Document))] - [MemberData(nameof(DataDashAttributeData_CSharpBlock))] - public void Rewrite_GeneratesExpectedOutputForUnboundDataDashAttributes( - string documentContent, - MarkupBlock expectedOutput) - { - // Act & Assert - RunParseTreeRewriterTest(documentContent, expectedOutput, Enumerable.Empty(), "input"); - } - - public static TheoryData MinimizedAttributeData_Document - { - get - { - var factory = CreateDefaultSpanFactory(); - var noErrors = new RazorError[0]; - var errorFormat = "Attribute '{0}' on tag helper element '{1}' requires a value. Tag helper bound " + - "attributes of type '{2}' cannot be empty or contain only whitespace."; - var emptyKeyFormat = "The tag helper attribute '{0}' in element '{1}' is missing a key. The " + - "syntax is '<{1} {0}{{ key }}=\"value\">'."; - var stringType = typeof(string).FullName; - var intType = typeof(int).FullName; - var expressionString = "@DateTime.Now + 1"; - var expression = new Func(index => - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(index, 0, index)), - new SourceLocation(index, 0, index)), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - factory.Markup(" +") - .With(new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", index + 13, 0, index + 13), - value: new LocationTagged("+", index + 14, 0, index + 14))), - factory.Markup(" 1") - .With(new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", index + 15, 0, index + 15), - value: new LocationTagged("1", index + 16, 0, index + 16))))); - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - })), - noErrors - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-string", "p", stringType), 3, 0, 3, 12) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-string", "input", stringType), 7, 0, 7, 21) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-int", "input", intType), 7, 0, 7, 18) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] { new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 3, 0, 3, 9) } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("int-dictionary", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "int-dictionary", "input", typeof(IDictionary).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 14), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("string-dictionary", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "string-dictionary", "input", typeof(IDictionary).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 17), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("int-prefix-", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "int-prefix-", "input", typeof(int).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 11), - new RazorError( - string.Format(emptyKeyFormat, "int-prefix-", "input"), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 11), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("string-prefix-", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "string-prefix-", "input", typeof(string).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 14), - new RazorError( - string.Format(emptyKeyFormat, "string-prefix-", "input"), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 14), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("int-prefix-value", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "int-prefix-value", "input", typeof(int).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 16), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("string-prefix-value", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "string-prefix-value", "input", typeof(string).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 19), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("int-prefix-value", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "int-prefix-value", "input", typeof(int).FullName), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 16), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("string-prefix-value", new MarkupBlock(), HtmlAttributeValueStyle.SingleQuotes), - })), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("int-prefix-value", factory.CodeMarkup("3"), HtmlAttributeValueStyle.SingleQuotes), - })), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode( - "string-prefix-value", - new MarkupBlock( - factory.Markup("some"), - factory.Markup(" string")), - HtmlAttributeValueStyle.SingleQuotes), - })), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-string", "input", stringType), - absoluteIndex: 24, - lineIndex: 0, - columnIndex: 24, - length: 21) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 3, 0, 3, 9), - new RazorError(string.Format(errorFormat, "bound-string", "p", stringType), 13, 0, 13, 12), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-int", "input", intType), 7, 0, 7, 18), - new RazorError( - string.Format(errorFormat, "bound-required-string", "input", stringType), - absoluteIndex: 43, - lineIndex: 0, - columnIndex: 43, - length: 21) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 3, 0, 3, 9), - new RazorError(string.Format(errorFormat, "bound-string", "p", stringType), 13, 0, 13, 12), - new RazorError(string.Format(errorFormat, "bound-string", "p", stringType), 26, 0, 26, 12), - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - })), - noErrors - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-string", "p", stringType), - absoluteIndex: 3, - lineIndex: 0, - columnIndex: 3, - length: 12) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - })), - noErrors - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-string", "p", stringType), - absoluteIndex: 15, - lineIndex: 0, - columnIndex: 15, - length: 12) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-string", "input", stringType), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 21) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-string", "input", stringType), - absoluteIndex: 19, - lineIndex: 0, - columnIndex: 19, - length: 21) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-int", "input", intType), 7, 0, 7, 18) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 3, 0, 3, 9) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-required-int", "input", intType), 19, 0, 19, 18) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("class", factory.Markup("btn"), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 15, 0, 15, 9) - } - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("class", expression(14), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-int", "input", intType), 33, 0, 33, 18) - } - }, - { - $"

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("class", expression(10), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 29, 0, 29, 9) - } - }, - { - $"", - new MarkupBlock( - new MarkupTagHelperBlock( - "input", - TagMode.SelfClosing, - attributes: new List() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", expression(36), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", expression(86), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormat, "bound-required-int", "input", intType), 10, 0, 10, 18), - new RazorError( - string.Format(errorFormat, "bound-required-string", "input", stringType), - absoluteIndex: 57, - lineIndex: 0, - columnIndex: 57, - length: 21), - } - }, - { - $"

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", expression(23), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("class", expression(64), HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError(string.Format(errorFormat, "bound-int", "p", intType), 6, 0, 6, 9), - new RazorError(string.Format(errorFormat, "bound-string", "p", stringType), 44, 0, 44, 12), - new RazorError(string.Format(errorFormat, "bound-string", "p", stringType), 84, 0, 84, 12), - } - }, - }; - } - } - - public static TheoryData MinimizedAttributeData_CSharpBlock - { - get - { - var factory = CreateDefaultSpanFactory(); - var documentData = MinimizedAttributeData_Document; - Func, MarkupBlock> buildStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder(), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()); - }; - Action updateDynamicChunkGenerators = (block) => - { - var tagHelperBlock = block.Children.First() as MarkupTagHelperBlock; - - for (var i = 0; i < tagHelperBlock.Attributes.Count; i++) - { - var attribute = tagHelperBlock.Attributes[i]; - var holderBlock = attribute.Value as Block; - - if (holderBlock == null) - { - continue; - } - - var valueBlock = holderBlock.Children.FirstOrDefault() as Block; - if (valueBlock != null) - { - var chunkGenerator = valueBlock.ChunkGenerator as DynamicAttributeBlockChunkGenerator; - - if (chunkGenerator != null) - { - var blockBuilder = new BlockBuilder(holderBlock); - var expressionBlockBuilder = new BlockBuilder(valueBlock); - var newChunkGenerator = new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - chunkGenerator.Prefix.Value, - new SourceLocation( - chunkGenerator.Prefix.Location.AbsoluteIndex + 2, - chunkGenerator.Prefix.Location.LineIndex, - chunkGenerator.Prefix.Location.CharacterIndex + 2)), - new SourceLocation( - chunkGenerator.ValueStart.AbsoluteIndex + 2, - chunkGenerator.ValueStart.LineIndex, - chunkGenerator.ValueStart.CharacterIndex + 2)); - - expressionBlockBuilder.ChunkGenerator = newChunkGenerator; - blockBuilder.Children[0] = expressionBlockBuilder.Build(); - - for (var j = 1; j < blockBuilder.Children.Count; j++) - { - var span = blockBuilder.Children[j] as Span; - if (span != null) - { - var literalChunkGenerator = - span.ChunkGenerator as LiteralAttributeChunkGenerator; - - var spanBuilder = new SpanBuilder(span); - spanBuilder.ChunkGenerator = new LiteralAttributeChunkGenerator( - prefix: new LocationTagged( - literalChunkGenerator.Prefix.Value, - new SourceLocation( - literalChunkGenerator.Prefix.Location.AbsoluteIndex + 2, - literalChunkGenerator.Prefix.Location.LineIndex, - literalChunkGenerator.Prefix.Location.CharacterIndex + 2)), - value: new LocationTagged( - literalChunkGenerator.Value.Value, - new SourceLocation( - literalChunkGenerator.Value.Location.AbsoluteIndex + 2, - literalChunkGenerator.Value.Location.LineIndex, - literalChunkGenerator.Value.Location.CharacterIndex + 2))); - - blockBuilder.Children[j] = spanBuilder.Build(); - } - } - - tagHelperBlock.Attributes[i] = new TagHelperAttributeNode( - attribute.Name, - blockBuilder.Build(), - attribute.ValueStyle); - } - } - } - }; - - foreach (var data in documentData) - { - data[0] = $"@{{{data[0]}}}"; - - updateDynamicChunkGenerators(data[1] as MarkupBlock); - - data[1] = buildStatementBlock(() => data[1] as MarkupBlock); - - var errors = data[2] as RazorError[]; - - for (var i = 0; i < errors.Length; i++) - { - var error = errors[i]; - error.Location = SourceLocation.Advance(error.Location, "@{"); - } - } - - return documentData; - } - } - - public static TheoryData MinimizedAttributeData_PartialTags - { - get - { - var factory = CreateDefaultSpanFactory(); - var noErrors = new RazorError[0]; - var errorFormatUnclosed = "Found a malformed '{0}' tag helper. Tag helpers must have a start and " + - "end tag or be self closing."; - var errorFormatNoCloseAngle = "Missing close angle for tag helper '{0}'."; - var errorFormatNoValue = "Attribute '{0}' on tag helper element '{1}' requires a value. Tag helper bound " + - "attributes of type '{2}' cannot be empty or contain only whitespace."; - var stringType = typeof(string).FullName; - var intType = typeof(int).FullName; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "() - { - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatUnclosed, "input"), - new SourceLocation(1, 0, 1), - length: 5), - } - }, - { - "() - { - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatUnclosed, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatNoValue, "bound-required-string", "input", stringType), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 21), - } - }, - { - "() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatUnclosed, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatNoValue, "bound-required-int", "input", intType), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 18), - } - }, - { - "() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatUnclosed, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatNoValue, "bound-required-int", "input", intType), - absoluteIndex: 7, - lineIndex: 0, - columnIndex: 7, - length: 18), - new RazorError( - string.Format(errorFormatNoValue, "bound-required-string", "input", stringType), - absoluteIndex: 43, - lineIndex: 0, - columnIndex: 43, - length: 21), - } - }, - { - "

        () - { - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(errorFormatNoValue, "bound-string", "p", stringType), 3, 0, 3, 12), - } - }, - { - "

        () - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError(string.Format(errorFormatNoValue, "bound-int", "p", intType), 3, 0, 3, 9), - } - }, - { - "

        () - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - })), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError(string.Format(errorFormatNoValue, "bound-int", "p", intType), 3, 0, 3, 9), - new RazorError( - string.Format(errorFormatNoValue, "bound-string", "p", stringType), 13, 0, 13, 12), - } - }, - { - "() - { - new TagHelperAttributeNode("bound-required-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("unbound-required", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-required-string", null, HtmlAttributeValueStyle.Minimized), - }, - children: new MarkupTagHelperBlock( - "p", - TagMode.StartTagAndEndTag, - attributes: new List() - { - new TagHelperAttributeNode("bound-int", null, HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode("bound-string", null, HtmlAttributeValueStyle.Minimized), - }))), - new[] - { - new RazorError( - string.Format(errorFormatNoCloseAngle, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatUnclosed, "input"), - new SourceLocation(1, 0, 1), - length: 5), - new RazorError( - string.Format(errorFormatNoValue, "bound-required-int", "input", intType), 7, 0, 7, 18), - new RazorError( - string.Format(errorFormatNoValue, "bound-required-string", "input", stringType), - absoluteIndex: 43, - lineIndex: 0, - columnIndex: 43, - length: 21), - new RazorError( - string.Format(errorFormatNoCloseAngle, "p"), - new SourceLocation(65, 0, 65), - length: 1), - new RazorError( - string.Format(errorFormatUnclosed, "p"), - new SourceLocation(65, 0, 65), - length: 1), - new RazorError(string.Format(errorFormatNoValue, "bound-int", "p", intType), 67, 0, 67, 9), - new RazorError( - string.Format(errorFormatNoValue, "bound-string", "p", stringType), - absoluteIndex: 77, - lineIndex: 0, - columnIndex: 77, - length: 12), - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(MinimizedAttributeData_Document))] - [MemberData(nameof(MinimizedAttributeData_CSharpBlock))] - [MemberData(nameof(MinimizedAttributeData_PartialTags))] - 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 - { - Name = "bound-required-string", - PropertyName = "BoundRequiredString", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "unbound-required" } - } - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper1", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "bound-required-string", - PropertyName = "BoundRequiredString", - TypeName = typeof(string).FullName, - IsStringProperty = true - } - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "bound-required-string" } - } - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "bound-required-int", - PropertyName = "BoundRequiredInt", - TypeName = typeof(int).FullName - } - }, - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "bound-required-int" } - } - }, - new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper3", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "int-dictionary", - PropertyName ="DictionaryOfIntProperty", - TypeName = typeof(IDictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "string-dictionary", - PropertyName = "DictionaryOfStringProperty", - TypeName = typeof(IDictionary).FullName - }, - new TagHelperAttributeDescriptor - { - Name = "int-prefix-", - PropertyName = "DictionaryOfIntProperty", - TypeName = typeof(int).FullName, - IsIndexer = true - }, - new TagHelperAttributeDescriptor - { - Name = "string-prefix-", - PropertyName = "DictionaryOfStringProperty", - TypeName = typeof(string).FullName, - IsIndexer = true, - IsStringProperty = true - } - } - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "bound-string", - PropertyName = "BoundRequiredString", - TypeName = typeof(string).FullName, - IsStringProperty = true - }, - new TagHelperAttributeDescriptor - { - Name = "bound-int", - PropertyName = "BoundRequiredString", - TypeName = typeof(int).FullName - } - } - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperParseTreeRewriterTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperParseTreeRewriterTest.cs deleted file mode 100644 index d329f1ec79..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperParseTreeRewriterTest.cs +++ /dev/null @@ -1,4513 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Test.Parser.TagHelpers.Internal; -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.TagHelpers.Internal -{ - public class TagHelperParseTreeRewriterTest : TagHelperRewritingTestBase - { - public static TheoryData GetAttributeNameValuePairsData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - Func> kvp = - (key, value) => new KeyValuePair(key, value); - var empty = Enumerable.Empty>(); - var csharp = TagHelperParseTreeRewriter.InvalidAttributeValueMarker; - - // documentContent, expectedPairs - return new TheoryData>> - { - { "", empty }, - { "", empty }, - { "", new[] { kvp("href", csharp) } }, - { "", new[] { kvp("href", $"prefix{csharp} suffix") } }, - { "", new[] { kvp("href", "~/home") } }, - { "", new[] { kvp("href", "~/home"), kvp("", "") } }, - { - "", - new[] { kvp("href", $"{csharp}::0"), kvp("class", "btn btn-success"), kvp("random", "") } - }, - { "", new[] { kvp("href", "") } }, - { "> expectedPairs) - { - // Arrange - var errorSink = new ErrorSink(); - var parseResult = ParseDocument(documentContent, errorSink); - var document = parseResult.Document; - var rewriters = RazorParser.GetDefaultRewriters(new HtmlMarkupParser()); - var rewritingContext = new RewritingContext(document, errorSink); - foreach (var rewriter in rewriters) - { - rewriter.Rewrite(rewritingContext); - } - var block = rewritingContext.SyntaxTree.Children.First(); - var parseTreeRewriter = new TagHelperParseTreeRewriter(provider: null); - - // Assert - Guard - var tagBlock = Assert.IsType(block); - Assert.Equal(BlockType.Tag, tagBlock.Type); - Assert.Empty(errorSink.Errors); - - // Act - var pairs = parseTreeRewriter.GetAttributeNameValuePairs(tagBlock); - - // Assert - Assert.Equal(expectedPairs, pairs); - } - - public static TheoryData PartialRequiredParentData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - Func errorFormatUnclosed = (location, tagName) => - new RazorError( - $"Found a malformed '{tagName}' tag helper. Tag helpers must have a start and end tag or be " + - "self closing.", - new SourceLocation(location, 0, location), - tagName.Length); - Func errorFormatNoCloseAngle = (location, tagName) => - new RazorError( - $"Missing close angle for tag helper '{tagName}'.", - new SourceLocation(location, 0, location), - tagName.Length); - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong"))), - new[] { errorFormatUnclosed(1, "p"), errorFormatUnclosed(4, "strong") } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong"))), - new[] { errorFormatUnclosed(1, "p") } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong")), - blockFactory.MarkupTagBlock("")), - new[] { errorFormatUnclosed(4, "strong") } - }, - { - "<

        <

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("strong", - blockFactory.MarkupTagBlock(""))), - new[] { errorFormatNoCloseAngle(17, "strong"), errorFormatUnclosed(25, "strong") } - }, - { - "<

        <

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("strong", - blockFactory.MarkupTagBlock(""))), - new[] { errorFormatUnclosed(26, "strong") } - }, - - { - "<

        <

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("<"), - new MarkupTagHelperBlock("custom", - blockFactory.MarkupTagBlock(""))), - new[] { errorFormatUnclosed(27, "custom") } - }, - }; - } - } - - [Theory] - [MemberData(nameof(PartialRequiredParentData))] - 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); - } - - public static TheoryData NestedVoidSelfClosingRequiredParentData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - // documentContent, expectedOutput - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - new MarkupTagHelperBlock("strong"))) - }, - { - "


        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("
        "), - new MarkupTagHelperBlock("strong"))) - }, - { - "


        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("
        ")), - new MarkupTagHelperBlock("strong"))) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("input", TagMode.StartTagOnly), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("input", TagMode.SelfClosing), - new MarkupTagHelperBlock("strong", TagMode.SelfClosing))) - }, - { - "


        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("
        "), - new MarkupTagHelperBlock("strong", TagMode.SelfClosing))) - }, - { - "


        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("
        ")), - new MarkupTagHelperBlock("strong", TagMode.SelfClosing))) - }, - }; - } - } - - [Theory] - [MemberData(nameof(NestedVoidSelfClosingRequiredParentData))] - public void Rewrite_UnderstandsNestedVoidSelfClosingRequiredParent( - string documentContent, - MarkupBlock expectedOutput) - { - // Arrange - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "input", - TypeName = "InputTagHelper", - AssemblyName = "SomeAssembly", - TagStructure = TagStructure.WithoutEndTag, - }, - new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly", - RequiredParent = "p", - }, - new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly", - RequiredParent = "input", - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly" - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - public static TheoryData NestedRequiredParentData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - // documentContent, expectedOutput - return new TheoryData - { - { - "", - new MarkupBlock( - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong"))) - }, - { - "
        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("
        "), - new MarkupTagHelperBlock("strong"), - blockFactory.MarkupTagBlock("
        ")) - }, - { - "", - new MarkupBlock( - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("")))) - }, - }; - } - } - - [Theory] - [MemberData(nameof(NestedRequiredParentData))] - public void Rewrite_UnderstandsNestedRequiredParent(string documentContent, MarkupBlock expectedOutput) - { - // 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 = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly" - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - [Fact] - public void Rewrite_UnderstandsTagHelperPrefixAndAllowedChildren() - { - // Arrange - var documentContent = ""; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("th:p", - new MarkupTagHelperBlock("th:strong"))); - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "strong" }, - Prefix = "th:" - }, - new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly", - Prefix = "th:" - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData( - descriptorProvider, - documentContent, - expectedOutput, - expectedErrors: Enumerable.Empty()); - } - - public static TheoryData InvalidHtmlScriptBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - blockFactory.MarkupTagBlock("")) - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" types='", 7, 0, 7), - suffix: new LocationTagged("'", 24, 0, 24)), - factory.Markup(" types='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 15, 0, 15), - value: new LocationTagged("text/html", 15, 0, 15))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup(""), - blockFactory.MarkupTagBlock("")) - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" type='", 7, 0, 7), - suffix: new LocationTagged("'", 31, 0, 31)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 14, 0, 14), - value: new LocationTagged("text/html", 14, 0, 14))), - factory.Markup(" invalid").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 23, 0, 23), - value: new LocationTagged("invalid", 24, 0, 24))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup(""), - blockFactory.MarkupTagBlock("")) - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" type='", 7, 0, 7), - suffix: new LocationTagged("'", 23, 0, 23)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/ng-*").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 14, 0, 14), - value: new LocationTagged("text/ng-*", 14, 0, 14))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "type", - prefix: new LocationTagged(" type='", 24, 0, 24), - suffix: new LocationTagged("'", 40, 0, 40)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 31, 0, 31), - value: new LocationTagged("text/html", 31, 0, 31))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup(""), - blockFactory.MarkupTagBlock("")) - }, - }; - } - } - - [Theory] - [MemberData(nameof(InvalidHtmlScriptBlockData))] - public void TagHelperParseTreeRewriter_DoesNotUnderstandTagHelpersInInvalidHtmlTypedScriptTags( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "input"); - } - - public static TheoryData HtmlScriptBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" type='", 7, 0, 7), - suffix: new LocationTagged("'", 23, 0, 23)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 14, 0, 14), - value: new LocationTagged("text/html", 14, 0, 14))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - new MarkupTagHelperBlock("input", TagMode.SelfClosing), - blockFactory.MarkupTagBlock("")) - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" id='", 7, 0, 7), - suffix: new LocationTagged("'", 21, 0, 21)), - factory.Markup(" id='").With(SpanChunkGenerator.Null), - factory.Markup("scriptTag").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 12, 0, 12), - value: new LocationTagged("scriptTag", 12, 0, 12))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "type", - prefix: new LocationTagged(" type='", 22, 0, 22), - suffix: new LocationTagged("'", 38, 0, 38)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 29, 0, 29), - value: new LocationTagged("text/html", 29, 0, 29))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 39, 0, 39), - suffix: new LocationTagged("'", 56, 0, 56)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("something").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 47, 0, 47), - value: new LocationTagged("something", 47, 0, 47))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - new MarkupTagHelperBlock("input", TagMode.SelfClosing), - blockFactory.MarkupTagBlock("")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" type='", 7, 0, 7), - suffix: new LocationTagged("'", 23, 0, 23)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 14, 0, 14), - value: new LocationTagged("text/html", 14, 0, 14))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - new MarkupTagHelperBlock("p", - new MarkupTagBlock( - factory.Markup("(" type='", 35, 0, 35), - suffix: new LocationTagged("'", 51, 0, 51)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 42, 0, 42), - value: new LocationTagged("text/html", 42, 0, 42))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - new MarkupTagHelperBlock("input", TagMode.SelfClosing), - blockFactory.MarkupTagBlock("")), - blockFactory.MarkupTagBlock("")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" type='", 7, 0, 7), - suffix: new LocationTagged("'", 23, 0, 23)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 14, 0, 14), - value: new LocationTagged("text/html", 14, 0, 14))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - new MarkupTagHelperBlock("p", - new MarkupTagBlock( - factory.Markup("(" type='", 35, 0, 35), - suffix: new LocationTagged("'", 52, 0, 52)), - factory.Markup(" type='").With(SpanChunkGenerator.Null), - factory.Markup("text/").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 42, 0, 42), - value: new LocationTagged("text/", 42, 0, 42))), - factory.Markup(" html").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 47, 0, 47), - value: new LocationTagged("html", 48, 0, 48))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup(""), - blockFactory.MarkupTagBlock("")), - blockFactory.MarkupTagBlock("")) - }, - }; - } - } - - [Theory] - [MemberData(nameof(HtmlScriptBlockData))] - public void TagHelperParseTreeRewriter_UnderstandsTagHelpersInHtmlTypedScriptTags( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p", "input"); - } - - [Fact] - public void Rewrite_CanHandleInvalidChildrenWithWhitespace() - { - // Arrange - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var documentContent = $"

        {Environment.NewLine} {Environment.NewLine} Hello" + - $"{Environment.NewLine} {Environment.NewLine}

        "; - var newLineLength = Environment.NewLine.Length; - var expectedErrors = new[] { - new RazorError( - RazorResources.FormatTagHelperParseTreeRewriter_InvalidNestedTag("strong", "p", "br"), - absoluteIndex: 8 + newLineLength, - lineIndex: 1, - columnIndex: 5, - length: 6), - }; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup(Environment.NewLine + " "), - blockFactory.MarkupTagBlock(""), - factory.Markup(Environment.NewLine + " Hello" + Environment.NewLine + " "), - blockFactory.MarkupTagBlock(""), - factory.Markup(Environment.NewLine))); - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "br" }, - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors); - } - - [Fact] - public void Rewrite_RecoversWhenRequiredAttributeMismatchAndRestrictedChildren() - { - // Arrange - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var documentContent = ""; - - var expectedErrors = new[] { - new RazorError( - RazorResources.FormatTagHelperParseTreeRewriter_InvalidNestedTag("strong", "strong", "br"), - absoluteIndex: 18, - lineIndex: 0, - columnIndex: 18, - length: 6) - }; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("strong", - new List - { - new TagHelperAttributeNode("required", null, HtmlAttributeValueStyle.Minimized) - }, - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""))); - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "required" } }, - AllowedChildren = new[] { "br" } - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors); - } - - [Fact] - public void Rewrite_CanHandleMultipleTagHelpersWithAllowedChildren_OneNull() - { - // Arrange - var factory = CreateDefaultSpanFactory(); - var documentContent = "

        Hello World

        "; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", - factory.Markup("Hello World")), - new MarkupTagHelperBlock("br", TagMode.StartTagOnly))); - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper1", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "strong", "br" } - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper2", - AssemblyName = "SomeAssembly" - }, - new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly" - }, - new TagHelperDescriptor - { - TagName = "br", - TypeName = "BRTagHelper", - AssemblyName = "SomeAssembly", - TagStructure = TagStructure.WithoutEndTag - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - [Fact] - public void Rewrite_CanHandleMultipleTagHelpersWithAllowedChildren() - { - // Arrange - var factory = CreateDefaultSpanFactory(); - var documentContent = "

        Hello World

        "; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", - factory.Markup("Hello World")), - new MarkupTagHelperBlock("br", TagMode.StartTagOnly))); - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper1", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "strong" } - }, - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper2", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "br" } - }, - new TagHelperDescriptor - { - TagName = "strong", - TypeName = "StrongTagHelper", - AssemblyName = "SomeAssembly" - }, - new TagHelperDescriptor - { - TagName = "br", - TypeName = "BRTagHelper", - AssemblyName = "SomeAssembly", - TagStructure = TagStructure.WithoutEndTag - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - public static TheoryData AllowedChildrenData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - Func nestedTagError = - (childName, parentName, allowed, location, length) => new RazorError( - RazorResources.FormatTagHelperParseTreeRewriter_InvalidNestedTag( - childName, - parentName, - allowed), - absoluteIndex: location, - lineIndex: 0, - columnIndex: location, - length: length); - Func nestedContentError = - (parentName, allowed, location, length) => new RazorError( - RazorResources.FormatTagHelperParseTreeRewriter_CannotHaveNonTagContent(parentName, allowed), - absoluteIndex: location, - lineIndex: 0, - columnIndex: location, - length: length); - - return new TheoryData, MarkupBlock, RazorError[]> - { - { - "


        ", - new[] { "br" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("br", TagMode.SelfClosing))), - new RazorError[0] - }, - { - $"

        {Environment.NewLine}
        {Environment.NewLine}

        ", - new[] { "br" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup(Environment.NewLine), - new MarkupTagHelperBlock("br", TagMode.SelfClosing), - factory.Markup(Environment.NewLine))), - new RazorError[0] - }, - { - "


        ", - new[] { "strong" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("br", TagMode.StartTagOnly))), - new[] { nestedTagError("br", "p", "strong", 4, 2) } - }, - { - "

        Hello

        ", - new[] { "strong" }, - new MarkupBlock(new MarkupTagHelperBlock("p", factory.Markup("Hello"))), - new[] { nestedContentError("p", "strong", 3, 5) } - }, - { - "


        ", - new[] { "br", "strong" }, - new MarkupBlock(new MarkupTagHelperBlock("p", blockFactory.MarkupTagBlock("
        "))), - new[] { nestedTagError("hr", "p", "br, strong", 4, 2) } - }, - { - "


        Hello

        ", - new[] { "strong" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("br", TagMode.StartTagOnly), - factory.Markup("Hello"))), - new[] { nestedTagError("br", "p", "strong", 4, 2), nestedContentError("p", "strong", 7, 5) } - }, - { - "

        Title:
        Something

        ", - new[] { "strong" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", factory.Markup("Title:")), - new MarkupTagHelperBlock("br", TagMode.SelfClosing), - factory.Markup("Something"))), - new[] - { - nestedContentError("strong", "strong", 11, 6), - nestedTagError("br", "p", "strong", 27, 2), - nestedContentError("p", "strong", 32, 9), - } - }, - { - "

        Title:
        Something

        ", - new[] { "strong", "br" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", factory.Markup("Title:")), - new MarkupTagHelperBlock("br", TagMode.SelfClosing), - factory.Markup("Something"))), - new[] - { - nestedContentError("strong", "strong, br", 11, 6), - nestedContentError("p", "strong, br", 32, 9), - } - }, - { - "

        Title:
        Something

        ", - new[] { "strong", "br" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup(" "), - new MarkupTagHelperBlock("strong", factory.Markup("Title:")), - factory.Markup(" "), - new MarkupTagHelperBlock("br", TagMode.SelfClosing), - factory.Markup(" Something"))), - new[] - { - nestedContentError("strong", "strong, br", 13, 6), - nestedContentError("p", "strong, br", 38, 9), - } - }, - { - "

        Title:
        A Very Cool

        Something

        ", - new[] { "strong" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", - factory.Markup("Title:"), - new MarkupTagHelperBlock("br", TagMode.StartTagOnly), - blockFactory.MarkupTagBlock(""), - factory.Markup("A Very Cool"), - blockFactory.MarkupTagBlock("")), - new MarkupTagHelperBlock("br", TagMode.SelfClosing), - factory.Markup("Something"))), - new[] - { - nestedContentError("strong", "strong", 11, 6), - nestedTagError("br", "strong", "strong", 18, 2), - nestedTagError("em", "strong", "strong", 22, 2), - nestedTagError("br", "p", "strong", 51, 2), - nestedContentError("p", "strong", 56, 9) - } - }, - { - "

        Title:
        A Very Cool

        Something

        ", - new[] { "custom" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock(""), - factory.Markup("Title:"), - new MarkupTagHelperBlock("br", TagMode.StartTagOnly), - blockFactory.MarkupTagBlock(""), - factory.Markup("A Very Cool"), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - new MarkupTagHelperBlock("br", TagMode.SelfClosing), - factory.Markup("Something"))), - new[] - { - nestedTagError("br", "p", "custom", 51, 2), - nestedContentError("p", "custom", 56, 9) - } - }, - { - "

        ", - new[] { "custom" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("<

        ", - new[] { "custom" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock("<"))), - new[] - { - nestedContentError("p", "custom", 3, 1), - } - }, - { - "


        :Hello:

        ", - new[] { "custom", "strong" }, - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock(""), - new MarkupTagHelperBlock("br", TagMode.StartTagOnly), - factory.Markup(":"), - new MarkupTagHelperBlock("strong", - new MarkupTagHelperBlock("strong", - factory.Markup("Hello"))), - factory.Markup(":"), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""))), - new[] - { - nestedContentError("strong", "custom, strong", 32, 5), - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(AllowedChildrenData))] - public void Rewrite_UnderstandsAllowedChildren( - string documentContent, - IEnumerable 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); - } - - [Fact] - public void Rewrite_UnderstandsNullTagNameWithAllowedChildrenForCatchAll() - { - // Arrange - var documentContent = "

        "; - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "custom" }, - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "CatchAllTagHelper", - AssemblyName = "SomeAssembly", - } - }; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("p", - BlockFactory.MarkupTagBlock(""; - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - AssemblyName = "SomeAssembly", - AllowedChildren = new[] { "custom" }, - Prefix = "th:", - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "CatchAllTagHelper", - AssemblyName = "SomeAssembly", - Prefix = "th:", - } - }; - var expectedOutput = new MarkupBlock( - new MarkupTagHelperBlock("th:p", - BlockFactory.MarkupTagBlock(""; - var expectedOutput = new MarkupBlock(new MarkupTagHelperBlock("input", TagMode.StartTagOnly)); - 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 RazorError[0]); - } - - [Fact] - 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 = ""; - var expectedOutput = new MarkupBlock(blockFactory.MarkupTagBlock("")); - 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 }); - } - - [Fact] - 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 = ""; - 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 }); - } - - public static TheoryData RequiredAttributeData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var dateTimeNow = new Func(index => - new MarkupBlock( - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged( - string.Empty, - new SourceLocation(index, 0, index)), - new SourceLocation(index, 0, index)), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))))); - - // documentContent, expectedOutput - return new TheoryData - { - { - "

        ", - new MarkupBlock(blockFactory.MarkupTagBlock("

        ")) - }, - { - "

        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        ")) - }, - { - "
        ", - new MarkupBlock(blockFactory.MarkupTagBlock("
        ")) - }, - { - "
        ", - new MarkupBlock( - blockFactory.MarkupTagBlock("
        "), - blockFactory.MarkupTagBlock("
        ")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", dateTimeNow(10)) - })) - }, - { - "

        words and spaces

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: factory.Markup("words and spaces"))) - }, - { - "

        words and spaces

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", dateTimeNow(10)) - }, - children: factory.Markup("words and spaces"))) - }, - { - "

        wordsandspaces

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new SyntaxTreeNode[] - { - factory.Markup("words"), - blockFactory.MarkupTagBlock(""), - factory.Markup("and"), - blockFactory.MarkupTagBlock(""), - factory.Markup("spaces") - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("catchAll", dateTimeNow(18)) - })) - }, - { - "words and spaces", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: factory.Markup("words and spaces"))) - }, - { - "words and spaces", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", dateTimeNow(18)) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" class=\"", 4, 0, 4), - suffix: new LocationTagged("\"", 15, 0, 15)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 12, 0, 12), - value: new LocationTagged("btn", 12, 0, 12))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(" />"))) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("(" class=\"", 4, 0, 4), - suffix: new LocationTagged("\"", 15, 0, 15)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 12, 0, 12), - value: new LocationTagged("btn", 12, 0, 12))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - blockFactory.MarkupTagBlock("
        ")) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("notRequired", factory.Markup("a")), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("notRequired", dateTimeNow(16)), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })) - }, - { - "

        words and spaces

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("notRequired", factory.Markup("a")), - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("style", dateTimeNow(12)), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })) - }, - { - "
        words and spaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        words and spaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", dateTimeNow(12)), - new TagHelperAttributeNode("class", dateTimeNow(34)) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        wordsandspaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new SyntaxTreeNode[] - { - factory.Markup("words"), - blockFactory.MarkupTagBlock(""), - factory.Markup("and"), - blockFactory.MarkupTagBlock(""), - factory.Markup("spaces") - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")), - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - })) - }, - { - "

        words and spaces

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")), - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")), - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - })) - }, - { - "
        words and spaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")), - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        words and spaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")), - new TagHelperAttributeNode("catchAll", - new MarkupBlock( - new MarkupBlock( - factory.Markup("@").Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("hi"))), - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        words and " + - "spaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", dateTimeNow(12)), - new TagHelperAttributeNode("class", dateTimeNow(34)), - new TagHelperAttributeNode("catchAll", dateTimeNow(59)) - }, - children: factory.Markup("words and spaces"))) - }, - { - "
        wordsandspaces
        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "div", - attributes: new List - { - new TagHelperAttributeNode("style", new MarkupBlock()), - new TagHelperAttributeNode("class", factory.Markup("btn")), - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new SyntaxTreeNode[] - { - factory.Markup("words"), - blockFactory.MarkupTagBlock(""), - factory.Markup("and"), - blockFactory.MarkupTagBlock(""), - factory.Markup("spaces") - })) - }, - }; - } - } - - [Theory] - [MemberData(nameof(RequiredAttributeData))] - public void Rewrite_RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly( - string documentContent, - MarkupBlock expectedOutput) - { - // Arrange - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "pTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "class" } } - }, - new TagHelperDescriptor - { - TagName = "div", - TypeName = "divTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] - { - new TagHelperRequiredAttributeDescriptor { Name = "class" }, - new TagHelperRequiredAttributeDescriptor { Name = "style" } - } - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "catchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "catchAll" } } - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - public static TheoryData NestedRequiredAttributeData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var dateTimeNow = new MarkupBlock( - new MarkupBlock( - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))); - - // documentContent, expectedOutput - return new TheoryData - { - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new[] - { - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        ") - })) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new SyntaxTreeNode[] - { - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new[] - { - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("
        "), - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new SyntaxTreeNode[] - { - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock("

        "), - })) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new[] - { - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        ") - }))) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new[] - { - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - }))) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new[] - { - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        ") - }))) - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new[] - { - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - }))) - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new[] - { - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        "), - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: new[] - { - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        ") - }), - blockFactory.MarkupTagBlock("

        "), - blockFactory.MarkupTagBlock("

        "), - })) - }, - { - "" + - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new[] - { - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - new MarkupTagHelperBlock( - "strong", - attributes: new List - { - new TagHelperAttributeNode("catchAll", factory.Markup("hi")) - }, - children: new[] - { - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - }), - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""), - })) - }, - }; - } - } - - [Theory] - [MemberData(nameof(NestedRequiredAttributeData))] - public void Rewrite_NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly( - string documentContent, - MarkupBlock expectedOutput) - { - // Arrange - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "pTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "class" } } - }, - new TagHelperDescriptor - { - TagName = "*", - TypeName = "catchAllTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "catchAll" } } - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors: new RazorError[0]); - } - - public static TheoryData MalformedRequiredAttributeData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatUnclosed = "Found a malformed '{0}' tag helper. Tag helpers must have a start and " + - "end tag or be self closing."; - var errorFormatNoCloseAngle = "Missing close angle for tag helper '{0}'."; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - " - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        - { - new TagHelperAttributeNode("notRequired", factory.Markup("hi")), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        "), - blockFactory.MarkupTagBlock(" - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(17, 0, 17), - length: 1) - } - }, - { - "

        - { - new TagHelperAttributeNode("notRequired", factory.Markup("hi")), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(34, 0, 34), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: blockFactory.MarkupTagBlock("

        "))), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - attributes: new List - { - new TagHelperAttributeNode("notRequired", factory.Markup("hi")), - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: blockFactory.MarkupTagBlock("

        "))), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatUnclosed, "p"), - new SourceLocation(1, 0, 1), - length: 1), - } - }, - { - "

        - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(17, 0, 17), - length: 1) - } - }, - { - "

        - { - new TagHelperAttributeNode("notRequired", factory.Markup("hi")), - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - new[] - { - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(1, 0, 1), - length: 1), - new RazorError( - string.Format(CultureInfo.InvariantCulture, errorFormatNoCloseAngle, "p"), - new SourceLocation(34, 0, 34), - length: 1) - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(MalformedRequiredAttributeData))] - public void Rewrite_RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - // Arrange - var descriptors = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "pTagHelper", - AssemblyName = "SomeAssembly", - RequiredAttributes = new[] { new TagHelperRequiredAttributeDescriptor { Name = "class" } } - } - }; - var descriptorProvider = new TagHelperDescriptorProvider(descriptors); - - // Act & Assert - EvaluateData(descriptorProvider, documentContent, expectedOutput, expectedErrors); - } - - public static TheoryData PrefixedTagHelperBoundData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var availableDescriptorsColon = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - Prefix = "th:", - TagName = "myth", - TypeName = "mythTagHelper", - AssemblyName = "SomeAssembly" - }, - new TagHelperDescriptor - { - Prefix = "th:", - TagName = "myth2", - TypeName = "mythTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new [] - { - new TagHelperAttributeDescriptor - { - Name = "bound", - PropertyName = "Bound", - TypeName = typeof(bool).FullName - } - } - } - }; - var availableDescriptorsText = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - Prefix = "PREFIX", - TagName = "myth", - TypeName = "mythTagHelper", - AssemblyName = "SomeAssembly" - }, - new TagHelperDescriptor - { - Prefix = "PREFIX", - TagName = "myth2", - TypeName = "mythTagHelper2", - AssemblyName = "SomeAssembly", - Attributes = new [] - { - new TagHelperAttributeDescriptor - { - Name = "bound", - PropertyName = "Bound", - TypeName = typeof(bool).FullName - }, - } - } - }; - var availableDescriptorsCatchAll = new TagHelperDescriptor[] - { - new TagHelperDescriptor - { - Prefix = "myth", - TagName = "*", - TypeName = "mythTagHelper", - AssemblyName = "SomeAssembly" - } - }; - - // documentContent, expectedOutput, availableDescriptors - return new TheoryData> - { - { - "", - new MarkupBlock(blockFactory.MarkupTagBlock("")), - availableDescriptorsCatchAll - }, - { - "words and spaces", - new MarkupBlock( - blockFactory.MarkupTagBlock(""), - factory.Markup("words and spaces"), - blockFactory.MarkupTagBlock("")), - availableDescriptorsCatchAll - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("th:myth", tagMode: TagMode.SelfClosing)), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("PREFIXmyth", tagMode: TagMode.SelfClosing)), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("th:myth")), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("PREFIXmyth")), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "th:myth", - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""))), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "PREFIXmyth", - blockFactory.MarkupTagBlock(""), - blockFactory.MarkupTagBlock(""))), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "th:myth />")), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "PREFIXmyth />")), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "th:myth>"), - blockFactory.EscapedMarkupTagBlock("")), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "PREFIXmyth>"), - blockFactory.EscapedMarkupTagBlock("")), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "th:myth", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "PREFIXmyth", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "th:myth2", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "PREFIXmyth2", - tagMode: TagMode.SelfClosing, - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - })), - availableDescriptorsText - }, - { - "words and spaces", - new MarkupBlock( - new MarkupTagHelperBlock( - "th:myth", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: factory.Markup("words and spaces"))), - availableDescriptorsColon - }, - { - "words and spaces", - new MarkupBlock( - new MarkupTagHelperBlock( - "PREFIXmyth", - attributes: new List - { - new TagHelperAttributeNode("class", factory.Markup("btn")) - }, - children: factory.Markup("words and spaces"))), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "th:myth2", - tagMode: TagMode.SelfClosing, - attributes: new List - { - { - new TagHelperAttributeNode( - "bound", - new MarkupBlock( - new MarkupBlock( - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.AnyExceptNewline))))) - } - })), - availableDescriptorsColon - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "PREFIXmyth2", - tagMode: TagMode.SelfClosing, - attributes: new List - { - { - new TagHelperAttributeNode( - "bound", - new MarkupBlock( - new MarkupBlock( - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.AnyExceptNewline))))) - } - })), - availableDescriptorsText - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock( - "PREFIXmyth2", - tagMode: TagMode.SelfClosing, - attributes: new List - { - { - new TagHelperAttributeNode( - "bound", - new MarkupBlock( - new MarkupBlock( - factory.CodeMarkup("@"), - factory - .CodeMarkup("@") - .With(SpanChunkGenerator.Null)), - new MarkupBlock( - factory - .EmptyHtml() - .As(SpanKind.Code) - .AsCodeMarkup(), - new ExpressionBlock( - factory.CSharpCodeMarkup("@"), - factory.CSharpCodeMarkup("DateTime.Now") - .With(new ExpressionChunkGenerator()))))) - } - })), - availableDescriptorsText - }, - }; - } - } - - [Theory] - [MemberData(nameof(PrefixedTagHelperBoundData))] - public void Rewrite_AllowsPrefixedTagHelpers( - string documentContent, - MarkupBlock expectedOutput, - IEnumerable availableDescriptors) - { - // Arrange - var descriptorProvider = new TagHelperDescriptorProvider(availableDescriptors); - - // Act & Assert - EvaluateData( - descriptorProvider, - documentContent, - expectedOutput, - expectedErrors: Enumerable.Empty()); - } - - public static TheoryData OptOut_WithAttributeTextTagData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatNormalUnclosed = - "The \"{0}\" element was not closed. All elements must be either self-closing or have a " + - "matching end tag."; - var errorMatchingBrace = - "The code block is missing a closing \"}\" character. Make sure you have a matching \"}\" " + - "character for all the \"{\" characters within this block, and that none of the \"}\" " + - "characters are being interpreted as markup."; - - Func, MarkupBlock> buildStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder(), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()); - }; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 8, 0, 8), - suffix: new LocationTagged("\"", 19, 0, 19)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn", 16, 0, 16))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - factory.Markup("}")))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorFormatNormalUnclosed, "!text"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5) - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 8, 0, 8), - suffix: new LocationTagged("\"", 19, 0, 19)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn", 16, 0, 16))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{words with spaces}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 8, 0, 8), - suffix: new LocationTagged("\"", 19, 0, 19)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn", 16, 0, 16))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - factory.Markup("words with spaces"), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 8, 0, 8), - suffix: new LocationTagged("'", 25, 0, 25)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("btn1").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn1", 16, 0, 16))), - factory.Markup(" btn2").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 20, 0, 20), - value: new LocationTagged("btn2", 21, 0, 21))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class2", - prefix: new LocationTagged(" class2=", 26, 0, 26), - suffix: new LocationTagged(string.Empty, 37, 0, 37)), - factory.Markup(" class2=").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 34, 0, 34), - value: new LocationTagged("btn", 34, 0, 34)))), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 8, 0, 8), - suffix: new LocationTagged("'", 39, 0, 39)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("btn1").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn1", 16, 0, 16))), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged(" ", 20, 0, 20), 21, 0, 21), - factory.Markup(" ").With(SpanChunkGenerator.Null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - factory.Markup(" btn2").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 34, 0, 34), - value: new LocationTagged("btn2", 35, 0, 35))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - }; - } - } - - public static TheoryData OptOut_WithBlockTextTagData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatMalformed = - "Found a malformed '{0}' tag helper. Tag helpers must have a start and end tag or be self " + - "closing."; - var errorFormatNormalUnclosed = - "The \"{0}\" element was not closed. All elements must be either self-closing or have a " + - "matching end tag."; - var errorFormatNormalNotStarted = - "Encountered end tag \"{0}\" with no matching start tag. Are your start/end tags properly " + - "balanced?"; - var errorMatchingBrace = - "The code block is missing a closing \"}\" character. Make sure you have a matching \"}\" " + - "character for all the \"{\" characters within this block, and that none of the \"}\" " + - "characters are being interpreted as markup."; - - Func, MarkupBlock> buildStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder(), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()); - }; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "text>", AcceptedCharacters.None), - factory.Markup("}")))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorFormatNormalUnclosed, "!text", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5), - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new [] - { - new RazorError( - string.Format(errorFormatNormalNotStarted, "!text", CultureInfo.InvariantCulture), - absoluteIndex: 4, lineIndex: 0, columnIndex: 4, length: 5), - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "text>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{words and spaces}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "text>", AcceptedCharacters.None), - factory.Markup("words and spaces"), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "text>", AcceptedCharacters.None), - blockFactory.MarkupTagBlock("", AcceptedCharacters.None))), - new [] - { - new RazorError( - string.Format(errorFormatNormalUnclosed, "!text", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5), - new RazorError( - string.Format(errorFormatMalformed, "text", CultureInfo.InvariantCulture), - absoluteIndex: 11, lineIndex: 0, columnIndex: 11, length: 4) - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock(factory.MarkupTransition("")), - new MarkupTagBlock( - factory.Markup("").Accepts(AcceptedCharacters.None)))), - new [] - { - new RazorError( - string.Format(errorFormatNormalUnclosed, "text", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 4) - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "text>", AcceptedCharacters.None), - new MarkupTagHelperBlock("text"), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock(factory.MarkupTransition("")), - new MarkupTagBlock( - factory.Markup("<").Accepts(AcceptedCharacters.None), - factory.BangEscape(), - factory.Markup("text>").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None), - factory.Markup("}")))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorFormatNormalUnclosed, "text", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 4) - } - }, - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "text>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)), - new MarkupBlock( - blockFactory.MarkupTagBlock("", AcceptedCharacters.None)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()), - new [] - { - new RazorError( - string.Format(errorFormatNormalNotStarted, "text", CultureInfo.InvariantCulture), - absoluteIndex: 19, lineIndex: 0, columnIndex: 19, length: 4), - new RazorError( - string.Format(errorFormatMalformed, "text", CultureInfo.InvariantCulture), - absoluteIndex: 19, lineIndex: 0, columnIndex: 19, length: 4) - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(OptOut_WithAttributeTextTagData))] - [MemberData(nameof(OptOut_WithBlockTextTagData))] - public void Rewrite_AllowsTagHelperElementOptForCompleteTextTagInCSharpBlock( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "p", "text"); - } - - public static TheoryData OptOut_WithPartialTextTagData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorMatchingBrace = - "The code block is missing a closing \"}\" character. Make sure you have a matching \"}\" " + - "character for all the \"{\" characters within this block, and that none of the \"}\" " + - "characters are being interpreted as markup."; - var errorEOFMatchingBrace = - "End of file or an unexpected character was reached before the \"{0}\" tag could be parsed. " + - "Elements inside markup blocks must be complete. They must either be self-closing " + - "(\"
        \") or have matching end tags (\"

        Hello

        \"). If you intended " + - "to display a \"<\" character, use the \"<\" HTML entity."; - - Func, MarkupBlock> buildPartialStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder())); - }; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "@{ new MarkupBlock(blockFactory.EscapedMarkupTagBlock("<", "text}"))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!text}"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 6) - } - }, - { - "@{ new MarkupBlock( - blockFactory.EscapedMarkupTagBlock( - "<", - "text /", - new MarkupBlock(factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!text"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=", 8, 0, 8), - suffix: new LocationTagged(string.Empty, 16, 0, 16)), - factory.Markup(" class=").With(SpanChunkGenerator.Null), - factory.Markup("}").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 15, 0, 15), - value: new LocationTagged("}", 15, 0, 15))))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!text"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 8, 0, 8), - suffix: new LocationTagged(string.Empty, 20, 0, 20)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn}").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn}", 16, 0, 16))))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!text"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 8, 0, 8), - suffix: new LocationTagged("\"", 19, 0, 19)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn", 16, 0, 16))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - new MarkupBlock(factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!text"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("text"), - - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 8, 0, 8), - suffix: new LocationTagged("\"", 19, 0, 19)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 16, 0, 16), - value: new LocationTagged("btn", 16, 0, 16))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(" /"), - new MarkupBlock(factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!text"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 5) - } - } - }; - } - } - - [Theory] - [MemberData(nameof(OptOut_WithPartialTextTagData))] - public void Rewrite_AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "text"); - } - - public static TheoryData OptOut_WithPartialData_CSharp - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorMatchingBrace = - "The code block is missing a closing \"}\" character. Make sure you have a matching \"}\" " + - "character for all the \"{\" characters within this block, and that none of the \"}\" " + - "characters are being interpreted as markup."; - var errorEOFMatchingBrace = - "End of file or an unexpected character was reached before the \"{0}\" tag could be parsed. " + - "Elements inside markup blocks must be complete. They must either be self-closing " + - "(\"
        \") or have matching end tags (\"

        Hello

        \"). If you intended " + - "to display a \"<\" character, use the \"<\" HTML entity."; - - Func, MarkupBlock> buildPartialStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder())); - }; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "@{ new MarkupBlock(blockFactory.EscapedMarkupTagBlock("<", "}"))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!}"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{ new MarkupBlock(blockFactory.EscapedMarkupTagBlock("<", "p}"))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p}"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 3) - } - }, - { - "@{ new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p /", new MarkupBlock(factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=", 5, 0, 5), - suffix: new LocationTagged(string.Empty, 13, 0, 13)), - factory.Markup(" class=").With(SpanChunkGenerator.Null), - factory.Markup("}").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 12, 0, 12), - value: new LocationTagged("}", 12, 0, 12))))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged(string.Empty, 17, 0, 17)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn}").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn}", 13, 0, 13))))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged(string.Empty, 19, 0, 19)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn", 13, 0, 13))), - new MarkupBlock( - factory.Markup("@").With(new LiteralAttributeChunkGenerator(new LocationTagged(string.Empty, 16, 0, 16), new LocationTagged("@", 16, 0, 16))).Accepts(AcceptedCharacters.None), - factory.Markup("@").With(SpanChunkGenerator.Null).Accepts(AcceptedCharacters.None)), - factory.Markup("}").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 18, 0, 18), - value: new LocationTagged("}", 18, 0, 18))))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged("\"", 16, 0, 16)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn", 13, 0, 13))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - new MarkupBlock(factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{ new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged("\"", 16, 0, 16)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn", 13, 0, 13))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(" /"), - new MarkupBlock( - factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorEOFMatchingBrace, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - } - }; - } - } - - [Theory] - [MemberData(nameof(OptOut_WithPartialData_CSharp))] - public void Rewrite_AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p"); - } - - public static TheoryData OptOut_WithPartialData_HTML - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - // documentContent, expectedOutput - return new TheoryData - { - { - "(" class=", 3, 0, 3), - suffix: new LocationTagged(string.Empty, 10, 0, 10)), - factory.Markup(" class=").With(SpanChunkGenerator.Null)))) - }, - { - "(" class=\"", 3, 0, 3), - suffix: new LocationTagged(string.Empty, 14, 0, 14)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn", 11, 0, 11)))))) - }, - { - "(" class=\"", 3, 0, 3), - suffix: new LocationTagged("\"", 14, 0, 14)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn", 11, 0, 11))), - factory.Markup("\"").With(SpanChunkGenerator.Null)))) - }, - { - "(" class=\"", 3, 0, 3), - suffix: new LocationTagged("\"", 14, 0, 14)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn", 11, 0, 11))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(" /"))) - } - }; - } - } - - [Theory] - [MemberData(nameof(OptOut_WithPartialData_HTML))] - public void Rewrite_AllowsTagHelperElementOptForIncompleteHTML( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, new RazorError[0], "strong", "p"); - } - - public static TheoryData OptOut_WithBlockData_CSharp - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatMalformed = - "Found a malformed '{0}' tag helper. Tag helpers must have a start and end tag or be self " + - "closing."; - var errorFormatNormalUnclosed = - "The \"{0}\" element was not closed. All elements must be either self-closing or have a " + - "matching end tag."; - var errorFormatNormalNotStarted = - "Encountered end tag \"{0}\" with no matching start tag. Are your start/end tags properly " + - "balanced?"; - var errorMatchingBrace = - "The code block is missing a closing \"}\" character. Make sure you have a matching \"}\" " + - "character for all the \"{\" characters within this block, and that none of the \"}\" " + - "characters are being interpreted as markup."; - - Func, MarkupBlock> buildStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder(), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()); - }; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - factory.Markup("}")))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorFormatNormalUnclosed, "!p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2), - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new [] - { - new RazorError( - string.Format(errorFormatNormalNotStarted, "!p", CultureInfo.InvariantCulture), - absoluteIndex: 4, lineIndex: 0, columnIndex: 4, length: 2), - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{words and spaces}", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - factory.Markup("words and spaces"), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{

        }", - buildStatementBlock( - () => new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.MarkupTagBlock("

        ", AcceptedCharacters.None))), - new [] - { - new RazorError( - string.Format(errorFormatNormalUnclosed, "!p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2), - new RazorError( - string.Format(errorFormatMalformed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 8, lineIndex: 0, columnIndex: 8, length: 1) - } - }, - { - "@{

        }", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)))), - new [] - { - new RazorError( - string.Format(errorFormatNormalUnclosed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 1), - new RazorError( - string.Format(errorFormatMalformed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 1) - } - }, - { - "@{

        }", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)))), - new RazorError[0] - }, - { - "@{

        }", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None), - factory.Markup("}"))))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorFormatNormalUnclosed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 1), - new RazorError( - string.Format(errorFormatMalformed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 1) - } - }, - { - "@{

        }", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)), - new MarkupBlock( - blockFactory.MarkupTagBlock("

        ", AcceptedCharacters.None)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()), - new [] - { - new RazorError( - string.Format(errorFormatNormalNotStarted, "p", CultureInfo.InvariantCulture), - absoluteIndex: 13, lineIndex: 0, columnIndex: 13, length: 1), - new RazorError( - string.Format(errorFormatMalformed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 13, lineIndex: 0, columnIndex: 13, length: 1) - } - }, - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagHelperBlock("strong", - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new MarkupBlock( - blockFactory.MarkupTagBlock("
        ", AcceptedCharacters.None)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()), - new [] - { - new RazorError( - string.Format(errorFormatNormalUnclosed, "strong", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 6), - new RazorError( - string.Format(errorFormatMalformed, "strong", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 6), - new RazorError( - string.Format(errorFormatNormalNotStarted, "strong", CultureInfo.InvariantCulture), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 6), - new RazorError( - string.Format(errorFormatMalformed, "strong", CultureInfo.InvariantCulture), - absoluteIndex: 17, lineIndex: 0, columnIndex: 17, length: 6) - } - }, - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagHelperBlock("strong")), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()), - new RazorError[0] - }, - { - "@{

        }", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)))), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>", AcceptedCharacters.None), - blockFactory.MarkupTagBlock("", AcceptedCharacters.None)), - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()), - new [] - { - new RazorError( - string.Format(errorFormatNormalUnclosed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 1), - new RazorError( - string.Format(errorFormatMalformed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 1), - new RazorError( - string.Format(errorFormatMalformed, "strong", CultureInfo.InvariantCulture), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 6), - new RazorError( - string.Format(errorFormatNormalUnclosed, "!p", CultureInfo.InvariantCulture), - absoluteIndex: 24, lineIndex: 0, columnIndex: 24, length: 2), - new RazorError( - string.Format(errorFormatMalformed, "strong", CultureInfo.InvariantCulture), - absoluteIndex: 29, lineIndex: 0, columnIndex: 29, length: 6), - new RazorError( - string.Format(errorFormatNormalNotStarted, "!p", CultureInfo.InvariantCulture), - absoluteIndex: 38, lineIndex: 0, columnIndex: 38, length: 2), - } - }, - }; - } - } - - public static TheoryData OptOut_WithAttributeData_CSharp - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatNormalUnclosed = - "The \"{0}\" element was not closed. All elements must be either self-closing or have a " + - "matching end tag."; - var errorMatchingBrace = - "The code block is missing a closing \"}\" character. Make sure you have a matching \"}\" " + - "character for all the \"{\" characters within this block, and that none of the \"}\" " + - "characters are being interpreted as markup."; - - Func, MarkupBlock> buildStatementBlock = (insideBuilder) => - { - return new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - insideBuilder(), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()); - }; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "@{}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged("\"", 16, 0, 16)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn", 13, 0, 13))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - factory.Markup("}")))), - new [] - { - new RazorError( - errorMatchingBrace, - absoluteIndex: 1, lineIndex: 0, columnIndex: 1, length: 1), - new RazorError( - string.Format(errorFormatNormalUnclosed, "!p"), - absoluteIndex: 3, lineIndex: 0, columnIndex: 3, length: 2) - } - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged("\"", 16, 0, 16)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn", 13, 0, 13))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{words with spaces}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 5, 0, 5), - suffix: new LocationTagged("\"", 16, 0, 16)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn", 13, 0, 13))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - factory.Markup("words with spaces"), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 5, 0, 5), - suffix: new LocationTagged("'", 22, 0, 22)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("btn1").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn1", 13, 0, 13))), - factory.Markup(" btn2").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 17, 0, 17), - value: new LocationTagged("btn2", 18, 0, 18))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class2", - prefix: new LocationTagged(" class2=", 23, 0, 23), - suffix: new LocationTagged(string.Empty, 34, 0, 34)), - factory.Markup(" class2=").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 31, 0, 31), - value: new LocationTagged("btn", 31, 0, 31)))), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - { - "@{}", - buildStatementBlock( - () => new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 5, 0, 5), - suffix: new LocationTagged("'", 36, 0, 36)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("btn1").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 13, 0, 13), - value: new LocationTagged("btn1", 13, 0, 13))), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged(" ", 17, 0, 17), 18, 0, 18), - factory.Markup(" ").With(SpanChunkGenerator.Null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - factory.Markup(" btn2").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 31, 0, 31), - value: new LocationTagged("btn2", 32, 0, 32))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">").Accepts(AcceptedCharacters.None)), - blockFactory.EscapedMarkupTagBlock("", AcceptedCharacters.None))), - new RazorError[0] - }, - }; - } - } - - [Theory] - [MemberData(nameof(OptOut_WithBlockData_CSharp))] - [MemberData(nameof(OptOut_WithAttributeData_CSharp))] - public void Rewrite_AllowsTagHelperElementOptOutCSharp( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p"); - } - - public static TheoryData OptOut_WithBlockData_HTML - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - var errorFormatUnclosed = "Found a malformed '{0}' tag helper. Tag helpers must have a start and " + - "end tag or be self closing."; - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>")), - new RazorError[0] - }, - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>"), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "words and spaces", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>"), - factory.Markup("words and spaces"), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "

        ", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>"), - blockFactory.MarkupTagBlock("

        ")), - new [] - { - new RazorError( - string.Format(errorFormatUnclosed, "p", CultureInfo.InvariantCulture), - absoluteIndex: 6, lineIndex: 0, columnIndex: 6, length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", blockFactory.EscapedMarkupTagBlock(""))), - new [] - { - new RazorError( - string.Format(errorFormatUnclosed, "p", CultureInfo.InvariantCulture), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.EscapedMarkupTagBlock("<", "p>"), - blockFactory.EscapedMarkupTagBlock(""))), - new RazorError[0] - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - blockFactory.EscapedMarkupTagBlock("<", "p>"), - blockFactory.EscapedMarkupTagBlock(""))), - new [] - { - new RazorError( - string.Format(errorFormatUnclosed, "p", CultureInfo.InvariantCulture), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - { - "

        ", - new MarkupBlock( - blockFactory.EscapedMarkupTagBlock("<", "p>"), - blockFactory.EscapedMarkupTagBlock(""), - blockFactory.MarkupTagBlock("

        ")), - new [] - { - new RazorError( - string.Format(errorFormatUnclosed, "p", CultureInfo.InvariantCulture), - new SourceLocation(11, 0, 11), - length: 1) - } - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("strong", - blockFactory.EscapedMarkupTagBlock(""))), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagHelperBlock("strong"), - blockFactory.EscapedMarkupTagBlock("<", "p>"), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("strong", - blockFactory.EscapedMarkupTagBlock(""), - blockFactory.EscapedMarkupTagBlock("<", "p>")), - blockFactory.EscapedMarkupTagBlock(""))), - new [] - { - new RazorError( - string.Format(errorFormatUnclosed, "p", CultureInfo.InvariantCulture), - new SourceLocation(1, 0, 1), - length: 1) - } - }, - }; - } - } - - public static TheoryData OptOut_WithAttributeData_HTML - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - // documentContent, expectedOutput, expectedErrors - return new TheoryData - { - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 3, 0, 3), - suffix: new LocationTagged("\"", 14, 0, 14)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn", 11, 0, 11))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">"))), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 3, 0, 3), - suffix: new LocationTagged("\"", 14, 0, 14)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn", 11, 0, 11))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "words and spaces", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class=\"", 3, 0, 3), - suffix: new LocationTagged("\"", 14, 0, 14)), - factory.Markup(" class=\"").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn", 11, 0, 11))), - factory.Markup("\"").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - factory.Markup("words and spaces"), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 3, 0, 3), - suffix: new LocationTagged("'", 20, 0, 20)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("btn1").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn1", 11, 0, 11))), - factory.Markup(" btn2").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 15, 0, 15), - value: new LocationTagged("btn2", 16, 0, 16))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class2", - prefix: new LocationTagged(" class2=", 21, 0, 21), - suffix: new LocationTagged(string.Empty, 32, 0, 32)), - factory.Markup(" class2=").With(SpanChunkGenerator.Null), - factory.Markup("btn").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 29, 0, 29), - value: new LocationTagged("btn", 29, 0, 29)))), - factory.Markup(">")), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("<"), - factory.BangEscape(), - factory.Markup("p"), - new MarkupBlock( - new AttributeBlockChunkGenerator( - name: "class", - prefix: new LocationTagged(" class='", 3, 0, 3), - suffix: new LocationTagged("'", 34, 0, 34)), - factory.Markup(" class='").With(SpanChunkGenerator.Null), - factory.Markup("btn1").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(string.Empty, 11, 0, 11), - value: new LocationTagged("btn1", 11, 0, 11))), - new MarkupBlock( - new DynamicAttributeBlockChunkGenerator( - new LocationTagged(" ", 15, 0, 15), 16, 0, 16), - factory.Markup(" ").With(SpanChunkGenerator.Null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - factory.Markup(" btn2").With( - new LiteralAttributeChunkGenerator( - prefix: new LocationTagged(" ", 29, 0, 29), - value: new LocationTagged("btn2", 30, 0, 30))), - factory.Markup("'").With(SpanChunkGenerator.Null)), - factory.Markup(">")), - blockFactory.EscapedMarkupTagBlock("")), - new RazorError[0] - }, - }; - } - } - - [Theory] - [MemberData(nameof(OptOut_WithBlockData_HTML))] - [MemberData(nameof(OptOut_WithAttributeData_HTML))] - public void Rewrite_AllowsTagHelperElementOptOutHTML( - string documentContent, - MarkupBlock expectedOutput, - RazorError[] expectedErrors) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors, "strong", "p"); - } - - public static IEnumerable TextTagsBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - - // Should re-write text tags that aren't in C# blocks - yield return new object[] - { - "Hello World", - new MarkupBlock( - new MarkupTagHelperBlock("text", - factory.Markup("Hello World"))) - }; - yield return new object[] - { - "@{Hello World}", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock( - factory.MarkupTransition("")), - factory.Markup("Hello World").Accepts(AcceptedCharacters.None), - new MarkupTagBlock( - factory.MarkupTransition(""))), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()) - }; - yield return new object[] - { - "@{

        Hello World

        }", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock( - factory.MarkupTransition("")), - new MarkupTagHelperBlock("p", - factory.Markup("Hello World")), - new MarkupTagBlock( - factory.MarkupTransition(""))), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()) - }; - yield return new object[] - { - "@{

        Hello World

        }", - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("text", - factory.Markup("Hello World")))), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml()) - }; - } - } - - [Theory] - [MemberData(nameof(TextTagsBlockData))] - public void TagHelperParseTreeRewriter_DoesNotRewriteTextTagTransitionTagHelpers( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p", "text"); - } - - public static IEnumerable SpecialTagsBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - yield return new object[] - { - "", - new MarkupBlock( - new MarkupTagBlock( - factory.Markup("")), - factory.Markup(""), - new MarkupTagBlock( - factory.Markup(""))) - }; - } - } - - [Theory] - [MemberData(nameof(SpecialTagsBlockData))] - public void TagHelperParseTreeRewriter_DoesNotRewriteSpecialTagTagHelpers( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "!--", "?xml", "![CDATA[", "!DOCTYPE"); - } - - public static IEnumerable NestedBlockData - { - get - { - var factory = CreateDefaultSpanFactory(); - var blockFactory = new BlockFactory(factory); - - yield return new object[] - { - "

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("div"))) - }; - yield return new object[] - { - "

        Hello World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hello World "), - new MarkupTagHelperBlock("div"))) - }; - yield return new object[] - { - "

        Hel

        lo

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hel"), - new MarkupTagHelperBlock("p", - factory.Markup("lo"))), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - new MarkupTagHelperBlock("div", - factory.Markup("World")))) - }; - yield return new object[] - { - "

        Hello

        World

        ", - new MarkupBlock( - new MarkupTagHelperBlock("p", - factory.Markup("Hel"), - blockFactory.MarkupTagBlock(""), - factory.Markup("lo"), - blockFactory.MarkupTagBlock("")), - factory.Markup(" "), - new MarkupTagHelperBlock("p", - blockFactory.MarkupTagBlock(""), - factory.Markup("World"), - blockFactory.MarkupTagBlock(""))) - }; - } - } - - [Theory] - [MemberData(nameof(NestedBlockData))] - public void TagHelperParseTreeRewriter_RewritesNestedTagHelperTagBlocks( - string documentContent, - MarkupBlock expectedOutput) - { - RunParseTreeRewriterTest(documentContent, expectedOutput, "p", "div"); - } - - [Fact] - public void Rewrite_HandlesMalformedNestedNonTagHelperTags_Correctly() - { - var documentContent = "
        @{
        }"; - var expectedOutput = new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("
        ")), - new StatementBlock( - Factory.CodeTransition(), - Factory.MetaCode("{").Accepts(AcceptedCharacters.None), - new MarkupBlock( - new MarkupTagBlock( - Factory.Markup("
        ").Accepts(AcceptedCharacters.None))), - Factory.EmptyCSharp().AsStatement(), - Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - Factory.EmptyHtml()); - var expectedErrors = new[] - { - new RazorError( - "Encountered end tag \"div\" with no matching start tag. Are your start/end tags properly balanced?", - new SourceLocation(9, 0, 9), - 3), - }; - - RunParseTreeRewriterTest(documentContent, expectedOutput, expectedErrors); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperRewritingTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperRewritingTestBase.cs deleted file mode 100644 index 4f3d2a3a75..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/Internal/TagHelperRewritingTestBase.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers.Internal; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; - -namespace Microsoft.AspNetCore.Razor.Test.Parser.TagHelpers.Internal -{ - public class TagHelperRewritingTestBase : CsHtmlMarkupParserTestBase - { - public void RunParseTreeRewriterTest( - string documentContent, - MarkupBlock expectedOutput, - params string[] tagNames) - { - RunParseTreeRewriterTest( - documentContent, - expectedOutput, - errors: Enumerable.Empty(), - tagNames: tagNames); - } - - public void RunParseTreeRewriterTest( - string documentContent, - MarkupBlock expectedOutput, - IEnumerable errors, - params string[] tagNames) - { - var providerContext = BuildProviderContext(tagNames); - - EvaluateData(providerContext, documentContent, expectedOutput, errors); - } - - public TagHelperDescriptorProvider BuildProviderContext(params string[] tagNames) - { - var descriptors = new List(); - - foreach (var tagName in tagNames) - { - descriptors.Add( - new TagHelperDescriptor - { - TagName = tagName, - TypeName = tagName + "taghelper", - AssemblyName = "SomeAssembly" - }); - } - - return new TagHelperDescriptorProvider(descriptors); - } - - public override ParserContext CreateParserContext( - ITextDocument input, - ParserBase codeParser, - ParserBase markupParser, - ErrorSink errorSink) - { - return base.CreateParserContext(input, codeParser, markupParser, errorSink); - } - - public void EvaluateData( - TagHelperDescriptorProvider provider, - string documentContent, - MarkupBlock expectedOutput, - IEnumerable expectedErrors) - { - var errorSink = new ErrorSink(); - var results = ParseDocument(documentContent, errorSink); - var rewritingContext = new RewritingContext(results.Document, errorSink); - new TagHelperParseTreeRewriter(provider).Rewrite(rewritingContext); - var rewritten = rewritingContext.SyntaxTree; - var actualErrors = errorSink.Errors.OrderBy(error => error.Location.AbsoluteIndex) - .ToList(); - - EvaluateRazorErrors(actualErrors, expectedErrors.ToList()); - EvaluateParseTree(rewritten, expectedOutput); - } - - public static SpanFactory CreateDefaultSpanFactory() - { - return new SpanFactory - { - MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), - CodeTokenizerFactory = doc => new CSharpTokenizer(doc) - }; - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperBlockTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperBlockTest.cs deleted file mode 100644 index b6b2df82f4..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperBlockTest.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.TagHelpers -{ - public class TagHelperBlockTest - { - [Fact] - public void FlattenFlattensSelfClosingTagHelpers() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var blockFactory = new BlockFactory(spanFactory); - var tagHelper = (TagHelperBlock)blockFactory.TagHelperBlock( - tagName: "input", - tagMode: TagMode.SelfClosing, - start: SourceLocation.Zero, - startTag: blockFactory.MarkupTagBlock(""), - children: new SyntaxTreeNode[0], - endTag: null); - spanFactory.Reset(); - var expectedNode = spanFactory.Markup(""); - - // Act - var flattenedNodes = tagHelper.Flatten(); - - // Assert - var node = Assert.Single(flattenedNodes); - Assert.True(node.EquivalentTo(expectedNode)); - } - - [Fact] - public void FlattenFlattensStartAndEndTagTagHelpers() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var blockFactory = new BlockFactory(spanFactory); - var tagHelper = (TagHelperBlock)blockFactory.TagHelperBlock( - tagName: "div", - tagMode: TagMode.StartTagAndEndTag, - start: SourceLocation.Zero, - startTag: blockFactory.MarkupTagBlock("
        "), - children: new SyntaxTreeNode[0], - endTag: blockFactory.MarkupTagBlock("
        ")); - spanFactory.Reset(); - var expectedStartTag = spanFactory.Markup("
        "); - var expectedEndTag = spanFactory.Markup("
        "); - - // Act - var flattenedNodes = tagHelper.Flatten(); - - // Assert - Assert.Collection( - flattenedNodes, - first => - { - Assert.True(first.EquivalentTo(expectedStartTag)); - }, - second => - { - Assert.True(second.EquivalentTo(expectedEndTag)); - }); - } - - [Fact] - public void FlattenFlattensStartAndEndTagWithChildrenTagHelpers() - { - // Arrange - var spanFactory = SpanFactory.CreateCsHtml(); - var blockFactory = new BlockFactory(spanFactory); - var tagHelper = (TagHelperBlock)blockFactory.TagHelperBlock( - tagName: "div", - tagMode: TagMode.StartTagAndEndTag, - start: SourceLocation.Zero, - startTag: blockFactory.MarkupTagBlock("
        "), - children: new SyntaxTreeNode[] { spanFactory.Markup("Hello World") }, - endTag: blockFactory.MarkupTagBlock("
        ")); - spanFactory.Reset(); - var expectedStartTag = spanFactory.Markup("
        "); - var expectedChildren = spanFactory.Markup("Hello World"); - var expectedEndTag = spanFactory.Markup("
        "); - - // Act - var flattenedNodes = tagHelper.Flatten(); - - // Assert - Assert.Collection( - flattenedNodes, - first => - { - Assert.True(first.EquivalentTo(expectedStartTag)); - }, - second => - { - Assert.True(second.EquivalentTo(expectedChildren)); - }, - third => - { - Assert.True(third.EquivalentTo(expectedEndTag)); - }); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperDirectiveSpanVisitorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperDirectiveSpanVisitorTest.cs deleted file mode 100644 index 0975c4e0b0..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/TagHelpers/TagHelperDirectiveSpanVisitorTest.cs +++ /dev/null @@ -1,426 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.Extensions.Internal; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser.TagHelpers.Internal -{ - public class TagHelperDirectiveSpanVisitorTest - { - private static readonly SpanFactory Factory = SpanFactory.CreateCsHtml(); - - public static TheoryData QuotedTagHelperDirectivesData - { - get - { - var factory = new SpanFactory - { - MarkupTokenizerFactory = doc => new HtmlTokenizer(doc), - CodeTokenizerFactory = doc => new CSharpTokenizer(doc), - }; - - // document, expectedDescriptors - return new TheoryData> - { - { - new MarkupBlock(factory.Code("\"*, someAssembly\"").AsAddTagHelper("*, someAssembly")), - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "*, someAssembly", - DirectiveType = TagHelperDirectiveType.AddTagHelper - }, - } - }, - { - new MarkupBlock(factory.Code("\"*, someAssembly\"").AsRemoveTagHelper("*, someAssembly")), - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "*, someAssembly", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }, - } - }, - { - new MarkupBlock(factory.Code("\"th:\"").AsTagHelperPrefixDirective("th:")), - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th:", - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - } - }, - { - new MarkupBlock(factory.Code(" \"*, someAssembly \" ").AsAddTagHelper("*, someAssembly ")), - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "*, someAssembly", - DirectiveType = TagHelperDirectiveType.AddTagHelper - }, - } - }, - { - new MarkupBlock(factory.Code(" \"*, someAssembly \" ").AsRemoveTagHelper("*, someAssembly ")), - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "*, someAssembly", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }, - } - }, - { - new MarkupBlock(factory.Code(" \" th :\"").AsTagHelperPrefixDirective(" th :")), - new[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "th :", - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }, - } - }, - }; - } - } - - [Theory] - [MemberData(nameof(QuotedTagHelperDirectivesData))] - public void GetDescriptors_LocatesQuotedTagHelperDirectives_CreatesDirectiveDescriptors( - MarkupBlock document, - IEnumerable expectedDescriptors) - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver(); - var tagHelperDirectiveSpanVisitor = new TagHelperDirectiveSpanVisitor(resolver, new ErrorSink()); - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - Assert.Equal( - expectedDescriptors, - resolver.DirectiveDescriptors, - TagHelperDirectiveDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_InvokesResolveOnceForAllDirectives() - { - // Arrange - var resolver = new Mock(); - resolver.Setup(mock => mock.Resolve(It.IsAny())) - .Returns(Enumerable.Empty()); - var tagHelperDirectiveSpanVisitor = new TagHelperDirectiveSpanVisitor( - resolver.Object, - new ErrorSink()); - var document = new MarkupBlock( - Factory.Code("one").AsAddTagHelper("one"), - Factory.Code("two").AsRemoveTagHelper("two"), - Factory.Code("three").AsRemoveTagHelper("three"), - Factory.Code("four").AsTagHelperPrefixDirective("four")); - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - resolver.Verify(mock => mock.Resolve(It.IsAny()), Times.Once); - } - - [Fact] - public void GetDescriptors_LocatesTagHelperChunkGenerator_CreatesDirectiveDescriptors() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver(); - var tagHelperDirectiveSpanVisitor = new TagHelperDirectiveSpanVisitor(resolver, new ErrorSink()); - var document = new MarkupBlock( - Factory.Code("one").AsAddTagHelper("one"), - Factory.Code("two").AsRemoveTagHelper("two"), - Factory.Code("three").AsRemoveTagHelper("three"), - Factory.Code("four").AsTagHelperPrefixDirective("four")); - var expectedDescriptors = new TagHelperDirectiveDescriptor[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "one", - DirectiveType = TagHelperDirectiveType.AddTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "two", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "three", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "four", - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }; - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - Assert.Equal( - expectedDescriptors, - resolver.DirectiveDescriptors, - TagHelperDirectiveDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_CanOverrideResolutionContext() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver(); - var expectedInitialDirectiveDescriptors = new TagHelperDirectiveDescriptor[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "one", - DirectiveType = TagHelperDirectiveType.AddTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "two", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "three", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }, - new TagHelperDirectiveDescriptor - { - DirectiveText = "four", - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - } - }; - var expectedEndDirectiveDescriptors = new TagHelperDirectiveDescriptor[] - { - new TagHelperDirectiveDescriptor - { - DirectiveText = "custom", - DirectiveType = TagHelperDirectiveType.AddTagHelper - } - }; - var tagHelperDirectiveSpanVisitor = new CustomTagHelperDirectiveSpanVisitor( - resolver, - (descriptors, errorSink) => - { - Assert.Equal( - expectedInitialDirectiveDescriptors, - descriptors, - TagHelperDirectiveDescriptorComparer.Default); - - return new TagHelperDescriptorResolutionContext(expectedEndDirectiveDescriptors, errorSink); - }); - var document = new MarkupBlock( - Factory.Code("one").AsAddTagHelper("one"), - Factory.Code("two").AsRemoveTagHelper("two"), - Factory.Code("three").AsRemoveTagHelper("three"), - Factory.Code("four").AsTagHelperPrefixDirective("four")); - - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - Assert.Equal(expectedEndDirectiveDescriptors, - resolver.DirectiveDescriptors, - TagHelperDirectiveDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_LocatesTagHelperPrefixDirectiveChunkGenerator() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver(); - var tagHelperDirectiveSpanVisitor = new TagHelperDirectiveSpanVisitor(resolver, new ErrorSink()); - var document = new MarkupBlock( - new DirectiveBlock( - Factory.CodeTransition(), - Factory - .MetaCode(SyntaxConstants.CSharp.TagHelperPrefixKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("something").AsTagHelperPrefixDirective("something"))); - var expectedDirectiveDescriptor = - new TagHelperDirectiveDescriptor - { - DirectiveText = "something", - DirectiveType = TagHelperDirectiveType.TagHelperPrefix - }; - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - var directiveDescriptor = Assert.Single(resolver.DirectiveDescriptors); - Assert.Equal( - expectedDirectiveDescriptor, - directiveDescriptor, - TagHelperDirectiveDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_LocatesAddTagHelperChunkGenerator() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver(); - var tagHelperDirectiveSpanVisitor = new TagHelperDirectiveSpanVisitor(resolver, new ErrorSink()); - var document = new MarkupBlock( - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("something").AsAddTagHelper("something")) - ); - var expectedRegistration = new TagHelperDirectiveDescriptor - { - DirectiveText = "something", - DirectiveType = TagHelperDirectiveType.AddTagHelper - }; - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - var directiveDescriptor = Assert.Single(resolver.DirectiveDescriptors); - Assert.Equal(expectedRegistration, directiveDescriptor, TagHelperDirectiveDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_LocatesNestedRemoveTagHelperChunkGenerator() - { - // Arrange - var resolver = new TestTagHelperDescriptorResolver(); - var tagHelperDirectiveSpanVisitor = new TagHelperDirectiveSpanVisitor(resolver, new ErrorSink()); - var document = new MarkupBlock( - new DirectiveBlock( - Factory.CodeTransition(), - Factory.MetaCode(SyntaxConstants.CSharp.RemoveTagHelperKeyword + " ") - .Accepts(AcceptedCharacters.None), - Factory.Code("something").AsRemoveTagHelper("something")) - ); - var expectedRegistration = new TagHelperDirectiveDescriptor - { - DirectiveText = "something", - DirectiveType = TagHelperDirectiveType.RemoveTagHelper - }; - - // Act - tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - // Assert - var directiveDescriptor = Assert.Single(resolver.DirectiveDescriptors); - Assert.Equal(expectedRegistration, directiveDescriptor, TagHelperDirectiveDescriptorComparer.Default); - } - - [Fact] - public void GetDescriptors_RemoveTagHelperNotInDocument_DoesNotThrow() - { - // Arrange - var tagHelperDirectiveSpanVisitor = - new TagHelperDirectiveSpanVisitor( - new TestTagHelperDescriptorResolver(), - new ErrorSink()); - var document = new MarkupBlock(Factory.Markup("Hello World")); - - // Act - var descriptors = tagHelperDirectiveSpanVisitor.GetDescriptors(document); - - Assert.Empty(descriptors); - } - - private class TestTagHelperDescriptorResolver : ITagHelperDescriptorResolver - { - public TestTagHelperDescriptorResolver() - { - DirectiveDescriptors = new List(); - } - - public List DirectiveDescriptors { get; } - - public IEnumerable Resolve(TagHelperDescriptorResolutionContext resolutionContext) - { - DirectiveDescriptors.AddRange(resolutionContext.DirectiveDescriptors); - - return Enumerable.Empty(); - } - } - - private class TagHelperDirectiveDescriptorComparer : IEqualityComparer - { - public static readonly TagHelperDirectiveDescriptorComparer Default = - new TagHelperDirectiveDescriptorComparer(); - - private TagHelperDirectiveDescriptorComparer() - { - } - - public bool Equals(TagHelperDirectiveDescriptor directiveDescriptorX, - TagHelperDirectiveDescriptor directiveDescriptorY) - { - return string.Equals(directiveDescriptorX.DirectiveText, - directiveDescriptorY.DirectiveText, - StringComparison.Ordinal) && - directiveDescriptorX.DirectiveType == directiveDescriptorY.DirectiveType; - } - - public int GetHashCode(TagHelperDirectiveDescriptor directiveDescriptor) - { - var hashCodeCombiner = HashCodeCombiner.Start(); - hashCodeCombiner.Add(base.GetHashCode()); - hashCodeCombiner.Add(directiveDescriptor.DirectiveText); - hashCodeCombiner.Add(directiveDescriptor.DirectiveType); - - return hashCodeCombiner; - } - } - - private class CustomTagHelperDirectiveSpanVisitor : TagHelperDirectiveSpanVisitor - { - private Func, - ErrorSink, - TagHelperDescriptorResolutionContext> _replacer; - - public CustomTagHelperDirectiveSpanVisitor( - ITagHelperDescriptorResolver descriptorResolver, - Func, - ErrorSink, - TagHelperDescriptorResolutionContext> replacer) - : base(descriptorResolver, new ErrorSink()) - { - _replacer = replacer; - } - - protected override TagHelperDescriptorResolutionContext GetTagHelperDescriptorResolutionContext( - IEnumerable descriptors, - ErrorSink errorSink) - { - return _replacer(descriptors, errorSink); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/TextReaderExtensionsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/TextReaderExtensionsTest.cs deleted file mode 100644 index 53af2c9135..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/TextReaderExtensionsTest.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class TextReaderExtensionsTest - { - [Fact] - public void ReadUntilWithCharReadsAllTextUpToSpecifiedCharacterButNotPast() - { - RunReaderTest("foo bar baz @biz", "foo bar baz ", '@', r => r.ReadUntil('@')); - } - - [Fact] - public void ReadUntilWithCharWithInclusiveFlagReadsAllTextUpToSpecifiedCharacterButNotPastIfInclusiveFalse() - { - RunReaderTest("foo bar baz @biz", "foo bar baz ", '@', r => r.ReadUntil('@', inclusive: false)); - } - - [Fact] - public void ReadUntilWithCharWithInclusiveFlagReadsAllTextUpToAndIncludingSpecifiedCharacterIfInclusiveTrue() - { - RunReaderTest("foo bar baz @biz", "foo bar baz @", 'b', r => r.ReadUntil('@', inclusive: true)); - } - - [Fact] - public void ReadUntilWithCharReadsToEndIfSpecifiedCharacterNotFound() - { - RunReaderTest("foo bar baz", "foo bar baz", -1, r => r.ReadUntil('@')); - } - - [Fact] - public void ReadUntilWithMultipleTerminatorsReadsUntilAnyTerminatorIsFound() - { - RunReaderTest("", " r.ReadUntil('/', '>')); - } - - [Fact] - public void ReadUntilWithMultipleTerminatorsHonorsInclusiveFlagWhenFalse() - { - // NOTE: Using named parameters would be difficult here, hence the inline comment - RunReaderTest("", " r.ReadUntil(/* inclusive */ false, '/', '>')); - } - - [Fact] - public void ReadUntilWithMultipleTerminatorsHonorsInclusiveFlagWhenTrue() - { - // NOTE: Using named parameters would be difficult here, hence the inline comment - RunReaderTest("", "', r => r.ReadUntil(/* inclusive */ true, '/', '>')); - } - - [Fact] - public void ReadUntilWithPredicateStopsWhenPredicateIsTrue() - { - RunReaderTest("foo bar baz 0 zoop zork zoink", "foo bar baz ", '0', r => r.ReadUntil(c => Char.IsDigit(c))); - } - - [Fact] - public void ReadUntilWithPredicateHonorsInclusiveFlagWhenFalse() - { - RunReaderTest("foo bar baz 0 zoop zork zoink", "foo bar baz ", '0', r => r.ReadUntil(c => Char.IsDigit(c), inclusive: false)); - } - - [Fact] - public void ReadUntilWithPredicateHonorsInclusiveFlagWhenTrue() - { - RunReaderTest("foo bar baz 0 zoop zork zoink", "foo bar baz 0", ' ', r => r.ReadUntil(c => Char.IsDigit(c), inclusive: true)); - } - - [Fact] - public void ReadWhileWithPredicateStopsWhenPredicateIsFalse() - { - RunReaderTest("012345a67890", "012345", 'a', r => r.ReadWhile(c => Char.IsDigit(c))); - } - - [Fact] - public void ReadWhileWithPredicateHonorsInclusiveFlagWhenFalse() - { - RunReaderTest("012345a67890", "012345", 'a', r => r.ReadWhile(c => Char.IsDigit(c), inclusive: false)); - } - - [Fact] - public void ReadWhileWithPredicateHonorsInclusiveFlagWhenTrue() - { - RunReaderTest("012345a67890", "012345a", '6', r => r.ReadWhile(c => Char.IsDigit(c), inclusive: true)); - } - - private static void RunReaderTest(string testString, string expectedOutput, int expectedPeek, Func action) - { - // Arrange - var reader = new StringReader(testString); - - // Act - var read = action(reader); - - // Assert - Assert.Equal(expectedOutput, read); - - if (expectedPeek == -1) - { - Assert.True(reader.Peek() == -1, "Expected that the reader would be positioned at the end of the input stream"); - } - else - { - Assert.Equal((char)expectedPeek, (char)reader.Peek()); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Parser/WhitespaceRewriterTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Parser/WhitespaceRewriterTest.cs deleted file mode 100644 index 97c39bc981..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Parser/WhitespaceRewriterTest.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Parser -{ - public class WhitespaceRewriterTest - { - [Fact] - public void Rewrite_Moves_Whitespace_Preceeding_ExpressionBlock_To_Parent_Block() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var start = new MarkupBlock( - factory.Markup("test"), - new ExpressionBlock( - factory.Code(" ").AsExpression(), - factory.CodeTransition(SyntaxConstants.TransitionString), - factory.Code("foo").AsExpression() - ), - factory.Markup("test") - ); - var rewriter = new WhiteSpaceRewriter(new HtmlMarkupParser().BuildSpan); - var rewritingContext = new RewritingContext(start, new ErrorSink()); - - // Act - rewriter.Rewrite(rewritingContext); - - factory.Reset(); - - // Assert - ParserTestBase.EvaluateParseTree(rewritingContext.SyntaxTree, new MarkupBlock( - factory.Markup("test"), - factory.Markup(" "), - new ExpressionBlock( - factory.CodeTransition(SyntaxConstants.TransitionString), - factory.Code("foo").AsExpression() - ), - factory.Markup("test") - )); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/PartialParsingTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/PartialParsingTestBase.cs deleted file mode 100644 index f1b06fd8ae..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/PartialParsingTestBase.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Web.WebPages.TestUtils; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Test.Utils; -using Microsoft.AspNetCore.Razor.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public abstract class PartialParsingTestBase - where TLanguage : RazorCodeLanguage, new() - { - private const string TestLinePragmaFileName = "C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml"; - - protected static void RunFullReparseTest(TextChange change, PartialParseResult additionalFlags = (PartialParseResult)0) - { - // Arrange - using (var manager = CreateParserManager()) - { - manager.InitializeWithDocument(change.OldBuffer); - - // Act - var result = manager.CheckForStructureChangesAndWait(change); - - // Assert - Assert.Equal(PartialParseResult.Rejected | additionalFlags, result); - Assert.Equal(2, manager.ParseCount); - } - } - - protected static void RunPartialParseTest(TextChange change, Block newTreeRoot, PartialParseResult additionalFlags = (PartialParseResult)0) - { - // Arrange - using (var manager = CreateParserManager()) - { - manager.InitializeWithDocument(change.OldBuffer); - - // Act - var result = manager.CheckForStructureChangesAndWait(change); - - // Assert - Assert.Equal(PartialParseResult.Accepted | additionalFlags, result); - Assert.Equal(1, manager.ParseCount); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, newTreeRoot); - } - } - - protected static TestParserManager CreateParserManager() - { - var host = CreateHost(); - var parser = new RazorEditorParser(host, TestLinePragmaFileName); - return new TestParserManager(parser); - } - - protected static RazorEngineHost CreateHost(ITagHelperDescriptorResolver descriptorResolver = null) - { - return new RazorEngineHost(new TLanguage()) - { - GeneratedClassContext = new GeneratedClassContext( - "Execute", - "Write", - "WriteLiteral", - "WriteTo", - "WriteLiteralTo", - "Template", - "DefineSection", - new GeneratedTagHelperContext()), - DesignTimeMode = true, - TagHelperDescriptorResolver = descriptorResolver - }; - } - - protected static void RunTypeKeywordTest(string keyword) - { - var before = "@" + keyword.Substring(0, keyword.Length - 1); - var after = "@" + keyword; - var changed = new StringTextBuffer(after); - var old = new StringTextBuffer(before); - RunFullReparseTest(new TextChange(keyword.Length, 0, old, 1, changed), additionalFlags: PartialParseResult.SpanContextChanged); - } - - protected class TestParserManager : IDisposable - { - public int ParseCount; - - private readonly ManualResetEventSlim _parserComplete; - - public TestParserManager(RazorEditorParser parser) - { - _parserComplete = new ManualResetEventSlim(); - ParseCount = 0; - Parser = parser; - parser.DocumentParseComplete += (sender, args) => - { - Interlocked.Increment(ref ParseCount); - _parserComplete.Set(); - }; - } - - public RazorEditorParser Parser { get; } - - public void InitializeWithDocument(ITextBuffer startDocument) - { - CheckForStructureChangesAndWait(new TextChange(0, 0, new StringTextBuffer(string.Empty), startDocument.Length, startDocument)); - } - - public PartialParseResult CheckForStructureChangesAndWait(TextChange change) - { - var result = Parser.CheckForStructureChanges(change); - if (result.HasFlag(PartialParseResult.Rejected)) - { - WaitForParse(); - } - return result; - } - - public void WaitForParse() - { - MiscUtils.DoWithTimeoutIfNotDebugging(_parserComplete.Wait); // Wait for the parse to finish - _parserComplete.Reset(); - } - - public void Dispose() - { - Parser.Dispose(); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/RazorCodeLanguageTest.cs b/test/Microsoft.AspNetCore.Razor.Test/RazorCodeLanguageTest.cs deleted file mode 100644 index 0c92bbc20b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/RazorCodeLanguageTest.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class RazorCodeLanguageTest - { - [Fact] - public void ServicesPropertyContainsEntriesForCSharpCodeLanguageService() - { - // Assert - Assert.Equal(1, RazorCodeLanguage.Languages.Count); - Assert.IsType(RazorCodeLanguage.Languages["cshtml"]); - } - - [Fact] - public void GetServiceByExtensionReturnsEntryMatchingExtensionWithoutPreceedingDot() - { - Assert.IsType(RazorCodeLanguage.GetLanguageByExtension("cshtml")); - } - - [Fact] - public void GetServiceByExtensionReturnsEntryMatchingExtensionWithPreceedingDot() - { - Assert.IsType(RazorCodeLanguage.GetLanguageByExtension(".cshtml")); - } - - [Fact] - public void GetServiceByExtensionReturnsNullIfNoServiceForSpecifiedExtension() - { - Assert.Null(RazorCodeLanguage.GetLanguageByExtension("foobar")); - } - - [Fact] - public void MultipleCallsToGetServiceWithSameExtensionReturnSameObject() - { - // Arrange - var expected = RazorCodeLanguage.GetLanguageByExtension("cshtml"); - - // Act - var actual = RazorCodeLanguage.GetLanguageByExtension("cshtml"); - - // Assert - Assert.Same(expected, actual); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/RazorEditorParserTest.cs b/test/Microsoft.AspNetCore.Razor.Test/RazorEditorParserTest.cs deleted file mode 100644 index e1794ca336..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/RazorEditorParserTest.cs +++ /dev/null @@ -1,1390 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Web.WebPages.TestUtils; -using Microsoft.AspNetCore.Razor.Compilation.TagHelpers; -using Microsoft.AspNetCore.Razor.Editor; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.SyntaxTree; -using Microsoft.AspNetCore.Razor.Parser.TagHelpers; -using Microsoft.AspNetCore.Razor.TagHelpers; -using Microsoft.AspNetCore.Razor.Test.CodeGenerators; -using Microsoft.AspNetCore.Razor.Test.Framework; -using Microsoft.AspNetCore.Razor.Test.Utils; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Testing; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class RazorEditorParserTest : PartialParsingTestBase - { - private static readonly TestFile SimpleCSHTMLDocument = TestFile.Create("TestFiles/DesignTime/Simple.cshtml"); - private static readonly TestFile SimpleCSHTMLDocumentGenerated = TestFile.Create("TestFiles/DesignTime/Simple.txt"); - private const string TestLinePragmaFileName = "C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml"; - - public static TheoryData TagHelperPartialParseRejectData - { - get - { - var factory = SpanFactory.CreateCsHtml(); - - // change, expectedDocument - return new TheoryData - { - { - CreateInsertionChange("

        ", 2, " "), - new MarkupBlock( - new MarkupTagHelperBlock("p")) - }, - { - CreateInsertionChange("

        ", 6, " "), - new MarkupBlock( - new MarkupTagHelperBlock("p")) - }, - { - CreateInsertionChange("

        ", 12, " "), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "some-attr", - value: null, - valueStyle: HtmlAttributeValueStyle.Minimized) - })) - }, - { - CreateInsertionChange("

        ", 12, "ibute"), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "some-attribute", - value: null, - valueStyle: HtmlAttributeValueStyle.Minimized) - })) - }, - { - CreateInsertionChange("

        ", 2, " before"), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "before", - value: null, - valueStyle: HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode( - "some-attr", - value: null, - valueStyle: HtmlAttributeValueStyle.Minimized) - })) - }, - }; - } - } - - [Theory] - [MemberData(nameof(TagHelperPartialParseRejectData))] - public void TagHelperTagBodiesRejectPartialChanges(TextChange change, MarkupBlock expectedDocument) - { - // Arrange - var descriptors = new[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper" - }, - }; - var descriptorResolver = new Mock(); - descriptorResolver - .Setup(resolver => resolver.Resolve(It.IsAny())) - .Returns(descriptors); - var host = CreateHost(descriptorResolver.Object); - var parser = new RazorEditorParser(host, @"C:\This\Is\A\Test\Path"); - - using (var manager = new TestParserManager(parser)) - { - manager.InitializeWithDocument(change.OldBuffer); - - // Act - var result = manager.CheckForStructureChangesAndWait(change); - - // Assert - Assert.Equal(PartialParseResult.Rejected, result); - Assert.Equal(2, manager.ParseCount); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, expectedDocument); - } - } - - public static TheoryData TagHelperAttributeAcceptData - { - get - { - var factory = SpanFactory.CreateCsHtml(); - - // change, expectedDocument, partialParseResult - return new TheoryData - { - { - CreateInsertionChange("

        ", 22, "."), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "str-attr", - new MarkupBlock( - new MarkupBlock( - new ExpressionBlock( - factory.CodeTransition(), - factory - .Code("DateTime.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))), - HtmlAttributeValueStyle.SingleQuotes) - })), - PartialParseResult.Accepted | PartialParseResult.Provisional - }, - { - CreateInsertionChange("

        ", 21, "."), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "obj-attr", - factory.CodeMarkup("DateTime."), - HtmlAttributeValueStyle.SingleQuotes) - })), - PartialParseResult.Accepted - }, - { - CreateInsertionChange("

        ", 25, "."), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "obj-attr", - factory.CodeMarkup("1 + DateTime."), - HtmlAttributeValueStyle.SingleQuotes) - })), - PartialParseResult.Accepted - }, - { - CreateInsertionChange("

        ", 34, "."), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "before-attr", - value: null, - valueStyle: HtmlAttributeValueStyle.Minimized), - new TagHelperAttributeNode( - "str-attr", - new MarkupBlock( - new MarkupBlock( - new ExpressionBlock( - factory.CodeTransition(), - factory - .Code("DateTime.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)))), - HtmlAttributeValueStyle.SingleQuotes), - new TagHelperAttributeNode( - "after-attr", - value: null, - valueStyle: HtmlAttributeValueStyle.Minimized), - })), - PartialParseResult.Accepted | PartialParseResult.Provisional - }, - { - CreateInsertionChange("

        ", 29, "."), - new MarkupBlock( - new MarkupTagHelperBlock( - "p", - attributes: new List - { - new TagHelperAttributeNode( - "str-attr", - new MarkupBlock( - factory.Markup("before"), - new MarkupBlock( - factory.Markup(" "), - new ExpressionBlock( - factory.CodeTransition(), - factory - .Code("DateTime.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace))), - factory.Markup(" after")), - HtmlAttributeValueStyle.SingleQuotes) - })), - PartialParseResult.Accepted | PartialParseResult.Provisional - }, - }; - } - } - - [Theory] - [MemberData(nameof(TagHelperAttributeAcceptData))] - public void TagHelperAttributesAreLocatedAndAcceptChangesCorrectly( - TextChange change, - MarkupBlock expectedDocument, - PartialParseResult partialParseResult) - { - // Arrange - var descriptors = new[] - { - new TagHelperDescriptor - { - TagName = "p", - TypeName = "PTagHelper", - Attributes = new[] - { - new TagHelperAttributeDescriptor - { - Name = "obj-attr", - TypeName = typeof(object).FullName, - PropertyName = "ObjectAttribute", - }, - new TagHelperAttributeDescriptor - { - Name = "str-attr", - TypeName = typeof(string).FullName, - PropertyName = "StringAttribute", - }, - } - }, - }; - var descriptorResolver = new Mock(); - descriptorResolver - .Setup(resolver => resolver.Resolve(It.IsAny())) - .Returns(descriptors); - var host = CreateHost(descriptorResolver.Object); - var parser = new RazorEditorParser(host, @"C:\This\Is\A\Test\Path"); - - using (var manager = new TestParserManager(parser)) - { - manager.InitializeWithDocument(change.OldBuffer); - - // Act - var result = manager.CheckForStructureChangesAndWait(change); - - // Assert - Assert.Equal(partialParseResult, result); - Assert.Equal(1, manager.ParseCount); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, expectedDocument); - } - } - - [Fact] - public void ConstructorRequiresNonNullPhysicalPath() - { - Assert.Throws("sourceFileName", () => new RazorEditorParser(CreateCodeGenTestHost(), null)); - } - - [Fact] - public void ConstructorRequiresNonEmptyPhysicalPath() - { - Assert.Throws("sourceFileName", () => new RazorEditorParser(CreateCodeGenTestHost(), string.Empty)); - } - - [Theory] - [InlineData(" ")] - [InlineData("\r\n")] - [InlineData("abcdefg")] - [InlineData("\f\r\n abcd \t")] - public void TreesAreDifferentReturnsFalseForAddedContent(string content) - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var blockFactory = new BlockFactory(factory); - var original = new MarkupBlock( - blockFactory.MarkupTagBlock("

        "), - blockFactory.TagHelperBlock( - tagName: "div", - tagMode: TagMode.StartTagAndEndTag, - start: new SourceLocation(3, 0, 3), - startTag: blockFactory.MarkupTagBlock("

        "), - children: new SyntaxTreeNode[] - { - factory.Markup($"{Environment.NewLine}{Environment.NewLine}") - }, - endTag: blockFactory.MarkupTagBlock("
        ")), - blockFactory.MarkupTagBlock("

        ")); - - factory.Reset(); - - var modified = new MarkupBlock( - blockFactory.MarkupTagBlock("

        "), - blockFactory.TagHelperBlock( - tagName: "div", - tagMode: TagMode.StartTagAndEndTag, - start: new SourceLocation(3, 0, 3), - startTag: blockFactory.MarkupTagBlock("

        "), - children: new SyntaxTreeNode[] - { - factory.Markup($"{Environment.NewLine}{content}{Environment.NewLine}") - }, - endTag: blockFactory.MarkupTagBlock("
        ")), - blockFactory.MarkupTagBlock("

        ")); - original.LinkNodes(); - modified.LinkNodes(); - - var oldBuffer = new StringTextBuffer($"

        {Environment.NewLine}{Environment.NewLine}

        "); - var newBuffer = new StringTextBuffer( - $"

        {Environment.NewLine}{content}{Environment.NewLine}

        "); - - // Act - var treesAreDifferent = BackgroundParser.TreesAreDifferent( - original, - modified, - new[] - { - new TextChange( - position: 8 + Environment.NewLine.Length, - oldLength: 0, - oldBuffer: oldBuffer, - newLength: content.Length, - newBuffer: newBuffer) - }); - - // Assert - Assert.False(treesAreDifferent); - } - - [Fact] - public void TreesAreDifferentReturnsTrueIfTreeStructureIsDifferent() - { - var factory = SpanFactory.CreateCsHtml(); - var original = new MarkupBlock( - factory.Markup("

        "), - new ExpressionBlock( - factory.CodeTransition()), - factory.Markup("

        ")); - var modified = new MarkupBlock( - factory.Markup("

        "), - new ExpressionBlock( - factory.CodeTransition("@"), - factory.Code("f") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)), - factory.Markup("

        ")); - var oldBuffer = new StringTextBuffer("

        @

        "); - var newBuffer = new StringTextBuffer("

        @f

        "); - Assert.True(BackgroundParser.TreesAreDifferent( - original, - modified, - new[] - { - new TextChange(position: 4, oldLength: 0, oldBuffer: oldBuffer, newLength: 1, newBuffer: newBuffer) - })); - } - - [Fact] - public void TreesAreDifferentReturnsFalseIfTreeStructureIsSame() - { - var factory = SpanFactory.CreateCsHtml(); - var original = new MarkupBlock( - factory.Markup("

        "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("f") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)), - factory.Markup("

        ")); - factory.Reset(); - var modified = new MarkupBlock( - factory.Markup("

        "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)), - factory.Markup("

        ")); - original.LinkNodes(); - modified.LinkNodes(); - var oldBuffer = new StringTextBuffer("

        @f

        "); - var newBuffer = new StringTextBuffer("

        @foo

        "); - Assert.False(BackgroundParser.TreesAreDifferent( - original, - modified, - new[] - { - new TextChange(position: 5, oldLength: 0, oldBuffer: oldBuffer, newLength: 2, newBuffer: newBuffer) - })); - } - - [Fact] - public void CheckForStructureChangesRequiresNonNullBufferInChange() - { - var change = new TextChange(); - var parameterName = "change"; - var exception = Assert.Throws( - parameterName, - () => - { - using (var parser = new RazorEditorParser(CreateCodeGenTestHost(), "C:\\Foo.cshtml")) - { - parser.CheckForStructureChanges(change); - } - }); - ExceptionHelpers.ValidateArgumentException(parameterName, RazorResources.FormatStructure_Member_CannotBeNull(nameof(change.NewBuffer), nameof(TextChange)), exception); - } - - [Fact] - [ReplaceCulture] - public void CheckForStructureChangesStartsReparseAndFiresDocumentParseCompletedEventIfNoAdditionalChangesQueued() - { - // Arrange - using (var parser = new RazorEditorParser(CreateCodeGenTestHost(), TestLinePragmaFileName)) - { - var input = new StringTextBuffer(SimpleCSHTMLDocument.ReadAllText()); - - DocumentParseCompleteEventArgs capturedArgs = null; - var parseComplete = new ManualResetEventSlim(false); - - parser.DocumentParseComplete += (sender, args) => - { - capturedArgs = args; - parseComplete.Set(); - }; - - // Act - parser.CheckForStructureChanges(new TextChange(0, 0, new StringTextBuffer(string.Empty), input.Length, input)); - - // Assert - MiscUtils.DoWithTimeoutIfNotDebugging(parseComplete.Wait); - - Assert.Equal( - SimpleCSHTMLDocumentGenerated.ReadAllText(), - capturedArgs.GeneratorResults.GeneratedCode); - } - } - - [Fact] - public void CheckForStructureChangesStartsFullReparseIfChangeOverlapsMultipleSpans() - { - // Arrange - using (var parser = new RazorEditorParser(CreateHost(), TestLinePragmaFileName)) - { - var original = new StringTextBuffer("Foo @bar Baz"); - var changed = new StringTextBuffer("Foo @bap Daz"); - var change = new TextChange(7, 3, original, 3, changed); - - var parseComplete = new ManualResetEventSlim(); - var parseCount = 0; - parser.DocumentParseComplete += (sender, args) => - { - Interlocked.Increment(ref parseCount); - parseComplete.Set(); - }; - - Assert.Equal(PartialParseResult.Rejected, parser.CheckForStructureChanges(new TextChange(0, 0, new StringTextBuffer(string.Empty), 12, original))); - MiscUtils.DoWithTimeoutIfNotDebugging(parseComplete.Wait); // Wait for the parse to finish - parseComplete.Reset(); - - // Act - var result = parser.CheckForStructureChanges(change); - - // Assert - Assert.Equal(PartialParseResult.Rejected, result); - MiscUtils.DoWithTimeoutIfNotDebugging(parseComplete.Wait); - Assert.Equal(2, parseCount); - } - } - - [Fact] - public void AwaitPeriodInsertionAcceptedProvisionally() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @await Html. baz"); - var old = new StringTextBuffer("foo @await Html baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(15, 0, old, 1, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("await Html.").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz")), additionalFlags: PartialParseResult.Provisional); - } - - [Fact] - public void ImplicitExpressionAcceptsInnerInsertionsInStatementBlock() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime..Now" + Environment.NewLine - + "}"); - var old = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime.Now" + Environment.NewLine - + "}"); - - // Act and Assert - RunPartialParseTest(new TextChange(17, 0, old, 1, changed), - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime..Now") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Code(Environment.NewLine).AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - } - - [Fact] - public void ImplicitExpressionAcceptsInnerInsertions() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @DateTime..Now baz"); - var old = new StringTextBuffer("foo @DateTime.Now baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(13, 0, old, 1, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime..Now").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz")), additionalFlags: PartialParseResult.Provisional); - } - - [Fact] - public void ImplicitExpressionAcceptsWholeIdentifierReplacement() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @date baz"); - var changed = new StringTextBuffer("foo @DateTime baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(5, 4, old, 8, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionRejectsWholeIdentifierReplacementToKeyword() - { - // Arrange - var host = CreateHost(); - var parser = new RazorEditorParser(host, @"C:\This\Is\A\Test\Path"); - - using (var manager = new TestParserManager(parser)) - { - var old = new StringTextBuffer("foo @date baz"); - var changed = new StringTextBuffer("foo @if baz"); - var textChange = new TextChange(5, 4, old, 2, changed); - manager.InitializeWithDocument(old); - - // Act - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(PartialParseResult.Rejected, result); - Assert.Equal(2, manager.ParseCount); - } - } - - [Fact] - public void ImplicitExpressionRejectsWholeIdentifierReplacementToDirective() - { - // Arrange - var host = CreateHost(); - var parser = new RazorEditorParser(host, @"C:\This\Is\A\Test\Path"); - - using (var manager = new TestParserManager(parser)) - { - var old = new StringTextBuffer("foo @date baz"); - var changed = new StringTextBuffer("foo @inherits baz"); - var textChange = new TextChange(5, 4, old, 8, changed); - manager.InitializeWithDocument(old); - - // Act - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(PartialParseResult.Rejected | PartialParseResult.SpanContextChanged, result); - Assert.Equal(2, manager.ParseCount); - } - } - - [Fact] - public void ImplicitExpressionAcceptsPrefixIdentifierReplacements_SingleSymbol() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @dTime baz"); - var changed = new StringTextBuffer("foo @DateTime baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(5, 1, old, 4, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionAcceptsPrefixIdentifierReplacements_MultipleSymbols() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @dTime.Now baz"); - var changed = new StringTextBuffer("foo @DateTime.Now baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(5, 1, old, 4, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionAcceptsSuffixIdentifierReplacements_SingleSymbol() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @Datet baz"); - var changed = new StringTextBuffer("foo @DateTime baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(9, 1, old, 4, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionAcceptsSuffixIdentifierReplacements_MultipleSymbols() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @DateTime.n baz"); - var changed = new StringTextBuffer("foo @DateTime.Now baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(14, 1, old, 3, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionAcceptsSurroundedIdentifierReplacements() - { - // Arrange - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @DateTime.n.ToString() baz"); - var changed = new StringTextBuffer("foo @DateTime.Now.ToString() baz"); - - // Act and Assert - RunPartialParseTest(new TextChange(14, 1, old, 3, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("DateTime.Now.ToString()").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionAcceptsDotlessCommitInsertionsInStatementBlockAfterIdentifiers() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime." + Environment.NewLine - + "}"); - var old = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime" + Environment.NewLine - + "}"); - - var textChange = new TextChange(15 + Environment.NewLine.Length, 0, old, 1, changed); - using (var manager = CreateParserManager()) - { - Action applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) => - { - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(expectedResult, result); - Assert.Equal(1, manager.ParseCount); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(expectedCode) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Code(Environment.NewLine).AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - }; - - manager.InitializeWithDocument(textChange.OldBuffer); - - // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "DateTime."); - - old = changed; - changed = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime.." + Environment.NewLine - + "}"); - textChange = new TextChange(16 + Environment.NewLine.Length, 0, old, 1, changed); - - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "DateTime.."); - - old = changed; - changed = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime.Now." + Environment.NewLine - + "}"); - textChange = new TextChange(16 + Environment.NewLine.Length, 0, old, 3, changed); - - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "DateTime.Now."); - } - } - - [Fact] - public void ImplicitExpressionAcceptsDotlessCommitInsertionsInStatementBlock() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{" + Environment.NewLine - + " @DateT." + Environment.NewLine - + "}"); - var old = new StringTextBuffer("@{" + Environment.NewLine - + " @DateT" + Environment.NewLine - + "}"); - - var textChange = new TextChange(12 + Environment.NewLine.Length, 0, old, 1, changed); - using (var manager = CreateParserManager()) - { - Action applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) => - { - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(expectedResult, result); - Assert.Equal(1, manager.ParseCount); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(expectedCode) - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Code(Environment.NewLine).AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - }; - - manager.InitializeWithDocument(textChange.OldBuffer); - - // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "DateT."); - - old = changed; - changed = new StringTextBuffer("@{" + Environment.NewLine - + " @DateTime." + Environment.NewLine - + "}"); - textChange = new TextChange(12 + Environment.NewLine.Length, 0, old, 3, changed); - - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "DateTime."); - } - } - - [Fact] - public void ImplicitExpressionProvisionallyAcceptsDotlessCommitInsertions() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @DateT. baz"); - var old = new StringTextBuffer("foo @DateT baz"); - var textChange = new TextChange(10, 0, old, 1, changed); - using (var manager = CreateParserManager()) - { - Action applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) => - { - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(expectedResult, result); - Assert.Equal(1, manager.ParseCount); - - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(expectedCode).AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - }; - - manager.InitializeWithDocument(textChange.OldBuffer); - - // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "DateT."); - - old = changed; - changed = new StringTextBuffer("foo @DateTime. baz"); - textChange = new TextChange(10, 0, old, 3, changed); - - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "DateTime."); - } - } - - [Fact] - public void ImplicitExpressionProvisionallyAcceptsDotlessCommitInsertionsAfterIdentifiers() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @DateTime. baz"); - var old = new StringTextBuffer("foo @DateTime baz"); - var textChange = new TextChange(13, 0, old, 1, changed); - using (var manager = CreateParserManager()) - { - Action applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) => - { - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(expectedResult, result); - Assert.Equal(1, manager.ParseCount); - - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(expectedCode).AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - }; - - manager.InitializeWithDocument(textChange.OldBuffer); - - // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "DateTime."); - - old = changed; - changed = new StringTextBuffer("foo @DateTime.. baz"); - textChange = new TextChange(14, 0, old, 1, changed); - - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "DateTime.."); - - old = changed; - changed = new StringTextBuffer("foo @DateTime.Now. baz"); - textChange = new TextChange(14, 0, old, 3, changed); - - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "DateTime.Now."); - } - } - - [Fact] - public void ImplicitExpressionProvisionallyAcceptsCaseInsensitiveDotlessCommitInsertions_NewRoslynIntegration() - { - var factory = SpanFactory.CreateCsHtml(); - var old = new StringTextBuffer("foo @date baz"); - var changed = new StringTextBuffer("foo @date. baz"); - var textChange = new TextChange(9, 0, old, 1, changed); - using (var manager = CreateParserManager()) - { - Action applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) => - { - var result = manager.CheckForStructureChangesAndWait(textChange); - - // Assert - Assert.Equal(expectedResult, result); - Assert.Equal(1, manager.ParseCount); - - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(expectedCode).AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - }; - - manager.InitializeWithDocument(textChange.OldBuffer); - - // This is the process of a dotless commit when doing "." insertions to commit intellisense changes. - - // @date => @date. - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "date."); - - old = changed; - changed = new StringTextBuffer("foo @date baz"); - textChange = new TextChange(9, 1, old, 0, changed); - - // @date. => @date - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "date"); - - old = changed; - changed = new StringTextBuffer("foo @DateTime baz"); - textChange = new TextChange(5, 4, old, 8, changed); - - // @date => @DateTime - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, "DateTime"); - - old = changed; - changed = new StringTextBuffer("foo @DateTime. baz"); - textChange = new TextChange(13, 0, old, 1, changed); - - // @DateTime => @DateTime. - applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, "DateTime."); - } - } - - [Fact] - public void ImplicitExpressionProvisionallyAcceptsDeleteOfIdentifierPartsIfDotRemains() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @User. baz"); - var old = new StringTextBuffer("foo @User.Name baz"); - RunPartialParseTest(new TextChange(10, 4, old, 0, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("User.").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz")), - additionalFlags: PartialParseResult.Provisional); - } - - [Fact] - public void ImplicitExpressionAcceptsDeleteOfIdentifierPartsIfSomeOfIdentifierRemains() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @Us baz"); - var old = new StringTextBuffer("foo @User baz"); - RunPartialParseTest(new TextChange(7, 2, old, 0, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("Us").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionProvisionallyAcceptsMultipleInsertionIfItCausesIdentifierExpansionAndTrailingDot() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @User. baz"); - var old = new StringTextBuffer("foo @U baz"); - RunPartialParseTest(new TextChange(6, 0, old, 4, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("User.").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz")), - additionalFlags: PartialParseResult.Provisional); - } - - [Fact] - public void ImplicitExpressionAcceptsMultipleInsertionIfItOnlyCausesIdentifierExpansion() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @barbiz baz"); - var old = new StringTextBuffer("foo @bar baz"); - RunPartialParseTest(new TextChange(8, 0, old, 3, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("barbiz").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" baz"))); - } - - [Fact] - public void ImplicitExpressionAcceptsIdentifierExpansionAtEndOfNonWhitespaceCharacters() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{" + Environment.NewLine - + " @food" + Environment.NewLine - + "}"); - var old = new StringTextBuffer("@{" + Environment.NewLine - + " @foo" + Environment.NewLine - + "}"); - RunPartialParseTest(new TextChange(10 + Environment.NewLine.Length, 0, old, 1, changed), - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("food") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Code(Environment.NewLine).AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - } - - [Fact] - public void ImplicitExpressionAcceptsIdentifierAfterDotAtEndOfNonWhitespaceCharacters() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{" + Environment.NewLine - + " @foo.d" + Environment.NewLine - + "}"); - var old = new StringTextBuffer("@{" + Environment.NewLine - + " @foo." + Environment.NewLine - + "}"); - RunPartialParseTest(new TextChange(11 + Environment.NewLine.Length, 0, old, 1, changed), - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo.d") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Code(Environment.NewLine).AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - } - - [Fact] - public void ImplicitExpressionAcceptsDotAtEndOfNonWhitespaceCharacters() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{" + Environment.NewLine - + " @foo." + Environment.NewLine - + "}"); - var old = new StringTextBuffer("@{" + Environment.NewLine - + " @foo" + Environment.NewLine - + "}"); - RunPartialParseTest(new TextChange(10 + Environment.NewLine.Length, 0, old, 1, changed), - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.Code(Environment.NewLine + " ") - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code(@"foo.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Code(Environment.NewLine).AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - } - - [Fact] - public void ImplicitExpressionRejectsChangeWhichWouldHaveBeenAcceptedIfLastChangeWasProvisionallyAcceptedOnDifferentSpan() - { - var factory = SpanFactory.CreateCsHtml(); - - // Arrange - var dotTyped = new TextChange(8, 0, new StringTextBuffer("foo @foo @bar"), 1, new StringTextBuffer("foo @foo. @bar")); - var charTyped = new TextChange(14, 0, new StringTextBuffer("foo @foo. @bar"), 1, new StringTextBuffer("foo @foo. @barb")); - using (var manager = CreateParserManager()) - { - manager.InitializeWithDocument(dotTyped.OldBuffer); - - // Apply the dot change - Assert.Equal(PartialParseResult.Provisional | PartialParseResult.Accepted, manager.CheckForStructureChangesAndWait(dotTyped)); - - // Act (apply the identifier start char change) - var result = manager.CheckForStructureChangesAndWait(charTyped); - - // Assert - Assert.Equal(PartialParseResult.Rejected, result); - Assert.False(manager.Parser.LastResultProvisional, "LastResultProvisional flag should have been cleared but it was not"); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(". "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("barb") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.EmptyHtml())); - } - } - - [Fact] - public void ImplicitExpressionAcceptsIdentifierTypedAfterDotIfLastChangeWasProvisionalAcceptanceOfDot() - { - var factory = SpanFactory.CreateCsHtml(); - - // Arrange - var dotTyped = new TextChange(8, 0, new StringTextBuffer("foo @foo bar"), 1, new StringTextBuffer("foo @foo. bar")); - var charTyped = new TextChange(9, 0, new StringTextBuffer("foo @foo. bar"), 1, new StringTextBuffer("foo @foo.b bar")); - using (var manager = CreateParserManager()) - { - manager.InitializeWithDocument(dotTyped.OldBuffer); - - // Apply the dot change - Assert.Equal(PartialParseResult.Provisional | PartialParseResult.Accepted, manager.CheckForStructureChangesAndWait(dotTyped)); - - // Act (apply the identifier start char change) - var result = manager.CheckForStructureChangesAndWait(charTyped); - - // Assert - Assert.Equal(PartialParseResult.Accepted, result); - Assert.False(manager.Parser.LastResultProvisional, "LastResultProvisional flag should have been cleared but it was not"); - ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo.b") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" bar"))); - } - } - - [Fact] - public void ImplicitExpressionProvisionallyAcceptsDotAfterIdentifierInMarkup() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @foo. bar"); - var old = new StringTextBuffer("foo @foo bar"); - RunPartialParseTest(new TextChange(8, 0, old, 1, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" bar")), - additionalFlags: PartialParseResult.Provisional); - } - - [Fact] - public void ImplicitExpressionAcceptsAdditionalIdentifierCharactersIfEndOfSpanIsIdentifier() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("foo @foob bar"); - var old = new StringTextBuffer("foo @foo bar"); - RunPartialParseTest(new TextChange(8, 0, old, 1, changed), - new MarkupBlock( - factory.Markup("foo "), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foob") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.Markup(" bar"))); - } - - [Fact] - public void ImplicitExpressionAcceptsAdditionalIdentifierStartCharactersIfEndOfSpanIsDot() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{@foo.b}"); - var old = new StringTextBuffer("@{@foo.}"); - RunPartialParseTest(new TextChange(7, 0, old, 1, changed), - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo.b") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - } - - [Fact] - public void ImplicitExpressionAcceptsDotIfTrailingDotsAreAllowed() - { - var factory = SpanFactory.CreateCsHtml(); - var changed = new StringTextBuffer("@{@foo.}"); - var old = new StringTextBuffer("@{@foo}"); - RunPartialParseTest(new TextChange(6, 0, old, 1, changed), - new MarkupBlock( - factory.EmptyHtml(), - new StatementBlock( - factory.CodeTransition(), - factory.MetaCode("{").Accepts(AcceptedCharacters.None), - factory.EmptyCSharp() - .AsStatement() - .AutoCompleteWith(autoCompleteString: null), - new ExpressionBlock( - factory.CodeTransition(), - factory.Code("foo.") - .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true) - .Accepts(AcceptedCharacters.NonWhiteSpace)), - factory.EmptyCSharp().AsStatement(), - factory.MetaCode("}").Accepts(AcceptedCharacters.None)), - factory.EmptyHtml())); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfIfKeywordTyped() - { - RunTypeKeywordTest("if"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfDoKeywordTyped() - { - RunTypeKeywordTest("do"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfTryKeywordTyped() - { - RunTypeKeywordTest("try"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfForKeywordTyped() - { - RunTypeKeywordTest("for"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfForEachKeywordTyped() - { - RunTypeKeywordTest("foreach"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfWhileKeywordTyped() - { - RunTypeKeywordTest("while"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfSwitchKeywordTyped() - { - RunTypeKeywordTest("switch"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfLockKeywordTyped() - { - RunTypeKeywordTest("lock"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfUsingKeywordTyped() - { - RunTypeKeywordTest("using"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfSectionKeywordTyped() - { - RunTypeKeywordTest("section"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfInheritsKeywordTyped() - { - RunTypeKeywordTest("inherits"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfFunctionsKeywordTyped() - { - RunTypeKeywordTest("functions"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfNamespaceKeywordTyped() - { - RunTypeKeywordTest("namespace"); - } - - [Fact] - public void ImplicitExpressionCorrectlyTriggersReparseIfClassKeywordTyped() - { - RunTypeKeywordTest("class"); - } - - private static RazorEngineHost CreateCodeGenTestHost() - { - return new CodeGenTestHost(new CSharpRazorCodeLanguage()) { DesignTimeMode = true }; - } - - private static TextChange CreateInsertionChange(string initialText, int insertionLocation, string insertionText) - { - var changedText = initialText.Insert(insertionLocation, insertionText); - - var original = new StringTextBuffer(initialText); - var changed = new StringTextBuffer(changedText); - return new TextChange(insertionLocation, 0, original, insertionText.Length, changed); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/RazorEngineHostTest.cs b/test/Microsoft.AspNetCore.Razor.Test/RazorEngineHostTest.cs deleted file mode 100644 index 0ba3ae33e2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/RazorEngineHostTest.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class RazorEngineHostTest - { - [Fact] - public void ConstructorWithCodeLanguageSetsPropertiesAppropriately() - { - // Arrange - var language = new CSharpRazorCodeLanguage(); - - // Act - var host = new RazorEngineHost(language); - - // Assert - VerifyCommonDefaults(host); - Assert.Same(language, host.CodeLanguage); - Assert.IsType(host.CreateMarkupParser()); - } - - [Fact] - public void ConstructorWithCodeLanguageAndMarkupParserSetsPropertiesAppropriately() - { - // Arrange - var language = new CSharpRazorCodeLanguage(); - var expected = new HtmlMarkupParser(); - - // Act - var host = new RazorEngineHost(language, () => expected); - - // Assert - VerifyCommonDefaults(host); - Assert.Same(language, host.CodeLanguage); - Assert.Same(expected, host.CreateMarkupParser()); - } - - [Fact] - public void DecorateCodeParserDoesNotModifyIncomingParser() - { - // Arrange - var expected = new CSharpCodeParser(); - - // Act - var actual = CreateHost().DecorateCodeParser(expected); - - // Assert - Assert.Same(expected, actual); - } - - [Fact] - public void DecorateMarkupParserReturnsIncomingParser() - { - // Arrange - var expected = new HtmlMarkupParser(); - - // Act - var actual = CreateHost().DecorateMarkupParser(expected); - - // Assert - Assert.Same(expected, actual); - } - - [Fact] - public void DecorateChunkGeneratorReturnsIncomingChunkGenerator() - { - // Arrange - var expected = new RazorChunkGenerator("Foo", "Bar", "Baz", CreateHost()); - - // Act - var actual = CreateHost().DecorateChunkGenerator(expected); - - // Assert - Assert.Same(expected, actual); - } - - private static RazorEngineHost CreateHost() - { - return new RazorEngineHost(new CSharpRazorCodeLanguage()); - } - - private static void VerifyCommonDefaults(RazorEngineHost host) - { - Assert.Equal(GeneratedClassContext.Default, host.GeneratedClassContext); - Assert.Empty(host.NamespaceImports); - Assert.False(host.DesignTimeMode); - Assert.Equal(RazorEngineHost.InternalDefaultClassName, host.DefaultClassName); - Assert.Equal(RazorEngineHost.InternalDefaultNamespace, host.DefaultNamespace); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/RazorErrorTest.cs b/test/Microsoft.AspNetCore.Razor.Test/RazorErrorTest.cs deleted file mode 100644 index 110443dadc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/RazorErrorTest.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class RazorErrorTest - { - [Fact] - 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.FilePath)}\":null,\"" + - $"{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); - } - - [Fact] - public void RazorError_WithFilePath_CanBeSerialized() - { - // Arrange - var error = new RazorError( - message: "Testing", - location: new SourceLocation("some-path", absoluteIndex: 1, lineIndex: 2, characterIndex: 56), - length: 3); - var expectedSerializedError = - $"{{\"{nameof(RazorError.Message)}\":\"Testing\",\"{nameof(RazorError.Location)}\":{{\"" + - $"{nameof(SourceLocation.FilePath)}\":\"some-path\",\"" + - $"{nameof(SourceLocation.AbsoluteIndex)}\":1,\"{nameof(SourceLocation.LineIndex)}\":2,\"" + - $"{nameof(SourceLocation.CharacterIndex)}\":56}},\"{nameof(RazorError.Length)}\":3}}"; - - // Act - var serializedError = JsonConvert.SerializeObject(error); - - // Assert - Assert.Equal(expectedSerializedError, serializedError, StringComparer.Ordinal); - } - - [Fact] - 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(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); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/RazorTemplateEngineTest.cs b/test/Microsoft.AspNetCore.Razor.Test/RazorTemplateEngineTest.cs deleted file mode 100644 index b66d873844..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/RazorTemplateEngineTest.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading; -using System.Web.WebPages.TestUtils; -using Microsoft.AspNetCore.Razor.Chunks.Generators; -using Microsoft.AspNetCore.Razor.CodeGenerators; -using Microsoft.AspNetCore.Razor.Parser; -using Microsoft.AspNetCore.Razor.Parser.Internal; -using Microsoft.AspNetCore.Razor.Text; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class RazorTemplateEngineTest - { - [Fact] - public void InvalidRazorEngineHostReturnsParseErrorsAtDesignTime() - { - // Arrange - var host = new InvalidRazorEngineHost(new CSharpRazorCodeLanguage()) - { - DesignTimeMode = true - }; - var razorEngine = new RazorTemplateEngine(host); - var input = new StringTextBuffer("
        Hello @(\"World\")
        "); - var exception = new InvalidOperationException("Hello World"); - var expectedError = RazorResources.FormatFatalException("test", Environment.NewLine, exception.Message); - - // Act - var result = razorEngine.GenerateCode(input, className: null, rootNamespace: null, sourceFileName: "test"); - - // Assert - Assert.Empty(result.Document.Children); - Assert.Empty(result.ChunkTree.Children); - Assert.Empty(result.DesignTimeLineMappings); - Assert.Empty(result.GeneratedCode); - - var error = Assert.Single(result.ParserErrors); - Assert.Equal(expectedError, error.Message, StringComparer.Ordinal); - Assert.Equal(SourceLocation.Undefined, error.Location); - Assert.Equal(-1, error.Length); - } - - [Fact] - public void InvalidRazorEngineHostThrowsAtRuntime() - { - // Arrange - var host = new InvalidRazorEngineHost(new CSharpRazorCodeLanguage()) - { - DesignTimeMode = false - }; - var razorEngine = new RazorTemplateEngine(host); - var input = new StringTextBuffer("
        Hello @(\"World\")
        "); - - // Act - var thrownException = Assert.Throws(() => - razorEngine.GenerateCode(input, className: null, rootNamespace: null, sourceFileName: "test")); - - // Assert - Assert.Equal("Hello World", thrownException.Message, StringComparer.Ordinal); - } - - [Fact] - public void ConstructorInitializesHost() - { - // Arrange - var host = new RazorEngineHost(new CSharpRazorCodeLanguage()); - - // Act - var engine = new RazorTemplateEngine(host); - - // Assert - Assert.Same(host, engine.Host); - } - - [Fact] - public void CreateParserMethodIsConstructedFromHost() - { - // Arrange - var host = CreateHost(); - var engine = new RazorTemplateEngine(host); - - // Act - var parser = engine.CreateParser("some-file"); - - // Assert - Assert.IsType(parser.CodeParser); - Assert.IsType(parser.MarkupParser); - } - - [Fact] - public void CreateParserMethodSetsParserContextToDesignTimeModeIfHostSetToDesignTimeMode() - { - // Arrange - var host = CreateHost(); - var engine = new RazorTemplateEngine(host); - host.DesignTimeMode = true; - - // Act - var parser = engine.CreateParser("some-file"); - - // Assert - Assert.True(parser.DesignTimeMode); - } - - [Fact] - public void CreateParserMethodPassesParsersThroughDecoratorMethodsOnHost() - { - // Arrange - var expectedCode = new Mock().Object; - var expectedMarkup = new Mock().Object; - - var mockHost = new Mock(new CSharpRazorCodeLanguage()) { CallBase = true }; - mockHost.Setup(h => h.DecorateCodeParser(It.IsAny())) - .Returns(expectedCode); - mockHost.Setup(h => h.DecorateMarkupParser(It.IsAny())) - .Returns(expectedMarkup); - var engine = new RazorTemplateEngine(mockHost.Object); - - // Act - var actual = engine.CreateParser("some-file"); - - // Assert - Assert.Equal(expectedCode, actual.CodeParser); - Assert.Equal(expectedMarkup, actual.MarkupParser); - } - - [Fact] - public void CreateChunkGeneratorMethodPassesChunkGeneratorThroughDecorateMethodOnHost() - { - // Arrange - var mockHost = new Mock(new CSharpRazorCodeLanguage()) { CallBase = true }; - - var expected = new Mock("Foo", "Bar", "Baz", mockHost.Object).Object; - - mockHost.Setup(h => h.DecorateChunkGenerator(It.IsAny())) - .Returns(expected); - var engine = new RazorTemplateEngine(mockHost.Object); - - // Act - var actual = engine.CreateChunkGenerator("Foo", "Bar", "Baz"); - - // Assert - Assert.Equal(expected, actual); - } - - [Fact] - public void CreateCodeGenerator_PassesChunkGeneratorThroughDecorateMethodOnHost() - { - // Arrange - var mockHost = new Mock(new CSharpRazorCodeLanguage()) { CallBase = true }; - var codeGeneratorContext = new CodeGeneratorContext( - mockHost.Object, - "different-class", - "different-ns", - string.Empty, - shouldGenerateLinePragmas: true, - errorSink: new ErrorSink()); - - var expected = new CSharpCodeGenerator(codeGeneratorContext); - - mockHost - .Setup(h => h.DecorateCodeGenerator(It.IsAny(), codeGeneratorContext)) - .Returns(expected); - var engine = new RazorTemplateEngine(mockHost.Object); - - // Act - var actual = engine.CreateCodeGenerator(codeGeneratorContext); - - // Assert - Assert.Equal(expected, actual); - } - - [Fact] - public void ParseTemplateCopiesTextReaderContentToSeekableTextReaderAndPassesToParseTemplateCore() - { - // Arrange - var mockEngine = new Mock(CreateHost()); - var reader = new StringReader("foo"); - var source = new CancellationTokenSource(); - - // Act - mockEngine.Object.ParseTemplate(reader, cancelToken: source.Token); - - // Assert - mockEngine.Verify(e => e.ParseTemplateCore( - It.Is(l => l.ReadToEnd() == "foo"), - null, - source.Token)); - } - - [Fact] - public void GenerateCodeCopiesTextReaderContentToSeekableTextReaderAndPassesToGenerateCodeCore() - { - // Arrange - var mockEngine = new Mock(CreateHost()); - var reader = new StringReader("foo"); - var source = new CancellationTokenSource(); - var className = "Foo"; - var ns = "Bar"; - var src = "Baz"; - - // Act - mockEngine.Object.GenerateCode( - reader, - className: className, - rootNamespace: ns, - sourceFileName: src, - cancelToken: source.Token); - - // Assert - mockEngine.Verify(e => e.GenerateCodeCore( - It.Is(l => l.ReadToEnd() == "foo"), - className, - ns, - src, - null, - source.Token)); - } - - [Fact] - public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource() - { - // Arrange - var engine = new RazorTemplateEngine(CreateHost()); - - // Act - var results = engine.ParseTemplate(new StringTextBuffer("foo @bar(")); - - // Assert - Assert.False(results.Success); - Assert.Single(results.ParserErrors); - Assert.NotNull(results.Document); - } - - [Fact] - public void GenerateOutputsResultsOfParsingAndGeneration() - { - // Arrange - var engine = new RazorTemplateEngine(CreateHost()); - - // Act - var results = engine.GenerateCode(new StringTextBuffer("foo @bar(")); - - // Assert - Assert.False(results.Success); - Assert.Single(results.ParserErrors); - Assert.NotNull(results.Document); - Assert.NotNull(results.GeneratedCode); - } - - [Fact] - public void GenerateOutputsDesignTimeMappingsIfDesignTimeSetOnHost() - { - // Arrange - var engine = new RazorTemplateEngine(CreateHost(designTime: true)); - - // Act - var results = engine.GenerateCode( - new StringTextBuffer("foo @bar()"), - className: null, - rootNamespace: null, - sourceFileName: "foo.cshtml"); - - // Assert - Assert.True(results.Success); - Assert.Empty(results.ParserErrors); - Assert.NotNull(results.Document); - Assert.NotNull(results.GeneratedCode); - Assert.NotNull(results.DesignTimeLineMappings); - } - - public static IEnumerable GenerateCodeCalculatesLinePragma_IfStreamInputIsUsedData - { - get - { - // Seekable stream - var content = Encoding.UTF8.GetBytes("Hello world"); - var stream = new MemoryStream(content); - - yield return new[] { stream }; - - // Non seekable stream - var mockStream = new Mock(content) - { - CallBase = true - }; - mockStream.Setup(m => m.CanSeek) - .Returns(false); - - yield return new[] { mockStream.Object }; - } - } - - [Theory] - [MemberData(nameof(GenerateCodeCalculatesLinePragma_IfStreamInputIsUsedData))] - public void GenerateCodeCalculatesChecksum_IfStreamInputIsUsed(Stream stream) - { - // Arrange - var engine = new TestableRazorTemplateEngine(); - - // Act - var results = engine.GenerateCode(stream, "some-class", "some-ns", "foo.cshtml"); - - // Assert - Assert.Equal("7b502c3a1f48c8609ae212cdfb639dee39673f5e", engine.Checksum); - } - - [Fact] - public void GenerateCode_DoesNotCalculateChecksum_InDesignTimeMode() - { - // Arrange - var engine = new TestableRazorTemplateEngine(); - engine.Host.DesignTimeMode = true; - - // Act - var results = engine.GenerateCode(Stream.Null, "some-class", "some-ns", "foo.cshtml"); - - // Assert - Assert.Null(engine.Checksum); - } - - [Fact] - public void GenerateCode_UsesDecoratedRazorParser() - { - // Arrange - Mock parser = null; - var host = new Mock(new CSharpRazorCodeLanguage()) - { - CallBase = true - }; - host.Setup(p => p.DecorateRazorParser(It.IsAny(), "foo.cshtml")) - .Returns((RazorParser p, string file) => - { - parser = new Mock(p) - { - CallBase = true - }; - return parser.Object; - }) - .Verifiable(); - - var engine = new RazorTemplateEngine(host.Object); - - // Act - var results = engine.GenerateCode(Stream.Null, "some-class", "some-ns", "foo.cshtml"); - - // Assert - Assert.NotNull(parser); - - parser.Verify(v => v.Parse(It.IsAny()), Times.Once()); - host.Verify(); - } - - private static RazorEngineHost CreateHost(bool designTime = false) - { - return new RazorEngineHost(new CSharpRazorCodeLanguage()) - { - DesignTimeMode = designTime - }; - } - - private class TestableRazorTemplateEngine : RazorTemplateEngine - { - public TestableRazorTemplateEngine() - : base(CreateHost()) - { - } - - public string Checksum { get; set; } - - protected internal override GeneratorResults GenerateCodeCore( - ITextDocument input, - string className, - string rootNamespace, - string sourceFileName, - string checksum, - CancellationToken? cancelToken) - { - Checksum = checksum; - return null; - } - } - - private class InvalidRazorEngineHost : RazorEngineHost - { - public InvalidRazorEngineHost(RazorCodeLanguage codeLanguage) : base(codeLanguage) - { - } - - public override string DefaultClassName - { - get - { - throw new InvalidOperationException("Hello World"); - } - set - { - } - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/SourceLocationTest.cs b/test/Microsoft.AspNetCore.Razor.Test/SourceLocationTest.cs deleted file mode 100644 index 76c35e776a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/SourceLocationTest.cs +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Testing; -using Xunit; - -namespace Microsoft.AspNetCore.Razor -{ - public class SourceLocationTest - { - [Fact] - public void ConstructorWithLineAndCharacterIndexSetsAssociatedProperties() - { - // Act - var loc = new SourceLocation(0, 42, 24); - - // Assert - Assert.Null(loc.FilePath); - Assert.Equal(0, loc.AbsoluteIndex); - Assert.Equal(42, loc.LineIndex); - Assert.Equal(24, loc.CharacterIndex); - } - - [Fact] - public void Constructor_SetsFilePathAndIndexes() - { - // Arrange - var filePath = "some-file-path"; - var absoluteIndex = 133; - var lineIndex = 23; - var characterIndex = 12; - - // Act - var sourceLocation = new SourceLocation(filePath, absoluteIndex, lineIndex, characterIndex); - - // Assert - Assert.Equal(filePath, sourceLocation.FilePath); - Assert.Equal(absoluteIndex, sourceLocation.AbsoluteIndex); - Assert.Equal(lineIndex, sourceLocation.LineIndex); - Assert.Equal(characterIndex, sourceLocation.CharacterIndex); - } - - [Theory] - [InlineData(null)] - [InlineData("some-file")] - public void GetHashCode_ReturnsSameValue_WhenEqual(string path) - { - // Arrange - var sourceLocationA = new SourceLocation(path, 10, 3, 4); - var sourceLocationB = new SourceLocation(path, 10, 3, 4); - var sourceLocationC = new SourceLocation(path, 10, 45, 8754); - - // Act - var hashCodeA = sourceLocationA.GetHashCode(); - var hashCodeB = sourceLocationB.GetHashCode(); - var hashCodeC = sourceLocationC.GetHashCode(); - - // Assert - Assert.Equal(hashCodeA, hashCodeB); - Assert.Equal(hashCodeA, hashCodeC); - } - - [Fact] - public void Equals_ReturnsTrue_FilePathsNullAndAbsoluteIndicesMatch() - { - // Arrange - var sourceLocationA = new SourceLocation(10, 3, 4); - var sourceLocationB = new SourceLocation(10, 45, 8754); - - // Act - var result = sourceLocationA.Equals(sourceLocationB); - - // Assert - Assert.True(result); - } - - [Fact] - public void Equals_ReturnsFalse_IfFilePathIsDifferent() - { - // Arrange - var sourceLocationA = new SourceLocation(10, 3, 4); - var sourceLocationB = new SourceLocation("different-file", 10, 3, 4); - - // Act - var result = sourceLocationA.Equals(sourceLocationB); - - // Assert - Assert.False(result); - } - - [Theory] - [InlineData(null)] - [InlineData("some-file")] - public void Equals_ReturnsTrue_IfFilePathAndIndexesAreSame(string path) - { - // Arrange - var sourceLocationA = new SourceLocation(path, 10, 3, 4); - var sourceLocationB = new SourceLocation(path, 10, 3, 4); - var sourceLocationC = new SourceLocation("different-path", 10, 3, 4); - - // Act - var result1 = sourceLocationA.Equals(sourceLocationB); - var result2 = sourceLocationA.Equals(sourceLocationC); - - // Assert - Assert.True(result1); - Assert.False(result2); - } - - [Fact] - public void CompareTo_ReturnsResultOfFilePathComparisons_WhenFilePathsAreDifferent() - { - // Arrange - var sourceLocationA = new SourceLocation("a-path", 1, 1, 1); - var sourceLocationB = new SourceLocation("b-path", 1, 1, 1); - - // Act - var result = sourceLocationA.CompareTo(sourceLocationB); - - // Assert - Assert.Equal(string.Compare(sourceLocationA.FilePath, sourceLocationB.FilePath, StringComparison.Ordinal), - result); - } - - [Theory] - [InlineData(null, 1, 2)] - [InlineData(null, 32, 32)] - [InlineData("same-path", 34, 32)] - [InlineData("same-path-b", 18, 32)] - public void CompareTo_ReturnsResultOfAbsoluteIndexComparisons_IfFilePathsMatch( - string path, int indexA, int indexB) - { - // Arrange - var sourceLocationA = new SourceLocation(path, indexA, 1, 1); - var sourceLocationB = new SourceLocation(path, indexB, 1, 1); - - // Act - var result = sourceLocationA.CompareTo(sourceLocationB); - - // Assert - Assert.Equal(indexA.CompareTo(indexB), result); - } - - [Fact] - public void Add_Throws_IfFilePathsDoNotMatch() - { - // Arrange - var sourceLocationA = new SourceLocation("a-path", 1, 1, 1); - var sourceLocationB = new SourceLocation("b-path", 1, 1, 1); - - // Act and Assert - ExceptionAssert.ThrowsArgument( - () => { var result = sourceLocationA + sourceLocationB; }, - "right", - $"Cannot perform '+' operations on 'SourceLocation' instances with different file paths."); - } - - [Theory] - [InlineData(null)] - [InlineData("same-path")] - public void Add_IgnoresCharacterIndexIfRightLineIndexIsNonZero(string path) - { - // Arrange - var sourceLocationA = new SourceLocation(path, 1, 2, 3); - var sourceLocationB = new SourceLocation(path, 4, 5, 6); - - // Act - var result = sourceLocationA + sourceLocationB; - - // Assert - Assert.Equal(path, result.FilePath); - Assert.Equal(5, result.AbsoluteIndex); - Assert.Equal(7, result.LineIndex); - Assert.Equal(6, result.CharacterIndex); - } - - [Theory] - [InlineData(null)] - [InlineData("same-path")] - public void Add_UsesCharacterIndexIfRightLineIndexIsZero(string path) - { - // Arrange - var sourceLocationA = new SourceLocation(path, 2, 5, 3); - var sourceLocationB = new SourceLocation(path, 4, 0, 6); - - // Act - var result = sourceLocationA + sourceLocationB; - - // Assert - Assert.Equal(path, result.FilePath); - Assert.Equal(6, result.AbsoluteIndex); - Assert.Equal(5, result.LineIndex); - Assert.Equal(9, result.CharacterIndex); - } - - [Fact] - public void Add_AllowsRightFilePathToBeNull_WhenLeftFilePathIsNonNull() - { - // Arrange - var left = new SourceLocation("left-path", 7, 1, 7); - var right = new SourceLocation(13, 1, 4); - - // Act - var result = left + right; - - // Assert - Assert.Equal(left.FilePath, result.FilePath); - Assert.Equal(20, result.AbsoluteIndex); - Assert.Equal(2, result.LineIndex); - Assert.Equal(4, result.CharacterIndex); - } - - [Fact] - public void Add_AllowsLeftFilePathToBeNull_WhenRightFilePathIsNonNull() - { - // Arrange - var left = new SourceLocation(4, 5, 6); - var right = new SourceLocation("right-path", 7, 8, 9); - - // Act - var result = left + right; - - // Assert - Assert.Equal(right.FilePath, result.FilePath); - Assert.Equal(11, result.AbsoluteIndex); - Assert.Equal(13, result.LineIndex); - Assert.Equal(9, result.CharacterIndex); - } - - [Fact] - public void Subtract_Throws_IfFilePathsDoNotMatch() - { - // Arrange - var sourceLocationA = new SourceLocation("a-path", 1, 1, 1); - var sourceLocationB = new SourceLocation("b-path", 1, 1, 1); - - // Act and Assert - ExceptionAssert.ThrowsArgument( - () => { var result = sourceLocationA - sourceLocationB; }, - "right", - "Cannot perform '-' operations on 'SourceLocation' instances with different file paths."); - } - - [Theory] - [InlineData(null)] - [InlineData("same-path")] - public void Subtract_UsesDifferenceOfCharacterIndexesIfLineIndexesAreSame(string path) - { - // Arrange - var sourceLocationA = new SourceLocation(path, 1, 5, 3); - var sourceLocationB = new SourceLocation(path, 5, 5, 6); - - // Act - var result = sourceLocationB - sourceLocationA; - - // Assert - Assert.Null(result.FilePath); - Assert.Equal(4, result.AbsoluteIndex); - Assert.Equal(0, result.LineIndex); - Assert.Equal(3, result.CharacterIndex); - } - - [Theory] - [InlineData(null)] - [InlineData("same-path")] - public void Subtract_UsesLeftCharacterIndexIfLineIndexesAreDifferent(string path) - { - // Arrange - var sourceLocationA = new SourceLocation(path, 2, 0, 3); - var sourceLocationB = new SourceLocation(path, 4, 5, 6); - - // Act - var result = sourceLocationB - sourceLocationA; - - // Assert - Assert.Null(result.FilePath); - Assert.Equal(2, result.AbsoluteIndex); - Assert.Equal(5, result.LineIndex); - Assert.Equal(6, result.CharacterIndex); - } - - [Theory] - [InlineData(null)] - [InlineData("path-to-file")] - public void Advance_PreservesSourceLocationFilePath(string path) - { - // Arrange - var sourceLocation = new SourceLocation(path, 15, 2, 8); - - // Act - var result = SourceLocation.Advance(sourceLocation, "Hello world"); - - // Assert - Assert.Equal(path, result.FilePath); - Assert.Equal(26, result.AbsoluteIndex); - Assert.Equal(2, result.LineIndex); - Assert.Equal(19, result.CharacterIndex); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/StringTextBuffer.cs b/test/Microsoft.AspNetCore.Razor.Test/StringTextBuffer.cs deleted file mode 100644 index cbbf3bf8b7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/StringTextBuffer.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; - -namespace System.Web.WebPages.TestUtils -{ - public class StringTextBuffer : ITextBuffer, IDisposable - { - private string _buffer; - public bool Disposed { get; set; } - - public StringTextBuffer(string buffer) - { - _buffer = buffer; - } - - public int Length - { - get { return _buffer.Length; } - } - - public int Position { get; set; } - - public int Read() - { - if (Position >= _buffer.Length) - { - return -1; - } - return _buffer[Position++]; - } - - public int Peek() - { - if (Position >= _buffer.Length) - { - return -1; - } - return _buffer[Position]; - } - - public void Dispose() - { - Disposed = true; - } - - public object VersionToken - { - get { return _buffer; } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AddTagHelperDirective.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AddTagHelperDirective.cs deleted file mode 100644 index aa584f80ae..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AddTagHelperDirective.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class AddTagHelperDirective - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - public AddTagHelperDirective() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.DesignTime.cs deleted file mode 100644 index c1c885d7a8..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.DesignTime.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class AttributeTargetingTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "*, something"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public AttributeTargetingTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "checkbox"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "AttributeTargetingTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "checkbox"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 7 "AttributeTargetingTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.cs deleted file mode 100644 index dd83bbd973..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/AttributeTargetingTagHelpers.cs +++ /dev/null @@ -1,129 +0,0 @@ -#pragma checksum "AttributeTargetingTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "6c8b55df08e7538ff6155a5bc3b8135b305ad08a" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class AttributeTargetingTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("catchAll", new global::Microsoft.AspNetCore.Html.HtmlString("hi"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "checkbox", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public AttributeTargetingTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(28, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(45, 9, true); - WriteLiteral("\r\n

        "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("strong", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(76, 5, true); - WriteLiteral("Hello"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(54, 36, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(90, 62, true); - WriteLiteral("World

        \r\n \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_2.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "AttributeTargetingTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(152, 40, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(192, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_2.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 7 "AttributeTargetingTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(198, 54, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(252, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(30, 228, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.DesignTime.cs deleted file mode 100644 index f117f36014..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.DesignTime.cs +++ /dev/null @@ -1,121 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Await - { - private static object @__o; -#line 1 "Await.cshtml" - - public async Task Foo() - { - return "Bar"; - } - -#line default -#line hidden - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public Await() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 10 "Await.cshtml" - __o = await Foo(); - -#line default -#line hidden -#line 11 "Await.cshtml" - __o = await Foo(); - -#line default -#line hidden -#line 12 "Await.cshtml" - await Foo(); - -#line default -#line hidden - -#line 13 "Await.cshtml" - - -#line default -#line hidden - -#line 13 "Await.cshtml" - __o = await Foo(); - -#line default -#line hidden -#line 13 "Await.cshtml" - - -#line default -#line hidden - -#line 14 "Await.cshtml" - __o = await; - -#line default -#line hidden -#line 19 "Await.cshtml" - __o = await Foo(1, 2); - -#line default -#line hidden -#line 20 "Await.cshtml" - __o = await Foo.Bar(1, 2); - -#line default -#line hidden -#line 21 "Await.cshtml" - __o = await Foo("bob", true); - -#line default -#line hidden -#line 22 "Await.cshtml" - await Foo(something, hello: "world"); - -#line default -#line hidden - -#line 23 "Await.cshtml" - await Foo.Bar(1, 2) - -#line default -#line hidden - -#line 24 "Await.cshtml" - - -#line default -#line hidden - -#line 24 "Await.cshtml" - __o = await Foo(boolValue: false); - -#line default -#line hidden -#line 24 "Await.cshtml" - - -#line default -#line hidden - -#line 25 "Await.cshtml" - __o = await ("wrrronggg"); - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.cs deleted file mode 100644 index cfe6ee051e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Await.cs +++ /dev/null @@ -1,167 +0,0 @@ -#pragma checksum "Await.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "00b5e01b7a405dcfde7e4d512ee930daaa1778b5" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Await - { -#line 1 "Await.cshtml" - - public async Task Foo() - { - return "Bar"; - } - -#line default -#line hidden - #line hidden - public Await() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(91, 100, true); - WriteLiteral("\r\n
        \r\n

        Basic Asynchronous Expression Test

        \r\n

        Basic Asynchronous Expression: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(192, 11, false); -#line 10 "Await.cshtml" - Write(await Foo()); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(203, 42, true); - WriteLiteral("

        \r\n

        Basic Asynchronous Template: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(247, 11, false); -#line 11 "Await.cshtml" - Write(await Foo()); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(259, 43, true); - WriteLiteral("

        \r\n

        Basic Asynchronous Statement: "); - Instrumentation.EndContext(); -#line 12 "Await.cshtml" - await Foo(); - -#line default -#line hidden - - Instrumentation.BeginContext(319, 54, true); - WriteLiteral("

        \r\n

        Basic Asynchronous Statement Nested: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(376, 11, false); -#line 13 "Await.cshtml" - Write(await Foo()); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(387, 5, true); - WriteLiteral(" "); - Instrumentation.EndContext(); -#line 13 "Await.cshtml" - - -#line default -#line hidden - - Instrumentation.BeginContext(393, 54, true); - WriteLiteral("

        \r\n

        Basic Incomplete Asynchronous Statement: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(448, 5, false); -#line 14 "Await.cshtml" - Write(await); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(453, 124, true); - WriteLiteral("

        \r\n
        \r\n\r\n
        \r\n

        Advanced Asynchronous Expression Test

        \r\n

        Advanced Asynchronous Expression: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(578, 15, false); -#line 19 "Await.cshtml" - Write(await Foo(1, 2)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(593, 56, true); - WriteLiteral("

        \r\n

        Advanced Asynchronous Expression Extended: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(650, 19, false); -#line 20 "Await.cshtml" - Write(await Foo.Bar(1, 2)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(669, 45, true); - WriteLiteral("

        \r\n

        Advanced Asynchronous Template: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(716, 22, false); -#line 21 "Await.cshtml" - Write(await Foo("bob", true)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(739, 46, true); - WriteLiteral("

        \r\n

        Advanced Asynchronous Statement: "); - Instrumentation.EndContext(); -#line 22 "Await.cshtml" - await Foo(something, hello: "world"); - -#line default -#line hidden - - Instrumentation.BeginContext(827, 55, true); - WriteLiteral("

        \r\n

        Advanced Asynchronous Statement Extended: "); - Instrumentation.EndContext(); -#line 23 "Await.cshtml" - await Foo.Bar(1, 2) - -#line default -#line hidden - - Instrumentation.BeginContext(906, 57, true); - WriteLiteral("

        \r\n

        Advanced Asynchronous Statement Nested: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(966, 27, false); -#line 24 "Await.cshtml" - Write(await Foo(boolValue: false)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(993, 5, true); - WriteLiteral(" "); - Instrumentation.EndContext(); -#line 24 "Await.cshtml" - - -#line default -#line hidden - - Instrumentation.BeginContext(999, 57, true); - WriteLiteral("

        \r\n

        Advanced Incomplete Asynchronous Statement: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(1057, 19, false); -#line 25 "Await.cshtml" - Write(await ("wrrronggg")); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(1076, 16, true); - WriteLiteral("

        \r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.CustomAttributeCodeGenerator.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.CustomAttributeCodeGenerator.cs deleted file mode 100644 index ae34345363..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.CustomAttributeCodeGenerator.cs +++ /dev/null @@ -1,127 +0,0 @@ -#pragma checksum "BasicTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "02f53fe4a386cdc0885235e5fd3f5d6d317dd4d6" -namespace TestOutput -{ - using System.Threading.Tasks; - - public class BasicTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data-delay", new global::Microsoft.AspNetCore.Html.HtmlString("1000"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data", new global::Microsoft.AspNetCore.Html.HtmlString("-delay1000"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "checkbox", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public BasicTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(33, 71, true); - WriteLiteral("\r\n
        \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(145, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(155, 25, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(180, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - BeginWriteTagHelperAttribute(); - WriteLiteral("2000 + "); -#line 6 "BasicTagHelpers.cshtml" - Write(ViewBag.DefaultInterval); - -#line default -#line hidden - WriteLiteral(" + 1"); - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __tagHelperExecutionContext.AddHtmlAttribute("data-interval", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_3.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(190, 71, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(261, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 7 "BasicTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = **From custom attribute code renderer**: true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(271, 39, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(310, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(104, 216, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(320, 8, true); - WriteLiteral("\r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.DesignTime.cs deleted file mode 100644 index 81c34212ac..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.DesignTime.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class BasicTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public BasicTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_PTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 6 "BasicTagHelpers.cshtml" - __o = ViewBag.DefaultInterval; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Type = "text"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "checkbox"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 7 "BasicTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.DesignTime.cs deleted file mode 100644 index fa7872ed7d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.DesignTime.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class BasicTagHelpers.Prefixed - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "THS"; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public BasicTagHelpers.Prefixed() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "checkbox"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 8 "BasicTagHelpers.Prefixed.cshtml" - __TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.cs deleted file mode 100644 index d0c91916b1..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.Prefixed.cs +++ /dev/null @@ -1,82 +0,0 @@ -#pragma checksum "BasicTagHelpers.Prefixed.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "859f448778119fd3043b1f19ea3d1f695558d6a6" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class BasicTagHelpers.Prefixed - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "checkbox", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public BasicTagHelpers.Prefixed() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(55, 52, true); - WriteLiteral("\r\n\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(133, 56, true); - WriteLiteral("\r\n

        \r\n \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_1.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 8 "BasicTagHelpers.Prefixed.cshtml" - __TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(189, 41, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(230, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(107, 136, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(243, 11, true); - WriteLiteral("\r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.RemoveTagHelper.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.RemoveTagHelper.cs deleted file mode 100644 index 62f22578dc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.RemoveTagHelper.cs +++ /dev/null @@ -1,23 +0,0 @@ -#pragma checksum "BasicTagHelpers.RemoveTagHelper.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4cc0436af5a28bdf170d94f0ae03ff19aff89b88" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class BasicTagHelpers.RemoveTagHelper - { - #line hidden - public BasicTagHelpers.RemoveTagHelper() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(70, 187, true); - WriteLiteral("\r\n
        \r\n

        \r\n

        \r\n \r\n \r\n

        \r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.cs deleted file mode 100644 index 79f8c21566..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/BasicTagHelpers.cs +++ /dev/null @@ -1,128 +0,0 @@ -#pragma checksum "BasicTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "02f53fe4a386cdc0885235e5fd3f5d6d317dd4d6" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class BasicTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data-delay", new global::Microsoft.AspNetCore.Html.HtmlString("1000"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data", new global::Microsoft.AspNetCore.Html.HtmlString("-delay1000"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "checkbox", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public BasicTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(33, 71, true); - WriteLiteral("\r\n
        \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(145, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(155, 25, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(180, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - BeginWriteTagHelperAttribute(); - WriteLiteral("2000 + "); -#line 6 "BasicTagHelpers.cshtml" - Write(ViewBag.DefaultInterval); - -#line default -#line hidden - WriteLiteral(" + 1"); - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __tagHelperExecutionContext.AddHtmlAttribute("data-interval", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_3.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(190, 71, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(261, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 7 "BasicTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(271, 39, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(310, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(104, 216, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(320, 8, true); - WriteLiteral("\r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Blocks.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Blocks.cs deleted file mode 100644 index 85e1499d82..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Blocks.cs +++ /dev/null @@ -1,197 +0,0 @@ -#pragma checksum "Blocks.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ba7d8f5f5159a2389c780aa606885ef6c917a45a" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Blocks - { - #line hidden - public Blocks() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "Blocks.cshtml" - - int i = 1; - -#line default -#line hidden - - Instrumentation.BeginContext(23, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 5 "Blocks.cshtml" - while(i <= 10) { - -#line default -#line hidden - - Instrumentation.BeginContext(44, 23, true); - WriteLiteral("

        Hello from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(69, 1, false); -#line 6 "Blocks.cshtml" - Write(i); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(71, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 7 "Blocks.cshtml" - i += 1; -} - -#line default -#line hidden - - Instrumentation.BeginContext(93, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 10 "Blocks.cshtml" - if(i == 11) { - -#line default -#line hidden - - Instrumentation.BeginContext(111, 31, true); - WriteLiteral("

        We wrote 10 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 12 "Blocks.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(145, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 14 "Blocks.cshtml" - switch(i) { - case 11: - -#line default -#line hidden - - Instrumentation.BeginContext(175, 46, true); - WriteLiteral("

        No really, we wrote 10 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 17 "Blocks.cshtml" - break; - default: - -#line default -#line hidden - - Instrumentation.BeginContext(251, 39, true); - WriteLiteral("

        Actually, we didn\'t...

        \r\n"); - Instrumentation.EndContext(); -#line 20 "Blocks.cshtml" - break; -} - -#line default -#line hidden - - Instrumentation.BeginContext(309, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 23 "Blocks.cshtml" - for(int j = 1; j <= 10; j += 2) { - -#line default -#line hidden - - Instrumentation.BeginContext(347, 29, true); - WriteLiteral("

        Hello again from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(378, 1, false); -#line 24 "Blocks.cshtml" - Write(j); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(380, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 25 "Blocks.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(389, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 27 "Blocks.cshtml" - try { - -#line default -#line hidden - - Instrumentation.BeginContext(399, 41, true); - WriteLiteral("

        That time, we wrote 5 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 29 "Blocks.cshtml" -} catch(Exception ex) { - -#line default -#line hidden - - Instrumentation.BeginContext(465, 33, true); - WriteLiteral("

        Oh no! An error occurred: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(500, 10, false); -#line 30 "Blocks.cshtml" - Write(ex.Message); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(511, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 31 "Blocks.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(520, 14, true); - WriteLiteral("\r\n

        i is now "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(535, 1, false); -#line 33 "Blocks.cshtml" - Write(i); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(536, 8, true); - WriteLiteral("

        \r\n\r\n"); - Instrumentation.EndContext(); -#line 35 "Blocks.cshtml" - lock(new object()) { - -#line default -#line hidden - - Instrumentation.BeginContext(567, 53, true); - WriteLiteral("

        This block is locked, for your security!

        \r\n"); - Instrumentation.EndContext(); -#line 37 "Blocks.cshtml" -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/AddGenerateChunkTest.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/AddGenerateChunkTest.cs deleted file mode 100644 index d78105f7ef..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/AddGenerateChunkTest.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Razor -{ - using System.Threading.Tasks; - - public class __CompiledTemplate - { - #line hidden - public __CompiledTemplate() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - WriteLiteral("hello"); -#line 1 "" -// asdf - -#line default -#line hidden - - WriteLiteral("world"); - WriteLiteral("hello"); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/BuildAfterExecuteContentTest.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/BuildAfterExecuteContentTest.cs deleted file mode 100644 index f7092af05a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/BuildAfterExecuteContentTest.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Razor -{ - using System.Threading.Tasks; - - public class __CompiledTemplate - { - #line hidden - public __CompiledTemplate() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - WriteLiteral("hello"); -#line 1 "" -// asdf - -#line default -#line hidden - - WriteLiteral("world"); - } - #pragma warning restore 1998 - // test add content. - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ChunkTreeWithUsings.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ChunkTreeWithUsings.cs deleted file mode 100644 index 89dc8bacb5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ChunkTreeWithUsings.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace TestNamespace -{ -#line 1 "" -using FakeNamespace1 - -#line default -#line hidden - ; -#line 1 "" -using FakeNamespace2.SubNamespace - -#line default -#line hidden - ; - using System.Threading.Tasks; - - public class TestClass - { - #line hidden - public TestClass() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ClearGenerateChunkTest.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ClearGenerateChunkTest.cs deleted file mode 100644 index c3d01fabd7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/ClearGenerateChunkTest.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Razor -{ - using System.Threading.Tasks; - - public class __CompiledTemplate - { - #line hidden - public __CompiledTemplate() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/DefaultGenerateChunkTest.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/DefaultGenerateChunkTest.cs deleted file mode 100644 index 2c1560599f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CSharpCodeGenerator/DefaultGenerateChunkTest.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace Razor -{ - using System.Threading.Tasks; - - public class __CompiledTemplate - { - #line hidden - public __CompiledTemplate() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - WriteLiteral("hello"); -#line 1 "" -// asdf - -#line default -#line hidden - - WriteLiteral("world"); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlock.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlock.cs deleted file mode 100644 index a2ade508bf..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlock.cs +++ /dev/null @@ -1,29 +0,0 @@ -#pragma checksum "CodeBlock.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "019ce8023d064d08ca88c597b764aea895ec5841" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class CodeBlock - { - #line hidden - public CodeBlock() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "CodeBlock.cshtml" - - for(int i = 1; i <= 10; i++) { - Output.Write("

        Hello from C#, #" + i.ToString() + "

        "); - } - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockAtEOF.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockAtEOF.cs deleted file mode 100644 index dfc6e23bdf..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockAtEOF.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class CodeBlockAtEOF - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public CodeBlockAtEOF() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "CodeBlockAtEOF.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockWithTextElement.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockWithTextElement.cs deleted file mode 100644 index b066ca0dd8..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/CodeBlockWithTextElement.cs +++ /dev/null @@ -1,53 +0,0 @@ -#pragma checksum "CodeBlockWithTextElement.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "13e48ff59aab8106ceb68dd4a10b0bdf10c322fc" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class CodeBlockWithTextElement - { - #line hidden - public CodeBlockWithTextElement() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "CodeBlockWithTextElement.cshtml" - - var a = 1; - -#line default -#line hidden - - Instrumentation.BeginContext(25, 3, true); - WriteLiteral("foo"); - Instrumentation.EndContext(); -#line 2 "CodeBlockWithTextElement.cshtml" - - var b = 1; - -#line default -#line hidden - - Instrumentation.BeginContext(63, 4, true); - WriteLiteral("bar "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(69, 3, false); -#line 3 "CodeBlockWithTextElement.cshtml" - Write(a+b); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 3 "CodeBlockWithTextElement.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.DesignTime.cs deleted file mode 100644 index dd0704fc65..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.DesignTime.cs +++ /dev/null @@ -1,215 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ComplexTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public ComplexTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "ComplexTagHelpers.cshtml" -if (true) -{ - var checkbox = "checkbox"; - - -#line default -#line hidden - -#line 10 "ComplexTagHelpers.cshtml" - - -#line default -#line hidden - -#line 10 "ComplexTagHelpers.cshtml" - if (false) - { - -#line default -#line hidden - - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "text"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 13 "ComplexTagHelpers.cshtml" - } - else - { - -#line default -#line hidden - - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 16 "ComplexTagHelpers.cshtml" - __o = checkbox; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Type = string.Empty; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 16 "ComplexTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 17 "ComplexTagHelpers.cshtml" - __o = true ? "checkbox" : "anything"; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Type = string.Empty; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 18 "ComplexTagHelpers.cshtml" - if(true) { - -#line default -#line hidden - -#line 18 "ComplexTagHelpers.cshtml" - } else { - -#line default -#line hidden - -#line 18 "ComplexTagHelpers.cshtml" - } - -#line default -#line hidden - - __TestNamespace_InputTagHelper.Type = string.Empty; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 19 "ComplexTagHelpers.cshtml" - } - -#line default -#line hidden - - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 8 "ComplexTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden -#line 22 "ComplexTagHelpers.cshtml" - - -#line default -#line hidden - -#line 22 "ComplexTagHelpers.cshtml" - var @object = false; - -#line default -#line hidden - - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 23 "ComplexTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = (@object); - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 21 "ComplexTagHelpers.cshtml" - __TestNamespace_PTagHelper.Age = DateTimeOffset.Now.Year - 1970; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 26 "ComplexTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = (DateTimeOffset.Now.Year > 2014); - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 25 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = -1970 + @DateTimeOffset.Now.Year; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 29 "ComplexTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = DateTimeOffset.Now.Year > 2014; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 28 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = DateTimeOffset.Now.Year - 1970; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 32 "ComplexTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = @( DateTimeOffset.Now.Year ) > 2014 ; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 31 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = ("My age is this long.".Length); - -#line default -#line hidden -#line 34 "ComplexTagHelpers.cshtml" - __o = someMethod(item => new Template(async(__razor_template_writer) => { - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 34 "ComplexTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = checked; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 34 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = 123; - -#line default -#line hidden -} -) -); - -#line default -#line hidden -#line 36 "ComplexTagHelpers.cshtml" -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.cs deleted file mode 100644 index 1d22386568..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ComplexTagHelpers.cs +++ /dev/null @@ -1,535 +0,0 @@ -#pragma checksum "ComplexTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "3cc5f5ed458e4e33874c4242798b195a31ab065c" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ComplexTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", new global::Microsoft.AspNetCore.Html.HtmlString(""), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("Enter in a new time..."), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("unbound", new global::Microsoft.AspNetCore.Html.HtmlString("first value"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("unbound", new global::Microsoft.AspNetCore.Html.HtmlString("second value"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("unbound", new global::Microsoft.AspNetCore.Html.HtmlString("hello"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("unbound", new global::Microsoft.AspNetCore.Html.HtmlString("world"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("hello"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public ComplexTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 3 "ComplexTagHelpers.cshtml" - if (true) -{ - var checkbox = "checkbox"; - - -#line default -#line hidden - - Instrumentation.BeginContext(82, 55, true); - WriteLiteral("
        \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(175, 34, true); - WriteLiteral("\r\n

        Set Time:

        \r\n"); - Instrumentation.EndContext(); -#line 10 "ComplexTagHelpers.cshtml" - - -#line default -#line hidden - -#line 10 "ComplexTagHelpers.cshtml" - if (false) - { - -#line default -#line hidden - - Instrumentation.BeginContext(249, 16, true); - WriteLiteral(" "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(268, 10, true); - WriteLiteral("New Time: "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_0.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(278, 66, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(265, 83, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(348, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 13 "ComplexTagHelpers.cshtml" - } - else - { - -#line default -#line hidden - - Instrumentation.BeginContext(398, 16, true); - WriteLiteral(" "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(417, 14, true); - WriteLiteral("Current Time: "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - BeginWriteTagHelperAttribute(); -#line 16 "ComplexTagHelpers.cshtml" - WriteLiteral(checkbox); - -#line default -#line hidden - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper.Type = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("type", __TestNamespace_InputTagHelper.Type, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 16 "ComplexTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(431, 37, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(414, 58, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(472, 18, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - BeginWriteTagHelperAttribute(); -#line 17 "ComplexTagHelpers.cshtml" - WriteLiteral(true ? "checkbox" : "anything"); - -#line default -#line hidden - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper.Type = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("tYPe", __TestNamespace_InputTagHelper.Type, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(490, 50, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(540, 18, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - BeginWriteTagHelperAttribute(); -#line 18 "ComplexTagHelpers.cshtml" - if(true) { - -#line default -#line hidden - - WriteLiteral("checkbox"); -#line 18 "ComplexTagHelpers.cshtml" - } else { - -#line default -#line hidden - - WriteLiteral("anything"); -#line 18 "ComplexTagHelpers.cshtml" - } - -#line default -#line hidden - - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper.Type = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("type", __TestNamespace_InputTagHelper.Type, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(558, 79, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(639, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 19 "ComplexTagHelpers.cshtml" - } - -#line default -#line hidden - - Instrumentation.BeginContext(656, 8, true); - WriteLiteral(" "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "time", 3, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 146, "Current", 146, 7, true); - AddHtmlAttributeValue(" ", 153, "Time:", 154, 6, true); -#line 8 "ComplexTagHelpers.cshtml" -AddHtmlAttributeValue(" ", 159, DateTime.Now, 160, 14, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(137, 529, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(668, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(765, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 22 "ComplexTagHelpers.cshtml" - - -#line default -#line hidden - -#line 22 "ComplexTagHelpers.cshtml" - var @object = false; - -#line default -#line hidden - - Instrumentation.BeginContext(805, 12, true); - WriteLiteral(" "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); -#line 23 "ComplexTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = (@object); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("ChecKED", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(817, 28, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(845, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); -#line 21 "ComplexTagHelpers.cshtml" - __TestNamespace_PTagHelper.Age = DateTimeOffset.Now.Year - 1970; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(678, 181, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(859, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(911, 14, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); -#line 26 "ComplexTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = (DateTimeOffset.Now.Year > 2014); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(925, 85, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(1010, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 25 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = -1970 + @DateTimeOffset.Now.Year; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(869, 155, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(1024, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(1074, 14, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); -#line 29 "ComplexTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = DateTimeOffset.Now.Year > 2014; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(1088, 48, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(1136, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 28 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = DateTimeOffset.Now.Year - 1970; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(1034, 116, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(1150, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(1202, 14, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); -#line 32 "ComplexTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = @( DateTimeOffset.Now.Year ) > 2014 ; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(1216, 63, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(1279, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 31 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = ("My age is this long.".Length); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(1160, 133, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(1293, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(1304, 11, false); -#line 34 "ComplexTagHelpers.cshtml" - Write(someMethod(item => new Template(async(__razor_template_writer) => { - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); -#line 34 "ComplexTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = checked; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(1343, 26, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 34 "ComplexTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = 123; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(1316, 57, false); - WriteTo(__razor_template_writer, __tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); -} -) -)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(1374, 14, true); - WriteLiteral("\r\n
        \r\n"); - Instrumentation.EndContext(); -#line 36 "ComplexTagHelpers.cshtml" -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.DesignTime.cs deleted file mode 100644 index 15ba430321..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.DesignTime.cs +++ /dev/null @@ -1,162 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ConditionalAttributes - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public ConditionalAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "ConditionalAttributes.cshtml" - - var ch = true; - var cls = "bar"; - - -#line default -#line hidden - -#line 4 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 5 "ConditionalAttributes.cshtml" - __o = cls; - -#line default -#line hidden -#line 5 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 6 "ConditionalAttributes.cshtml" - __o = cls; - -#line default -#line hidden -#line 6 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 7 "ConditionalAttributes.cshtml" - __o = cls; - -#line default -#line hidden -#line 7 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 8 "ConditionalAttributes.cshtml" - __o = ch; - -#line default -#line hidden -#line 8 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 9 "ConditionalAttributes.cshtml" - __o = ch; - -#line default -#line hidden -#line 9 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 10 "ConditionalAttributes.cshtml" - if(cls != null) { - -#line default -#line hidden - -#line 10 "ConditionalAttributes.cshtml" - __o = cls; - -#line default -#line hidden -#line 10 "ConditionalAttributes.cshtml" - } - -#line default -#line hidden - -#line 10 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 11 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 12 "ConditionalAttributes.cshtml" - __o = Url.Content("~/Scripts/jquery-1.6.2.min.js"); - -#line default -#line hidden -#line 12 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 13 "ConditionalAttributes.cshtml" - __o = Url.Content("~/Scripts/modernizr-2.0.6-development-only.js"); - -#line default -#line hidden -#line 13 "ConditionalAttributes.cshtml" - - - -#line default -#line hidden - -#line 14 "ConditionalAttributes.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.cs deleted file mode 100644 index 4fe76000d9..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ConditionalAttributes.cs +++ /dev/null @@ -1,136 +0,0 @@ -#pragma checksum "ConditionalAttributes.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "088be4e50958bcab0f1d1ac04d2c28dcd8049bf5" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ConditionalAttributes - { - #line hidden - public ConditionalAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "ConditionalAttributes.cshtml" - - var ch = true; - var cls = "bar"; - -#line default -#line hidden - - Instrumentation.BeginContext(46, 28, true); - WriteLiteral("
        \r\n \r\n 0 TagHelpers.\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(240, 11, true); - WriteLiteral("1 TagHelper"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "href", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 231, "~/", 231, 2, true); -#line 8 "CssSelectorTagHelperAttributes.cshtml" -AddHtmlAttributeValue("", 233, false, 233, 6, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(223, 32, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(255, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(288, 11, true); - WriteLiteral("1 TagHelper"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(257, 46, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(303, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(337, 11, true); - WriteLiteral("1 TagHelper"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "href", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - AddHtmlAttributeValue("", 314, "~/?hello=world", 314, 14, true); -#line 10 "CssSelectorTagHelperAttributes.cshtml" -AddHtmlAttributeValue(" ", 328, false, 329, 7, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(305, 47, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(352, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_CatchAllTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(354, 42, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(396, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_CatchAllTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper2); - __TestNamespace_InputTagHelper2.Type = (string)__tagHelperAttribute_6.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(398, 43, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(441, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_CatchAllTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper2); - __TestNamespace_InputTagHelper2.Type = (string)__tagHelperAttribute_7.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(443, 45, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DesignTime.cs deleted file mode 100644 index ab5c840087..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DesignTime.cs +++ /dev/null @@ -1,70 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class DesignTime - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public DesignTime() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 2 "DesignTime.cshtml" - for(int i = 1; i <= 10; i++) { - - -#line default -#line hidden - -#line 3 "DesignTime.cshtml" - __o = i; - -#line default -#line hidden -#line 3 "DesignTime.cshtml" - - } - -#line default -#line hidden - -#line 8 "DesignTime.cshtml" -__o = Foo(Bar.Baz); - -#line default -#line hidden -#line 9 "DesignTime.cshtml" -__o = Foo(item => new Template(async(__razor_template_writer) => { -#line 9 "DesignTime.cshtml" - __o = baz; - -#line default -#line hidden -} -) -); - -#line default -#line hidden - DefineSection("Footer", async(__razor_section_writer) => { -#line 14 "DesignTime.cshtml" -__o = bar; - -#line default -#line hidden - } - ); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.DesignTime.cs deleted file mode 100644 index 2ccc2637c3..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.DesignTime.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class DuplicateAttributeTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public DuplicateAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "button"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "button"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 5 "DuplicateAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = "button"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "DuplicateAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 3 "DuplicateAttributeTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = 3; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.cs deleted file mode 100644 index e391bebd50..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateAttributeTagHelpers.cs +++ /dev/null @@ -1,142 +0,0 @@ -#pragma checksum "DuplicateAttributeTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "b7cbc77774bfe558f4548cc5b3760f88754a329e" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class DuplicateAttributeTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("AGE", new global::Microsoft.AspNetCore.Html.HtmlString("40"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("Age", new global::Microsoft.AspNetCore.Html.HtmlString("500"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "button", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("TYPE", new global::Microsoft.AspNetCore.Html.HtmlString("checkbox"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("checkbox"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("checked", new global::Microsoft.AspNetCore.Html.HtmlString("false"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "button", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("checked", new global::Microsoft.AspNetCore.Html.HtmlString("true"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("checked", new global::Microsoft.AspNetCore.Html.HtmlString("true"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public DuplicateAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(63, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_2.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(69, 39, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(108, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_2.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 5 "DuplicateAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(114, 70, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(184, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_6.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "DuplicateAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(190, 96, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(286, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 3 "DuplicateAttributeTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = 3; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(33, 259, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateTargetTagHelper.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateTargetTagHelper.cs deleted file mode 100644 index c4274767f5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DuplicateTargetTagHelper.cs +++ /dev/null @@ -1,57 +0,0 @@ -#pragma checksum "DuplicateTargetTagHelper.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1014725b9048d825ce97b0e5e260ac35f057fe0a" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class DuplicateTargetTagHelper - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "checkbox", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public DuplicateTargetTagHelper() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_0.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); - __TestNamespace_CatchAllTagHelper.Type = __TestNamespace_InputTagHelper.Type; -#line 3 "DuplicateTargetTagHelper.cshtml" -__TestNamespace_InputTagHelper.Checked = true; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_CatchAllTagHelper.Checked = __TestNamespace_InputTagHelper.Checked; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(33, 40, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.DesignTime.cs deleted file mode 100644 index 0d0e312108..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.DesignTime.cs +++ /dev/null @@ -1,199 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class DynamicAttributeTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - #line hidden - public DynamicAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_InputTagHelper = CreateTagHelper(); -#line 3 "DynamicAttributeTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); -#line 5 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - -#line 5 "DynamicAttributeTagHelpers.cshtml" - __o = string.Empty; - -#line default -#line hidden -#line 5 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - -#line 5 "DynamicAttributeTagHelpers.cshtml" - __o = false; - -#line default -#line hidden -#line 5 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - - __TestNamespace_InputTagHelper = CreateTagHelper(); -#line 7 "DynamicAttributeTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Bound = string.Empty; -#line 7 "DynamicAttributeTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); -#line 9 "DynamicAttributeTagHelpers.cshtml" - __o = long.MinValue; - -#line default -#line hidden -#line 9 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - -#line 9 "DynamicAttributeTagHelpers.cshtml" - __o = string.Empty; - -#line default -#line hidden -#line 9 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - -#line 9 "DynamicAttributeTagHelpers.cshtml" - __o = false; - -#line default -#line hidden -#line 9 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - -#line 9 "DynamicAttributeTagHelpers.cshtml" - __o = int.MaxValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Bound = string.Empty; -#line 10 "DynamicAttributeTagHelpers.cshtml" - __o = long.MinValue; - -#line default -#line hidden -#line 10 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - -#line 10 "DynamicAttributeTagHelpers.cshtml" - __o = string.Empty; - -#line default -#line hidden -#line 10 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - -#line 10 "DynamicAttributeTagHelpers.cshtml" - __o = false; - -#line default -#line hidden -#line 10 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - -#line 10 "DynamicAttributeTagHelpers.cshtml" - __o = int.MaxValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); -#line 12 "DynamicAttributeTagHelpers.cshtml" - __o = long.MinValue; - -#line default -#line hidden -#line 12 "DynamicAttributeTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden -#line 12 "DynamicAttributeTagHelpers.cshtml" - __o = int.MaxValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); -#line 14 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - -#line 14 "DynamicAttributeTagHelpers.cshtml" - __o = string.Empty; - -#line default -#line hidden -#line 14 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - -#line 14 "DynamicAttributeTagHelpers.cshtml" - __o = false; - -#line default -#line hidden -#line 14 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.cs deleted file mode 100644 index 61d21421e9..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/DynamicAttributeTagHelpers.cs +++ /dev/null @@ -1,321 +0,0 @@ -#pragma checksum "DynamicAttributeTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "107e341010aad754fc5c952722dbfdc7e33fc38e" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class DynamicAttributeTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - #line hidden - public DynamicAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unbound", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 49, "prefix", 49, 6, true); -#line 3 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue(" ", 55, DateTime.Now, 56, 14, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(33, 40, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(73, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unbound", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 93, new Template(async(__razor_attribute_value_writer) => { -#line 5 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - - Instrumentation.BeginContext(107, 12, false); -#line 5 "DynamicAttributeTagHelpers.cshtml" -WriteTo(__razor_attribute_value_writer, string.Empty); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 5 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - - Instrumentation.BeginContext(130, 5, false); -#line 5 "DynamicAttributeTagHelpers.cshtml" - WriteTo(__razor_attribute_value_writer, false); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 5 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - - } - ), 93, 44, false); - AddHtmlAttributeValue(" ", 137, "suffix", 138, 7, true); - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(77, 71, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(148, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - BeginWriteTagHelperAttribute(); - WriteLiteral("prefix "); -#line 7 "DynamicAttributeTagHelpers.cshtml" - WriteLiteral(DateTime.Now); - -#line default -#line hidden - WriteLiteral(" suffix"); - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper.Bound = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("bound", __TestNamespace_InputTagHelper.Bound, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unbound", 3, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 204, "prefix", 204, 6, true); -#line 7 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue(" ", 210, DateTime.Now, 211, 14, false); - -#line default -#line hidden - AddHtmlAttributeValue(" ", 224, "suffix", 225, 7, true); - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(152, 83, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(235, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - BeginWriteTagHelperAttribute(); -#line 9 "DynamicAttributeTagHelpers.cshtml" - WriteLiteral(long.MinValue); - -#line default -#line hidden - WriteLiteral(" "); -#line 9 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - -#line 9 "DynamicAttributeTagHelpers.cshtml" - WriteLiteral(string.Empty); - -#line default -#line hidden -#line 9 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - -#line 9 "DynamicAttributeTagHelpers.cshtml" - WriteLiteral(false); - -#line default -#line hidden -#line 9 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - - WriteLiteral(" "); -#line 9 "DynamicAttributeTagHelpers.cshtml" - WriteLiteral(int.MaxValue); - -#line default -#line hidden - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper.Bound = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("bound", __TestNamespace_InputTagHelper.Bound, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unbound", 3, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); -#line 10 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue("", 345, long.MinValue, 345, 14, false); - -#line default -#line hidden - AddHtmlAttributeValue(" ", 359, new Template(async(__razor_attribute_value_writer) => { -#line 10 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - - Instrumentation.BeginContext(374, 12, false); -#line 10 "DynamicAttributeTagHelpers.cshtml" - WriteTo(__razor_attribute_value_writer, string.Empty); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 10 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - - Instrumentation.BeginContext(397, 5, false); -#line 10 "DynamicAttributeTagHelpers.cshtml" - WriteTo(__razor_attribute_value_writer, false); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 10 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - - } - ), 360, 45, false); -#line 10 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue(" ", 404, int.MaxValue, 405, 14, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(239, 183, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(422, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unbound", 5, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); -#line 12 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue("", 442, long.MinValue, 442, 14, false); - -#line default -#line hidden -#line 12 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue(" ", 456, DateTime.Now, 457, 14, false); - -#line default -#line hidden - AddHtmlAttributeValue(" ", 470, "static", 471, 7, true); - AddHtmlAttributeValue(" ", 477, "content", 481, 11, true); -#line 12 "DynamicAttributeTagHelpers.cshtml" -AddHtmlAttributeValue(" ", 488, int.MaxValue, 489, 14, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(426, 80, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(506, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unbound", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 526, new Template(async(__razor_attribute_value_writer) => { -#line 14 "DynamicAttributeTagHelpers.cshtml" - if (true) { - -#line default -#line hidden - - Instrumentation.BeginContext(540, 12, false); -#line 14 "DynamicAttributeTagHelpers.cshtml" -WriteTo(__razor_attribute_value_writer, string.Empty); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 14 "DynamicAttributeTagHelpers.cshtml" - } else { - -#line default -#line hidden - - Instrumentation.BeginContext(563, 5, false); -#line 14 "DynamicAttributeTagHelpers.cshtml" - WriteTo(__razor_attribute_value_writer, false); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 14 "DynamicAttributeTagHelpers.cshtml" - } - -#line default -#line hidden - - } - ), 526, 44, false); - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(510, 64, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.DesignTime.cs deleted file mode 100644 index aa780a5ec2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.DesignTime.cs +++ /dev/null @@ -1,55 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyAttributeTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - #line hidden - public EmptyAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = ""; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 4 "EmptyAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = ; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __TestNamespace_InputTagHelper.Type = ""; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "EmptyAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = ; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 5 "EmptyAttributeTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = ; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.cs deleted file mode 100644 index e1dda8f7ec..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyAttributeTagHelpers.cs +++ /dev/null @@ -1,113 +0,0 @@ -#pragma checksum "EmptyAttributeTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ab5e45403d2c57cfdbab9546c3a27eea94f0fb5c" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyAttributeTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString(""), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - #line hidden - public EmptyAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(25, 13, true); - WriteLiteral("\r\n
        \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_0.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 4 "EmptyAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = ; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(38, 34, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(72, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(88, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_0.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "EmptyAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.Checked = ; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("checked", __TestNamespace_InputTagHelper2.Checked, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(98, 34, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(132, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 5 "EmptyAttributeTagHelpers.cshtml" -__TestNamespace_PTagHelper.Age = ; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(78, 64, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(142, 8, true); - WriteLiteral("\r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyCodeBlock.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyCodeBlock.cs deleted file mode 100644 index eb0800cdd6..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyCodeBlock.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyCodeBlock - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public EmptyCodeBlock() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "EmptyCodeBlock.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyExplicitExpression.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyExplicitExpression.cs deleted file mode 100644 index fbbc8eb332..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyExplicitExpression.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyExplicitExpression - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public EmptyExplicitExpression() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "EmptyExplicitExpression.cshtml" -__o = ; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpression.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpression.cs deleted file mode 100644 index 494a30144d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpression.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyImplicitExpression - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public EmptyImplicitExpression() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "EmptyImplicitExpression.cshtml" -__o = ; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.Tabs.cs deleted file mode 100644 index 7d0abf3422..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.Tabs.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyImplicitExpressionInCode - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public EmptyImplicitExpressionInCode() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "EmptyImplicitExpressionInCode.cshtml" - - - -#line default -#line hidden - -#line 2 "EmptyImplicitExpressionInCode.cshtml" -__o = ; - -#line default -#line hidden -#line 2 "EmptyImplicitExpressionInCode.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.cs deleted file mode 100644 index b155a95fb7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EmptyImplicitExpressionInCode.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EmptyImplicitExpressionInCode - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public EmptyImplicitExpressionInCode() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "EmptyImplicitExpressionInCode.cshtml" - - - -#line default -#line hidden - -#line 2 "EmptyImplicitExpressionInCode.cshtml" -__o = ; - -#line default -#line hidden -#line 2 "EmptyImplicitExpressionInCode.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.DesignTime.cs deleted file mode 100644 index d751974b76..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.DesignTime.cs +++ /dev/null @@ -1,82 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EnumTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - #line hidden - public EnumTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "EnumTagHelpers.cshtml" - - var enumValue = MyEnum.MyValue; - -#line default -#line hidden - - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 7 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = MyEnum.MyValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 8 "EnumTagHelpers.cshtml" - __o = MyEnum.MySecondValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 9 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = global::Microsoft.AspNetCore.Razor.Test.CodeGenerators.MyEnum.MyValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 10 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = global::Microsoft.AspNetCore.Razor.Test.CodeGenerators.MyEnum.MySecondValue; - -#line default -#line hidden -#line 10 "EnumTagHelpers.cshtml" -__TestNamespace_CatchAllTagHelper.CatchAll = global::Microsoft.AspNetCore.Razor.Test.CodeGenerators.MyEnum.MyValue; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 11 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = enumValue; - -#line default -#line hidden -#line 11 "EnumTagHelpers.cshtml" -__TestNamespace_CatchAllTagHelper.CatchAll = enumValue; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.cs deleted file mode 100644 index f2deaa0f28..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EnumTagHelpers.cs +++ /dev/null @@ -1,162 +0,0 @@ -#pragma checksum "EnumTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f9124dcd7da8c06ab193a971690c676c5e0adaac" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EnumTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - #line hidden - public EnumTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 3 "EnumTagHelpers.cshtml" - - var enumValue = MyEnum.MyValue; - -#line default -#line hidden - - Instrumentation.BeginContext(77, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); -#line 7 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = MyEnum.MyValue; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("value", __TestNamespace_InputTagHelper.Value, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(79, 33, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(112, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); -#line 8 "EnumTagHelpers.cshtml" -AddHtmlAttributeValue("", 128, MyEnum.MySecondValue, 128, 21, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(114, 39, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(153, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); -#line 9 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = global::Microsoft.AspNetCore.Razor.Test.CodeGenerators.MyEnum.MyValue; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("value", __TestNamespace_InputTagHelper.Value, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(155, 25, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(180, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); -#line 10 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = global::Microsoft.AspNetCore.Razor.Test.CodeGenerators.MyEnum.MySecondValue; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("value", __TestNamespace_InputTagHelper.Value, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); -#line 10 "EnumTagHelpers.cshtml" -__TestNamespace_CatchAllTagHelper.CatchAll = global::Microsoft.AspNetCore.Razor.Test.CodeGenerators.MyEnum.MyValue; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("catch-all", __TestNamespace_CatchAllTagHelper.CatchAll, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(182, 50, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(232, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); -#line 11 "EnumTagHelpers.cshtml" -__TestNamespace_InputTagHelper.Value = enumValue; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("value", __TestNamespace_InputTagHelper.Value, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); -#line 11 "EnumTagHelpers.cshtml" -__TestNamespace_CatchAllTagHelper.CatchAll = enumValue; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("catch-all", __TestNamespace_CatchAllTagHelper.CatchAll, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(234, 51, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(285, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.DesignTime.cs deleted file mode 100644 index 2da21ca935..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.DesignTime.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EscapedTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public EscapedTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 4 "EscapedTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 6 "EscapedTagHelpers.cshtml" - __o = DateTime.Now; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Type = string.Empty; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 6 "EscapedTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.cs deleted file mode 100644 index 24cae06ea5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/EscapedTagHelpers.cs +++ /dev/null @@ -1,75 +0,0 @@ -#pragma checksum "EscapedTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "93da17a7091c4d218cfc54282dec1b7b7beac072" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class EscapedTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public EscapedTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(25, 72, true); - WriteLiteral("\r\n
        \r\n \r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpression.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpression.cs deleted file mode 100644 index 5b4efaa4b0..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpression.cs +++ /dev/null @@ -1,30 +0,0 @@ -#pragma checksum "ExplicitExpression.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a897a227b26c531d644bdff988df46d3c8178346" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ExplicitExpression - { - #line hidden - public ExplicitExpression() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(0, 8, true); - WriteLiteral("1 + 1 = "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(10, 3, false); -#line 1 "ExplicitExpression.cshtml" - Write(1+1); - -#line default -#line hidden - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionAtEOF.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionAtEOF.cs deleted file mode 100644 index 5d622dc91c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionAtEOF.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ExplicitExpressionAtEOF - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public ExplicitExpressionAtEOF() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "ExplicitExpressionAtEOF.cshtml" -__o = ; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.DesignTime.cs deleted file mode 100644 index eccd240bec..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.DesignTime.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ExplicitExpressionWithMarkup - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public ExplicitExpressionWithMarkup() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "ExplicitExpressionWithMarkup.cshtml" -item => new Template(async(__razor_template_writer) => { -} -) -; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.cs deleted file mode 100644 index 7d82532ea1..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExplicitExpressionWithMarkup.cs +++ /dev/null @@ -1,36 +0,0 @@ -#pragma checksum "ExplicitExpressionWithMarkup.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1252c799cdeb86a71e4304f01ebaae540fa26894" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ExplicitExpressionWithMarkup - { - #line hidden - public ExplicitExpressionWithMarkup() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(0, 5, true); - WriteLiteral("
        "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(14, 0, false); -#line 1 "ExplicitExpressionWithMarkup.cshtml" - Write(item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(8, 6, true); - WriteLiteralTo(__razor_template_writer, "
        "); - Instrumentation.EndContext(); -} -) -); - -#line default -#line hidden - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExpressionsInCode.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExpressionsInCode.cs deleted file mode 100644 index ca08cf1f7d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ExpressionsInCode.cs +++ /dev/null @@ -1,88 +0,0 @@ -#pragma checksum "ExpressionsInCode.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8c7ae67489dbddec9f2dbef3c2b65def1149e507" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ExpressionsInCode - { - #line hidden - public ExpressionsInCode() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "ExpressionsInCode.cshtml" - - object foo = null; - string bar = "Foo"; - -#line default -#line hidden - - Instrumentation.BeginContext(56, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 6 "ExpressionsInCode.cshtml" - if(foo != null) { - - -#line default -#line hidden - - Instrumentation.BeginContext(83, 3, false); -#line 7 "ExpressionsInCode.cshtml" -Write(foo); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 7 "ExpressionsInCode.cshtml" - -} else { - -#line default -#line hidden - - Instrumentation.BeginContext(98, 25, true); - WriteLiteral("

        Foo is Null!

        \r\n"); - Instrumentation.EndContext(); -#line 10 "ExpressionsInCode.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(126, 7, true); - WriteLiteral("\r\n

        \r\n"); - Instrumentation.EndContext(); -#line 13 "ExpressionsInCode.cshtml" - if(!String.IsNullOrEmpty(bar)) { - - -#line default -#line hidden - - Instrumentation.BeginContext(174, 21, false); -#line 14 "ExpressionsInCode.cshtml" -Write(bar.Replace("F", "B")); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 14 "ExpressionsInCode.cshtml" - -} - -#line default -#line hidden - - Instrumentation.BeginContext(201, 4, true); - WriteLiteral("

        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.Tabs.cs deleted file mode 100644 index dbdeaa69d8..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.Tabs.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class FunctionsBlock - { - private static object @__o; -#line 1 "FunctionsBlock.cshtml" - - - -#line default -#line hidden -#line 5 "FunctionsBlock.cshtml" - - Random _rand = new Random(); - private int RandomInt() { - return _rand.Next(); - } - -#line default -#line hidden - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public FunctionsBlock() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 12 "FunctionsBlock.cshtml" - __o = RandomInt(); - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.cs deleted file mode 100644 index 1418718f62..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.DesignTime.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class FunctionsBlock - { - private static object @__o; -#line 1 "FunctionsBlock.cshtml" - - - -#line default -#line hidden -#line 5 "FunctionsBlock.cshtml" - - Random _rand = new Random(); - private int RandomInt() { - return _rand.Next(); - } - -#line default -#line hidden - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public FunctionsBlock() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 12 "FunctionsBlock.cshtml" - __o = RandomInt(); - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.cs deleted file mode 100644 index 0543d15861..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock.cs +++ /dev/null @@ -1,48 +0,0 @@ -#pragma checksum "FunctionsBlock.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "94813053694a285515d791c48d703f1131881d0c" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class FunctionsBlock - { -#line 1 "FunctionsBlock.cshtml" - - - -#line default -#line hidden -#line 5 "FunctionsBlock.cshtml" - - Random _rand = new Random(); - private int RandomInt() { - return _rand.Next(); - } - -#line default -#line hidden - #line hidden - public FunctionsBlock() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(19, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(140, 26, true); - WriteLiteral("\r\nHere\'s a random number: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(167, 11, false); -#line 12 "FunctionsBlock.cshtml" - Write(RandomInt()); - -#line default -#line hidden - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlockMinimal.DesignTime.Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlockMinimal.DesignTime.Tabs.cs deleted file mode 100644 index b35b565bed..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlockMinimal.DesignTime.Tabs.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class FunctionsBlockMinimal - { - private static object @__o; -#line 3 "FunctionsBlockMinimal.cshtml" - -string foo(string input) { - return input + "!"; -} - -#line default -#line hidden - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public FunctionsBlockMinimal() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock_Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock_Tabs.cs deleted file mode 100644 index 799be52572..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/FunctionsBlock_Tabs.cs +++ /dev/null @@ -1,48 +0,0 @@ -#pragma checksum "FunctionsBlock_Tabs.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "3e566e32504e461e14de41901beb954faf0a3724" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class FunctionsBlock_Tabs - { -#line 1 "FunctionsBlock_Tabs.cshtml" - - - -#line default -#line hidden -#line 5 "FunctionsBlock_Tabs.cshtml" - - Random _rand = new Random(); - private int RandomInt() { - return _rand.Next(); - } - -#line default -#line hidden - #line hidden - public FunctionsBlock_Tabs() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(19, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(125, 26, true); - WriteLiteral("\r\nHere\'s a random number: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(152, 11, false); -#line 12 "FunctionsBlock_Tabs.cshtml" - Write(RandomInt()); - -#line default -#line hidden - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HiddenSpansInCode.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HiddenSpansInCode.cs deleted file mode 100644 index 801afd6a3d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HiddenSpansInCode.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class HiddenSpansInCode - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public HiddenSpansInCode() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "HiddenSpansInCode.cshtml" - - - -#line default -#line hidden - -#line 2 "HiddenSpansInCode.cshtml" - @Da - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Double.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Double.cs deleted file mode 100644 index 762800e139..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Double.cs +++ /dev/null @@ -1,23 +0,0 @@ -#pragma checksum "HtmlCommentWithQuote_Double.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a07711bc1fd0478b3b8329a68ab2028ef93429df" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class HtmlCommentWithQuote_Double - { - #line hidden - public HtmlCommentWithQuote_Double() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(0, 45, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Single.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Single.cs deleted file mode 100644 index a95ffb4691..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/HtmlCommentWithQuote_Single.cs +++ /dev/null @@ -1,23 +0,0 @@ -#pragma checksum "HtmlCommentWithQuote_Single.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "2d9bb4407e7aac9563aaeac9f0534a48f54e3d44" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class HtmlCommentWithQuote_Single - { - #line hidden - public HtmlCommentWithQuote_Single() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(0, 45, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpression.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpression.cs deleted file mode 100644 index 2cd6ebeebc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpression.cs +++ /dev/null @@ -1,45 +0,0 @@ -#pragma checksum "ImplicitExpression.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "77befd9645f3c2d9ab48b935faebf9f731f42abc" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ImplicitExpression - { - #line hidden - public ImplicitExpression() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "ImplicitExpression.cshtml" - for(int i = 1; i <= 10; i++) { - -#line default -#line hidden - - Instrumentation.BeginContext(33, 21, true); - WriteLiteral("

        This is item #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(55, 1, false); -#line 2 "ImplicitExpression.cshtml" - Write(i); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(56, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 3 "ImplicitExpression.cshtml" -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpressionAtEOF.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpressionAtEOF.cs deleted file mode 100644 index 6d16d13c43..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ImplicitExpressionAtEOF.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ImplicitExpressionAtEOF - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public ImplicitExpressionAtEOF() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "ImplicitExpressionAtEOF.cshtml" -__o = ; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.DesignTime.cs deleted file mode 100644 index 0c952d7cd0..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.DesignTime.cs +++ /dev/null @@ -1,70 +0,0 @@ -namespace TestOutput -{ -#line 1 "Imports.cshtml" -using System.IO - -#line default -#line hidden - ; -#line 2 "Imports.cshtml" -using Foo = System.Text.Encoding - -#line default -#line hidden - ; -#line 3 "Imports.cshtml" -using System - -#line default -#line hidden - ; -#line 5 "Imports.cshtml" -using static System - -#line default -#line hidden - ; -#line 6 "Imports.cshtml" -using static System.Console - -#line default -#line hidden - ; -#line 7 "Imports.cshtml" -using static global::System.Text.Encoding - -#line default -#line hidden - ; - using System.Threading.Tasks; - - public class Imports - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public Imports() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 9 "Imports.cshtml" - __o = typeof(Path).FullName; - -#line default -#line hidden -#line 10 "Imports.cshtml" - __o = typeof(Foo).FullName; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.cs deleted file mode 100644 index a44bf96adf..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Imports.cs +++ /dev/null @@ -1,81 +0,0 @@ -#pragma checksum "Imports.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f452adb7c255f6d9d6d2573c6add7cb28022b151" -namespace TestOutput -{ -#line 1 "Imports.cshtml" -using System.IO - -#line default -#line hidden - ; -#line 2 "Imports.cshtml" -using Foo = System.Text.Encoding - -#line default -#line hidden - ; -#line 3 "Imports.cshtml" -using System - -#line default -#line hidden - ; -#line 5 "Imports.cshtml" -using static System - -#line default -#line hidden - ; -#line 6 "Imports.cshtml" -using static System.Console - -#line default -#line hidden - ; -#line 7 "Imports.cshtml" -using static global::System.Text.Encoding - -#line default -#line hidden - ; - using System.Threading.Tasks; - - public class Imports - { - #line hidden - public Imports() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(68, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(166, 30, true); - WriteLiteral("\r\n

        Path\'s full type name is "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(197, 21, false); -#line 9 "Imports.cshtml" - Write(typeof(Path).FullName); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(218, 40, true); - WriteLiteral("

        \r\n

        Foo\'s actual full type name is "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(259, 20, false); -#line 10 "Imports.cshtml" - Write(typeof(Foo).FullName); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(279, 4, true); - WriteLiteral("

        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/IncompleteTagHelper.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/IncompleteTagHelper.cs deleted file mode 100644 index 6e82339611..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/IncompleteTagHelper.cs +++ /dev/null @@ -1,45 +0,0 @@ -#pragma checksum "IncompleteTagHelper.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "762284e0617212ef833fd39f08039bf078039570" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class IncompleteTagHelper - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString(""), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public IncompleteTagHelper() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(33, 10, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Designtime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Designtime.cs deleted file mode 100644 index 55781e57a9..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Designtime.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Inherits : foo.bar>.boz bar - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 -#line 3 "Inherits.cshtml" - foo.bar>.boz bar __inheritsHelper = null; - -#line default -#line hidden - #pragma warning restore 219 - } - #line hidden - public Inherits() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "Inherits.cshtml" -__o = foo(); - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Runtime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Runtime.cs deleted file mode 100644 index c875e9d4c1..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Inherits.Runtime.cs +++ /dev/null @@ -1,30 +0,0 @@ -#pragma checksum "Inherits.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "72d6e21c6366f99a17c63abebb46db3470f4d1da" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Inherits : foo.bar>.boz bar - { - #line hidden - public Inherits() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(1, 5, false); -#line 1 "Inherits.cshtml" -Write(foo()); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(6, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/InlineBlocks.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/InlineBlocks.cs deleted file mode 100644 index a1045939cb..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/InlineBlocks.cs +++ /dev/null @@ -1,62 +0,0 @@ -#pragma checksum "InlineBlocks.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "e827e93343a95c7254a19287b095dfba9390d29f" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class InlineBlocks - { - #line hidden - public InlineBlocks() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - DefineSection("Link", async(__razor_section_writer) => { - } - ); - Instrumentation.BeginContext(13, 23, true); - WriteLiteral("(string link) {\r\n { -#line 2 "InlineBlocks.cshtml" - if(link != null) { - -#line default -#line hidden - - Instrumentation.BeginContext(64, 4, false); -#line 2 "InlineBlocks.cshtml" -WriteTo(__razor_attribute_value_writer, link); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 2 "InlineBlocks.cshtml" - } else { - -#line default -#line hidden - - Instrumentation.BeginContext(84, 1, true); - WriteLiteralTo(__razor_attribute_value_writer, "#"); - Instrumentation.EndContext(); -#line 2 "InlineBlocks.cshtml" - } - -#line default -#line hidden - - } - ), 43, 50, false); - EndWriteAttribute(); - Instrumentation.BeginContext(95, 6, true); - WriteLiteral(" />\r\n}"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Instrumented.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Instrumented.cs deleted file mode 100644 index e18a590214..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Instrumented.cs +++ /dev/null @@ -1,208 +0,0 @@ -#pragma checksum "Instrumented.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "9b521264e3e64710635c0f0490a368845d90da66" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Instrumented - { - #line hidden - public Instrumented() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "Instrumented.cshtml" - - int i = 1; - var foo = - -#line default -#line hidden - - item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(35, 10, true); - WriteLiteralTo(__razor_template_writer, "

        Bar

        "); - Instrumentation.EndContext(); - } - ) -#line 3 "Instrumented.cshtml" - ; - -#line default -#line hidden - - Instrumentation.BeginContext(48, 43, true); - WriteLiteral(" Hello, World\r\n

        Hello, World

        \r\n"); - Instrumentation.EndContext(); -#line 6 "Instrumented.cshtml" - -#line default -#line hidden - - Instrumentation.BeginContext(96, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 8 "Instrumented.cshtml" - while(i <= 10) { - -#line default -#line hidden - - Instrumentation.BeginContext(117, 23, true); - WriteLiteral("

        Hello from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(142, 1, false); -#line 9 "Instrumented.cshtml" - Write(i); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(144, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 10 "Instrumented.cshtml" - i += 1; -} - -#line default -#line hidden - - Instrumentation.BeginContext(166, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 13 "Instrumented.cshtml" - if(i == 11) { - -#line default -#line hidden - - Instrumentation.BeginContext(184, 31, true); - WriteLiteral("

        We wrote 10 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 15 "Instrumented.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(218, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 17 "Instrumented.cshtml" - switch(i) { - case 11: - -#line default -#line hidden - - Instrumentation.BeginContext(248, 46, true); - WriteLiteral("

        No really, we wrote 10 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 20 "Instrumented.cshtml" - break; - default: - -#line default -#line hidden - - Instrumentation.BeginContext(324, 39, true); - WriteLiteral("

        Actually, we didn\'t...

        \r\n"); - Instrumentation.EndContext(); -#line 23 "Instrumented.cshtml" - break; -} - -#line default -#line hidden - - Instrumentation.BeginContext(382, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 26 "Instrumented.cshtml" - for(int j = 1; j <= 10; j += 2) { - -#line default -#line hidden - - Instrumentation.BeginContext(420, 29, true); - WriteLiteral("

        Hello again from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(451, 1, false); -#line 27 "Instrumented.cshtml" - Write(j); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(453, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 28 "Instrumented.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(462, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 30 "Instrumented.cshtml" - try { - -#line default -#line hidden - - Instrumentation.BeginContext(472, 41, true); - WriteLiteral("

        That time, we wrote 5 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 32 "Instrumented.cshtml" -} catch(Exception ex) { - -#line default -#line hidden - - Instrumentation.BeginContext(538, 33, true); - WriteLiteral("

        Oh no! An error occurred: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(573, 10, false); -#line 33 "Instrumented.cshtml" - Write(ex.Message); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(584, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 34 "Instrumented.cshtml" -} - -#line default -#line hidden - - Instrumentation.BeginContext(593, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 36 "Instrumented.cshtml" - lock(new object()) { - -#line default -#line hidden - - Instrumentation.BeginContext(618, 53, true); - WriteLiteral("

        This block is locked, for your security!

        \r\n"); - Instrumentation.EndContext(); -#line 38 "Instrumented.cshtml" -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MarkupInCodeBlock.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MarkupInCodeBlock.cs deleted file mode 100644 index 48cbe037cf..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MarkupInCodeBlock.cs +++ /dev/null @@ -1,46 +0,0 @@ -#pragma checksum "MarkupInCodeBlock.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "cf059b36d7e93e260c1d5b852f7a59e6c99ae33d" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class MarkupInCodeBlock - { - #line hidden - public MarkupInCodeBlock() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "MarkupInCodeBlock.cshtml" - - for(int i = 1; i <= 10; i++) { - -#line default -#line hidden - - Instrumentation.BeginContext(40, 27, true); - WriteLiteral("

        Hello from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(69, 12, false); -#line 3 "MarkupInCodeBlock.cshtml" - Write(i.ToString()); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(82, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 4 "MarkupInCodeBlock.cshtml" - } - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.DesignTime.cs deleted file mode 100644 index d6a4f08419..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.DesignTime.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class MinimizedTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - #line hidden - public MinimizedTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper.BoundRequiredString = "hello"; - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper.BoundRequiredString = "world"; - __TestNamespace_InputTagHelper.BoundRequiredString = "hello2"; - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper.BoundRequiredString = "world"; - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.cs deleted file mode 100644 index f752d66320..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/MinimizedTagHelpers.cs +++ /dev/null @@ -1,139 +0,0 @@ -#pragma checksum "MinimizedTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1356aa716cf24203ad0a7415f199cce7e97089db" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class MinimizedTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("catchall-unbound-required"); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("input-unbound-required"); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("input-bound-required-string", "hello", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("catchall-bound-string", "world", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("input-bound-required-string", "hello2", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("catchall-unbound-required", new global::Microsoft.AspNetCore.Html.HtmlString("hello"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("input-unbound-required", new global::Microsoft.AspNetCore.Html.HtmlString("hello2"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("input-bound-required-string", "world", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public MinimizedTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(62, 34, true); - WriteLiteral("\r\n \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(96, 59, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(155, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - __TestNamespace_InputTagHelper.BoundRequiredString = (string)__tagHelperAttribute_3.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(161, 119, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(280, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - __TestNamespace_CatchAllTagHelper.BoundRequiredString = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper.BoundRequiredString = (string)__tagHelperAttribute_5.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(286, 176, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(462, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __TestNamespace_InputTagHelper.BoundRequiredString = (string)__tagHelperAttribute_8.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(468, 206, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(674, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(33, 647, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.DesignTime.cs deleted file mode 100644 index f9c3a3651a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.DesignTime.cs +++ /dev/null @@ -1,58 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NestedCSharp - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public NestedCSharp() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "NestedCSharp.cshtml" - - - -#line default -#line hidden - -#line 2 "NestedCSharp.cshtml" - foreach (var result in (dynamic)Url) - { - - -#line default -#line hidden - -#line 5 "NestedCSharp.cshtml" - __o = result.SomeValue; - -#line default -#line hidden -#line 6 "NestedCSharp.cshtml" - - } - -#line default -#line hidden - -#line 7 "NestedCSharp.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.cs deleted file mode 100644 index ec93481e5b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCSharp.cs +++ /dev/null @@ -1,59 +0,0 @@ -#pragma checksum "NestedCSharp.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "2b9e8dcf7c08153c15ac84973938a7c0254f2369" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NestedCSharp - { - #line hidden - public NestedCSharp() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "NestedCSharp.cshtml" - - - -#line default -#line hidden - -#line 2 "NestedCSharp.cshtml" - foreach (var result in (dynamic)Url) - { - -#line default -#line hidden - - Instrumentation.BeginContext(54, 27, true); - WriteLiteral("
        \r\n "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(82, 16, false); -#line 5 "NestedCSharp.cshtml" - Write(result.SomeValue); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(98, 19, true); - WriteLiteral(".\r\n
        \r\n"); - Instrumentation.EndContext(); -#line 7 "NestedCSharp.cshtml" - } - -#line default -#line hidden - -#line 7 "NestedCSharp.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCodeBlocks.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCodeBlocks.cs deleted file mode 100644 index bd30b011cb..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedCodeBlocks.cs +++ /dev/null @@ -1,41 +0,0 @@ -#pragma checksum "NestedCodeBlocks.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a4eb7397719094ea9da5b7d6674d317314fa26b4" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NestedCodeBlocks - { - #line hidden - public NestedCodeBlocks() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "NestedCodeBlocks.cshtml" - if(foo) { - - -#line default -#line hidden - -#line 2 "NestedCodeBlocks.cshtml" - if(bar) { - } - -#line default -#line hidden - -#line 3 "NestedCodeBlocks.cshtml" - -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.DesignTime.cs deleted file mode 100644 index 4a6474409d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.DesignTime.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NestedScriptTagTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public NestedScriptTagTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 6 "NestedScriptTagTagHelpers.cshtml" - - -#line default -#line hidden - -#line 6 "NestedScriptTagTagHelpers.cshtml" - for(var i = 0; i < 5; i++) { - -#line default -#line hidden - - __TestNamespace_InputTagHelper = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 8 "NestedScriptTagTagHelpers.cshtml" - __o = ViewBag.DefaultInterval; - -#line default -#line hidden - __TestNamespace_InputTagHelper.Type = "text"; - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; -#line 8 "NestedScriptTagTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.Checked = true; - -#line default -#line hidden -#line 10 "NestedScriptTagTagHelpers.cshtml" - } - -#line default -#line hidden - - __TestNamespace_PTagHelper = CreateTagHelper(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.cs deleted file mode 100644 index a28ce753a2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NestedScriptTagTagHelpers.cs +++ /dev/null @@ -1,118 +0,0 @@ -#pragma checksum "NestedScriptTagTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "e3cbc45bc2d4185bf69128f14721795d68e6961a" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NestedScriptTagTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data-delay", new global::Microsoft.AspNetCore.Html.HtmlString("1000"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public NestedScriptTagTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 106, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); -#line 10 "NestedScriptTagTagHelpers.cshtml" - } - -#line default -#line hidden - - Instrumentation.BeginContext(437, 129, true); - WriteLiteral(" \r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(137, 433, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(570, 23, true); - WriteLiteral("\r\n
        \r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NoLinePragmas.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NoLinePragmas.cs deleted file mode 100644 index 86d4c229b3..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NoLinePragmas.cs +++ /dev/null @@ -1,204 +0,0 @@ -#pragma checksum "" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "682929a2038f56f4737f1b7aa3c9eaa5488cc001" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NoLinePragmas - { - #line hidden - public NoLinePragmas() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "" - - int i = 1; - -#line default -#line hidden - - Instrumentation.BeginContext(23, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 5 "" - while(i <= 10) { - -#line default -#line hidden - - Instrumentation.BeginContext(44, 23, true); - WriteLiteral("

        Hello from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(69, 1, false); -#line 6 "" - Write(i); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(71, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 7 "" - i += 1; -} - -#line default -#line hidden - - Instrumentation.BeginContext(93, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 10 "" - if(i == 11) { - -#line default -#line hidden - - Instrumentation.BeginContext(111, 31, true); - WriteLiteral("

        We wrote 10 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 12 "" -} - -#line default -#line hidden - - Instrumentation.BeginContext(145, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 14 "" - switch(i) { - case 11: - -#line default -#line hidden - - Instrumentation.BeginContext(175, 46, true); - WriteLiteral("

        No really, we wrote 10 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 17 "" - break; - default: - -#line default -#line hidden - - Instrumentation.BeginContext(251, 39, true); - WriteLiteral("

        Actually, we didn\'t...

        \r\n"); - Instrumentation.EndContext(); -#line 20 "" - break; -} - -#line default -#line hidden - - Instrumentation.BeginContext(309, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 23 "" - for(int j = 1; j <= 10; j += 2) { - -#line default -#line hidden - - Instrumentation.BeginContext(347, 29, true); - WriteLiteral("

        Hello again from C#, #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(378, 1, false); -#line 24 "" - Write(j); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(380, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 25 "" -} - -#line default -#line hidden - - Instrumentation.BeginContext(389, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 27 "" - try { - -#line default -#line hidden - - Instrumentation.BeginContext(399, 41, true); - WriteLiteral("

        That time, we wrote 5 lines!

        \r\n"); - Instrumentation.EndContext(); -#line 29 "" -} catch(Exception ex) { - -#line default -#line hidden - - Instrumentation.BeginContext(465, 33, true); - WriteLiteral("

        Oh no! An error occurred: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(500, 10, false); -#line 30 "" - Write(ex.Message); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(511, 6, true); - WriteLiteral("

        \r\n"); - Instrumentation.EndContext(); -#line 31 "" -} - - -#line default -#line hidden - -#line 33 "" - - -#line default -#line hidden - - Instrumentation.BeginContext(558, 12, true); - WriteLiteral("

        i is now "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(571, 1, false); -#line 34 "" - Write(i); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(572, 8, true); - WriteLiteral("

        \r\n\r\n"); - Instrumentation.EndContext(); -#line 36 "" - lock(new object()) { - -#line default -#line hidden - - Instrumentation.BeginContext(603, 53, true); - WriteLiteral("

        This block is locked, for your security!

        \r\n"); - Instrumentation.EndContext(); -#line 38 "" -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.DesignTime.cs deleted file mode 100644 index c9c332648d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.DesignTime.cs +++ /dev/null @@ -1,99 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NullConditionalExpressions - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public NullConditionalExpressions() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - -#line 2 "NullConditionalExpressions.cshtml" -__o = ViewBag?.Data; - -#line default -#line hidden -#line 2 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - -#line 3 "NullConditionalExpressions.cshtml" -__o = ViewBag.IntIndexer?[0]; - -#line default -#line hidden -#line 3 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - -#line 4 "NullConditionalExpressions.cshtml" -__o = ViewBag.StrIndexer?["key"]; - -#line default -#line hidden -#line 4 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - -#line 5 "NullConditionalExpressions.cshtml" -__o = ViewBag?.Method(Value?[23]?.More)?["key"]; - -#line default -#line hidden -#line 5 "NullConditionalExpressions.cshtml" - - -#line default -#line hidden - -#line 8 "NullConditionalExpressions.cshtml" -__o = ViewBag?.Data; - -#line default -#line hidden -#line 9 "NullConditionalExpressions.cshtml" -__o = ViewBag.IntIndexer?[0]; - -#line default -#line hidden -#line 10 "NullConditionalExpressions.cshtml" -__o = ViewBag.StrIndexer?["key"]; - -#line default -#line hidden -#line 11 "NullConditionalExpressions.cshtml" -__o = ViewBag?.Method(Value?[23]?.More)?["key"]; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.cs deleted file mode 100644 index c5bd057802..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/NullConditionalExpressions.cs +++ /dev/null @@ -1,122 +0,0 @@ -#pragma checksum "NullConditionalExpressions.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "c8c4f34e0768aea12ef6ce8e3fe0e384ad023faf" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class NullConditionalExpressions - { - #line hidden - public NullConditionalExpressions() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - - Instrumentation.BeginContext(9, 13, false); -#line 2 "NullConditionalExpressions.cshtml" -Write(ViewBag?.Data); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 2 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - - Instrumentation.BeginContext(29, 22, false); -#line 3 "NullConditionalExpressions.cshtml" -Write(ViewBag.IntIndexer?[0]); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 3 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - - Instrumentation.BeginContext(58, 26, false); -#line 4 "NullConditionalExpressions.cshtml" -Write(ViewBag.StrIndexer?["key"]); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 4 "NullConditionalExpressions.cshtml" - - - -#line default -#line hidden - - Instrumentation.BeginContext(91, 41, false); -#line 5 "NullConditionalExpressions.cshtml" -Write(ViewBag?.Method(Value?[23]?.More)?["key"]); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 5 "NullConditionalExpressions.cshtml" - - -#line default -#line hidden - - Instrumentation.BeginContext(137, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(140, 13, false); -#line 8 "NullConditionalExpressions.cshtml" -Write(ViewBag?.Data); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(153, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(156, 22, false); -#line 9 "NullConditionalExpressions.cshtml" -Write(ViewBag.IntIndexer?[0]); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(178, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(181, 26, false); -#line 10 "NullConditionalExpressions.cshtml" -Write(ViewBag.StrIndexer?["key"]); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(207, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(210, 41, false); -#line 11 "NullConditionalExpressions.cshtml" -Write(ViewBag?.Method(Value?[23]?.More)?["key"]); - -#line default -#line hidden - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.Tabs.cs deleted file mode 100644 index 805f6011d1..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.Tabs.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class OpenedIf - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public OpenedIf() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "OpenedIf.cshtml" -if (true) { - -#line default -#line hidden - -#line 4 "OpenedIf.cshtml" - - -#line default -#line hidden - -#line 5 "OpenedIf.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.cs deleted file mode 100644 index fdd7959c3a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/OpenedIf.DesignTime.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class OpenedIf - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public OpenedIf() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "OpenedIf.cshtml" -if (true) { - -#line default -#line hidden - -#line 4 "OpenedIf.cshtml" - - -#line default -#line hidden - -#line 5 "OpenedIf.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ParserError.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ParserError.cs deleted file mode 100644 index 371110c1fa..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/ParserError.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class ParserError - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public ParserError() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "ParserError.cshtml" - -/* -int i =10; -int j =20; -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.DesignTime.cs deleted file mode 100644 index b99ba9cebf..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.DesignTime.cs +++ /dev/null @@ -1,120 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class PrefixedAttributeTagHelpers - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.InputTagHelper1 __TestNamespace_InputTagHelper1 = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - #line hidden - public PrefixedAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 3 "PrefixedAttributeTagHelpers.cshtml" - - var literate = "or illiterate"; - var intDictionary = new Dictionary - { - { "three", 3 }, - }; - var stringDictionary = new SortedDictionary - { - { "name", "value" }, - }; - -#line default -#line hidden - - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 16 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty = intDictionary; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty = __TestNamespace_InputTagHelper1.IntDictionaryProperty; -#line 16 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.StringDictionaryProperty = stringDictionary; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.StringDictionaryProperty = __TestNamespace_InputTagHelper1.StringDictionaryProperty; - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 17 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty = intDictionary; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty = __TestNamespace_InputTagHelper1.IntDictionaryProperty; -#line 17 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.IntDictionaryProperty["garlic"] = 37; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty["garlic"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["garlic"]; -#line 17 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.IntProperty = 42; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"] = __TestNamespace_InputTagHelper1.IntProperty; - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 19 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntProperty = 42; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"] = __TestNamespace_InputTagHelper1.IntProperty; -#line 19 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty["salt"] = 37; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty["salt"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["salt"]; -#line 19 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.IntDictionaryProperty["pepper"] = 98; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty["pepper"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["pepper"]; - __TestNamespace_InputTagHelper1.StringProperty = "string"; - __TestNamespace_InputTagHelper2.StringDictionaryProperty["grabber"] = __TestNamespace_InputTagHelper1.StringProperty; - __TestNamespace_InputTagHelper1.StringDictionaryProperty["paprika"] = "another string"; - __TestNamespace_InputTagHelper2.StringDictionaryProperty["paprika"] = __TestNamespace_InputTagHelper1.StringDictionaryProperty["paprika"]; -#line 21 "PrefixedAttributeTagHelpers.cshtml" - __o = literate; - -#line default -#line hidden - __TestNamespace_InputTagHelper1.StringDictionaryProperty["cumin"] = string.Empty; - __TestNamespace_InputTagHelper2.StringDictionaryProperty["cumin"] = __TestNamespace_InputTagHelper1.StringDictionaryProperty["cumin"]; - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); -#line 22 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty["value"] = 37; - -#line default -#line hidden - __TestNamespace_InputTagHelper2.IntDictionaryProperty["value"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["value"]; - __TestNamespace_InputTagHelper1.StringDictionaryProperty["thyme"] = "string"; - __TestNamespace_InputTagHelper2.StringDictionaryProperty["thyme"] = __TestNamespace_InputTagHelper1.StringDictionaryProperty["thyme"]; - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.Reversed.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.Reversed.cs deleted file mode 100644 index 5827739961..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.Reversed.cs +++ /dev/null @@ -1,247 +0,0 @@ -#pragma checksum "PrefixedAttributeTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5ae668a393146e4a06179eb37952603907a9b825" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class PrefixedAttributeTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private global::TestNamespace.InputTagHelper1 __TestNamespace_InputTagHelper1 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("checkbox"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("password"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("radio"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("int-prefix-salt", new global::Microsoft.AspNetCore.Html.HtmlString("8"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("string-prefix-grabber", "string", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("string-prefix-paprika", "another string", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("string-prefix-thyme", "string", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public PrefixedAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 3 "PrefixedAttributeTagHelpers.cshtml" - - var literate = "or illiterate"; - var intDictionary = new Dictionary - { - { "three", 3 }, - }; - var stringDictionary = new SortedDictionary - { - { "name", "value" }, - }; - -#line default -#line hidden - - Instrumentation.BeginContext(280, 49, true); - WriteLiteral("\r\n
        \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 16 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.IntDictionaryProperty = intDictionary; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-dictionary", __TestNamespace_InputTagHelper2.IntDictionaryProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntDictionaryProperty = __TestNamespace_InputTagHelper2.IntDictionaryProperty; -#line 16 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.StringDictionaryProperty = stringDictionary; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("string-dictionary", __TestNamespace_InputTagHelper2.StringDictionaryProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.StringDictionaryProperty = __TestNamespace_InputTagHelper2.StringDictionaryProperty; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(329, 92, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(421, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - if (__TestNamespace_InputTagHelper2.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-garlic", "TestNamespace.InputTagHelper2", "IntDictionaryProperty")); - } - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - if (__TestNamespace_InputTagHelper1.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-garlic", "TestNamespace.InputTagHelper1", "IntDictionaryProperty")); - } - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); -#line 17 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.IntDictionaryProperty = intDictionary; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-dictionary", __TestNamespace_InputTagHelper2.IntDictionaryProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntDictionaryProperty = __TestNamespace_InputTagHelper2.IntDictionaryProperty; -#line 17 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.IntDictionaryProperty["garlic"] = 37; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-garlic", __TestNamespace_InputTagHelper2.IntDictionaryProperty["garlic"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntDictionaryProperty["garlic"] = __TestNamespace_InputTagHelper2.IntDictionaryProperty["garlic"]; -#line 17 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"] = 42; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-grabber", __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntProperty = __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"]; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(427, 103, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(530, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - if (__TestNamespace_InputTagHelper2.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-grabber", "TestNamespace.InputTagHelper2", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper2.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-grabber", "TestNamespace.InputTagHelper2", "StringDictionaryProperty")); - } - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - if (__TestNamespace_InputTagHelper1.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-salt", "TestNamespace.InputTagHelper1", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper1.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-paprika", "TestNamespace.InputTagHelper1", "StringDictionaryProperty")); - } - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); -#line 19 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"] = 42; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-grabber", __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntProperty = __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"]; -#line 19 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.IntDictionaryProperty["salt"] = 37; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-salt", __TestNamespace_InputTagHelper2.IntDictionaryProperty["salt"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntDictionaryProperty["salt"] = __TestNamespace_InputTagHelper2.IntDictionaryProperty["salt"]; -#line 19 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper2.IntDictionaryProperty["pepper"] = 98; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-pepper", __TestNamespace_InputTagHelper2.IntDictionaryProperty["pepper"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntDictionaryProperty["pepper"] = __TestNamespace_InputTagHelper2.IntDictionaryProperty["pepper"]; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); - __TestNamespace_InputTagHelper2.StringDictionaryProperty["grabber"] = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper1.StringProperty = __TestNamespace_InputTagHelper2.StringDictionaryProperty["grabber"]; - __TestNamespace_InputTagHelper2.StringDictionaryProperty["paprika"] = (string)__tagHelperAttribute_5.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); - __TestNamespace_InputTagHelper1.StringDictionaryProperty["paprika"] = __TestNamespace_InputTagHelper2.StringDictionaryProperty["paprika"]; - BeginWriteTagHelperAttribute(); - WriteLiteral("literate "); -#line 21 "PrefixedAttributeTagHelpers.cshtml" - WriteLiteral(literate); - -#line default -#line hidden - WriteLiteral("?"); - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper2.StringDictionaryProperty["cumin"] = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("string-prefix-cumin", __TestNamespace_InputTagHelper2.StringDictionaryProperty["cumin"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.StringDictionaryProperty["cumin"] = __TestNamespace_InputTagHelper2.StringDictionaryProperty["cumin"]; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(536, 257, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(793, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - if (__TestNamespace_InputTagHelper2.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-value", "TestNamespace.InputTagHelper2", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper2.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-thyme", "TestNamespace.InputTagHelper2", "StringDictionaryProperty")); - } - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - if (__TestNamespace_InputTagHelper1.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-value", "TestNamespace.InputTagHelper1", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper1.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-thyme", "TestNamespace.InputTagHelper1", "StringDictionaryProperty")); - } -#line 22 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper2.IntDictionaryProperty["value"] = 37; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-value", __TestNamespace_InputTagHelper2.IntDictionaryProperty["value"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper1.IntDictionaryProperty["value"] = __TestNamespace_InputTagHelper2.IntDictionaryProperty["value"]; - __TestNamespace_InputTagHelper2.StringDictionaryProperty["thyme"] = (string)__tagHelperAttribute_6.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); - __TestNamespace_InputTagHelper1.StringDictionaryProperty["thyme"] = __TestNamespace_InputTagHelper2.StringDictionaryProperty["thyme"]; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(799, 60, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(859, 8, true); - WriteLiteral("\r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.cs deleted file mode 100644 index 1ec8d1f6c9..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/PrefixedAttributeTagHelpers.cs +++ /dev/null @@ -1,247 +0,0 @@ -#pragma checksum "PrefixedAttributeTagHelpers.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5ae668a393146e4a06179eb37952603907a9b825" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class PrefixedAttributeTagHelpers - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.InputTagHelper1 __TestNamespace_InputTagHelper1 = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("checkbox"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("password"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("radio"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("int-prefix-salt", new global::Microsoft.AspNetCore.Html.HtmlString("8"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("string-prefix-grabber", "string", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("string-prefix-paprika", "another string", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("string-prefix-thyme", "string", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public PrefixedAttributeTagHelpers() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 3 "PrefixedAttributeTagHelpers.cshtml" - - var literate = "or illiterate"; - var intDictionary = new Dictionary - { - { "three", 3 }, - }; - var stringDictionary = new SortedDictionary - { - { "name", "value" }, - }; - -#line default -#line hidden - - Instrumentation.BeginContext(280, 49, true); - WriteLiteral("\r\n
        \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 16 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty = intDictionary; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-dictionary", __TestNamespace_InputTagHelper1.IntDictionaryProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty = __TestNamespace_InputTagHelper1.IntDictionaryProperty; -#line 16 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.StringDictionaryProperty = stringDictionary; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("string-dictionary", __TestNamespace_InputTagHelper1.StringDictionaryProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.StringDictionaryProperty = __TestNamespace_InputTagHelper1.StringDictionaryProperty; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(329, 92, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(421, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - if (__TestNamespace_InputTagHelper1.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-garlic", "TestNamespace.InputTagHelper1", "IntDictionaryProperty")); - } - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - if (__TestNamespace_InputTagHelper2.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-garlic", "TestNamespace.InputTagHelper2", "IntDictionaryProperty")); - } - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); -#line 17 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty = intDictionary; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-dictionary", __TestNamespace_InputTagHelper1.IntDictionaryProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty = __TestNamespace_InputTagHelper1.IntDictionaryProperty; -#line 17 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.IntDictionaryProperty["garlic"] = 37; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-garlic", __TestNamespace_InputTagHelper1.IntDictionaryProperty["garlic"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty["garlic"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["garlic"]; -#line 17 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.IntProperty = 42; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-grabber", __TestNamespace_InputTagHelper1.IntProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"] = __TestNamespace_InputTagHelper1.IntProperty; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(427, 103, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(530, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - if (__TestNamespace_InputTagHelper1.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-salt", "TestNamespace.InputTagHelper1", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper1.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-paprika", "TestNamespace.InputTagHelper1", "StringDictionaryProperty")); - } - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - if (__TestNamespace_InputTagHelper2.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-grabber", "TestNamespace.InputTagHelper2", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper2.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-grabber", "TestNamespace.InputTagHelper2", "StringDictionaryProperty")); - } - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); -#line 19 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntProperty = 42; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-grabber", __TestNamespace_InputTagHelper1.IntProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty["grabber"] = __TestNamespace_InputTagHelper1.IntProperty; -#line 19 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty["salt"] = 37; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-salt", __TestNamespace_InputTagHelper1.IntDictionaryProperty["salt"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty["salt"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["salt"]; -#line 19 "PrefixedAttributeTagHelpers.cshtml" - __TestNamespace_InputTagHelper1.IntDictionaryProperty["pepper"] = 98; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-pepper", __TestNamespace_InputTagHelper1.IntDictionaryProperty["pepper"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty["pepper"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["pepper"]; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); - __TestNamespace_InputTagHelper1.StringProperty = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper2.StringDictionaryProperty["grabber"] = __TestNamespace_InputTagHelper1.StringProperty; - __TestNamespace_InputTagHelper1.StringDictionaryProperty["paprika"] = (string)__tagHelperAttribute_5.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); - __TestNamespace_InputTagHelper2.StringDictionaryProperty["paprika"] = __TestNamespace_InputTagHelper1.StringDictionaryProperty["paprika"]; - BeginWriteTagHelperAttribute(); - WriteLiteral("literate "); -#line 21 "PrefixedAttributeTagHelpers.cshtml" - WriteLiteral(literate); - -#line default -#line hidden - WriteLiteral("?"); - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_InputTagHelper1.StringDictionaryProperty["cumin"] = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("string-prefix-cumin", __TestNamespace_InputTagHelper1.StringDictionaryProperty["cumin"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.StringDictionaryProperty["cumin"] = __TestNamespace_InputTagHelper1.StringDictionaryProperty["cumin"]; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(536, 257, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(793, 6, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper1 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper1); - if (__TestNamespace_InputTagHelper1.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-value", "TestNamespace.InputTagHelper1", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper1.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-thyme", "TestNamespace.InputTagHelper1", "StringDictionaryProperty")); - } - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - if (__TestNamespace_InputTagHelper2.IntDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("int-prefix-value", "TestNamespace.InputTagHelper2", "IntDictionaryProperty")); - } - if (__TestNamespace_InputTagHelper2.StringDictionaryProperty == null) - { - throw new InvalidOperationException(FormatInvalidIndexerAssignment("string-prefix-thyme", "TestNamespace.InputTagHelper2", "StringDictionaryProperty")); - } -#line 22 "PrefixedAttributeTagHelpers.cshtml" -__TestNamespace_InputTagHelper1.IntDictionaryProperty["value"] = 37; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("int-prefix-value", __TestNamespace_InputTagHelper1.IntDictionaryProperty["value"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __TestNamespace_InputTagHelper2.IntDictionaryProperty["value"] = __TestNamespace_InputTagHelper1.IntDictionaryProperty["value"]; - __TestNamespace_InputTagHelper1.StringDictionaryProperty["thyme"] = (string)__tagHelperAttribute_6.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); - __TestNamespace_InputTagHelper2.StringDictionaryProperty["thyme"] = __TestNamespace_InputTagHelper1.StringDictionaryProperty["thyme"]; - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(799, 60, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(859, 8, true); - WriteLiteral("\r\n
        "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.DesignTime.cs deleted file mode 100644 index 465aa1f57c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.DesignTime.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class RazorComments - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public RazorComments() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 4 "RazorComments.cshtml" - - - -#line default -#line hidden - -#line 5 "RazorComments.cshtml" - - Exception foo = - -#line default -#line hidden - -#line 6 "RazorComments.cshtml" - null; - if(foo != null) { - throw foo; - } - -#line default -#line hidden - -#line 12 "RazorComments.cshtml" - var bar = "@* bar *@"; - -#line default -#line hidden - -#line 13 "RazorComments.cshtml" - __o = bar; - -#line default -#line hidden -#line 15 "RazorComments.cshtml" -__o = ab; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.cs deleted file mode 100644 index 01d041e1ad..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RazorComments.cs +++ /dev/null @@ -1,78 +0,0 @@ -#pragma checksum "RazorComments.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "45c16f152aef80d7de27c7df32dc522af5842197" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class RazorComments - { - #line hidden - public RazorComments() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(0, 34, true); - WriteLiteral("\r\n

        This should be shown

        \r\n\r\n"); - Instrumentation.EndContext(); -#line 4 "RazorComments.cshtml" - - - -#line default -#line hidden - -#line 5 "RazorComments.cshtml" - - Exception foo = - -#line default -#line hidden - -#line 6 "RazorComments.cshtml" - null; - if(foo != null) { - throw foo; - } - -#line default -#line hidden - - Instrumentation.BeginContext(234, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 12 "RazorComments.cshtml" - var bar = "@* bar *@"; - -#line default -#line hidden - - Instrumentation.BeginContext(265, 44, true); - WriteLiteral("

        But this should show the comment syntax: "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(310, 3, false); -#line 13 "RazorComments.cshtml" - Write(bar); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(313, 8, true); - WriteLiteral("

        \r\n\r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(323, 1, false); -#line 15 "RazorComments.cshtml" -Write(ab); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(330, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RemoveTagHelperDirective.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RemoveTagHelperDirective.cs deleted file mode 100644 index 4fdfa42ead..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/RemoveTagHelperDirective.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class RemoveTagHelperDirective - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - public RemoveTagHelperDirective() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Sections.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Sections.cs deleted file mode 100644 index f7e4419d3c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Sections.cs +++ /dev/null @@ -1,99 +0,0 @@ -#pragma checksum "Sections.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ec9a74381c339244a887565526c11056ece494a3" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Sections - { - #line hidden - public Sections() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "Sections.cshtml" - - Layout = "_SectionTestLayout.cshtml" - -#line default -#line hidden - - Instrumentation.BeginContext(49, 31, true); - WriteLiteral("\r\n
        This is in the Body>\r\n\r\n"); - Instrumentation.EndContext(); - DefineSection("Section2", async(__razor_section_writer) => { - Instrumentation.BeginContext(99, 10, true); - WriteLiteralTo(__razor_section_writer, "\r\n
        \r\n"); - Instrumentation.EndContext(); - } - ); - Instrumentation.BeginContext(161, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - DefineSection("Section1", async(__razor_section_writer) => { - Instrumentation.BeginContext(182, 39, true); - WriteLiteralTo(__razor_section_writer, "\r\n
        This is in Section 1
        \r\n"); - Instrumentation.EndContext(); - } - ); - Instrumentation.BeginContext(224, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - DefineSection("NestedDelegates", async(__razor_section_writer) => { - Instrumentation.BeginContext(252, 2, true); - WriteLiteralTo(__razor_section_writer, "\r\n"); - Instrumentation.EndContext(); -#line 16 "Sections.cshtml" - - -#line default -#line hidden - -#line 16 "Sections.cshtml" - Func f = - -#line default -#line hidden - - item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(288, 6, true); - WriteLiteralTo(__razor_template_writer, ""); - Instrumentation.EndContext(); - Instrumentation.BeginContext(295, 4, false); -#line 16 "Sections.cshtml" - WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(299, 7, true); - WriteLiteralTo(__razor_template_writer, ""); - Instrumentation.EndContext(); - } - ) -#line 16 "Sections.cshtml" - ; - -#line default -#line hidden - - } - ); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SimpleUnspacedIf.DesignTime.Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SimpleUnspacedIf.DesignTime.Tabs.cs deleted file mode 100644 index 5d40ef164a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SimpleUnspacedIf.DesignTime.Tabs.cs +++ /dev/null @@ -1,40 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class SimpleUnspacedIf - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public SimpleUnspacedIf() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "SimpleUnspacedIf.cshtml" -if (true) -{ - - -#line default -#line hidden - -#line 3 "SimpleUnspacedIf.cshtml" - -} - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.DesignTime.cs deleted file mode 100644 index 5287820258..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.DesignTime.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class SingleTagHelper - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - #line hidden - public SingleTagHelper() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 3 "SingleTagHelper.cshtml" -__TestNamespace_PTagHelper.Age = 1337; - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.cs deleted file mode 100644 index 09b6b98cdc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelper.cs +++ /dev/null @@ -1,58 +0,0 @@ -#pragma checksum "SingleTagHelper.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4d7ff17da750ffcbca3130faffef1030e5eb03b8" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class SingleTagHelper - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public SingleTagHelper() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(67, 11, true); - WriteLiteral("Body of Tag"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 3 "SingleTagHelper.cshtml" -__TestNamespace_PTagHelper.Age = 1337; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(33, 49, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelperWithNewlineBeforeAttributes.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelperWithNewlineBeforeAttributes.cs deleted file mode 100644 index 57fd3c922c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SingleTagHelperWithNewlineBeforeAttributes.cs +++ /dev/null @@ -1,58 +0,0 @@ -#pragma checksum "SingleTagHelperWithNewlineBeforeAttributes.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "83a2d9976b209020f80917aa61a3338e37d3c446" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class SingleTagHelperWithNewlineBeforeAttributes - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public SingleTagHelperWithNewlineBeforeAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(71, 11, true); - WriteLiteral("Body of Tag"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 4 "SingleTagHelperWithNewlineBeforeAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 1337; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(33, 53, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/StringLiterals.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/StringLiterals.cs deleted file mode 100644 index d6ae5caedd..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/StringLiterals.cs +++ /dev/null @@ -1,279 +0,0 @@ -#pragma checksum "StringLiterals.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "3c21118a6113e76e4f71d17e3ae081f13d451427" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class StringLiterals - { - #line hidden - public StringLiterals() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(0, 2013, true); - WriteLiteral(@"

        This is line 1

        -

        This is line 2

        -

        This is line 3

        -

        This is line 4

        -

        This is line 5

        -

        This is line 6

        -

        This is line 7

        -

        This is line 8

        -

        This is line 9

        -

        This is line 10

        -

        This is line 11

        -

        This is line 12

        -

        This is line 13

        -

        This is line 14

        -

        This is line 15

        -

        This is line 16

        -

        This is line 17

        -

        This is line 18

        -

        This is line 19

        -

        This is line 20

        -

        This is line 21

        -

        This is line 22

        -

        This is line 23

        -

        This is line 24

        -

        This is line 25

        -

        This is line 26

        -

        This is line 27

        -

        This is line 28

        -

        This is line 29

        -

        This is line 30

        -

        This is line 31

        -

        This is line 32

        -

        This is line 33

        -

        This is line 34

        -

        This is line 35

        -

        This is line 36

        -

        This is line 37

        -

        This is line 38

        -

        This is line 39

        -

        This is line 40

        -

        This is line 41

        -

        This is line 42

        -

        This is line 43

        -<"); - WriteLiteral(@"p>This is line 44

        -

        This is line 45

        -

        This is line 46

        -

        This is line 47

        -

        This is line 48

        -

        This is line 49

        -

        This is line 50

        -

        This is line 51

        -

        This is line 52

        -

        This is line 53

        -

        This is line 54

        -

        This is line 55

        -

        This is line 56

        -

        This is line 57

        -

        This is line 58

        -

        This is line 59

        -

        This is line 60

        -

        This is line 61

        -

        This is line 62

        -

        This is line 63

        -

        This is line 64

        -

        This is line 65

        -

        This is line 66

        -

        This is line 67

        -

        This is line 68

        -

        This is line 69

        -

        This is line 70

        -

        This is line 71

        -

        This is line 72

        -

        This is line 73

        -

        This is line 74

        -

        This is line 75

        -

        This is line 76

        -

        This is line 77

        -

        This is line 78

        -

        This is line 79

        -

        This is line 80

        -

        This is line 81

        -

        This is line 82

        -

        This is line 83

        -

        This is line 84


        - -"); - Instrumentation.EndContext(); - DefineSection("WriteLiteralsToInHere", async(__razor_section_writer) => { - Instrumentation.BeginContext(2045, 2618, true); - WriteLiteralTo(__razor_section_writer, @" -

        This is line 1 nested

        -

        This is line 2 nested

        -

        This is line 3 nested

        -

        This is line 4 nested

        -

        This is line 5 nested

        -

        This is line 6 nested

        -

        This is line 7 nested

        -

        This is line 8 nested

        -

        This is line 9 nested

        -

        This is line 10 nested

        -

        This is line 11 nested

        -

        This is line 12 nested

        -

        This is line 13 nested

        -

        This is line 14 nested

        -

        This is line 15 nested

        -

        This is line 16 nested

        -

        This is line 17 nested

        -

        This is line 18 nested

        -

        This is line 19 nested

        -

        This is line 20 nested

        -

        This is line 21 nested

        -

        This is line 22 nested

        -

        This is line 23 nested

        -

        This is line 24 nested

        -

        This is line 25 nested

        -

        This is line 26 nested

        -

        This is line 27 nested

        -

        This is line 28 nested

        -

        This is line 29 nested

        -

        This is l"); - WriteLiteralTo(__razor_section_writer, @"ine 30 nested

        -

        This is line 31 nested

        -

        This is line 32 nested

        -

        This is line 33 nested

        -

        This is line 34 nested

        -

        This is line 35 nested

        -

        This is line 36 nested

        -

        This is line 37 nested

        -

        This is line 38 nested

        -

        This is line 39 nested

        -

        This is line 40 nested

        -

        This is line 41 nested

        -

        This is line 42 nested

        -

        This is line 43 nested

        -

        This is line 44 nested

        -

        This is line 45 nested

        -

        This is line 46 nested

        -

        This is line 47 nested

        -

        This is line 48 nested

        -

        This is line 49 nested

        -

        This is line 50 nested

        -

        This is line 51 nested

        -

        This is line 52 nested

        -

        This is line 53 nested

        -

        This is line 54 nested

        -

        This is line 55 nested

        -

        This is line 56 nested

        -

        This is line 57 nested

        -

        This is line 58 nested

        -

        This is line 59 ne"); - WriteLiteralTo(__razor_section_writer, @"sted

        -

        This is line 60 nested

        -

        This is line 61 nested

        -

        This is line 62 nested

        -

        This is line 63 nested

        -

        This is line 64 nested

        -

        This is line 65 nested

        -

        This is line 66 nested

        -

        This is line 67 nested

        -

        This is line 68 nested

        -

        This is line 69 nested

        -

        This is line 70 nested

        -

        This is line 71 nested

        -

        This is line 72 nested

        -

        This is line 73 nested

        -

        This is line 74 nested

        -

        This is line 75 nested

        -"); - Instrumentation.EndContext(); - } - ); - Instrumentation.BeginContext(4666, 1026, true); - WriteLiteral(@"

        This is line 1

        -

        This is line 2

        -

        This is line 3

        -

        This is line 4

        -

        This is line 5

        -

        This is line 6

        -

        This is line 7

        -

        This is line 8

        -

        This is line 9

        -

        This is line 10

        -

        This is line 11

        -

        This is line 12

        -

        This is line 13

        -

        This is line 14

        -

        This is line 15

        -

        This is line 16

        -

        This is line 17

        -

        This is line 18

        -

        This is line 19

        -

        This is line 20

        -

        This is line 21

        -

        This is line 22

        -

        This is line 23

        -

        This is line 24

        -

        This is line 25

        -

        This is line 26

        -

        This is line 27

        -

        This is line 28

        -

        This is line 29

        -

        This is line 30

        -

        This is line 31

        -

        This is line 32

        -

        This is line 33

        -

        This is line 34

        -

        This is line 35

        -

        This is line 36

        -

        This is line 37

        -

        This is line 38

        -

        This is line 39

        -

        This is line 40

        -

        This is line 41

        -

        This is line 42

        -

        This is line 43

        hi!"); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - DefineSection("WriteLiteralsToInHereAlso", async(__razor_section_writer) => { - Instrumentation.BeginContext(5728, 1023, true); - WriteLiteralTo(__razor_section_writer, @" -

        This is line 1 nested

        -

        This is line 2 nested

        -

        This is line 3 nested

        -

        This is line 4 nested

        -

        This is line 5 nested

        -

        This is line 6 nested

        -

        This is line 7 nested

        -

        This is line 8 nested

        -

        This is line 9 nested

        -

        This is line 10 nested

        -

        This is line 11 nested

        -

        This is line 12 nested

        -

        This is line 13 nested

        -

        This is line 14 nested

        -

        This is line 15 nested

        -

        This is line 16 nested

        -

        This is line 17 nested

        -

        This is line 18 nested

        -

        This is line 19 nested

        -

        This is line 20 nested

        -

        This is line 21 nested

        -

        This is line 22 nested

        -

        This is line 23 nested

        -

        This is line 24 nested

        -

        This is line 25 nested

        -

        This is line 26 nested

        -

        This is line 27 nested

        -

        This is line 28 nested

        -

        This is line 29 nested

        -

        30

        -"); - Instrumentation.EndContext(); - } - ); - Instrumentation.BeginContext(6752, 1, true); - WriteLiteral("!"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.DesignTime.cs deleted file mode 100644 index 3aee94ce7b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.DesignTime.cs +++ /dev/null @@ -1,58 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class SymbolBoundAttributes - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "*, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - #line hidden - public SymbolBoundAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 12 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.ListItems = items; - -#line default -#line hidden - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 13 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.ArrayItems = items; - -#line default -#line hidden - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 14 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.Event1 = doSomething(); - -#line default -#line hidden - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); -#line 15 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.Event2 = doSomething(); - -#line default -#line hidden - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper.StringProperty1 = "value"; - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __TestNamespace_CatchAllTagHelper.StringProperty2 = "value"; - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.cs deleted file mode 100644 index 59bf02545e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/SymbolBoundAttributes.cs +++ /dev/null @@ -1,194 +0,0 @@ -#pragma checksum "SymbolBoundAttributes.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "85cdc137d6a8c95fa926441de44d5187d5c8051e" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class SymbolBoundAttributes - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.CatchAllTagHelper __TestNamespace_CatchAllTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("bound"); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("[item]", new global::Microsoft.AspNetCore.Html.HtmlString("items"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("[(item)]", new global::Microsoft.AspNetCore.Html.HtmlString("items"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("(click)", new global::Microsoft.AspNetCore.Html.HtmlString("doSomething()"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("(^click)", new global::Microsoft.AspNetCore.Html.HtmlString("doSomething()"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("*something", "value", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("*something", new global::Microsoft.AspNetCore.Html.HtmlString("value"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("#localminimized"); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("#local", "value", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("#local", new global::Microsoft.AspNetCore.Html.HtmlString("value"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public SymbolBoundAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(23, 253, true); - WriteLiteral("\r\n
          \r\n
            \r\n\r\n\r\n\r\n
            \r\n
            \r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("ul", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 12 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.ListItems = items; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("[item]", __TestNamespace_CatchAllTagHelper.ListItems, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(276, 45, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(321, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("ul", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 13 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.ArrayItems = items; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("[(item)]", __TestNamespace_CatchAllTagHelper.ArrayItems, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(323, 49, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(372, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(436, 8, true); - WriteLiteral("Click Me"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 14 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.Event1 = doSomething(); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("(click)", __TestNamespace_CatchAllTagHelper.Event1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(374, 79, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(453, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(519, 8, true); - WriteLiteral("Click Me"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 15 "SymbolBoundAttributes.cshtml" -__TestNamespace_CatchAllTagHelper.Event2 = doSomething(); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("(^click)", __TestNamespace_CatchAllTagHelper.Event2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(455, 81, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(536, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("template", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(592, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __TestNamespace_CatchAllTagHelper.StringProperty1 = (string)__tagHelperAttribute_5.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(538, 67, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(605, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(607, 33, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(640, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_CatchAllTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_CatchAllTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); - __TestNamespace_CatchAllTagHelper.StringProperty2 = (string)__tagHelperAttribute_8.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_9); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(642, 47, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersInSection.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersInSection.cs deleted file mode 100644 index 1ccaa62c3e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersInSection.cs +++ /dev/null @@ -1,116 +0,0 @@ -#pragma checksum "TagHelpersInSection.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f23e7b19a8af7b8fe9c6cb784e5a4bc60537c66b" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class TagHelpersInSection - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.MyTagHelper __TestNamespace_MyTagHelper = null; - private global::TestNamespace.NestedTagHelper __TestNamespace_NestedTagHelper = null; - #line hidden - public TagHelpersInSection() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 3 "TagHelpersInSection.cshtml" - - var code = "some code"; - -#line default -#line hidden - - Instrumentation.BeginContext(69, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - DefineSection("MySection", async(__razor_section_writer) => { - Instrumentation.BeginContext(91, 21, true); - WriteLiteralTo(__razor_section_writer, "\r\n
            \r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("mytaghelper", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(215, 52, true); - WriteLiteral("\r\n In None ContentBehavior.\r\n "); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("nestedtaghelper", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(284, 26, true); - WriteLiteral("Some buffered values with "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(311, 4, false); -#line 11 "TagHelpersInSection.cshtml" - Write(code); - -#line default -#line hidden - Instrumentation.EndContext(); - } - ); - __TestNamespace_NestedTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_NestedTagHelper); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(267, 66, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(333, 10, true); - WriteLiteral("\r\n "); - Instrumentation.EndContext(); - } - ); - __TestNamespace_MyTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_MyTagHelper); - BeginWriteTagHelperAttribute(); - WriteLiteral("Current Time: "); -#line 9 "TagHelpersInSection.cshtml" - WriteLiteral(DateTime.Now); - -#line default -#line hidden - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __TestNamespace_MyTagHelper.BoundProperty = __tagHelperStringValueBuffer; - __tagHelperExecutionContext.AddTagHelperAttribute("boundproperty", __TestNamespace_MyTagHelper.BoundProperty, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "unboundproperty", 3, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 186, "Current", 186, 7, true); - AddHtmlAttributeValue(" ", 193, "Time:", 194, 6, true); -#line 9 "TagHelpersInSection.cshtml" -AddHtmlAttributeValue(" ", 199, DateTime.Now, 200, 14, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(112, 245, false); - WriteTo(__razor_section_writer, __tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(357, 14, true); - WriteLiteralTo(__razor_section_writer, "\r\n
            \r\n"); - Instrumentation.EndContext(); - } - ); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersWithWeirdlySpacedAttributes.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersWithWeirdlySpacedAttributes.cs deleted file mode 100644 index 4f072e2088..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TagHelpersWithWeirdlySpacedAttributes.cs +++ /dev/null @@ -1,131 +0,0 @@ -#pragma checksum "TagHelpersWithWeirdlySpacedAttributes.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "44db1fa170a6845ec719f4200e4bb1f639830b49" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class TagHelpersWithWeirdlySpacedAttributes - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("Hello World"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private global::TestNamespace.InputTagHelper __TestNamespace_InputTagHelper = null; - private global::TestNamespace.InputTagHelper2 __TestNamespace_InputTagHelper2 = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data-content", new global::Microsoft.AspNetCore.Html.HtmlString("hello"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data-content", new global::Microsoft.AspNetCore.Html.HtmlString("hello2"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.SingleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "password", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("data-content", new global::Microsoft.AspNetCore.Html.HtmlString("blah"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public TagHelpersWithWeirdlySpacedAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); - Instrumentation.BeginContext(31, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(103, 11, true); - WriteLiteral("Body of Tag"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 6 "TagHelpersWithWeirdlySpacedAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 1337; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - BeginWriteTagHelperAttribute(); -#line 7 "TagHelpersWithWeirdlySpacedAttributes.cshtml" - Write(true); - -#line default -#line hidden - __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); - __tagHelperExecutionContext.AddHtmlAttribute("data-content", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(33, 85, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(118, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_1.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(122, 47, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(169, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); -#line 11 "TagHelpersWithWeirdlySpacedAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 1234; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(173, 46, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(219, 4, true); - WriteLiteral("\r\n\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "test", async() => { - } - ); - __TestNamespace_InputTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper); - __TestNamespace_InputTagHelper2 = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_InputTagHelper2); - __TestNamespace_InputTagHelper.Type = (string)__tagHelperAttribute_4.Value; - __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); - __TestNamespace_InputTagHelper2.Type = __TestNamespace_InputTagHelper.Type; - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(223, 51, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Templates.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Templates.cs deleted file mode 100644 index 64f83f0179..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/Templates.cs +++ /dev/null @@ -1,229 +0,0 @@ -#pragma checksum "Templates.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ecd19ba0b3ae7ac597e19534c93fd2023208ae59" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class Templates - { -#line 1 "Templates.cshtml" - - public HelperResult Repeat(int times, Func template) { - return new HelperResult((writer) => { - for(int i = 0; i < times; i++) { - ((HelperResult)template(i)).WriteTo(writer); - } - }); - } - -#line default -#line hidden - #line hidden - public Templates() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - Instrumentation.BeginContext(280, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); -#line 11 "Templates.cshtml" - - Func foo = - -#line default -#line hidden - - item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(325, 11, true); - WriteLiteralTo(__razor_template_writer, "This works "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(337, 4, false); -#line 12 "Templates.cshtml" - WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(341, 1, true); - WriteLiteralTo(__razor_template_writer, "!"); - Instrumentation.EndContext(); - } - ) -#line 12 "Templates.cshtml" - ; - - -#line default -#line hidden - - Instrumentation.BeginContext(357, 7, false); -#line 13 "Templates.cshtml" -Write(foo("")); - -#line default -#line hidden - Instrumentation.EndContext(); -#line 13 "Templates.cshtml" - - -#line default -#line hidden - - Instrumentation.BeginContext(369, 8, true); - WriteLiteral("\r\n
              \r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(379, 11, false); -#line 17 "Templates.cshtml" -Write(Repeat(10, item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(391, 10, true); - WriteLiteralTo(__razor_template_writer, "
            • Item #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(402, 4, false); -#line 17 "Templates.cshtml" -WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(406, 5, true); - WriteLiteralTo(__razor_template_writer, "
            • "); - Instrumentation.EndContext(); -} -) -)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(413, 16, true); - WriteLiteral("\r\n
            \r\n\r\n

            \r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(430, 16, false); -#line 21 "Templates.cshtml" -Write(Repeat(10, - item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(448, 14, true); - WriteLiteralTo(__razor_template_writer, " This is line#"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(463, 4, false); -#line 22 "Templates.cshtml" -WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(467, 17, true); - WriteLiteralTo(__razor_template_writer, " of markup
            \r\n"); - Instrumentation.EndContext(); -} -) -)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(485, 15, true); - WriteLiteral("\r\n

            \r\n\r\n

            \r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(501, 16, false); -#line 27 "Templates.cshtml" -Write(Repeat(10, - item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(519, 15, true); - WriteLiteralTo(__razor_template_writer, ": This is line#"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(535, 4, false); -#line 28 "Templates.cshtml" -WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(539, 18, true); - WriteLiteralTo(__razor_template_writer, " of markup
            \r\n"); - Instrumentation.EndContext(); -} -) -)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(558, 15, true); - WriteLiteral("\r\n

            \r\n\r\n

            \r\n"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(574, 16, false); -#line 33 "Templates.cshtml" -Write(Repeat(10, - item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(592, 16, true); - WriteLiteralTo(__razor_template_writer, ":: This is line#"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(609, 4, false); -#line 34 "Templates.cshtml" -WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(613, 18, true); - WriteLiteralTo(__razor_template_writer, " of markup
            \r\n"); - Instrumentation.EndContext(); -} -) -)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(632, 22, true); - WriteLiteral("\r\n

            \r\n\r\n\r\n
              \r\n "); - Instrumentation.EndContext(); - Instrumentation.BeginContext(655, 11, false); -#line 40 "Templates.cshtml" -Write(Repeat(10, item => new Template(async(__razor_template_writer) => { - Instrumentation.BeginContext(667, 20, true); - WriteLiteralTo(__razor_template_writer, "
            • \r\n Item #"); - Instrumentation.EndContext(); - Instrumentation.BeginContext(688, 4, false); -#line 41 "Templates.cshtml" -WriteTo(__razor_template_writer, item); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(692, 2, true); - WriteLiteralTo(__razor_template_writer, "\r\n"); - Instrumentation.EndContext(); -#line 42 "Templates.cshtml" - - -#line default -#line hidden - -#line 42 "Templates.cshtml" - var parent = item; - -#line default -#line hidden - - Instrumentation.BeginContext(725, 77, true); - WriteLiteralTo(__razor_template_writer, "
                \r\n
              • Child Items... ?
              • \r\n
              \r\n
            • "); - Instrumentation.EndContext(); -} -) -)); - -#line default -#line hidden - Instrumentation.EndContext(); - Instrumentation.BeginContext(864, 8, true); - WriteLiteral("\r\n
            "); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.DesignTime.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.DesignTime.cs deleted file mode 100644 index 07674f6e61..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.DesignTime.cs +++ /dev/null @@ -1,83 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class TransitionsInTagHelperAttributes - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - string __tagHelperDirectiveSyntaxHelper = null; - __tagHelperDirectiveSyntaxHelper = "something, nice"; - #pragma warning restore 219 - } - #line hidden - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - #line hidden - public TransitionsInTagHelperAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 2 "TransitionsInTagHelperAttributes.cshtml" - - var @class = "container-fluid"; - var @int = 1; - -#line default -#line hidden - - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 7 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 1337; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 8 "TransitionsInTagHelperAttributes.cshtml" - __o = @class; - -#line default -#line hidden -#line 8 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 42; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 9 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 42 + @int; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 10 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = int; - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 11 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = (@int); - -#line default -#line hidden - __TestNamespace_PTagHelper = CreateTagHelper(); -#line 12 "TransitionsInTagHelperAttributes.cshtml" - __o = @class; - -#line default -#line hidden -#line 12 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 4 * @(@int + 2); - -#line default -#line hidden - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.cs deleted file mode 100644 index 8512fc9107..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/TransitionsInTagHelperAttributes.cs +++ /dev/null @@ -1,186 +0,0 @@ -#pragma checksum "TransitionsInTagHelperAttributes.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "b9b5a5baa9e2ea89cb37a127c0623b083bff74c3" -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class TransitionsInTagHelperAttributes - { - #line hidden - #pragma warning disable 0414 - private string __tagHelperStringValueBuffer = null; - #pragma warning restore 0414 - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperExecutionContext __tagHelperExecutionContext = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner __tagHelperRunner = null; - private global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager __tagHelperScopeManager = null; - private global::TestNamespace.PTagHelper __TestNamespace_PTagHelper = null; - private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("test"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - #line hidden - public TransitionsInTagHelperAttributes() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { - __tagHelperRunner = __tagHelperRunner ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperRunner(); - __tagHelperScopeManager = __tagHelperScopeManager ?? new global::Microsoft.AspNetCore.Razor.Runtime.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); -#line 2 "TransitionsInTagHelperAttributes.cshtml" - - var @class = "container-fluid"; - var @int = 1; - -#line default -#line hidden - - Instrumentation.BeginContext(95, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - Instrumentation.BeginContext(126, 11, true); - WriteLiteral("Body of Tag"); - Instrumentation.EndContext(); - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 107, new Template(async(__razor_attribute_value_writer) => { - } - ), 107, 6, false); - EndAddHtmlAttributeValues(__tagHelperExecutionContext); -#line 7 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 1337; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - if (!__tagHelperExecutionContext.Output.IsContentModified) - { - await __tagHelperExecutionContext.SetOutputContentAsync(); - } - Instrumentation.BeginContext(97, 44, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(141, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); -#line 8 "TransitionsInTagHelperAttributes.cshtml" -AddHtmlAttributeValue("", 153, @class, 153, 9, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); -#line 8 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 42; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(143, 34, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(177, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 9 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 42 + @int; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(179, 36, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(215, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 10 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = int; - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(217, 31, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(248, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); -#line 11 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = (@int); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(250, 34, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(284, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "test", async() => { - } - ); - __TestNamespace_PTagHelper = CreateTagHelper(); - __tagHelperExecutionContext.Add(__TestNamespace_PTagHelper); - BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "class", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - AddHtmlAttributeValue("", 296, "custom-", 296, 7, true); -#line 12 "TransitionsInTagHelperAttributes.cshtml" -AddHtmlAttributeValue("", 303, @class, 303, 9, false); - -#line default -#line hidden - EndAddHtmlAttributeValues(__tagHelperExecutionContext); -#line 12 "TransitionsInTagHelperAttributes.cshtml" -__TestNamespace_PTagHelper.Age = 4 * @(@int + 2); - -#line default -#line hidden - __tagHelperExecutionContext.AddTagHelperAttribute("age", __TestNamespace_PTagHelper.Age, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); - await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); - Instrumentation.BeginContext(286, 54, false); - Write(__tagHelperExecutionContext.Output); - Instrumentation.EndContext(); - __tagHelperExecutionContext = __tagHelperScopeManager.End(); - Instrumentation.BeginContext(340, 2, true); - WriteLiteral("\r\n"); - Instrumentation.EndContext(); - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.Tabs.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.Tabs.cs deleted file mode 100644 index 5c894203d7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.Tabs.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class UnfinishedExpressionInCode - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public UnfinishedExpressionInCode() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "UnfinishedExpressionInCode.cshtml" - - -#line default -#line hidden - -#line 2 "UnfinishedExpressionInCode.cshtml" -__o = DateTime.; - -#line default -#line hidden -#line 2 "UnfinishedExpressionInCode.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.cs b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.cs deleted file mode 100644 index 813dd7d91e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Output/UnfinishedExpressionInCode.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace TestOutput -{ - using System; - using System.Threading.Tasks; - - public class UnfinishedExpressionInCode - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public UnfinishedExpressionInCode() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "UnfinishedExpressionInCode.cshtml" - - -#line default -#line hidden - -#line 2 "UnfinishedExpressionInCode.cshtml" -__o = DateTime.; - -#line default -#line hidden -#line 2 "UnfinishedExpressionInCode.cshtml" - - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AddTagHelperDirective.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AddTagHelperDirective.cshtml deleted file mode 100644 index 924029743e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AddTagHelperDirective.cshtml +++ /dev/null @@ -1 +0,0 @@ -@addTagHelper something, nice \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AttributeTargetingTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AttributeTargetingTagHelpers.cshtml deleted file mode 100644 index 0b7f7f0092..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/AttributeTargetingTagHelpers.cshtml +++ /dev/null @@ -1,8 +0,0 @@ -@addTagHelper *, something - -

            -

            HelloWorld

            - - - -

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Await.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Await.cshtml deleted file mode 100644 index 69b68e07c5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Await.cshtml +++ /dev/null @@ -1,26 +0,0 @@ -@functions { - public async Task Foo() - { - return "Bar"; - } -} - -
            -

            Basic Asynchronous Expression Test

            -

            Basic Asynchronous Expression: @await Foo()

            -

            Basic Asynchronous Template: @(await Foo())

            -

            Basic Asynchronous Statement: @{ await Foo(); }

            -

            Basic Asynchronous Statement Nested: @{ @await Foo() }

            -

            Basic Incomplete Asynchronous Statement: @await

            -
            - -
            -

            Advanced Asynchronous Expression Test

            -

            Advanced Asynchronous Expression: @await Foo(1, 2)

            -

            Advanced Asynchronous Expression Extended: @await Foo.Bar(1, 2)

            -

            Advanced Asynchronous Template: @(await Foo("bob", true))

            -

            Advanced Asynchronous Statement: @{ await Foo(something, hello: "world"); }

            -

            Advanced Asynchronous Statement Extended: @{ await Foo.Bar(1, 2) }

            -

            Advanced Asynchronous Statement Nested: @{ @await Foo(boolValue: false) }

            -

            Advanced Incomplete Asynchronous Statement: @await ("wrrronggg")

            -
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.Prefixed.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.Prefixed.cshtml deleted file mode 100644 index 73e9407a3d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.Prefixed.cshtml +++ /dev/null @@ -1,10 +0,0 @@ -@tagHelperPrefix "THS" -@addTagHelper something, nice - - - -

            - - -
            -
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.RemoveTagHelper.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.RemoveTagHelper.cshtml deleted file mode 100644 index b8b5bcbf73..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.RemoveTagHelper.cshtml +++ /dev/null @@ -1,10 +0,0 @@ -@addTagHelper something, nice -@removeTagHelper "doesntmatter, nice" - -
            -

            -

            - - -

            -
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.cshtml deleted file mode 100644 index fb0515d0a3..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/BasicTagHelpers.cshtml +++ /dev/null @@ -1,9 +0,0 @@ -@addTagHelper "something, nice" - -
            -

            -

            - - -

            -
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Blocks.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Blocks.cshtml deleted file mode 100644 index 8d27de89cc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Blocks.cshtml +++ /dev/null @@ -1,37 +0,0 @@ -@{ - int i = 1; -} - -@while(i <= 10) { -

            Hello from C#, #@(i)

            - i += 1; -} - -@if(i == 11) { -

            We wrote 10 lines!

            -} - -@switch(i) { - case 11: -

            No really, we wrote 10 lines!

            - break; - default: -

            Actually, we didn't...

            - break; -} - -@for(int j = 1; j <= 10; j += 2) { -

            Hello again from C#, #@(j)

            -} - -@try { -

            That time, we wrote 5 lines!

            -} catch(Exception ex) { -

            Oh no! An error occurred: @(ex.Message)

            -} - -

            i is now @i

            - -@lock(new object()) { -

            This block is locked, for your security!

            -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlock.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlock.cshtml deleted file mode 100644 index 1c78883a10..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlock.cshtml +++ /dev/null @@ -1,5 +0,0 @@ -@{ - for(int i = 1; i <= 10; i++) { - Output.Write("

            Hello from C#, #" + i.ToString() + "

            "); - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockAtEOF.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockAtEOF.cshtml deleted file mode 100644 index 38417d481c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockAtEOF.cshtml +++ /dev/null @@ -1 +0,0 @@ -@{ \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockWithTextElement.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockWithTextElement.cshtml deleted file mode 100644 index 9c34a940eb..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CodeBlockWithTextElement.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@{ - var a = 1; foo - var b = 1; bar @(a+b) -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ComplexTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ComplexTagHelpers.cshtml deleted file mode 100644 index e14e76dbb0..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ComplexTagHelpers.cshtml +++ /dev/null @@ -1,36 +0,0 @@ -@addTagHelper something, nice - -@if (true) -{ - var checkbox = "checkbox"; - -
            -

            -

            Set Time:

            - @if (false) - { -

            New Time:

            - } - else - { -

            Current Time:

            - - - } -

            -

            - @{ var @object = false;} - -

            -

            - -

            -

            - -

            -

            - -

            - @someMethod(@

            ) -
            -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ConditionalAttributes.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ConditionalAttributes.cshtml deleted file mode 100644 index be1a9c2079..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ConditionalAttributes.cshtml +++ /dev/null @@ -1,15 +0,0 @@ -@{ - var ch = true; - var cls = "bar"; - -

            -

            -

            - - -

            - - - - -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CssSelectorTagHelperAttributes.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CssSelectorTagHelperAttributes.cshtml deleted file mode 100644 index 9b83d5f7fb..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/CssSelectorTagHelperAttributes.cshtml +++ /dev/null @@ -1,13 +0,0 @@ -@addTagHelper "*, something" - -2 TagHelpers. -1 TagHelper. -2 TagHelpers -2 TagHelpers -0 TagHelpers. -1 TagHelper -1 TagHelper -1 TagHelper - - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DesignTime.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DesignTime.cshtml deleted file mode 100644 index 5dcaeebdbf..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DesignTime.cshtml +++ /dev/null @@ -1,15 +0,0 @@ -

            - @for(int i = 1; i <= 10; i++) { -

            This is item #@i

            - } -
            - -

            -@(Foo(Bar.Baz)) -@Foo(@

            Bar @baz Biz

            ) -

            - -@section Footer { -

            Foo

            - @bar -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateAttributeTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateAttributeTagHelpers.cshtml deleted file mode 100644 index fb38512fde..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateAttributeTagHelpers.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -@addTagHelper something, nice - -

            - - - -

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateTargetTagHelper.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateTargetTagHelper.cshtml deleted file mode 100644 index d4429862bc..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DuplicateTargetTagHelper.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@addTagHelper something, nice - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DynamicAttributeTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DynamicAttributeTagHelpers.cshtml deleted file mode 100644 index 8480908aca..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/DynamicAttributeTagHelpers.cshtml +++ /dev/null @@ -1,14 +0,0 @@ -@addTagHelper something, nice - - - - - - - - - - - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyAttributeTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyAttributeTagHelpers.cshtml deleted file mode 100644 index afe5f6ad7b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyAttributeTagHelpers.cshtml +++ /dev/null @@ -1,8 +0,0 @@ -@addTagHelper something - -
            - -

            - -

            -
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyCodeBlock.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyCodeBlock.cshtml deleted file mode 100644 index 0366199cd5..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyCodeBlock.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -This is markup - -@{} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyExplicitExpression.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyExplicitExpression.cshtml deleted file mode 100644 index 6790c7eba2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyExplicitExpression.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -This is markup - -@() \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpression.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpression.cshtml deleted file mode 100644 index 021306da6b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpression.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -This is markup - -@! \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpressionInCode.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpressionInCode.cshtml deleted file mode 100644 index a1db8cd602..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EmptyImplicitExpressionInCode.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - @ -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EnumTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EnumTagHelpers.cshtml deleted file mode 100644 index 903e99ebe4..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EnumTagHelpers.cshtml +++ /dev/null @@ -1,11 +0,0 @@ -@addTagHelper something, nice - -@{ - var enumValue = MyEnum.MyValue; -} - - - - - - diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EscapedTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EscapedTagHelpers.cshtml deleted file mode 100644 index 2cd3a16374..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/EscapedTagHelpers.cshtml +++ /dev/null @@ -1,8 +0,0 @@ -@addTagHelper something - - - - - Not a TagHelper: - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpression.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpression.cshtml deleted file mode 100644 index 10730f1114..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpression.cshtml +++ /dev/null @@ -1 +0,0 @@ -1 + 1 = @(1+1) \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionAtEOF.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionAtEOF.cshtml deleted file mode 100644 index a0fdfc9a21..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionAtEOF.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -This is markup - -@( \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionWithMarkup.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionWithMarkup.cshtml deleted file mode 100644 index 70d8cefd95..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExplicitExpressionWithMarkup.cshtml +++ /dev/null @@ -1 +0,0 @@ -
            @(@
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExpressionsInCode.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExpressionsInCode.cshtml deleted file mode 100644 index a4d4caa007..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ExpressionsInCode.cshtml +++ /dev/null @@ -1,16 +0,0 @@ -@{ - object foo = null; - string bar = "Foo"; -} - -@if(foo != null) { - @foo -} else { -

            Foo is Null!

            -} - -

            -@if(!String.IsNullOrEmpty(bar)) { - @(bar.Replace("F", "B")) -} -

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock.cshtml deleted file mode 100644 index 5d06b37224..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock.cshtml +++ /dev/null @@ -1,12 +0,0 @@ -@functions { - -} - -@functions { - Random _rand = new Random(); - private int RandomInt() { - return _rand.Next(); - } -} - -Here's a random number: @RandomInt() \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlockMinimal.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlockMinimal.cshtml deleted file mode 100644 index 6b3de50b2c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlockMinimal.cshtml +++ /dev/null @@ -1,7 +0,0 @@ - - - @functions{ -string foo(string input) { - return input + "!"; -} -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock_Tabs.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock_Tabs.cshtml deleted file mode 100644 index 14a280f136..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/FunctionsBlock_Tabs.cshtml +++ /dev/null @@ -1,12 +0,0 @@ -@functions { - -} - -@functions { - Random _rand = new Random(); - private int RandomInt() { - return _rand.Next(); - } -} - -Here's a random number: @RandomInt() \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HiddenSpansInCode.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HiddenSpansInCode.cshtml deleted file mode 100644 index a6addbe97c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HiddenSpansInCode.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - @@Da -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Double.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Double.cshtml deleted file mode 100644 index 6a99437910..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Double.cshtml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Single.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Single.cshtml deleted file mode 100644 index dc1b21a546..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/HtmlCommentWithQuote_Single.cshtml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpression.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpression.cshtml deleted file mode 100644 index dcce7fa572..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpression.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@for(int i = 1; i <= 10; i++) { -

            This is item #@i

            -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpressionAtEOF.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpressionAtEOF.cshtml deleted file mode 100644 index 365d20e003..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ImplicitExpressionAtEOF.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -This is markup - -@ \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Imports.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Imports.cshtml deleted file mode 100644 index 90b2ae8222..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Imports.cshtml +++ /dev/null @@ -1,10 +0,0 @@ -@using System.IO -@using Foo = System.Text.Encoding -@using System - -@using static System -@using static System.Console -@using static global::System.Text.Encoding - -

            Path's full type name is @typeof(Path).FullName

            -

            Foo's actual full type name is @typeof(Foo).FullName

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/IncompleteTagHelper.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/IncompleteTagHelper.cshtml deleted file mode 100644 index add07acf43..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/IncompleteTagHelper.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@addTagHelper something, nice - -

            # }" /> -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Instrumented.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Instrumented.cshtml deleted file mode 100644 index bd273c57e1..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Instrumented.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@{ - int i = 1; - var foo = @

            Bar

            ; - @:Hello, World -

            Hello, World

            -} - -@while(i <= 10) { -

            Hello from C#, #@(i)

            - i += 1; -} - -@if(i == 11) { -

            We wrote 10 lines!

            -} - -@switch(i) { - case 11: -

            No really, we wrote 10 lines!

            - break; - default: -

            Actually, we didn't...

            - break; -} - -@for(int j = 1; j <= 10; j += 2) { -

            Hello again from C#, #@(j)

            -} - -@try { -

            That time, we wrote 5 lines!

            -} catch(Exception ex) { -

            Oh no! An error occurred: @(ex.Message)

            -} - -@lock(new object()) { -

            This block is locked, for your security!

            -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MarkupInCodeBlock.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MarkupInCodeBlock.cshtml deleted file mode 100644 index 712ef42848..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MarkupInCodeBlock.cshtml +++ /dev/null @@ -1,5 +0,0 @@ -@{ - for(int i = 1; i <= 10; i++) { -

            Hello from C#, #@(i.ToString())

            - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MinimizedTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MinimizedTagHelpers.cshtml deleted file mode 100644 index ea9c6a1f36..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/MinimizedTagHelpers.cshtml +++ /dev/null @@ -1,18 +0,0 @@ -@addTagHelper something, nice - -

            - - - - - -

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCSharp.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCSharp.cshtml deleted file mode 100644 index 8387e8a28a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCSharp.cshtml +++ /dev/null @@ -1,8 +0,0 @@ -@{ - @foreach (var result in (dynamic)Url) - { -
            - @result.SomeValue. -
            - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCodeBlocks.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCodeBlocks.cshtml deleted file mode 100644 index 070875f5fa..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedCodeBlocks.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@if(foo) { - @if(bar) { - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedScriptTagTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedScriptTagTagHelpers.cshtml deleted file mode 100644 index 6ebcc156f0..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NestedScriptTagTagHelpers.cshtml +++ /dev/null @@ -1,16 +0,0 @@ -@addTagHelper something, nice - - - } - -

            -
            - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NoLinePragmas.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NoLinePragmas.cshtml deleted file mode 100644 index 36e96c46b9..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NoLinePragmas.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@{ - int i = 1; -} - -@while(i <= 10) { -

            Hello from C#, #@(i)

            - i += 1; -} - -@if(i == 11) { -

            We wrote 10 lines!

            -} - -@switch(i) { - case 11: -

            No really, we wrote 10 lines!

            - break; - default: -

            Actually, we didn't...

            - break; -} - -@for(int j = 1; j <= 10; j += 2) { -

            Hello again from C#, #@(j)

            -} - -@try { -

            That time, we wrote 5 lines!

            -} catch(Exception ex) { -

            Oh no! An error occurred: @(ex.Message)

            -} - -@* With has no equivalent in C# *@ -

            i is now @i

            - -@lock(new object()) { -

            This block is locked, for your security!

            -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NullConditionalExpressions.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NullConditionalExpressions.cshtml deleted file mode 100644 index fa87620317..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/NullConditionalExpressions.cshtml +++ /dev/null @@ -1,11 +0,0 @@ -@{ - @ViewBag?.Data - @ViewBag.IntIndexer?[0] - @ViewBag.StrIndexer?["key"] - @ViewBag?.Method(Value?[23]?.More)?["key"] -} - -@ViewBag?.Data -@ViewBag.IntIndexer?[0] -@ViewBag.StrIndexer?["key"] -@ViewBag?.Method(Value?[23]?.More)?["key"] \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/OpenedIf.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/OpenedIf.cshtml deleted file mode 100644 index 33162eb90b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/OpenedIf.cshtml +++ /dev/null @@ -1,5 +0,0 @@ - - -@if (true) { - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ParserError.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ParserError.cshtml deleted file mode 100644 index ab30e853fd..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/ParserError.cshtml +++ /dev/null @@ -1,5 +0,0 @@ -@{ -/* -int i =10; -int j =20; -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/PrefixedAttributeTagHelpers.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/PrefixedAttributeTagHelpers.cshtml deleted file mode 100644 index 5cca6769e7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/PrefixedAttributeTagHelpers.cshtml +++ /dev/null @@ -1,23 +0,0 @@ -@addTagHelper something, nice - -@{ - var literate = "or illiterate"; - var intDictionary = new Dictionary - { - { "three", 3 }, - }; - var stringDictionary = new SortedDictionary - { - { "name", "value" }, - }; -} - -
            - - - - -
            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RazorComments.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RazorComments.cshtml deleted file mode 100644 index bd4820f914..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RazorComments.cshtml +++ /dev/null @@ -1,15 +0,0 @@ -@*This is not going to be rendered*@ -

            This should @* not *@ be shown

            - -@{ - @* throw new Exception("Oh no!") *@ - Exception foo = @* new Exception("Oh no!") *@ null; - if(foo != null) { - throw foo; - } -} - -@{ var bar = "@* bar *@"; } -

            But this should show the comment syntax: @bar

            - -@(a@**@b) diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RemoveTagHelperDirective.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RemoveTagHelperDirective.cshtml deleted file mode 100644 index fae5f78d2d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/RemoveTagHelperDirective.cshtml +++ /dev/null @@ -1 +0,0 @@ -@removeTagHelper something, nice \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Sections.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Sections.cshtml deleted file mode 100644 index 952461002f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Sections.cshtml +++ /dev/null @@ -1,17 +0,0 @@ -@{ - Layout = "_SectionTestLayout.cshtml" -} - -
            This is in the Body> - -@section Section2 { -
            This is in Section 2
            -} - -@section Section1 { -
            This is in Section 1
            -} - -@section NestedDelegates { - @{ Func f = @@item; } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SimpleUnspacedIf.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SimpleUnspacedIf.cshtml deleted file mode 100644 index 27f2750eb2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SimpleUnspacedIf.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@if (true) -{ -
            -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelper.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelper.cshtml deleted file mode 100644 index b331d1208f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelper.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@addTagHelper something, nice - -

            Body of Tag

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelperWithNewlineBeforeAttributes.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelperWithNewlineBeforeAttributes.cshtml deleted file mode 100644 index 5b6b28d786..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SingleTagHelperWithNewlineBeforeAttributes.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@addTagHelper something, nice - -

            Body of Tag

            \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/StringLiterals.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/StringLiterals.cshtml deleted file mode 100644 index 19d498abfe..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/StringLiterals.cshtml +++ /dev/null @@ -1,237 +0,0 @@ -

            This is line 1

            -

            This is line 2

            -

            This is line 3

            -

            This is line 4

            -

            This is line 5

            -

            This is line 6

            -

            This is line 7

            -

            This is line 8

            -

            This is line 9

            -

            This is line 10

            -

            This is line 11

            -

            This is line 12

            -

            This is line 13

            -

            This is line 14

            -

            This is line 15

            -

            This is line 16

            -

            This is line 17

            -

            This is line 18

            -

            This is line 19

            -

            This is line 20

            -

            This is line 21

            -

            This is line 22

            -

            This is line 23

            -

            This is line 24

            -

            This is line 25

            -

            This is line 26

            -

            This is line 27

            -

            This is line 28

            -

            This is line 29

            -

            This is line 30

            -

            This is line 31

            -

            This is line 32

            -

            This is line 33

            -

            This is line 34

            -

            This is line 35

            -

            This is line 36

            -

            This is line 37

            -

            This is line 38

            -

            This is line 39

            -

            This is line 40

            -

            This is line 41

            -

            This is line 42

            -

            This is line 43

            -

            This is line 44

            -

            This is line 45

            -

            This is line 46

            -

            This is line 47

            -

            This is line 48

            -

            This is line 49

            -

            This is line 50

            -

            This is line 51

            -

            This is line 52

            -

            This is line 53

            -

            This is line 54

            -

            This is line 55

            -

            This is line 56

            -

            This is line 57

            -

            This is line 58

            -

            This is line 59

            -

            This is line 60

            -

            This is line 61

            -

            This is line 62

            -

            This is line 63

            -

            This is line 64

            -

            This is line 65

            -

            This is line 66

            -

            This is line 67

            -

            This is line 68

            -

            This is line 69

            -

            This is line 70

            -

            This is line 71

            -

            This is line 72

            -

            This is line 73

            -

            This is line 74

            -

            This is line 75

            -

            This is line 76

            -

            This is line 77

            -

            This is line 78

            -

            This is line 79

            -

            This is line 80

            -

            This is line 81

            -

            This is line 82

            -

            This is line 83

            -

            This is line 84


            - -@section WriteLiteralsToInHere { -

            This is line 1 nested

            -

            This is line 2 nested

            -

            This is line 3 nested

            -

            This is line 4 nested

            -

            This is line 5 nested

            -

            This is line 6 nested

            -

            This is line 7 nested

            -

            This is line 8 nested

            -

            This is line 9 nested

            -

            This is line 10 nested

            -

            This is line 11 nested

            -

            This is line 12 nested

            -

            This is line 13 nested

            -

            This is line 14 nested

            -

            This is line 15 nested

            -

            This is line 16 nested

            -

            This is line 17 nested

            -

            This is line 18 nested

            -

            This is line 19 nested

            -

            This is line 20 nested

            -

            This is line 21 nested

            -

            This is line 22 nested

            -

            This is line 23 nested

            -

            This is line 24 nested

            -

            This is line 25 nested

            -

            This is line 26 nested

            -

            This is line 27 nested

            -

            This is line 28 nested

            -

            This is line 29 nested

            -

            This is line 30 nested

            -

            This is line 31 nested

            -

            This is line 32 nested

            -

            This is line 33 nested

            -

            This is line 34 nested

            -

            This is line 35 nested

            -

            This is line 36 nested

            -

            This is line 37 nested

            -

            This is line 38 nested

            -

            This is line 39 nested

            -

            This is line 40 nested

            -

            This is line 41 nested

            -

            This is line 42 nested

            -

            This is line 43 nested

            -

            This is line 44 nested

            -

            This is line 45 nested

            -

            This is line 46 nested

            -

            This is line 47 nested

            -

            This is line 48 nested

            -

            This is line 49 nested

            -

            This is line 50 nested

            -

            This is line 51 nested

            -

            This is line 52 nested

            -

            This is line 53 nested

            -

            This is line 54 nested

            -

            This is line 55 nested

            -

            This is line 56 nested

            -

            This is line 57 nested

            -

            This is line 58 nested

            -

            This is line 59 nested

            -

            This is line 60 nested

            -

            This is line 61 nested

            -

            This is line 62 nested

            -

            This is line 63 nested

            -

            This is line 64 nested

            -

            This is line 65 nested

            -

            This is line 66 nested

            -

            This is line 67 nested

            -

            This is line 68 nested

            -

            This is line 69 nested

            -

            This is line 70 nested

            -

            This is line 71 nested

            -

            This is line 72 nested

            -

            This is line 73 nested

            -

            This is line 74 nested

            -

            This is line 75 nested

            -} -

            This is line 1

            -

            This is line 2

            -

            This is line 3

            -

            This is line 4

            -

            This is line 5

            -

            This is line 6

            -

            This is line 7

            -

            This is line 8

            -

            This is line 9

            -

            This is line 10

            -

            This is line 11

            -

            This is line 12

            -

            This is line 13

            -

            This is line 14

            -

            This is line 15

            -

            This is line 16

            -

            This is line 17

            -

            This is line 18

            -

            This is line 19

            -

            This is line 20

            -

            This is line 21

            -

            This is line 22

            -

            This is line 23

            -

            This is line 24

            -

            This is line 25

            -

            This is line 26

            -

            This is line 27

            -

            This is line 28

            -

            This is line 29

            -

            This is line 30

            -

            This is line 31

            -

            This is line 32

            -

            This is line 33

            -

            This is line 34

            -

            This is line 35

            -

            This is line 36

            -

            This is line 37

            -

            This is line 38

            -

            This is line 39

            -

            This is line 40

            -

            This is line 41

            -

            This is line 42

            -

            This is line 43

            hi! -@section WriteLiteralsToInHereAlso { -

            This is line 1 nested

            -

            This is line 2 nested

            -

            This is line 3 nested

            -

            This is line 4 nested

            -

            This is line 5 nested

            -

            This is line 6 nested

            -

            This is line 7 nested

            -

            This is line 8 nested

            -

            This is line 9 nested

            -

            This is line 10 nested

            -

            This is line 11 nested

            -

            This is line 12 nested

            -

            This is line 13 nested

            -

            This is line 14 nested

            -

            This is line 15 nested

            -

            This is line 16 nested

            -

            This is line 17 nested

            -

            This is line 18 nested

            -

            This is line 19 nested

            -

            This is line 20 nested

            -

            This is line 21 nested

            -

            This is line 22 nested

            -

            This is line 23 nested

            -

            This is line 24 nested

            -

            This is line 25 nested

            -

            This is line 26 nested

            -

            This is line 27 nested

            -

            This is line 28 nested

            -

            This is line 29 nested

            -

            30

            -}! \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SymbolBoundAttributes.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SymbolBoundAttributes.cshtml deleted file mode 100644 index 2974c94c74..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/SymbolBoundAttributes.cshtml +++ /dev/null @@ -1,19 +0,0 @@ -@addTagHelper *, nice - -
              -
                - - - -
                -
                - -
                  -
                    - - - -
                    -
                    \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersInSection.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersInSection.cshtml deleted file mode 100644 index 55705c6b00..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersInSection.cshtml +++ /dev/null @@ -1,14 +0,0 @@ -@addTagHelper something, nice - -@{ - var code = "some code"; -} - -@section MySection { -
                    - - In None ContentBehavior. - Some buffered values with @code - -
                    -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersWithWeirdlySpacedAttributes.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersWithWeirdlySpacedAttributes.cshtml deleted file mode 100644 index d390bc024d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TagHelpersWithWeirdlySpacedAttributes.cshtml +++ /dev/null @@ -1,15 +0,0 @@ -@addTagHelper something, nice - -

                    Body of Tag

                    - - - -

                    - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Templates.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Templates.cshtml deleted file mode 100644 index 1edba0340b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/Templates.cshtml +++ /dev/null @@ -1,48 +0,0 @@ -@functions { - public HelperResult Repeat(int times, Func template) { - return new HelperResult((writer) => { - for(int i = 0; i < times; i++) { - ((HelperResult)template(i)).WriteTo(writer); - } - }); - } -} - -@{ - Func foo = @This works @item!; - @foo("") -} - -
                      -@(Repeat(10, @
                    • Item #@item
                    • )) -
                    - -

                    -@Repeat(10, - @: This is line#@item of markup
                    -) -

                    - -

                    -@Repeat(10, - @:: This is line#@item of markup
                    -) -

                    - -

                    -@Repeat(10, - @::: This is line#@item of markup
                    -) -

                    - - -
                      - @Repeat(10, @
                    • - Item #@item - @{var parent = item;} -
                        -
                      • Child Items... ?
                      • - @*Repeat(10, @
                      • Item #@(parent).@item
                      • )*@ -
                      -
                    • ) -
                    \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TransitionsInTagHelperAttributes.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TransitionsInTagHelperAttributes.cshtml deleted file mode 100644 index b05d39b2ce..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/TransitionsInTagHelperAttributes.cshtml +++ /dev/null @@ -1,12 +0,0 @@ -@addTagHelper something, nice -@{ - var @class = "container-fluid"; - var @int = 1; -} - -

                    Body of Tag

                    -

                    -

                    -

                    -

                    -

                    diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/UnfinishedExpressionInCode.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/UnfinishedExpressionInCode.cshtml deleted file mode 100644 index bf1d796466..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/CodeGenerator/Source/UnfinishedExpressionInCode.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ -@DateTime. -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.cshtml b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.cshtml deleted file mode 100644 index b50db22f77..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.cshtml +++ /dev/null @@ -1,16 +0,0 @@ -@{ - string hello = "Hello, World"; -} - - - - Simple Page - - -

                    Simple Page

                    -

                    @hello

                    -

                    - @foreach(char c in hello) {@c} -

                    - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.txt b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.txt deleted file mode 100644 index 74c8e7e7bd..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/DesignTime/Simple.txt +++ /dev/null @@ -1,53 +0,0 @@ -namespace Razor -{ - using System.Threading.Tasks; - - public class __CompiledTemplate - { - private static object @__o; - private void @__RazorDesignTimeHelpers__() - { - #pragma warning disable 219 - #pragma warning restore 219 - } - #line hidden - public __CompiledTemplate() - { - } - - #pragma warning disable 1998 - public override async Task ExecuteAsync() - { -#line 1 "C:\This\Path\Is\Just\For\Line\Pragmas.cshtml" - - string hello = "Hello, World"; - -#line default -#line hidden - -#line 11 "C:\This\Path\Is\Just\For\Line\Pragmas.cshtml" - __o = hello; - -#line default -#line hidden -#line 13 "C:\This\Path\Is\Just\For\Line\Pragmas.cshtml" - foreach(char c in hello) { - -#line default -#line hidden - -#line 13 "C:\This\Path\Is\Just\For\Line\Pragmas.cshtml" - __o = c; - -#line default -#line hidden -#line 13 "C:\This\Path\Is\Just\For\Line\Pragmas.cshtml" - } - -#line default -#line hidden - - } - #pragma warning restore 1998 - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/nested-1000.html b/test/Microsoft.AspNetCore.Razor.Test/TestFiles/nested-1000.html deleted file mode 100644 index 3c35bdbcbe..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/TestFiles/nested-1000.html +++ /dev/null @@ -1,2002 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/Text/LineTrackingStringBufferTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Text/LineTrackingStringBufferTest.cs deleted file mode 100644 index 9afaffeb25..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Text/LineTrackingStringBufferTest.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public class LineTrackingStringBufferTest - { - [Fact] - public void CtorInitializesProperties() - { - var buffer = new LineTrackingStringBuffer(); - Assert.Equal(0, buffer.Length); - } - - [Fact] - public void CharAtCorrectlyReturnsLocation() - { - var buffer = new LineTrackingStringBuffer(); - buffer.Append("foo\rbar\nbaz\r\nbiz"); - LineTrackingStringBuffer.CharacterReference chr = buffer.CharAt(14); - Assert.Equal('i', chr.Character); - Assert.Equal(new SourceLocation(14, 3, 1), chr.Location); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Text/LookaheadTextReaderTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Text/LookaheadTextReaderTestBase.cs deleted file mode 100644 index 00348e916e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Text/LookaheadTextReaderTestBase.cs +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Text; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public abstract class LookaheadTextReaderTestBase - { - protected abstract LookaheadTextReader CreateReader(string testString); - - protected void RunPeekTest(string input, int peekAt = 0) - { - RunPeekOrReadTest(input, peekAt, false); - } - - protected void RunReadTest(string input, int readAt = 0) - { - RunPeekOrReadTest(input, readAt, true); - } - - protected void RunSourceLocationTest(string input, SourceLocation expected, int checkAt = 0) - { - RunSourceLocationTest(input, expected, r => AdvanceReader(checkAt, r)); - } - - protected void RunSourceLocationTest(string input, SourceLocation expected, Action readerAction) - { - // Arrange - var reader = CreateReader(input); - readerAction(reader); - - // Act - var actual = reader.CurrentLocation; - - // Assert - Assert.Equal(expected, actual); - } - - protected void RunEndLookaheadUpdatesSourceLocationTest() - { - SourceLocation? expectedLocation = null; - SourceLocation? actualLocation = null; - - RunLookaheadTest("abc\r\ndef\r\nghi", null, - Read(6), - CaptureSourceLocation(s => expectedLocation = s), - Lookahead(Read(6)), - CaptureSourceLocation(s => actualLocation = s)); - // Assert - Assert.Equal(expectedLocation.Value.AbsoluteIndex, actualLocation.Value.AbsoluteIndex); - Assert.Equal(expectedLocation.Value.CharacterIndex, actualLocation.Value.CharacterIndex); - Assert.Equal(expectedLocation.Value.LineIndex, actualLocation.Value.LineIndex); - } - - protected void RunReadToEndTest() - { - // Arrange - var reader = CreateReader("abcdefg"); - - // Act - var str = reader.ReadToEnd(); - - // Assert - Assert.Equal("abcdefg", str); - } - - protected void RunCancelBacktrackOutsideLookaheadTest() - { - // Arrange - var reader = CreateReader("abcdefg"); - - // Act and Assert - var exception = Assert.Throws(() => reader.CancelBacktrack()); - Assert.Equal(RazorResources.CancelBacktrack_Must_Be_Called_Within_Lookahead, exception.Message); - } - - protected Action CaptureSourceLocation(Action capture) - { - return (_, reader) => { capture(reader.CurrentLocation); }; - } - - protected Action Read(int count) - { - return (builder, reader) => - { - for (int i = 0; i < count; i++) - { - Read(builder, reader); - } - }; - } - - protected void Read(StringBuilder builder, LookaheadTextReader reader) - { - builder.Append((char)reader.Read()); - } - - protected void ReadToEnd(StringBuilder builder, LookaheadTextReader reader) - { - builder.Append(reader.ReadToEnd()); - } - - protected void CancelBacktrack(StringBuilder builder, LookaheadTextReader reader) - { - reader.CancelBacktrack(); - } - - protected Action Lookahead(params Action[] readerCommands) - { - return (builder, reader) => - { - using (reader.BeginLookahead()) - { - RunAll(readerCommands, builder, reader); - } - }; - } - - protected void RunLookaheadTest(string input, string expected, params Action[] readerCommands) - { - // Arrange - var builder = new StringBuilder(); - using (LookaheadTextReader reader = CreateReader(input)) - { - RunAll(readerCommands, builder, reader); - } - - if (expected != null) - { - Assert.Equal(expected, builder.ToString()); - } - } - - protected void RunReadUntilTest(Func readMethod, int expectedRaw, int expectedChar, int expectedLine) - { - // Arrange - var reader = CreateReader("a\r\nbcd\r\nefg"); - - reader.Read(); // Reader: "\r\nbcd\r\nefg" - reader.Read(); // Reader: "\nbcd\r\nefg" - reader.Read(); // Reader: "bcd\r\nefg" - - // Act - string read; - SourceLocation actualLocation; - using (reader.BeginLookahead()) - { - read = readMethod(reader); - actualLocation = reader.CurrentLocation; - } - - // Assert - Assert.Equal(3, reader.CurrentLocation.AbsoluteIndex); - Assert.Equal(0, reader.CurrentLocation.CharacterIndex); - Assert.Equal(1, reader.CurrentLocation.LineIndex); - Assert.Equal(expectedRaw, actualLocation.AbsoluteIndex); - Assert.Equal(expectedChar, actualLocation.CharacterIndex); - Assert.Equal(expectedLine, actualLocation.LineIndex); - Assert.Equal('b', reader.Peek()); - Assert.Equal(read, readMethod(reader)); - } - - protected void RunBufferReadTest(Func readMethod) - { - // Arrange - var reader = CreateReader("abcdefg"); - - reader.Read(); // Reader: "bcdefg" - - // Act - char[] buffer = new char[4]; - var read = -1; - SourceLocation actualLocation; - using (reader.BeginLookahead()) - { - read = readMethod(reader, buffer, 0, 4); - actualLocation = reader.CurrentLocation; - } - - // Assert - Assert.Equal("bcde", new String(buffer)); - Assert.Equal(4, read); - Assert.Equal(5, actualLocation.AbsoluteIndex); - Assert.Equal(5, actualLocation.CharacterIndex); - Assert.Equal(0, actualLocation.LineIndex); - Assert.Equal(1, reader.CurrentLocation.CharacterIndex); - Assert.Equal(0, reader.CurrentLocation.LineIndex); - Assert.Equal('b', reader.Peek()); - } - - private static void RunAll(Action[] readerCommands, StringBuilder builder, LookaheadTextReader reader) - { - foreach (Action readerCommand in readerCommands) - { - readerCommand(builder, reader); - } - } - - private void RunPeekOrReadTest(string input, int offset, bool isRead) - { - using (LookaheadTextReader reader = CreateReader(input)) - { - AdvanceReader(offset, reader); - - // Act - int? actual = null; - if (isRead) - { - actual = reader.Read(); - } - else - { - actual = reader.Peek(); - } - - Assert.NotNull(actual); - - // Asserts - AssertReaderValueCorrect(actual.Value, input, offset, "Peek"); - - if (isRead) - { - AssertReaderValueCorrect(reader.Peek(), input, offset + 1, "Read"); - } - else - { - Assert.Equal(actual, reader.Peek()); - } - } - } - - private static void AdvanceReader(int offset, LookaheadTextReader reader) - { - for (int i = 0; i < offset; i++) - { - reader.Read(); - } - } - - private void AssertReaderValueCorrect(int actual, string input, int expectedOffset, string methodName) - { - if (expectedOffset < input.Length) - { - Assert.Equal(input[expectedOffset], actual); - } - else - { - Assert.Equal(-1, actual); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Text/SourceLocationTrackerTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Text/SourceLocationTrackerTest.cs deleted file mode 100644 index 23a4ffc7b6..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Text/SourceLocationTrackerTest.cs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public class SourceLocationTrackerTest - { - private static readonly SourceLocation TestStartLocation = new SourceLocation(10, 42, 45); - - [Fact] - public void ConstructorSetsCurrentLocationToZero() - { - Assert.Equal(SourceLocation.Zero, new SourceLocationTracker().CurrentLocation); - } - - [Fact] - public void ConstructorWithSourceLocationSetsCurrentLocationToSpecifiedValue() - { - var loc = new SourceLocation(10, 42, 4); - Assert.Equal(loc, new SourceLocationTracker(loc).CurrentLocation); - } - - [Fact] - public void UpdateLocationAdvancesCorrectlyForMultiLineString() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation("foo\nbar\rbaz\r\nbox"); - - // Assert - Assert.Equal(26, tracker.CurrentLocation.AbsoluteIndex); - Assert.Equal(45, tracker.CurrentLocation.LineIndex); - Assert.Equal(3, tracker.CurrentLocation.CharacterIndex); - } - - [Fact] - public void UpdateLocationAdvancesAbsoluteIndexOnNonNewlineCharacter() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('f', 'o'); - - // Assert - Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex); - } - - [Fact] - public void UpdateLocationAdvancesCharacterIndexOnNonNewlineCharacter() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('f', 'o'); - - // Assert - Assert.Equal(46, tracker.CurrentLocation.CharacterIndex); - } - - [Fact] - public void UpdateLocationDoesNotAdvanceLineIndexOnNonNewlineCharacter() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('f', 'o'); - - // Assert - Assert.Equal(42, tracker.CurrentLocation.LineIndex); - } - - [Fact] - public void UpdateLocationAdvancesLineIndexOnSlashN() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\n', 'o'); - - // Assert - Assert.Equal(43, tracker.CurrentLocation.LineIndex); - } - - [Fact] - public void UpdateLocationAdvancesAbsoluteIndexOnSlashN() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\n', 'o'); - - // Assert - Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex); - } - - [Fact] - public void UpdateLocationResetsCharacterIndexOnSlashN() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\n', 'o'); - - // Assert - Assert.Equal(0, tracker.CurrentLocation.CharacterIndex); - } - - [Fact] - public void UpdateLocationAdvancesLineIndexOnSlashRFollowedByNonNewlineCharacter() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\r', 'o'); - - // Assert - Assert.Equal(43, tracker.CurrentLocation.LineIndex); - } - - [Fact] - public void UpdateLocationAdvancesAbsoluteIndexOnSlashRFollowedByNonNewlineCharacter() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\r', 'o'); - - // Assert - Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex); - } - - [Fact] - public void UpdateLocationResetsCharacterIndexOnSlashRFollowedByNonNewlineCharacter() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\r', 'o'); - - // Assert - Assert.Equal(0, tracker.CurrentLocation.CharacterIndex); - } - - [Fact] - public void UpdateLocationDoesNotAdvanceLineIndexOnSlashRFollowedBySlashN() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\r', '\n'); - - // Assert - Assert.Equal(42, tracker.CurrentLocation.LineIndex); - } - - [Fact] - public void UpdateLocationAdvancesAbsoluteIndexOnSlashRFollowedBySlashN() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\r', '\n'); - - // Assert - Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex); - } - - [Fact] - public void UpdateLocationAdvancesCharacterIndexOnSlashRFollowedBySlashN() - { - // Arrange - var tracker = new SourceLocationTracker(TestStartLocation); - - // Act - tracker.UpdateLocation('\r', '\n'); - - // Assert - Assert.Equal(46, tracker.CurrentLocation.CharacterIndex); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Text/TextChangeTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Text/TextChangeTest.cs deleted file mode 100644 index 87db42f6c2..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Text/TextChangeTest.cs +++ /dev/null @@ -1,319 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Web.WebPages.TestUtils; -using Microsoft.AspNetCore.Razor.Test.Utils; -using Moq; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Text -{ - public class TextChangeTest - { - [Fact] - public void ConstructorRequiresNonNegativeOldPosition() - { - var parameterName = "oldPosition"; - var exception = Assert.Throws(parameterName, () => new TextChange(-1, 0, new Mock().Object, 0, 0, new Mock().Object)); - ExceptionHelpers.ValidateArgumentException(parameterName, "Value must be greater than or equal to 0.", exception); - } - - [Fact] - public void ConstructorRequiresNonNegativeNewPosition() - { - var parameterName = "newPosition"; - var exception = Assert.Throws(parameterName, () => new TextChange(0, 0, new Mock().Object, -1, 0, new Mock().Object)); - ExceptionHelpers.ValidateArgumentException(parameterName, "Value must be greater than or equal to 0.", exception); - } - - [Fact] - public void ConstructorRequiresNonNegativeOldLength() - { - var parameterName = "oldLength"; - var exception = Assert.Throws(parameterName, () => new TextChange(0, -1, new Mock().Object, 0, 0, new Mock().Object)); - ExceptionHelpers.ValidateArgumentException(parameterName, "Value must be greater than or equal to 0.", exception); - } - - [Fact] - public void ConstructorRequiresNonNegativeNewLength() - { - var parameterName = "newLength"; - var exception = Assert.Throws(parameterName, () => new TextChange(0, 0, new Mock().Object, 0, -1, new Mock().Object)); - ExceptionHelpers.ValidateArgumentException(parameterName, "Value must be greater than or equal to 0.", exception); - } - - [Fact] - public void ConstructorInitializesProperties() - { - // Act - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(42, 24, oldBuffer, 1337, newBuffer); - - // Assert - Assert.Equal(42, change.OldPosition); - Assert.Equal(24, change.OldLength); - Assert.Equal(1337, change.NewLength); - Assert.Same(newBuffer, change.NewBuffer); - Assert.Same(oldBuffer, change.OldBuffer); - } - - [Fact] - public void TestIsDelete() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 1, oldBuffer, 0, newBuffer); - - // Assert - Assert.True(change.IsDelete); - } - - [Fact] - public void TestDeleteCreatesTheRightSizeChange() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 1, oldBuffer, 0, newBuffer); - - // Assert - Assert.Equal(0, change.NewText.Length); - Assert.Equal(1, change.OldText.Length); - } - - [Fact] - public void TestIsInsert() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 0, oldBuffer, 35, newBuffer); - - // Assert - Assert.True(change.IsInsert); - } - - [Fact] - public void TestInsertCreateTheRightSizeChange() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 0, oldBuffer, 1, newBuffer); - - // Assert - Assert.Equal(1, change.NewText.Length); - Assert.Equal(0, change.OldText.Length); - } - - [Fact] - public void TestIsReplace() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 5, oldBuffer, 10, newBuffer); - - // Assert - Assert.True(change.IsReplace); - } - - [Fact] - public void ReplaceCreatesTheRightSizeChange() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 5, oldBuffer, 10, newBuffer); - - // Assert - Assert.Equal(10, change.NewText.Length); - Assert.Equal(5, change.OldText.Length); - } - - [Fact] - public void ReplaceCreatesTheRightSizeChange1() - { - // Arrange - var oldBuffer = new Mock().Object; - var newBuffer = new Mock().Object; - var change = new TextChange(0, 5, oldBuffer, 1, newBuffer); - - // Assert - Assert.Equal(1, change.NewText.Length); - Assert.Equal(5, change.OldText.Length); - } - - [Fact] - public void OldTextReturnsOldSpanFromOldBuffer() - { - // Arrange - var newBuffer = new StringTextBuffer("test"); - var oldBuffer = new StringTextBuffer("text"); - var textChange = new TextChange(2, 1, oldBuffer, 1, newBuffer); - - // Act - var text = textChange.OldText; - - // Assert - Assert.Equal("x", text); - } - - [Fact] - public void OldTextReturnsOldSpanFromOldBuffer2() - { - // Arrange - var newBuffer = new StringTextBuffer("test"); - var oldBuffer = new StringTextBuffer("text"); - var textChange = new TextChange(2, 2, oldBuffer, 1, newBuffer); - - // Act - var text = textChange.OldText; - - // Assert - Assert.Equal("xt", text); - } - - [Fact] - public void NewTextWithInsertReturnsChangedTextFromBuffer() - { - // Arrange - var newBuffer = new StringTextBuffer("test"); - var oldBuffer = new StringTextBuffer(""); - var textChange = new TextChange(0, 0, oldBuffer, 3, newBuffer); - - // Act - var text = textChange.NewText; - var oldText = textChange.OldText; - - // Assert - Assert.Equal("tes", text); - Assert.Equal("", oldText); - } - - [Fact] - public void NewTextWithDeleteReturnsEmptyString() - { - // Arrange - var newBuffer = new StringTextBuffer("test"); - var oldBuffer = new StringTextBuffer(""); - var textChange = new TextChange(1, 1, oldBuffer, 0, newBuffer); - - // Act - var text = textChange.NewText; - - // Assert - Assert.Equal(string.Empty, text); - } - - [Fact] - public void NewTextWithReplaceReturnsChangedTextFromBuffer() - { - // Arrange - var newBuffer = new StringTextBuffer("test"); - var oldBuffer = new StringTextBuffer("tebb"); - var textChange = new TextChange(2, 2, oldBuffer, 1, newBuffer); - - // Act - var newText = textChange.NewText; - var oldText = textChange.OldText; - - // Assert - Assert.Equal("s", newText); - Assert.Equal("bb", oldText); - } - - [Fact] - public void ApplyChangeWithInsertedTextReturnsNewContentWithChangeApplied() - { - // Arrange - var newBuffer = new StringTextBuffer("test"); - var oldBuffer = new StringTextBuffer(""); - var textChange = new TextChange(0, 0, oldBuffer, 3, newBuffer); - - // Act - var text = textChange.ApplyChange("abcd", 0); - - // Assert - Assert.Equal("tesabcd", text); - } - - [Fact] - public void ApplyChangeWithRemovedTextReturnsNewContentWithChangeApplied() - { - // Arrange - var newBuffer = new StringTextBuffer("abcdefg"); - var oldBuffer = new StringTextBuffer(""); - var textChange = new TextChange(1, 1, oldBuffer, 0, newBuffer); - - // Act - var text = textChange.ApplyChange("abcdefg", 1); - - // Assert - Assert.Equal("bcdefg", text); - } - - [Fact] - public void ApplyChangeWithReplacedTextReturnsNewContentWithChangeApplied() - { - // Arrange - var newBuffer = new StringTextBuffer("abcdefg"); - var oldBuffer = new StringTextBuffer(""); - var textChange = new TextChange(1, 1, oldBuffer, 2, newBuffer); - - // Act - var text = textChange.ApplyChange("abcdefg", 1); - - // Assert - Assert.Equal("bcbcdefg", text); - } - - [Fact] - public void NormalizeFixesUpIntelliSenseStyleReplacements() - { - // Arrange - var newBuffer = new StringTextBuffer("Date."); - var oldBuffer = new StringTextBuffer("Date"); - var original = new TextChange(0, 4, oldBuffer, 5, newBuffer); - - // Act - var normalized = original.Normalize(); - - // Assert - Assert.Equal(new TextChange(4, 0, oldBuffer, 1, newBuffer), normalized); - } - - [Fact] - public void NormalizeDoesntAffectChangesWithoutCommonPrefixes() - { - // Arrange - var newBuffer = new StringTextBuffer("DateTime."); - var oldBuffer = new StringTextBuffer("Date."); - var original = new TextChange(0, 5, oldBuffer, 9, newBuffer); - - // Act - var normalized = original.Normalize(); - - // Assert - Assert.Equal(original, normalized); - } - - [Fact] - public void NormalizeDoesntAffectShrinkingReplacements() - { - // Arrange - var newBuffer = new StringTextBuffer("D"); - var oldBuffer = new StringTextBuffer("DateTime"); - var original = new TextChange(0, 8, oldBuffer, 1, newBuffer); - - // Act - var normalized = original.Normalize(); - - // Assert - Assert.Equal(original, normalized); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerCommentTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerCommentTest.cs deleted file mode 100644 index cdb179a51c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerCommentTest.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class CSharpTokenizerCommentTest : CSharpTokenizerTestBase - { - [Fact] - public void Next_Ignores_Star_At_EOF_In_RazorComment() - { - TestTokenizer("@* Foo * Bar * Baz *", - new CSharpSymbol(0, 0, 0, "@", CSharpSymbolType.RazorCommentTransition), - new CSharpSymbol(1, 0, 1, "*", CSharpSymbolType.RazorCommentStar), - new CSharpSymbol(2, 0, 2, " Foo * Bar * Baz *", CSharpSymbolType.RazorComment)); - } - - [Fact] - public void Next_Ignores_Star_Without_Trailing_At() - { - TestTokenizer("@* Foo * Bar * Baz *@", - new CSharpSymbol(0, 0, 0, "@", CSharpSymbolType.RazorCommentTransition), - new CSharpSymbol(1, 0, 1, "*", CSharpSymbolType.RazorCommentStar), - new CSharpSymbol(2, 0, 2, " Foo * Bar * Baz ", CSharpSymbolType.RazorComment), - new CSharpSymbol(19, 0, 19, "*", CSharpSymbolType.RazorCommentStar), - new CSharpSymbol(20, 0, 20, "@", CSharpSymbolType.RazorCommentTransition)); - } - - [Fact] - public void Next_Returns_RazorComment_Token_For_Entire_Razor_Comment() - { - TestTokenizer("@* Foo Bar Baz *@", - new CSharpSymbol(0, 0, 0, "@", CSharpSymbolType.RazorCommentTransition), - new CSharpSymbol(1, 0, 1, "*", CSharpSymbolType.RazorCommentStar), - new CSharpSymbol(2, 0, 2, " Foo Bar Baz ", CSharpSymbolType.RazorComment), - new CSharpSymbol(15, 0, 15, "*", CSharpSymbolType.RazorCommentStar), - new CSharpSymbol(16, 0, 16, "@", CSharpSymbolType.RazorCommentTransition)); - } - - [Fact] - public void Next_Returns_Comment_Token_For_Entire_Single_Line_Comment() - { - TestTokenizer("// Foo Bar Baz", new CSharpSymbol(0, 0, 0, "// Foo Bar Baz", CSharpSymbolType.Comment)); - } - - [Fact] - public void Single_Line_Comment_Is_Terminated_By_Newline() - { - TestTokenizer("// Foo Bar Baz\na", new CSharpSymbol(0, 0, 0, "// Foo Bar Baz", CSharpSymbolType.Comment), IgnoreRemaining); - } - - [Fact] - public void Multi_Line_Comment_In_Single_Line_Comment_Has_No_Effect() - { - TestTokenizer("// Foo/*Bar*/ Baz\na", new CSharpSymbol(0, 0, 0, "// Foo/*Bar*/ Baz", CSharpSymbolType.Comment), IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Comment_Token_For_Entire_Multi_Line_Comment() - { - TestTokenizer("/* Foo\nBar\nBaz */", new CSharpSymbol(0, 0, 0, "/* Foo\nBar\nBaz */", CSharpSymbolType.Comment)); - } - - [Fact] - public void Multi_Line_Comment_Is_Terminated_By_End_Sequence() - { - TestTokenizer("/* Foo\nBar\nBaz */a", new CSharpSymbol(0, 0, 0, "/* Foo\nBar\nBaz */", CSharpSymbolType.Comment), IgnoreRemaining); - } - - [Fact] - public void Unterminated_Multi_Line_Comment_Captures_To_EOF() - { - TestTokenizer("/* Foo\nBar\nBaz", new CSharpSymbol(0, 0, 0, "/* Foo\nBar\nBaz", CSharpSymbolType.Comment), IgnoreRemaining); - } - - [Fact] - public void Nested_Multi_Line_Comments_Terminated_At_First_End_Sequence() - { - TestTokenizer("/* Foo/*\nBar\nBaz*/ */", new CSharpSymbol(0, 0, 0, "/* Foo/*\nBar\nBaz*/", CSharpSymbolType.Comment), IgnoreRemaining); - } - - [Fact] - public void Nested_Multi_Line_Comments_Terminated_At_Full_End_Sequence() - { - TestTokenizer("/* Foo\nBar\nBaz* */", new CSharpSymbol(0, 0, 0, "/* Foo\nBar\nBaz* */", CSharpSymbolType.Comment), IgnoreRemaining); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerIdentifierTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerIdentifierTest.cs deleted file mode 100644 index f742bc6e9d..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerIdentifierTest.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class CSharpTokenizerIdentifierTest : CSharpTokenizerTestBase - { - [Fact] - public void Simple_Identifier_Is_Recognized() - { - TestTokenizer("foo", new CSharpSymbol(0, 0, 0, "foo", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Starting_With_Underscore_Is_Recognized() - { - TestTokenizer("_foo", new CSharpSymbol(0, 0, 0, "_foo", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Contain_Digits() - { - TestTokenizer("foo4", new CSharpSymbol(0, 0, 0, "foo4", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Start_With_Titlecase_Letter() - { - TestTokenizer("ῼfoo", new CSharpSymbol(0, 0, 0, "ῼfoo", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Start_With_Letter_Modifier() - { - TestTokenizer("ᵊfoo", new CSharpSymbol(0, 0, 0, "ᵊfoo", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Start_With_Other_Letter() - { - TestTokenizer("ƻfoo", new CSharpSymbol(0, 0, 0, "ƻfoo", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Start_With_Number_Letter() - { - TestTokenizer("Ⅽool", new CSharpSymbol(0, 0, 0, "Ⅽool", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Contain_Non_Spacing_Mark() - { - TestTokenizer("foo\u0300", new CSharpSymbol(0, 0, 0, "foo\u0300", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Contain_Spacing_Combining_Mark() - { - TestTokenizer("fooः", new CSharpSymbol(0, 0, 0, "fooः", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Contain_Non_English_Digit() - { - TestTokenizer("foo١", new CSharpSymbol(0, 0, 0, "foo١", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Contain_Connector_Punctuation() - { - TestTokenizer("foo‿bar", new CSharpSymbol(0, 0, 0, "foo‿bar", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Identifier_Can_Contain_Format_Character() - { - TestTokenizer("foo؃bar", new CSharpSymbol(0, 0, 0, "foo؃bar", CSharpSymbolType.Identifier)); - } - - [Fact] - public void Keywords_Are_Recognized_As_Keyword_Tokens() - { - TestKeyword("abstract", CSharpKeyword.Abstract); - TestKeyword("byte", CSharpKeyword.Byte); - TestKeyword("class", CSharpKeyword.Class); - TestKeyword("delegate", CSharpKeyword.Delegate); - TestKeyword("event", CSharpKeyword.Event); - TestKeyword("fixed", CSharpKeyword.Fixed); - TestKeyword("if", CSharpKeyword.If); - TestKeyword("internal", CSharpKeyword.Internal); - TestKeyword("new", CSharpKeyword.New); - TestKeyword("override", CSharpKeyword.Override); - TestKeyword("readonly", CSharpKeyword.Readonly); - TestKeyword("short", CSharpKeyword.Short); - TestKeyword("struct", CSharpKeyword.Struct); - TestKeyword("try", CSharpKeyword.Try); - TestKeyword("unsafe", CSharpKeyword.Unsafe); - TestKeyword("volatile", CSharpKeyword.Volatile); - TestKeyword("as", CSharpKeyword.As); - TestKeyword("do", CSharpKeyword.Do); - TestKeyword("is", CSharpKeyword.Is); - TestKeyword("params", CSharpKeyword.Params); - TestKeyword("ref", CSharpKeyword.Ref); - TestKeyword("switch", CSharpKeyword.Switch); - TestKeyword("ushort", CSharpKeyword.Ushort); - TestKeyword("while", CSharpKeyword.While); - TestKeyword("case", CSharpKeyword.Case); - TestKeyword("const", CSharpKeyword.Const); - TestKeyword("explicit", CSharpKeyword.Explicit); - TestKeyword("float", CSharpKeyword.Float); - TestKeyword("null", CSharpKeyword.Null); - TestKeyword("sizeof", CSharpKeyword.Sizeof); - TestKeyword("typeof", CSharpKeyword.Typeof); - TestKeyword("implicit", CSharpKeyword.Implicit); - TestKeyword("private", CSharpKeyword.Private); - TestKeyword("this", CSharpKeyword.This); - TestKeyword("using", CSharpKeyword.Using); - TestKeyword("extern", CSharpKeyword.Extern); - TestKeyword("return", CSharpKeyword.Return); - TestKeyword("stackalloc", CSharpKeyword.Stackalloc); - TestKeyword("uint", CSharpKeyword.Uint); - TestKeyword("base", CSharpKeyword.Base); - TestKeyword("catch", CSharpKeyword.Catch); - TestKeyword("continue", CSharpKeyword.Continue); - TestKeyword("double", CSharpKeyword.Double); - TestKeyword("for", CSharpKeyword.For); - TestKeyword("in", CSharpKeyword.In); - TestKeyword("lock", CSharpKeyword.Lock); - TestKeyword("object", CSharpKeyword.Object); - TestKeyword("protected", CSharpKeyword.Protected); - TestKeyword("static", CSharpKeyword.Static); - TestKeyword("false", CSharpKeyword.False); - TestKeyword("public", CSharpKeyword.Public); - TestKeyword("sbyte", CSharpKeyword.Sbyte); - TestKeyword("throw", CSharpKeyword.Throw); - TestKeyword("virtual", CSharpKeyword.Virtual); - TestKeyword("decimal", CSharpKeyword.Decimal); - TestKeyword("else", CSharpKeyword.Else); - TestKeyword("operator", CSharpKeyword.Operator); - TestKeyword("string", CSharpKeyword.String); - TestKeyword("ulong", CSharpKeyword.Ulong); - TestKeyword("bool", CSharpKeyword.Bool); - TestKeyword("char", CSharpKeyword.Char); - TestKeyword("default", CSharpKeyword.Default); - TestKeyword("foreach", CSharpKeyword.Foreach); - TestKeyword("long", CSharpKeyword.Long); - TestKeyword("void", CSharpKeyword.Void); - TestKeyword("enum", CSharpKeyword.Enum); - TestKeyword("finally", CSharpKeyword.Finally); - TestKeyword("int", CSharpKeyword.Int); - TestKeyword("out", CSharpKeyword.Out); - TestKeyword("sealed", CSharpKeyword.Sealed); - TestKeyword("true", CSharpKeyword.True); - TestKeyword("goto", CSharpKeyword.Goto); - TestKeyword("unchecked", CSharpKeyword.Unchecked); - TestKeyword("interface", CSharpKeyword.Interface); - TestKeyword("break", CSharpKeyword.Break); - TestKeyword("checked", CSharpKeyword.Checked); - TestKeyword("namespace", CSharpKeyword.Namespace); - TestKeyword("when", CSharpKeyword.When); - } - - private void TestKeyword(string keyword, CSharpKeyword keywordType) - { - TestTokenizer(keyword, new CSharpSymbol(0, 0, 0, keyword, CSharpSymbolType.Keyword) { Keyword = keywordType }); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerLiteralTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerLiteralTest.cs deleted file mode 100644 index 8119a37603..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerLiteralTest.cs +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class CSharpTokenizerLiteralTest : CSharpTokenizerTestBase - { - [Fact] - public void Simple_Integer_Literal_Is_Recognized() - { - TestSingleToken("01189998819991197253", CSharpSymbolType.IntegerLiteral); - } - - [Fact] - public void Integer_Type_Suffix_Is_Recognized() - { - TestSingleToken("42U", CSharpSymbolType.IntegerLiteral); - TestSingleToken("42u", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("42L", CSharpSymbolType.IntegerLiteral); - TestSingleToken("42l", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("42UL", CSharpSymbolType.IntegerLiteral); - TestSingleToken("42Ul", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("42uL", CSharpSymbolType.IntegerLiteral); - TestSingleToken("42ul", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("42LU", CSharpSymbolType.IntegerLiteral); - TestSingleToken("42Lu", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("42lU", CSharpSymbolType.IntegerLiteral); - TestSingleToken("42lu", CSharpSymbolType.IntegerLiteral); - } - - [Fact] - public void Trailing_Letter_Is_Not_Part_Of_Integer_Literal_If_Not_Type_Sufix() - { - TestTokenizer("42a", new CSharpSymbol(0, 0, 0, "42", CSharpSymbolType.IntegerLiteral), IgnoreRemaining); - } - - [Fact] - public void Simple_Hex_Literal_Is_Recognized() - { - TestSingleToken("0x0123456789ABCDEF", CSharpSymbolType.IntegerLiteral); - } - - [Fact] - public void Integer_Type_Suffix_Is_Recognized_In_Hex_Literal() - { - TestSingleToken("0xDEADBEEFU", CSharpSymbolType.IntegerLiteral); - TestSingleToken("0xDEADBEEFu", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("0xDEADBEEFL", CSharpSymbolType.IntegerLiteral); - TestSingleToken("0xDEADBEEFl", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("0xDEADBEEFUL", CSharpSymbolType.IntegerLiteral); - TestSingleToken("0xDEADBEEFUl", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("0xDEADBEEFuL", CSharpSymbolType.IntegerLiteral); - TestSingleToken("0xDEADBEEFul", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("0xDEADBEEFLU", CSharpSymbolType.IntegerLiteral); - TestSingleToken("0xDEADBEEFLu", CSharpSymbolType.IntegerLiteral); - - TestSingleToken("0xDEADBEEFlU", CSharpSymbolType.IntegerLiteral); - TestSingleToken("0xDEADBEEFlu", CSharpSymbolType.IntegerLiteral); - } - - [Fact] - public void Trailing_Letter_Is_Not_Part_Of_Hex_Literal_If_Not_Type_Sufix() - { - TestTokenizer("0xDEADBEEFz", new CSharpSymbol(0, 0, 0, "0xDEADBEEF", CSharpSymbolType.IntegerLiteral), IgnoreRemaining); - } - - [Fact] - public void Dot_Followed_By_Non_Digit_Is_Not_Part_Of_Real_Literal() - { - TestTokenizer("3.a", new CSharpSymbol(0, 0, 0, "3", CSharpSymbolType.IntegerLiteral), IgnoreRemaining); - } - - [Fact] - public void Simple_Real_Literal_Is_Recognized() - { - TestTokenizer("3.14159", new CSharpSymbol(0, 0, 0, "3.14159", CSharpSymbolType.RealLiteral)); - } - - [Fact] - public void Real_Literal_Between_Zero_And_One_Is_Recognized() - { - TestTokenizer(".14159", new CSharpSymbol(0, 0, 0, ".14159", CSharpSymbolType.RealLiteral)); - } - - [Fact] - public void Integer_With_Real_Type_Suffix_Is_Recognized() - { - TestSingleToken("42F", CSharpSymbolType.RealLiteral); - TestSingleToken("42f", CSharpSymbolType.RealLiteral); - TestSingleToken("42D", CSharpSymbolType.RealLiteral); - TestSingleToken("42d", CSharpSymbolType.RealLiteral); - TestSingleToken("42M", CSharpSymbolType.RealLiteral); - TestSingleToken("42m", CSharpSymbolType.RealLiteral); - } - - [Fact] - public void Integer_With_Exponent_Is_Recognized() - { - TestSingleToken("1e10", CSharpSymbolType.RealLiteral); - TestSingleToken("1E10", CSharpSymbolType.RealLiteral); - TestSingleToken("1e+10", CSharpSymbolType.RealLiteral); - TestSingleToken("1E+10", CSharpSymbolType.RealLiteral); - TestSingleToken("1e-10", CSharpSymbolType.RealLiteral); - TestSingleToken("1E-10", CSharpSymbolType.RealLiteral); - } - - [Fact] - public void Real_Number_With_Type_Suffix_Is_Recognized() - { - TestSingleToken("3.14F", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14f", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14D", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14d", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14M", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14m", CSharpSymbolType.RealLiteral); - } - - [Fact] - public void Real_Number_With_Exponent_Is_Recognized() - { - TestSingleToken("3.14E10", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14e10", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14E+10", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14e+10", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14E-10", CSharpSymbolType.RealLiteral); - TestSingleToken("3.14e-10", CSharpSymbolType.RealLiteral); - } - - [Fact] - public void Real_Number_With_Exponent_And_Type_Suffix_Is_Recognized() - { - TestSingleToken("3.14E+10F", CSharpSymbolType.RealLiteral); - } - - [Fact] - public void Single_Character_Literal_Is_Recognized() - { - TestSingleToken("'f'", CSharpSymbolType.CharacterLiteral); - } - - [Fact] - public void Multi_Character_Literal_Is_Recognized() - { - TestSingleToken("'foo'", CSharpSymbolType.CharacterLiteral); - } - - [Fact] - public void Character_Literal_Is_Terminated_By_EOF_If_Unterminated() - { - TestSingleToken("'foo bar", CSharpSymbolType.CharacterLiteral); - } - - [Fact] - public void Character_Literal_Not_Terminated_By_Escaped_Quote() - { - TestSingleToken("'foo\\'bar'", CSharpSymbolType.CharacterLiteral); - } - - [Fact] - public void Character_Literal_Is_Terminated_By_EOL_If_Unterminated() - { - TestTokenizer("'foo\n", new CSharpSymbol(0, 0, 0, "'foo", CSharpSymbolType.CharacterLiteral), IgnoreRemaining); - } - - [Fact] - public void Character_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash() - { - TestTokenizer("'foo\\\n", new CSharpSymbol(0, 0, 0, "'foo\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining); - } - - [Fact] - public void Character_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff() - { - TestTokenizer("'foo\\\nflarg", new CSharpSymbol(0, 0, 0, "'foo\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining); - } - - [Fact] - public void Character_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash() - { - TestTokenizer("'foo\\" + Environment.NewLine, new CSharpSymbol(0, 0, 0, "'foo\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining); - } - - [Fact] - public void Character_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff() - { - TestTokenizer($"'foo\\{Environment.NewLine}flarg", new CSharpSymbol(0, 0, 0, "'foo\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining); - } - - [Fact] - public void Character_Literal_Allows_Escaped_Escape() - { - TestTokenizer("'foo\\\\'blah", new CSharpSymbol(0, 0, 0, "'foo\\\\'", CSharpSymbolType.CharacterLiteral), IgnoreRemaining); - } - - [Fact] - public void String_Literal_Is_Recognized() - { - TestSingleToken("\"foo\"", CSharpSymbolType.StringLiteral); - } - - [Fact] - public void String_Literal_Is_Terminated_By_EOF_If_Unterminated() - { - TestSingleToken("\"foo bar", CSharpSymbolType.StringLiteral); - } - - [Fact] - public void String_Literal_Not_Terminated_By_Escaped_Quote() - { - TestSingleToken("\"foo\\\"bar\"", CSharpSymbolType.StringLiteral); - } - - [Fact] - public void String_Literal_Is_Terminated_By_EOL_If_Unterminated() - { - TestTokenizer("\"foo\n", new CSharpSymbol(0, 0, 0, "\"foo", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void String_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash() - { - TestTokenizer("\"foo\\\n", new CSharpSymbol(0, 0, 0, "\"foo\\", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void String_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff() - { - TestTokenizer("\"foo\\\nflarg", new CSharpSymbol(0, 0, 0, "\"foo\\", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void String_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash() - { - TestTokenizer("\"foo\\" + Environment.NewLine, new CSharpSymbol(0, 0, 0, "\"foo\\", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void String_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff() - { - TestTokenizer($"\"foo\\{Environment.NewLine}flarg", new CSharpSymbol(0, 0, 0, "\"foo\\", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void String_Literal_Allows_Escaped_Escape() - { - TestTokenizer("\"foo\\\\\"blah", new CSharpSymbol(0, 0, 0, "\"foo\\\\\"", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void Verbatim_String_Literal_Can_Contain_Newlines() - { - TestSingleToken("@\"foo\nbar\nbaz\"", CSharpSymbolType.StringLiteral); - } - - [Fact] - public void Verbatim_String_Literal_Not_Terminated_By_Escaped_Double_Quote() - { - TestSingleToken("@\"foo\"\"bar\"", CSharpSymbolType.StringLiteral); - } - - [Fact] - public void Verbatim_String_Literal_Is_Terminated_By_Slash_Double_Quote() - { - TestTokenizer("@\"foo\\\"bar\"", new CSharpSymbol(0, 0, 0, "@\"foo\\\"", CSharpSymbolType.StringLiteral), IgnoreRemaining); - } - - [Fact] - public void Verbatim_String_Literal_Is_Terminated_By_EOF() - { - TestSingleToken("@\"foo", CSharpSymbolType.StringLiteral); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerOperatorsTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerOperatorsTest.cs deleted file mode 100644 index a0eade3635..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerOperatorsTest.cs +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class CSharpTokenizerOperatorsTest : CSharpTokenizerTestBase - { - [Fact] - public void LeftBrace_Is_Recognized() - { - TestSingleToken("{", CSharpSymbolType.LeftBrace); - } - - [Fact] - public void Plus_Is_Recognized() - { - TestSingleToken("+", CSharpSymbolType.Plus); - } - - [Fact] - public void Assign_Is_Recognized() - { - TestSingleToken("=", CSharpSymbolType.Assign); - } - - [Fact] - public void Arrow_Is_Recognized() - { - TestSingleToken("->", CSharpSymbolType.Arrow); - } - - [Fact] - public void AndAssign_Is_Recognized() - { - TestSingleToken("&=", CSharpSymbolType.AndAssign); - } - - [Fact] - public void RightBrace_Is_Recognized() - { - TestSingleToken("}", CSharpSymbolType.RightBrace); - } - - [Fact] - public void Minus_Is_Recognized() - { - TestSingleToken("-", CSharpSymbolType.Minus); - } - - [Fact] - public void LessThan_Is_Recognized() - { - TestSingleToken("<", CSharpSymbolType.LessThan); - } - - [Fact] - public void Equals_Is_Recognized() - { - TestSingleToken("==", CSharpSymbolType.Equals); - } - - [Fact] - public void OrAssign_Is_Recognized() - { - TestSingleToken("|=", CSharpSymbolType.OrAssign); - } - - [Fact] - public void LeftBracket_Is_Recognized() - { - TestSingleToken("[", CSharpSymbolType.LeftBracket); - } - - [Fact] - public void Star_Is_Recognized() - { - TestSingleToken("*", CSharpSymbolType.Star); - } - - [Fact] - public void GreaterThan_Is_Recognized() - { - TestSingleToken(">", CSharpSymbolType.GreaterThan); - } - - [Fact] - public void NotEqual_Is_Recognized() - { - TestSingleToken("!=", CSharpSymbolType.NotEqual); - } - - [Fact] - public void XorAssign_Is_Recognized() - { - TestSingleToken("^=", CSharpSymbolType.XorAssign); - } - - [Fact] - public void RightBracket_Is_Recognized() - { - TestSingleToken("]", CSharpSymbolType.RightBracket); - } - - [Fact] - public void Slash_Is_Recognized() - { - TestSingleToken("/", CSharpSymbolType.Slash); - } - - [Fact] - public void QuestionMark_Is_Recognized() - { - TestSingleToken("?", CSharpSymbolType.QuestionMark); - } - - [Fact] - public void LessThanEqual_Is_Recognized() - { - TestSingleToken("<=", CSharpSymbolType.LessThanEqual); - } - - [Fact] - public void LeftShift_Is_Not_Specially_Recognized() - { - TestTokenizer("<<", - new CSharpSymbol(0, 0, 0, "<", CSharpSymbolType.LessThan), - new CSharpSymbol(1, 0, 1, "<", CSharpSymbolType.LessThan)); - } - - [Fact] - public void LeftParen_Is_Recognized() - { - TestSingleToken("(", CSharpSymbolType.LeftParenthesis); - } - - [Fact] - public void Modulo_Is_Recognized() - { - TestSingleToken("%", CSharpSymbolType.Modulo); - } - - [Fact] - public void NullCoalesce_Is_Recognized() - { - TestSingleToken("??", CSharpSymbolType.NullCoalesce); - } - - [Fact] - public void GreaterThanEqual_Is_Recognized() - { - TestSingleToken(">=", CSharpSymbolType.GreaterThanEqual); - } - - [Fact] - public void EqualGreaterThan_Is_Recognized() - { - TestSingleToken("=>", CSharpSymbolType.GreaterThanEqual); - } - - [Fact] - public void RightParen_Is_Recognized() - { - TestSingleToken(")", CSharpSymbolType.RightParenthesis); - } - - [Fact] - public void And_Is_Recognized() - { - TestSingleToken("&", CSharpSymbolType.And); - } - - [Fact] - public void DoubleColon_Is_Recognized() - { - TestSingleToken("::", CSharpSymbolType.DoubleColon); - } - - [Fact] - public void PlusAssign_Is_Recognized() - { - TestSingleToken("+=", CSharpSymbolType.PlusAssign); - } - - [Fact] - public void Semicolon_Is_Recognized() - { - TestSingleToken(";", CSharpSymbolType.Semicolon); - } - - [Fact] - public void Tilde_Is_Recognized() - { - TestSingleToken("~", CSharpSymbolType.Tilde); - } - - [Fact] - public void DoubleOr_Is_Recognized() - { - TestSingleToken("||", CSharpSymbolType.DoubleOr); - } - - [Fact] - public void ModuloAssign_Is_Recognized() - { - TestSingleToken("%=", CSharpSymbolType.ModuloAssign); - } - - [Fact] - public void Colon_Is_Recognized() - { - TestSingleToken(":", CSharpSymbolType.Colon); - } - - [Fact] - public void Not_Is_Recognized() - { - TestSingleToken("!", CSharpSymbolType.Not); - } - - [Fact] - public void DoubleAnd_Is_Recognized() - { - TestSingleToken("&&", CSharpSymbolType.DoubleAnd); - } - - [Fact] - public void DivideAssign_Is_Recognized() - { - TestSingleToken("/=", CSharpSymbolType.DivideAssign); - } - - [Fact] - public void Comma_Is_Recognized() - { - TestSingleToken(",", CSharpSymbolType.Comma); - } - - [Fact] - public void Xor_Is_Recognized() - { - TestSingleToken("^", CSharpSymbolType.Xor); - } - - [Fact] - public void Decrement_Is_Recognized() - { - TestSingleToken("--", CSharpSymbolType.Decrement); - } - - [Fact] - public void MultiplyAssign_Is_Recognized() - { - TestSingleToken("*=", CSharpSymbolType.MultiplyAssign); - } - - [Fact] - public void Dot_Is_Recognized() - { - TestSingleToken(".", CSharpSymbolType.Dot); - } - - [Fact] - public void Or_Is_Recognized() - { - TestSingleToken("|", CSharpSymbolType.Or); - } - - [Fact] - public void Increment_Is_Recognized() - { - TestSingleToken("++", CSharpSymbolType.Increment); - } - - [Fact] - public void MinusAssign_Is_Recognized() - { - TestSingleToken("-=", CSharpSymbolType.MinusAssign); - } - - [Fact] - public void RightShift_Is_Not_Specially_Recognized() - { - TestTokenizer(">>", - new CSharpSymbol(0, 0, 0, ">", CSharpSymbolType.GreaterThan), - new CSharpSymbol(1, 0, 1, ">", CSharpSymbolType.GreaterThan)); - } - - [Fact] - public void Hash_Is_Recognized() - { - TestSingleToken("#", CSharpSymbolType.Hash); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTest.cs deleted file mode 100644 index 67e035902c..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTest.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class CSharpTokenizerTest : CSharpTokenizerTestBase - { - [Fact] - public void Next_Returns_Null_When_EOF_Reached() - { - TestTokenizer(""); - } - - [Fact] - public void Next_Returns_Newline_Token_For_Single_CR() - { - TestTokenizer("\r\ra", - new CSharpSymbol(0, 0, 0, "\r", CSharpSymbolType.NewLine), - new CSharpSymbol(1, 1, 0, "\r", CSharpSymbolType.NewLine), - IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Newline_Token_For_Single_LF() - { - TestTokenizer("\n\na", - new CSharpSymbol(0, 0, 0, "\n", CSharpSymbolType.NewLine), - new CSharpSymbol(1, 1, 0, "\n", CSharpSymbolType.NewLine), - IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Newline_Token_For_Single_NEL() - { - // NEL: Unicode "Next Line" U+0085 - TestTokenizer("\u0085\u0085a", - new CSharpSymbol(0, 0, 0, "\u0085", CSharpSymbolType.NewLine), - new CSharpSymbol(1, 1, 0, "\u0085", CSharpSymbolType.NewLine), - IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Newline_Token_For_Single_Line_Separator() - { - // Unicode "Line Separator" U+2028 - TestTokenizer("\u2028\u2028a", - new CSharpSymbol(0, 0, 0, "\u2028", CSharpSymbolType.NewLine), - new CSharpSymbol(1, 1, 0, "\u2028", CSharpSymbolType.NewLine), - IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Newline_Token_For_Single_Paragraph_Separator() - { - // Unicode "Paragraph Separator" U+2029 - TestTokenizer("\u2029\u2029a", - new CSharpSymbol(0, 0, 0, "\u2029", CSharpSymbolType.NewLine), - new CSharpSymbol(1, 1, 0, "\u2029", CSharpSymbolType.NewLine), - IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Single_Newline_Token_For_CRLF() - { - TestTokenizer("\r\n\r\na", - new CSharpSymbol(0, 0, 0, "\r\n", CSharpSymbolType.NewLine), - new CSharpSymbol(2, 1, 0, "\r\n", CSharpSymbolType.NewLine), - IgnoreRemaining); - } - - [Fact] - public void Next_Returns_Token_For_Whitespace_Characters() - { - TestTokenizer(" \f\t\u000B \n ", - new CSharpSymbol(0, 0, 0, " \f\t\u000B ", CSharpSymbolType.WhiteSpace), - new CSharpSymbol(5, 0, 5, "\n", CSharpSymbolType.NewLine), - new CSharpSymbol(6, 1, 0, " ", CSharpSymbolType.WhiteSpace)); - } - - [Fact] - public void Transition_Is_Recognized() - { - TestSingleToken("@", CSharpSymbolType.Transition); - } - - [Fact] - public void Transition_Is_Recognized_As_SingleCharacter() - { - TestTokenizer("@(", - new CSharpSymbol(0, 0, 0, "@", CSharpSymbolType.Transition), - new CSharpSymbol(1, 0, 1, "(", CSharpSymbolType.LeftParenthesis)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTestBase.cs deleted file mode 100644 index a91daa72e7..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/CSharpTokenizerTestBase.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; - -namespace Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal -{ - public abstract class CSharpTokenizerTestBase : TokenizerTestBase - { - private static CSharpSymbol _ignoreRemaining = new CSharpSymbol(0, 0, 0, string.Empty, CSharpSymbolType.Unknown); - - protected override CSharpSymbol IgnoreRemaining - { - get { return _ignoreRemaining; } - } - - protected override Tokenizer CreateTokenizer(ITextDocument source) - { - return new CSharpTokenizer(source); - } - - protected void TestSingleToken(string text, CSharpSymbolType expectedSymbolType) - { - TestTokenizer(text, new CSharpSymbol(0, 0, 0, text, expectedSymbolType)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTest.cs deleted file mode 100644 index f36a82c9cb..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTest.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class HtmlTokenizerTest : HtmlTokenizerTestBase - { - [Fact] - public void Next_Returns_Null_When_EOF_Reached() - { - TestTokenizer(""); - } - - [Fact] - public void Text_Is_Recognized() - { - TestTokenizer("foo-9309&smlkmb;::-3029022,.sdkq92384", - new HtmlSymbol(0, 0, 0, "foo-9309&smlkmb;::-3029022,.sdkq92384", HtmlSymbolType.Text)); - } - - [Fact] - public void Whitespace_Is_Recognized() - { - TestTokenizer(" \t\f ", - new HtmlSymbol(0, 0, 0, " \t\f ", HtmlSymbolType.WhiteSpace)); - } - - [Fact] - public void Newline_Is_Recognized() - { - TestTokenizer("\n\r\r\n", - new HtmlSymbol(0, 0, 0, "\n", HtmlSymbolType.NewLine), - new HtmlSymbol(1, 1, 0, "\r", HtmlSymbolType.NewLine), - new HtmlSymbol(2, 2, 0, "\r\n", HtmlSymbolType.NewLine)); - } - - [Fact] - public void Transition_Is_Not_Recognized_Mid_Text_If_Surrounded_By_Alphanumeric_Characters() - { - TestSingleToken("foo@bar", HtmlSymbolType.Text); - } - - [Fact] - public void OpenAngle_Is_Recognized() - { - TestSingleToken("<", HtmlSymbolType.OpenAngle); - } - - [Fact] - public void Bang_Is_Recognized() - { - TestSingleToken("!", HtmlSymbolType.Bang); - } - - [Fact] - public void Solidus_Is_Recognized() - { - TestSingleToken("/", HtmlSymbolType.ForwardSlash); - } - - [Fact] - public void QuestionMark_Is_Recognized() - { - TestSingleToken("?", HtmlSymbolType.QuestionMark); - } - - [Fact] - public void LeftBracket_Is_Recognized() - { - TestSingleToken("[", HtmlSymbolType.LeftBracket); - } - - [Fact] - public void CloseAngle_Is_Recognized() - { - TestSingleToken(">", HtmlSymbolType.CloseAngle); - } - - [Fact] - public void RightBracket_Is_Recognized() - { - TestSingleToken("]", HtmlSymbolType.RightBracket); - } - - [Fact] - public void Equals_Is_Recognized() - { - TestSingleToken("=", HtmlSymbolType.Equals); - } - - [Fact] - public void DoubleQuote_Is_Recognized() - { - TestSingleToken("\"", HtmlSymbolType.DoubleQuote); - } - - [Fact] - public void SingleQuote_Is_Recognized() - { - TestSingleToken("'", HtmlSymbolType.SingleQuote); - } - - [Fact] - public void Transition_Is_Recognized() - { - TestSingleToken("@", HtmlSymbolType.Transition); - } - - [Fact] - public void DoubleHyphen_Is_Recognized() - { - TestSingleToken("--", HtmlSymbolType.DoubleHyphen); - } - - [Fact] - public void SingleHyphen_Is_Not_Recognized() - { - TestSingleToken("-", HtmlSymbolType.Text); - } - - [Fact] - public void SingleHyphen_Mid_Text_Is_Not_Recognized_As_Separate_Token() - { - TestSingleToken("foo-bar", HtmlSymbolType.Text); - } - - [Fact] - public void Next_Ignores_Star_At_EOF_In_RazorComment() - { - TestTokenizer("@* Foo * Bar * Baz *", - new HtmlSymbol(0, 0, 0, "@", HtmlSymbolType.RazorCommentTransition), - new HtmlSymbol(1, 0, 1, "*", HtmlSymbolType.RazorCommentStar), - new HtmlSymbol(2, 0, 2, " Foo * Bar * Baz *", HtmlSymbolType.RazorComment)); - } - - [Fact] - public void Next_Ignores_Star_Without_Trailing_At() - { - TestTokenizer("@* Foo * Bar * Baz *@", - new HtmlSymbol(0, 0, 0, "@", HtmlSymbolType.RazorCommentTransition), - new HtmlSymbol(1, 0, 1, "*", HtmlSymbolType.RazorCommentStar), - new HtmlSymbol(2, 0, 2, " Foo * Bar * Baz ", HtmlSymbolType.RazorComment), - new HtmlSymbol(19, 0, 19, "*", HtmlSymbolType.RazorCommentStar), - new HtmlSymbol(20, 0, 20, "@", HtmlSymbolType.RazorCommentTransition)); - } - - [Fact] - public void Next_Returns_RazorComment_Token_For_Entire_Razor_Comment() - { - TestTokenizer("@* Foo Bar Baz *@", - new HtmlSymbol(0, 0, 0, "@", HtmlSymbolType.RazorCommentTransition), - new HtmlSymbol(1, 0, 1, "*", HtmlSymbolType.RazorCommentStar), - new HtmlSymbol(2, 0, 2, " Foo Bar Baz ", HtmlSymbolType.RazorComment), - new HtmlSymbol(15, 0, 15, "*", HtmlSymbolType.RazorCommentStar), - new HtmlSymbol(16, 0, 16, "@", HtmlSymbolType.RazorCommentTransition)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTestBase.cs deleted file mode 100644 index 7795a3d55a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/HtmlTokenizerTestBase.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer; -using Microsoft.AspNetCore.Razor.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; - -namespace Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal -{ - public abstract class HtmlTokenizerTestBase : TokenizerTestBase - { - private static HtmlSymbol _ignoreRemaining = new HtmlSymbol(0, 0, 0, string.Empty, HtmlSymbolType.Unknown); - - protected override HtmlSymbol IgnoreRemaining - { - get { return _ignoreRemaining; } - } - - protected override Tokenizer CreateTokenizer(ITextDocument source) - { - return new HtmlTokenizer(source); - } - - protected void TestSingleToken(string text, HtmlSymbolType expectedSymbolType) - { - TestTokenizer(text, new HtmlSymbol(0, 0, 0, text, expectedSymbolType)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/TokenizerLookaheadTest.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/TokenizerLookaheadTest.cs deleted file mode 100644 index c0f006ab2a..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/Internal/TokenizerLookaheadTest.cs +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using Microsoft.AspNetCore.Razor.Test.Tokenizer.Internal; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols.Internal; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Tokenizer.Internal -{ - public class TokenizerLookaheadTest : HtmlTokenizerTestBase - { - [Fact] - public void Lookahead_MaintainsExistingBufferWhenRejected() - { - // Arrange - var tokenizer = new ExposedTokenizer("01234"); - tokenizer.Buffer.Append("pre-existing values"); - - // Act - var result = tokenizer.Lookahead("0x", takeIfMatch: true, caseSensitive: true); - - // Assert - Assert.False(result); - Assert.Equal("pre-existing values", tokenizer.Buffer.ToString(), StringComparer.Ordinal); - } - - [Fact] - public void Lookahead_AddsToExistingBufferWhenSuccessfulAndTakeIfMatchIsTrue() - { - // Arrange - var tokenizer = new ExposedTokenizer("0x1234"); - tokenizer.Buffer.Append("pre-existing values"); - - // Act - var result = tokenizer.Lookahead("0x", takeIfMatch: true, caseSensitive: true); - - // Assert - Assert.True(result); - Assert.Equal("pre-existing values0x", tokenizer.Buffer.ToString(), StringComparer.Ordinal); - } - - [Fact] - public void Lookahead_MaintainsExistingBufferWhenSuccessfulAndTakeIfMatchIsFalse() - { - // Arrange - var tokenizer = new ExposedTokenizer("0x1234"); - tokenizer.Buffer.Append("pre-existing values"); - - // Act - var result = tokenizer.Lookahead("0x", takeIfMatch: false, caseSensitive: true); - - // Assert - Assert.True(result); - Assert.Equal("pre-existing values", tokenizer.Buffer.ToString(), StringComparer.Ordinal); - } - - [Fact] - public void After_Cancelling_Lookahead_Tokenizer_Returns_Same_Tokens_As_It_Did_Before_Lookahead() - { - var tokenizer = new HtmlTokenizer(new SeekableTextReader(new StringReader(""))); - using (tokenizer.Source.BeginLookahead()) - { - Assert.Equal(new HtmlSymbol(0, 0, 0, "<", HtmlSymbolType.OpenAngle), tokenizer.NextSymbol()); - Assert.Equal(new HtmlSymbol(1, 0, 1, "foo", HtmlSymbolType.Text), tokenizer.NextSymbol()); - Assert.Equal(new HtmlSymbol(4, 0, 4, ">", HtmlSymbolType.CloseAngle), tokenizer.NextSymbol()); - } - Assert.Equal(new HtmlSymbol(0, 0, 0, "<", HtmlSymbolType.OpenAngle), tokenizer.NextSymbol()); - Assert.Equal(new HtmlSymbol(1, 0, 1, "foo", HtmlSymbolType.Text), tokenizer.NextSymbol()); - Assert.Equal(new HtmlSymbol(4, 0, 4, ">", HtmlSymbolType.CloseAngle), tokenizer.NextSymbol()); - } - - [Fact] - public void After_Accepting_Lookahead_Tokenizer_Returns_Next_Token() - { - var tokenizer = new HtmlTokenizer(new SeekableTextReader(new StringReader(""))); - using (var lookahead = tokenizer.Source.BeginLookahead()) - { - Assert.Equal(new HtmlSymbol(0, 0, 0, "<", HtmlSymbolType.OpenAngle), tokenizer.NextSymbol()); - Assert.Equal(new HtmlSymbol(1, 0, 1, "foo", HtmlSymbolType.Text), tokenizer.NextSymbol()); - lookahead.Accept(); - } - Assert.Equal(new HtmlSymbol(4, 0, 4, ">", HtmlSymbolType.CloseAngle), tokenizer.NextSymbol()); - } - - private class ExposedTokenizer : Tokenizer - { - public ExposedTokenizer(string input) - : base(new SeekableTextReader(new StringReader(input))) - { - } - - public new StringBuilder Buffer - { - get - { - return base.Buffer; - } - } - - public override CSharpSymbolType RazorCommentStarType - { - get - { - throw new NotImplementedException(); - } - } - - public override CSharpSymbolType RazorCommentTransitionType - { - get - { - throw new NotImplementedException(); - } - } - - public override CSharpSymbolType RazorCommentType - { - get - { - throw new NotImplementedException(); - } - } - - protected override int StartState - { - get - { - throw new NotImplementedException(); - } - } - - protected override CSharpSymbol CreateSymbol( - SourceLocation start, - string content, - CSharpSymbolType type, - IReadOnlyList errors) - { - throw new NotImplementedException(); - } - - protected override StateResult Dispatch() - { - throw new NotImplementedException(); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/TokenizerTestBase.cs b/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/TokenizerTestBase.cs deleted file mode 100644 index fd7165700b..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Tokenizer/TokenizerTestBase.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.IO; -using System.Text; -using Microsoft.AspNetCore.Razor.Text; -using Microsoft.AspNetCore.Razor.Tokenizer; -using Microsoft.AspNetCore.Razor.Tokenizer.Symbols; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.Tokenizer -{ - public abstract class TokenizerTestBase - where TSymbolType : struct - where TSymbol : SymbolBase - { - protected abstract TSymbol IgnoreRemaining { get; } - protected abstract Tokenizer CreateTokenizer(ITextDocument source); - - protected void TestTokenizer(string input, params TSymbol[] expectedSymbols) - { - // Arrange - var success = true; - var output = new StringBuilder(); - using (StringReader reader = new StringReader(input)) - { - using (SeekableTextReader source = new SeekableTextReader(reader)) - { - Tokenizer tokenizer = CreateTokenizer(source); - var counter = 0; - TSymbol current = null; - while ((current = tokenizer.NextSymbol()) != null) - { - if (counter >= expectedSymbols.Length) - { - output.AppendLine(string.Format("F: Expected: << Nothing >>; Actual: {0}", current)); - success = false; - } - else if (ReferenceEquals(expectedSymbols[counter], IgnoreRemaining)) - { - output.AppendLine(string.Format("P: Ignored {0}", current)); - } - else - { - if (!Equals(expectedSymbols[counter], current)) - { - output.AppendLine(string.Format("F: Expected: {0}; Actual: {1}", expectedSymbols[counter], current)); - success = false; - } - else - { - output.AppendLine(string.Format("P: Expected: {0}", expectedSymbols[counter])); - } - counter++; - } - } - if (counter < expectedSymbols.Length && !ReferenceEquals(expectedSymbols[counter], IgnoreRemaining)) - { - success = false; - for (; counter < expectedSymbols.Length; counter++) - { - output.AppendLine(string.Format("F: Expected: {0}; Actual: << None >>", expectedSymbols[counter])); - } - } - } - } - Assert.True(success, Environment.NewLine + output.ToString()); - WriteTraceLine(output.Replace("{", "{{").Replace("}", "}}").ToString()); - } - - [Conditional("PARSER_TRACE")] - private static void WriteTraceLine(string format, params object[] args) - { - Trace.WriteLine(string.Format(format, args)); - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Utils/BaselineWriter.cs b/test/Microsoft.AspNetCore.Razor.Test/Utils/BaselineWriter.cs deleted file mode 100644 index 189cb82ba6..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Utils/BaselineWriter.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Diagnostics; -using System.IO; - -namespace Microsoft.AspNetCore.Razor.Test.Utils -{ - public static class BaselineWriter - { - private static object baselineLock = new object(); - - [Conditional("GENERATE_BASELINES")] - public static void WriteBaseline(string baselineFile, string output) - { - var root = RecursiveFind("Razor.sln", Path.GetFullPath(".")); - var baselinePath = Path.Combine(root, baselineFile); - - // Serialize writes to minimize contention for file handles and directory access. - lock (baselineLock) - { - // Update baseline - using (var stream = File.Open(baselinePath, FileMode.Create, FileAccess.Write)) - { - using (var writer = new StreamWriter(stream)) - { - writer.Write(output); - } - } - } - } - - private static string RecursiveFind(string path, string start) - { - var test = Path.Combine(start, path); - if (File.Exists(test)) - { - return start; - } - else - { - return RecursiveFind(path, new DirectoryInfo(start).Parent.FullName); - } - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Utils/ExceptionHelpers.cs b/test/Microsoft.AspNetCore.Razor.Test/Utils/ExceptionHelpers.cs deleted file mode 100644 index ed1f35a61f..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Utils/ExceptionHelpers.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.Utils -{ - public static class ExceptionHelpers - { - public static void ValidateArgumentException(string parameterName, string expectedMessage, ArgumentException exception) - { - Assert.Equal(string.Format("{0}{1}Parameter name: {2}", expectedMessage, Environment.NewLine, parameterName), exception.Message); - } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNetCore.Razor.Test/Utils/MiscUtils.cs b/test/Microsoft.AspNetCore.Razor.Test/Utils/MiscUtils.cs deleted file mode 100644 index 73f3b87ecd..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Utils/MiscUtils.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -#if DEBUG -using System.Diagnostics; -using System.Threading; -#endif -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.Utils -{ - class MiscUtils - { - public const int TimeoutInSeconds = 1; - - public static void DoWithTimeoutIfNotDebugging(Func withTimeout) - { -#if DEBUG - if (Debugger.IsAttached) - { - withTimeout(Timeout.Infinite); - } - else - { -#endif - Assert.True(withTimeout((int)TimeSpan.FromSeconds(TimeoutInSeconds).TotalMilliseconds), "Timeout expired!"); -#if DEBUG - } -#endif - } - } -} diff --git a/test/Microsoft.AspNetCore.Razor.Test/Utils/TestFile.cs b/test/Microsoft.AspNetCore.Razor.Test/Utils/TestFile.cs deleted file mode 100644 index 9a5dee760e..0000000000 --- a/test/Microsoft.AspNetCore.Razor.Test/Utils/TestFile.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Reflection; -using Xunit; - -namespace Microsoft.AspNetCore.Razor.Test.Utils -{ - public class TestFile - { - public TestFile(string resourceName, Assembly assembly) - { - Assembly = assembly; - ResourceName = Assembly.GetName().Name + "." + resourceName.Replace('/', '.'); - } - - public Assembly Assembly { get; } - - public string ResourceName { get; } - - public static TestFile Create(string localResourceName) - { - return new TestFile(localResourceName, typeof(TestFile).GetTypeInfo().Assembly); - } - - public Stream OpenRead() - { - var stream = Assembly.GetManifestResourceStream(ResourceName); - if (stream == null) - { - Assert.True(false, string.Format("Manifest resource: {0} not found", ResourceName)); - } - - return stream; - } - - public bool Exists() - { - var resourceNames = Assembly.GetManifestResourceNames(); - foreach (var resourceName in resourceNames) - { - // Resource names are case-sensitive. - if (string.Equals(ResourceName, resourceName, StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } - - public byte[] ReadAllBytes() - { - using (var stream = OpenRead()) - { - var buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); - - return buffer; - } - } - - public string ReadAllText() - { - using (var reader = new StreamReader(OpenRead())) - { - // The .Replace() calls normalize line endings, in case you get \n instead of \r\n - // since all the unit tests rely on the assumption that the files will have \r\n endings. - return reader.ReadToEnd().Replace("\r", "").Replace("\n", "\r\n"); - } - } - - /// - /// Saves the file to the specified path. - /// - public void Save(string filePath) - { - var directory = Path.GetDirectoryName(filePath); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - using (var outStream = File.Create(filePath)) - { - using (var inStream = OpenRead()) - { - inStream.CopyTo(outStream); - } - } - } - } -}