private static MetadataReference CreateMetadataReferenceWithXmlDocumentation(string path) { var xmlPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".xml"); var documentation = File.Exists(xmlPath) ? XmlDocumentationProvider.CreateFromFile(xmlPath) : null; return(MetadataReference.CreateFromFile(path, documentation: documentation)); }
private static XmlDocumentationProvider?FindXmlDocumentationSlow(string xmlPath, char[]?charBuffer = null) { if (!File.Exists(xmlPath)) { return(null); } // Might not be required once https://github.com/dotnet/roslyn/issues/23685 is done const int RedirectCheckBlockLength = 1024; string block; using (var reader = new StreamReader(xmlPath)) { charBuffer ??= new char[RedirectCheckBlockLength]; var count = reader.ReadBlock(charBuffer, 0, RedirectCheckBlockLength); block = new string(charBuffer, 0, count); } if (block.Length < RedirectCheckBlockLength) { var xml = XDocument.Parse(block); var redirect = xml.Root.Attribute("redirect")?.Value; if (redirect != null) { return(FindXmlDocumentationSlow(ExpandRedirectVariablesSlow(redirect), charBuffer)); } } return(XmlDocumentationProvider.CreateFromFile(xmlPath)); }
public ReflectionProvider(IEnumerable <string> assemblyPaths) { compilation = CSharpCompilation.Create("C") .AddReferences(assemblyPaths.Select(path => { DocumentationProvider documentationProvider = DocumentationProvider.Default; // Try to find the documentation in the framework doc path string docPath = Path.ChangeExtension(path, ".xml"); if (!File.Exists(docPath)) { docPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Reference Assemblies/Microsoft/Framework/.NETFramework/v4.X", $"{Path.GetFileNameWithoutExtension(path)}.xml"); } if (File.Exists(docPath)) { documentationProvider = XmlDocumentationProvider.CreateFromFile(docPath); } return(MetadataReference.CreateFromFile(path, documentation: documentationProvider)); })); documentationUtil = new DocumentationUtil(compilation); }
private Compilation AddAssemblyReferences(IExecutionContext context, List <ISymbol> symbols, Compilation compilation) { IEnumerable <IFile> assemblyFiles = context.FileSystem.GetInputFiles(_assemblyGlobs) .Where(x => (x.Path.Extension == ".dll" || x.Path.Extension == ".exe") && x.Exists); MetadataReference[] assemblyReferences = assemblyFiles.Select(assemblyFile => { // Create the metadata reference for the compilation IFile xmlFile = context.FileSystem.GetFile(assemblyFile.Path.ChangeExtension("xml")); if (xmlFile.Exists) { Trace.Verbose($"Creating metadata reference for assembly {assemblyFile.Path.FullPath} with XML documentation file at {xmlFile.Path.FullPath}"); return(MetadataReference.CreateFromFile( assemblyFile.Path.FullPath, documentation: XmlDocumentationProvider.CreateFromFile(xmlFile.Path.FullPath))); } Trace.Verbose($"Creating metadata reference for assembly {assemblyFile.Path.FullPath} without XML documentation file"); return((MetadataReference)MetadataReference.CreateFromFile(assemblyFile.Path.FullPath)); }).ToArray(); if (assemblyReferences.Length > 0) { compilation = compilation.AddReferences(assemblyReferences); symbols.AddRange(assemblyReferences .Select(x => (IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(x)) .Select(x => _assemblySymbols ? x : (ISymbol)x.GlobalNamespace)); } return(compilation); }
public MetadataReference GetMetadataReference(string filePath) { var cacheKey = _cacheKeyPrefix + filePath.ToLowerInvariant(); var assemblyMetadata = _cache.Get <AssemblyMetadata>(cacheKey); if (assemblyMetadata == null) { _logger.LogDebug(string.Format("Cache miss {0}", filePath)); using (var stream = File.OpenRead(filePath)) { var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata); assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var options = new MemoryCacheEntryOptions(); options.ExpirationTokens.Add(new FileWriteTimeTrigger(filePath)); _cache.Set(cacheKey, assemblyMetadata, options); } } var displayText = assemblyMetadata.GetModules().FirstOrDefault()?.Name; var documentationFile = Path.ChangeExtension(filePath, ".xml"); var documentationProvider = File.Exists(documentationFile) ? XmlDocumentationProvider.CreateFromFile(documentationFile) : null; return(assemblyMetadata.GetReference( documentationProvider, filePath: filePath, display: displayText)); }
public RoslynProject() { var host = MefHostServices.Create(MefHostServices.DefaultAssemblies); // workspace this.Workspace = new AdhocWorkspace(host); // project var filePath = typeof(object).Assembly.Location; var documentationProvider = XmlDocumentationProvider.CreateFromFile(@"./Resources/System.Runtime.xml"); var projectInfo = ProjectInfo .Create(ProjectId.CreateNewId(), VersionStamp.Create(), "OneDas", "OneDas", LanguageNames.CSharp) .WithMetadataReferences(new[] { MetadataReference.CreateFromFile(filePath, documentation: documentationProvider) }) .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var project = this.Workspace.AddProject(projectInfo); // code this.UseOnlyOnceDocument = this.Workspace.AddDocument(project.Id, "Code.cs", SourceText.From(string.Empty)); this.DocumentId = this.UseOnlyOnceDocument.Id; }
internal static MetadataReference RefFromType <TType>() { var location = typeof(TType).Assembly.Location; var documentationProvider = XmlDocumentationProvider.CreateFromFile(Path.ChangeExtension(location, ".pdb")); return(MetadataReference.CreateFromFile(location, documentation: documentationProvider)); }
// TODO Fix add reference to get xml docs to load for intellisense. private void BtnAddRef_Click(object sender, EventArgs e) { var assemblyLocation = PathHelper.PrecompiledLibraryToReferenceDll; Debug.Assert(File.Exists(assemblyLocation)); Debug.Assert(File.Exists(Path.ChangeExtension(assemblyLocation, ".xml"))); // Add reference to new dll. _csParser.Repository.AddFileReference(assemblyLocation); // Check that xml docs have loaded into roslyn foreach (var project in _csParser.Repository.Solution.Workspace.CurrentSolution.Projects) { var metaRef = project.MetadataReferences.SingleOrDefault(mr => mr.Display == assemblyLocation); var docProviderProperty = metaRef?.GetType().GetProperty("DocumentationProvider", BindingFlags.Instance | BindingFlags.NonPublic); var docProvider = docProviderProperty?.GetValue(metaRef) as DocumentationProvider; if (docProvider?.GetType().Name == "NullDocumentationProvider") { // Update the provider var xmlFile = Path.ChangeExtension(assemblyLocation, ".xml"); var xmlDocProvider = XmlDocumentationProvider.CreateFromFile(xmlFile); // TODO Some how update the existing meta reference to use this documentation provider? } } _csParser.ForceReparseText(); }
private static DocumentationProvider GetDocumentationProvider(string assemblyPath) { var assemblyDocumentationPath = Path.ChangeExtension(assemblyPath, ".xml"); return(File.Exists(assemblyDocumentationPath) ? XmlDocumentationProvider.CreateFromFile(assemblyDocumentationPath) : DocumentationProvider.Default); }
private static Project AddXmlDocumentation(Project project, Type type) { var assemblyPath = type.Assembly.Location; var assemblyXmlDocPath = Path.ChangeExtension(assemblyPath, "xml"); var assemblyDocProvider = XmlDocumentationProvider.CreateFromFile(assemblyXmlDocPath); project = project.AddMetadataReference(MetadataReference.CreateFromFile(assemblyPath, documentation: assemblyDocProvider)); return(project); }
public DocumentationProvider?GetDocumentation([NotNull] Assembly assembly) { foreach (var xmlPath in GetCandidatePaths(assembly)) { if (File.Exists(xmlPath)) { return(XmlDocumentationProvider.CreateFromFile(xmlPath)); } } return(null); }
private static MetadataReference ReferenceAssembly(string name) { var rootPath = Path.Combine( Path.GetDirectoryName(new Uri(typeof(Startup).Assembly.EscapedCodeBase).LocalPath) !, "ref-assemblies" ); var assemblyPath = Path.Combine(rootPath, name + ".dll"); var documentationPath = Path.Combine(rootPath, name + ".xml"); return(MetadataReference.CreateFromFile( assemblyPath, documentation: XmlDocumentationProvider.CreateFromFile(documentationPath) )); }
public DocumentationProvider?GetDocumentationProvider(string location) { string?finalPath = Path.ChangeExtension(location, "xml"); return(_assemblyPathToDocumentationProviderMap.GetOrAdd(location, _ => { if (!File.Exists(finalPath)) { finalPath = GetFilePath(RoslynHostReferences.ReferenceAssembliesPath.docPath, finalPath) ?? GetFilePath(RoslynHostReferences.ReferenceAssembliesPath.assemblyPath, finalPath); } return finalPath == null ? null : XmlDocumentationProvider.CreateFromFile(finalPath); })); }
/// <summary> /// Creates a ReflectionProvider given paths to assemblies and source files. /// </summary> /// <param name="assemblyPaths">Paths to assemblies.</param> /// <param name="sourcePaths">Paths to source files.</param> public ReflectionProvider(IEnumerable <string> assemblyPaths, IEnumerable <string> sourcePaths, IEnumerable <string> sources) { var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); // Create assembly metadata references var assemblyReferences = assemblyPaths.Select(path => { DocumentationProvider documentationProvider = DocumentationProvider.Default; // Try to find the documentation in the framework doc path string docPath = Path.ChangeExtension(path, ".xml"); if (!File.Exists(docPath)) { docPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Reference Assemblies/Microsoft/Framework/.NETFramework/v4.X", $"{Path.GetFileNameWithoutExtension(path)}.xml"); } if (File.Exists(docPath)) { documentationProvider = XmlDocumentationProvider.CreateFromFile(docPath); } return(MetadataReference.CreateFromFile(path, documentation: documentationProvider)); }); // Create syntax trees from sources sources = sources.Concat(sourcePaths.Select(path => File.ReadAllText(path))).Distinct(); var syntaxTrees = sources.Select(source => ParseSyntaxTree(source)); compilation = CSharpCompilation.Create("C", syntaxTrees, assemblyReferences, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); // Try to compile, on success create a new compilation that references the created assembly instead of the sources. // The compilation will fail eg. if the sources have references to the not-yet-compiled assembly. (EmitResult compilationResults, Stream stream) = CompileInMemory(compilation); if (compilationResults.Success) { assemblyReferences = assemblyReferences.Concat(new[] { MetadataReference.CreateFromStream(stream) }); compilation = CSharpCompilation.Create("C", references: assemblyReferences); } extensionMethods = new List <IMethodSymbol>(GetValidTypes().SelectMany(t => t.GetMethods().Where(m => m.IsExtensionMethod))); documentationUtil = new DocumentationUtil(compilation); }
public static IEnumerable <MetadataReference> GetMetadataReferences(this IEnumerable <string> filePaths) { foreach (var filePath in filePaths) { var expectedXmlFile = filePath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? ReplaceCaseInsensitive(filePath, ".dll", ".xml") : Path.Combine(Paths.InstallDirectory, "completion", "references", $"{Path.GetFileName(filePath)}.xml"); yield return(MetadataReference.CreateFromFile( filePath, documentation: XmlDocumentationProvider.CreateFromFile(expectedXmlFile))); } }
public DocumentationProvider?GetDocumentation([NotNull] Assembly assembly) { var fileName = Path.ChangeExtension(assembly.GetAssemblyFileFromCodeBase().Name, ".xml"); if (fileName == "System.Private.CoreLib.xml") { fileName = "System.Runtime.xml"; } var fullPath = Path.Combine(Path.GetDirectoryName(Current.AssemblyPath), fileName); if (!File.Exists(fullPath)) { return(null); } return(XmlDocumentationProvider.CreateFromFile(fullPath)); }
protected override DocumentationProvider CreateDocumentationProvider() { DocumentationProvider provider = null; try { string xmlName = Path.ChangeExtension(FilePath, ".xml"); if (File.Exists(xmlName)) { provider = XmlDocumentationProvider.CreateFromFile(xmlName); } else { provider = RoslynDocumentationProvider.Instance; } } catch (Exception e) { LoggingService.LogError("Error while creating xml documentation provider for: " + FilePath, e); } return(provider); }
private void InjectXMLDocumentationProviderIntoRuntimeMetadataReferenceResolver(ScriptMetadataResolver resolver) { var runtimeMetadataReferenceResolverField = typeof(ScriptMetadataResolver).GetField(ResolverField, BindingFlags.Instance | BindingFlags.NonPublic); var runtimeMetadataReferenceResolverValue = runtimeMetadataReferenceResolverField?.GetValue(resolver); if (runtimeMetadataReferenceResolverValue != null) { var runtimeMetadataReferenceResolverType = typeof(CommandLineScriptGlobals).GetTypeInfo().Assembly.GetType(RuntimeMetadataReferenceResolverType); var fileReferenceProviderField = runtimeMetadataReferenceResolverType?.GetField(FileReferenceProviderField, BindingFlags.Instance | BindingFlags.NonPublic); fileReferenceProviderField.SetValue(runtimeMetadataReferenceResolverValue, new Func <string, MetadataReferenceProperties, PortableExecutableReference>((path, properties) => { var documentationFile = Path.ChangeExtension(path, ".xml"); var documentationProvider = File.Exists(documentationFile) ? XmlDocumentationProvider.CreateFromFile(documentationFile) : null; return(MetadataReference.CreateFromFile(path, properties, documentationProvider)); })); } }
public DocumentationProvider GetDocumentationProvider(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException(nameof(assemblyPath)); } assemblyPath = Path.ChangeExtension(assemblyPath, "xml"); if ( !_assemblyPathToDocumentationProviderMap.TryGetValue( assemblyPath, out var provider ) ) { provider = _assemblyPathToDocumentationProviderMap.GetOrAdd( assemblyPath, _path => XmlDocumentationProvider.CreateFromFile(_path) ); } return(provider); }
public static void Main(string assembly, string output, string?xml = null) { #if DEBUG assembly = @"C:\Users\reflectronic\source\repos\reflectronic\sympl\Sympl.Compiler\bin\Debug\net5.0\Sympl.Compiler"; output = @"C:\Users\reflectronic\Documents\Test"; #endif if (Path.GetExtension(assembly) is not(".exe" or ".dll")) { assembly = File.Exists(assembly + ".dll") ? assembly + ".dll" : assembly + ".exe"; } if (xml is null) { xml = Path.ChangeExtension(assembly, ".xml"); } var reference = MetadataReference.CreateFromFile(assembly, documentation: XmlDocumentationProvider.CreateFromFile(xml)); var compilation = CSharpCompilation.Create("a", references: new[] { reference }); var assemblySymbol = (IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference) !; new MarkdownGenerator(new(compilation, assemblySymbol)).GenerateMarkdown(output); }
public Microsoft.CodeAnalysis.DocumentationProvider GetDocumentationProvider(string location) { var finalPath = Path.ChangeExtension(location, "xml"); if (!File.Exists(finalPath)) { return(null); } return(_assemblyPathToDocumentationProviderMap.GetOrAdd(location, _ => finalPath == null ? null : XmlDocumentationProvider.CreateFromFile(finalPath))); }
/// <summary> /// Creates documentation provider for assembly <i>asmPath</i>. /// Returns null if its xml file does not exist. /// Returns _DocumentationProvider if xml file is big and found or successfully created and successfully loaded database for it. /// Else returns XmlDocumentationProvider. /// </summary> public static DocumentationProvider Create(string asmPath) { if (s_d.TryGetValue(asmPath, out var dp)) { return(dp); } var xmlPath = Path.ChangeExtension(asmPath, "xml"); if (!AFile.GetProperties(xmlPath, out var px)) { return(null); } if (px.Size >= 10_000) { var md5 = new Au.Util.AHash.MD5(); md5.Add(xmlPath.Lower()); var dbPath = AFolders.ThisAppTemp + md5.Hash.ToString() + ".db"; try { if (!AFile.GetProperties(dbPath, out var pd) || pd.LastWriteTimeUtc != px.LastWriteTimeUtc) { //ADebug.Print($"creating db: {asmPath} -> {dbPath}"); AFile.Delete(dbPath); using (var d = new ASqlite(dbPath)) { using var trans = d.Transaction(); d.Execute("CREATE TABLE doc (name TEXT PRIMARY KEY, xml TEXT)"); using var statInsert = d.Statement("INSERT INTO doc VALUES (?, ?)"); var xr = AExtXml.LoadElem(xmlPath); foreach (var e in xr.Descendants("member")) { var name = e.Attr("name"); //remove <remarks> and <example>. foreach (var v in e.Descendants("remarks").ToArray()) { v.Remove(); } foreach (var v in e.Descendants("example").ToArray()) { v.Remove(); } using var reader = e.CreateReader(); reader.MoveToContent(); var xml = reader.ReadInnerXml(); //AOutput.Write(name, xml); statInsert.BindAll(name, xml).Step(); statInsert.Reset(); } trans.Commit(); d.Execute("VACUUM"); } File.SetLastWriteTimeUtc(dbPath, px.LastWriteTimeUtc); } var db = new ASqlite(dbPath, SLFlags.SQLITE_OPEN_READONLY); //never mind: we don't dispose it on process exit s_d[asmPath] = dp = new _DocumentationProvider { _db = db }; return(dp); } catch (Exception ex) { ADebug.Print(ex.ToStringWithoutStack()); } } return(XmlDocumentationProvider.CreateFromFile(xmlPath)); }
internal static PortableExecutableReference ResolveReferenceWithXmlDocumentationProvider(string path, MetadataReferenceProperties properties = default(MetadataReferenceProperties)) { var peReference = MetadataReference.CreateFromFile(path, properties, XmlDocumentationProvider.CreateFromFile(Path.ChangeExtension(path, ".xml"))); return(peReference); }
/// <summary> /// Creates a new <see cref="CachedMetadataReference"/> from an assembly file (optionally including the XML documentation). /// </summary> /// <param name="path">The path to the assembly file.</param> /// <param name="xmlDocumentationPath">The path to the XML documentation file for the assembly.</param> /// <returns> /// If a <see cref="CachedMetadataReference"/> has already been created from the same assembly file and the same XML documentation, a reference to the previously created object. /// Otherwise, a new <see cref="CachedMetadataReference"/> wrapping a <see cref="MetadataReference"/> created from the specified assembly file. /// </returns> public static CachedMetadataReference CreateFromFile(string path, string xmlDocumentationPath = null) { string key = path + ":*:" + xmlDocumentationPath; if (CachedReferences.TryGetValue(key, out CachedMetadataReference cached)) { return(cached); } else { MetadataReference metadataReference = MetadataReference.CreateFromFile(path, documentation: XmlDocumentationProvider.CreateFromFile(xmlDocumentationPath)); CachedMetadataReference reference = new CachedMetadataReference(metadataReference); CachedReferences.Add(key, reference); return(reference); } }
private static MetadataReference CreateReferenceFromFile(string path) { var documentationFile = Path.ChangeExtension(path, ".xml"); return(MetadataReference.CreateFromFile(path, documentation: XmlDocumentationProvider.CreateFromFile(documentationFile))); }
public MetadataReference ToMetadataReference() { var docs = HasDocumentation ? XmlDocumentationProvider.CreateFromFile(DocumentationPath) : null; return(MetadataReference.CreateFromFile(AssemblyPath, documentation: docs)); }
public virtual XmlDocumentationProvider CreateDocumentationFromXmlFile(string xmlDocCommentFilePath) => XmlDocumentationProvider.CreateFromFile(xmlDocCommentFilePath);
/// <summary> /// Gets standard framework dependencies and resolves any package dependencies passed in as /// MetadataReferences to provide the actual assembly file and documentation file together. /// </summary> /// <param name="dependencies">Package dependencies to be located on the file system.</param> /// <returns>An array of <see cref="MetadataReference"/> containing all resolved assemblies and documentation.</returns> public MetadataReference[] ResolveReferences(Dependency[] dependencies) { // Ensure we never have a null reference for the dependency list. if (dependencies == null) { throw new ArgumentNullException(nameof(dependencies)); } var assemblies = new[] { typeof(Uri).Assembly, typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(ConfigurationManager).Assembly, typeof(JObject).Assembly, typeof(HttpClient).Assembly, typeof(HttpContentExtensions).Assembly, typeof(Common.RouteRequest).Assembly, typeof(XmlElement).Assembly, typeof(XObject).Assembly, typeof(DataContractAttribute).Assembly, typeof(BasicHttpBinding).Assembly, typeof(DataSet).Assembly, typeof(DataRowExtensions).Assembly, typeof(Geography).Assembly }; // Pull in cache containing a list of documentation files to make finding an assemblies associated // XML doc file to be added to the MetadataReference. This directory search is only done once on // first request. var fileLookup = GetDocumentationLookup(); return(assemblies .Select(a => { // Locate the name of the assembly to determine what the documentation file name is. var assemblyName = a.GetName().Name; // Attempt to locate an xml documentation file in the cache. if (fileLookup.TryGetValue(assemblyName, out string docPath)) { return MetadataReference.CreateFromFile(a.Location, documentation: XmlDocumentationProvider.CreateFromFile(docPath)); } // Otherwise we have no documentation file and we'll return it without a doc provider. return MetadataReference.CreateFromFile(a.Location); }) // Iterate through each dependency to get actual MetadataReferences containing the assembly paths // and documentation paths for the assemblies contained with the package folders. // There can be multiple assemblies required for each NuGet package, so the ResolvePackageReferencesAsync() // method returns an array of MetadataReferences for each of the assemblies and matching documentation files. // Add the references to the final output to be included in the compilation. .Concat(dependencies.SelectMany(d => ResolvePackageReferences(d))) .ToArray()); }
private static async Task <ProjectHandler> TryGetPhpProjectAsync(string projectFile, ILogTarget log) { try { Project project = LoadProject(projectFile); if (!IsPhpProject(project)) { return(null); } SetupMultitargetingIfNecessary(project); var buildResult = await ResolveReferencesAsync(project); var projectInstance = buildResult.ProjectStateAfterBuild; var metadataReferences = GatherReferences(project, projectInstance, buildResult) .Select(path => MetadataReference.CreateFromFile(path, documentation: XmlDocumentationProvider.CreateFromFile(Path.ChangeExtension(path, "xml")))) .ToArray(); if (metadataReferences.Length == 0) { // dotnet restore hasn't run yet log?.LogMessage($"{Path.GetFileName(projectFile)}: could not be built; "); return(null); } var options = new PhpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, baseDirectory: Path.GetDirectoryName(projectFile), // compilation expects platform-specific slashes (backslashes on windows) specificDiagnosticOptions: null, sdkDirectory: null); // TODO: Get from MSBuild string projectName = Path.GetFileNameWithoutExtension(projectFile); var encoding = TryParseEncodingName(projectInstance.GetPropertyValue("CodePage")) ?? Encoding.UTF8; var nowarn = projectInstance.GetPropertyValue("NoWarn"); if (nowarn != null) { options = options.WithSpecificDiagnosticOptions(ParseNoWarn(nowarn)); } var syntaxTrees = ParseSourceFiles(projectInstance, encoding); var compilation = PhpCompilation.Create( projectName, syntaxTrees, references: metadataReferences, options: options); return(new ProjectHandler(compilation, projectInstance, encoding)); } catch (Exception ex) { log?.LogMessage($"{Path.GetFileName(projectFile)}: {ex.Message}"); return(null); } }