private void EnsureValidPageDirective(RazorCodeDocument codeDocument, PageDirective pageDirective) { Debug.Assert(pageDirective != null); if (pageDirective.DirectiveNode.IsImported()) { pageDirective.DirectiveNode.Diagnostics.Add( RazorExtensionsDiagnosticFactory.CreatePageDirective_CannotBeImported(pageDirective.DirectiveNode.Source.Value)); } else { // The document contains a page directive and it is not imported. // We now want to make sure this page directive exists at the top of the file. // We are going to do that by re-parsing the document until the very first line that is not Razor comment // or whitespace. We then make sure the page directive still exists in the re-parsed IR tree. var leadingDirectiveCodeDocument = RazorCodeDocument.Create(codeDocument.Source); LeadingDirectiveParsingEngine.Engine.Process(leadingDirectiveCodeDocument); var leadingDirectiveDocumentNode = leadingDirectiveCodeDocument.GetDocumentIntermediateNode(); if (!PageDirective.TryGetPageDirective(leadingDirectiveDocumentNode, out var _)) { // The page directive is not the leading directive. Add an error. pageDirective.DirectiveNode.Diagnostics.Add( RazorExtensionsDiagnosticFactory.CreatePageDirective_MustExistAtTheTopOfFile(pageDirective.DirectiveNode.Source.Value)); } } }
public void RazorPageDocumentClassifierPass_LogsErrorForImportedPageDirectives() { // Arrange var sourceSpan = new SourceSpan("import.cshtml", 0, 0, 0, 5); var expectedDiagnostic = RazorExtensionsDiagnosticFactory.CreatePageDirective_CannotBeImported(sourceSpan); var importDocument = RazorSourceDocument.Create("@page", "import.cshtml"); var sourceDocument = RazorSourceDocument.Create("<p>Hello World</p>", "main.cshtml"); var codeDocument = RazorCodeDocument.Create(sourceDocument, new[] { importDocument }); var engine = CreateRuntimeEngine(); var irDocument = CreateIRDocument(engine, codeDocument); var pass = new RazorPageDocumentClassifierPass { Engine = engine }; // Act pass.Execute(codeDocument, irDocument); // Assert var pageDirectives = irDocument.FindDirectiveReferences(PageDirective.Directive); var directive = Assert.Single(pageDirectives); var diagnostic = Assert.Single(directive.Node.Diagnostics); Assert.Equal(expectedDiagnostic, diagnostic); }
private void EnsureValidPageDirective(RazorCodeDocument codeDocument) { var document = codeDocument.GetDocumentIntermediateNode(); PageDirective.TryGetPageDirective(document, out var pageDirective); Debug.Assert(pageDirective != null); if (pageDirective.DirectiveNode.IsImported()) { pageDirective.DirectiveNode.Diagnostics.Add( RazorExtensionsDiagnosticFactory.CreatePageDirective_CannotBeImported(pageDirective.DirectiveNode.Source.Value)); } }