public static RazorHtmlDocument GetHtmlDocument(RazorCodeDocument codeDocument) { var options = codeDocument.GetCodeGenerationOptions(); if (options == null || !options.DesignTime) { // Not needed in run time. This pass generates the backing HTML document that is used to provide HTML intellisense. return(null); } var writer = new RazorHtmlWriter(codeDocument.Source); var syntaxTree = codeDocument.GetSyntaxTree(); writer.Visit(syntaxTree.Root); var generatedHtml = writer.Builder.ToString(); Debug.Assert( writer.Source.Length == writer.Builder.Length, $"The backing HTML document should be the same length as the original document. Expected: {writer.Source.Length} Actual: {writer.Builder.Length}"); var razorHtmlDocument = new DefaultRazorHtmlDocument(generatedHtml, options); return(razorHtmlDocument); }
// In general documents will have a relative path (relative to the project root). // We can only really compute a nice class/namespace when we know a relative path. // // However all kinds of thing are possible in tools. We shouldn't barf here if the document isn't // set up correctly. internal static bool TryComputeNamespaceAndClass(this RazorCodeDocument document, out string @namespace, out string @class) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var filePath = document.Source.FilePath; var relativePath = document.Source.RelativePath; if (filePath == null || relativePath == null || filePath.Length <= relativePath.Length) { @namespace = null; @class = null; return(false); } filePath = NormalizePath(filePath); relativePath = NormalizePath(relativePath); var options = document.GetCodeGenerationOptions() ?? document.GetDocumentIntermediateNode()?.Options; var rootNamespace = options?.RootNamespace; if (string.IsNullOrEmpty(rootNamespace)) { @namespace = null; @class = null; return(false); } var builder = new StringBuilder(); // Sanitize the base namespace, but leave the dots. var segments = rootNamespace.Split(NamespaceSeparators, StringSplitOptions.RemoveEmptyEntries); builder.Append(CSharpIdentifier.SanitizeIdentifier(segments[0])); for (var i = 1; i < segments.Length; i++) { builder.Append('.'); builder.Append(CSharpIdentifier.SanitizeIdentifier(segments[i])); } segments = relativePath.Split(PathSeparators, StringSplitOptions.RemoveEmptyEntries); // Skip the last segment because it's the FileName. for (var i = 0; i < segments.Length - 1; i++) { builder.Append('.'); builder.Append(CSharpIdentifier.SanitizeIdentifier(segments[i])); } @namespace = builder.ToString(); @class = CSharpIdentifier.SanitizeIdentifier(Path.GetFileNameWithoutExtension(relativePath)); return(true); }
protected override void ExecuteCore(RazorCodeDocument codeDocument) { var syntaxTree = codeDocument.GetSyntaxTree(); ThrowForMissingDocumentDependency(syntaxTree); // This might not have been set if there are no tag helpers. var tagHelperContext = codeDocument.GetTagHelperContext(); var document = new DocumentIntermediateNode(); var builder = IntermediateNodeBuilder.Create(document); document.Options = codeDocument.GetCodeGenerationOptions() ?? _optionsFeature.GetOptions(); var namespaces = new Dictionary <string, SourceSpan?>(StringComparer.Ordinal); // The import documents should be inserted logically before the main document. var imports = codeDocument.GetImportSyntaxTrees(); if (imports != null) { var importsVisitor = new ImportsVisitor(document, builder, namespaces, syntaxTree.Options.FeatureFlags); for (var j = 0; j < imports.Count; j++) { var import = imports[j]; importsVisitor.FilePath = import.Source.FilePath; importsVisitor.VisitBlock(import.Root); } } var tagHelperPrefix = tagHelperContext?.Prefix; var visitor = new MainSourceVisitor(document, builder, namespaces, tagHelperPrefix, syntaxTree.Options.FeatureFlags) { FilePath = syntaxTree.Source.FilePath, }; visitor.VisitBlock(syntaxTree.Root); // In each lowering piece above, namespaces were tracked. We render them here to ensure every // lowering action has a chance to add a source location to a namespace. Ultimately, closest wins. var i = 0; foreach (var @namespace in namespaces) { var @using = new UsingDirectiveIntermediateNode() { Content = @namespace.Key, Source = @namespace.Value, }; builder.Insert(i++, @using); } ImportDirectives(document); // The document should contain all errors that currently exist in the system. This involves // adding the errors from the primary and imported syntax trees. for (i = 0; i < syntaxTree.Diagnostics.Count; i++) { document.Diagnostics.Add(syntaxTree.Diagnostics[i]); } if (imports != null) { for (i = 0; i < imports.Count; i++) { var import = imports[i]; for (var j = 0; j < import.Diagnostics.Count; j++) { document.Diagnostics.Add(import.Diagnostics[j]); } } } codeDocument.SetDocumentIntermediateNode(document); }
protected override void ExecuteCore(RazorCodeDocument codeDocument) { var syntaxTree = codeDocument.GetSyntaxTree(); ThrowForMissingDocumentDependency(syntaxTree); // This might not have been set if there are no tag helpers. var tagHelperContext = codeDocument.GetTagHelperContext(); var document = new DocumentIntermediateNode(); var builder = IntermediateNodeBuilder.Create(document); document.Options = codeDocument.GetCodeGenerationOptions() ?? _optionsFeature.GetOptions(); IReadOnlyList <UsingReference> importedUsings = Array.Empty <UsingReference>(); // The import documents should be inserted logically before the main document. var imports = codeDocument.GetImportSyntaxTrees(); if (imports != null) { var importsVisitor = new ImportsVisitor(document, builder, syntaxTree.Options.FeatureFlags); for (var j = 0; j < imports.Count; j++) { var import = imports[j]; importsVisitor.FilePath = import.Source.FilePath; importsVisitor.VisitBlock(import.Root); } importedUsings = importsVisitor.Usings; } var tagHelperPrefix = tagHelperContext?.Prefix; var visitor = new MainSourceVisitor(document, builder, tagHelperPrefix, syntaxTree.Options.FeatureFlags) { FilePath = syntaxTree.Source.FilePath, }; visitor.VisitBlock(syntaxTree.Root); // 1. Prioritize non-imported usings over imported ones. // 2. Don't import usings that already exist in primary document. // 3. Allow duplicate usings in primary document (C# warning). var usingReferences = new List <UsingReference>(visitor.Usings); for (var j = importedUsings.Count - 1; j >= 0; j--) { if (!usingReferences.Contains(importedUsings[j])) { usingReferences.Insert(0, importedUsings[j]); } } // In each lowering piece above, namespaces were tracked. We render them here to ensure every // lowering action has a chance to add a source location to a namespace. Ultimately, closest wins. var i = 0; foreach (var reference in usingReferences) { var @using = new UsingDirectiveIntermediateNode() { Content = reference.Namespace, Source = reference.Source, }; builder.Insert(i++, @using); } ImportDirectives(document); // The document should contain all errors that currently exist in the system. This involves // adding the errors from the primary and imported syntax trees. for (i = 0; i < syntaxTree.Diagnostics.Count; i++) { document.Diagnostics.Add(syntaxTree.Diagnostics[i]); } if (imports != null) { for (i = 0; i < imports.Count; i++) { var import = imports[i]; for (var j = 0; j < import.Diagnostics.Count; j++) { document.Diagnostics.Add(import.Diagnostics[j]); } } } codeDocument.SetDocumentIntermediateNode(document); }
// In general documents will have a relative path (relative to the project root). // We can only really compute a nice namespace when we know a relative path. // // However all kinds of thing are possible in tools. We shouldn't barf here if the document isn't // set up correctly. public static bool TryComputeNamespace(this RazorCodeDocument document, bool fallbackToRootNamespace, out string @namespace) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var filePath = document.Source.FilePath; if (filePath == null || document.Source.RelativePath == null || filePath.Length < document.Source.RelativePath.Length) { @namespace = null; return(false); } // If the document or it's imports contains a @namespace directive, we want to use that over the root namespace. var baseNamespace = string.Empty; var appendSuffix = true; var lastNamespaceContent = string.Empty; var lastNamespaceLocation = SourceSpan.Undefined; var importSyntaxTrees = document.GetImportSyntaxTrees(); if (importSyntaxTrees != null) { // ImportSyntaxTrees is usually set. Just being defensive. foreach (var importSyntaxTree in importSyntaxTrees) { if (importSyntaxTree != null && NamespaceVisitor.TryGetLastNamespaceDirective(importSyntaxTree, out var importNamespaceContent, out var importNamespaceLocation)) { lastNamespaceContent = importNamespaceContent; lastNamespaceLocation = importNamespaceLocation; } } } var syntaxTree = document.GetSyntaxTree(); if (syntaxTree != null && NamespaceVisitor.TryGetLastNamespaceDirective(syntaxTree, out var namespaceContent, out var namespaceLocation)) { lastNamespaceContent = namespaceContent; lastNamespaceLocation = namespaceLocation; } StringSegment relativePath = document.Source.RelativePath; // If there are multiple @namespace directives in the heirarchy, // we want to pick the closest one to the current document. if (!string.IsNullOrEmpty(lastNamespaceContent)) { baseNamespace = lastNamespaceContent; var directiveLocationDirectory = NormalizeDirectory(lastNamespaceLocation.FilePath); var sourceFilePath = new StringSegment(document.Source.FilePath); // We're specifically using OrdinalIgnoreCase here because Razor treats all paths as case-insensitive. if (!sourceFilePath.StartsWith(directiveLocationDirectory, StringComparison.OrdinalIgnoreCase) || sourceFilePath.Length <= directiveLocationDirectory.Length) { // The most relevant directive is not from the directory hierarchy, can't compute a suffix. appendSuffix = false; } else { // We know that the document containing the namespace directive is in the current document's heirarchy. // Let's compute the actual relative path that we'll use to compute the namespace suffix. relativePath = sourceFilePath.Subsegment(directiveLocationDirectory.Length); } } else if (fallbackToRootNamespace) { var options = document.GetCodeGenerationOptions() ?? document.GetDocumentIntermediateNode()?.Options; baseNamespace = options?.RootNamespace; appendSuffix = true; } if (string.IsNullOrEmpty(baseNamespace)) { // There was no valid @namespace directive and we couldn't compute the RootNamespace. @namespace = null; return(false); } var builder = new StringBuilder(); // Sanitize the base namespace, but leave the dots. var segments = new StringTokenizer(baseNamespace, NamespaceSeparators); var first = true; foreach (var token in segments) { if (token.IsEmpty) { continue; } if (first) { first = false; } else { builder.Append('.'); } CSharpIdentifier.AppendSanitized(builder, token); } if (appendSuffix) { // If we get here, we already have a base namespace and the relative path that should be used as the namespace suffix. segments = new StringTokenizer(relativePath, PathSeparators); var previousLength = builder.Length; foreach (var token in segments) { if (token.IsEmpty) { continue; } previousLength = builder.Length; builder.Append('.'); CSharpIdentifier.AppendSanitized(builder, token); } // Trim the last segment because it's the FileName. builder.Length = previousLength; } @namespace = builder.ToString(); return(true); // We want to normalize the path of the file containing the '@namespace' directive to just the containing // directory with a trailing separator. // // Not using Path.GetDirectoryName here because it doesn't meet these requirements, and we want to handle // both 'view engine' style paths and absolute paths. // // We also don't normalize the separators here. We expect that all documents are using a consistent style of path. // // If we can't normalize the path, we just return null so it will be ignored. StringSegment NormalizeDirectory(string path) { if (string.IsNullOrEmpty(path)) { return(default);