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_LogsErrorIfDirectiveNotAtTopOfFile() { // Arrange var sourceSpan = new SourceSpan( "Test.cshtml", absoluteIndex: 14 + Environment.NewLine.Length * 2, lineIndex: 2, characterIndex: 0, length: 5 + Environment.NewLine.Length); var expectedDiagnostic = RazorExtensionsDiagnosticFactory.CreatePageDirective_MustExistAtTheTopOfFile(sourceSpan); var content = Environment.NewLine + "@somethingelse" + Environment.NewLine + "@page" + Environment.NewLine; var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create(content, "Test.cshtml")); var engine = CreateRuntimeEngine(); var irDocument = CreateIRDocument(engine, codeDocument); var pass = new RazorPageDocumentClassifierPass { Engine = engine }; // Act pass.Execute(codeDocument, irDocument); var visitor = new Visitor(); visitor.Visit(irDocument); // Assert var pageDirectives = irDocument.FindDirectiveReferences(PageDirective.Directive); var directive = Assert.Single(pageDirectives); var diagnostic = Assert.Single(directive.Node.Diagnostics); Assert.Equal(expectedDiagnostic, diagnostic); }