Example #1
0
        internal static async Task Main()
        {
            const string source = @"
using System;
using System.Collections.Generic;
using System.Linq;

class C
{
    void M()
    {
    }   
}
";

            ProjectId projectId = ProjectId.CreateNewId();

            Project project = new AdhocWorkspace()
                              .CurrentSolution
                              .AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp)
                              .AddMetadataReferences(
                projectId,
                new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                RuntimeMetadataReference.CreateFromAssemblyName("System.Core.dll"),
                RuntimeMetadataReference.CreateFromAssemblyName("System.Linq.dll"),
                RuntimeMetadataReference.CreateFromAssemblyName("System.Linq.Expressions.dll"),
                RuntimeMetadataReference.CreateFromAssemblyName("System.Runtime.dll"),
                RuntimeMetadataReference.CreateFromAssemblyName("System.Collections.Immutable.dll"),
                RuntimeMetadataReference.CreateFromAssemblyName("Microsoft.CodeAnalysis.dll"),
                RuntimeMetadataReference.CreateFromAssemblyName("Microsoft.CodeAnalysis.CSharp.dll"),
            })
                              .GetProject(projectId);

            var parseOptions = (CSharpParseOptions)project.ParseOptions;

            project = project.WithParseOptions(parseOptions.WithLanguageVersion(LanguageVersion.Latest));

            DocumentId documentId = DocumentId.CreateNewId(projectId);

            project = project
                      .Solution
                      .AddDocument(documentId, "Test.cs", SourceText.From(source))
                      .GetProject(projectId);

            Document document = project.GetDocument(documentId);

            SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);

            SyntaxTree tree = await document.GetSyntaxTreeAsync().ConfigureAwait(false);

            SyntaxNode root = await tree.GetRootAsync().ConfigureAwait(false);

            string s = document.GetSyntaxRootAsync().Result.ToFullString();

            Console.WriteLine(s);
            Console.ReadKey();
        }
Example #2
0
        private static Project CreateProject(FileAndSource[] sources)
        {
            string             fileNamePrefix = DefaultFilePathPrefix;
            string             fileExt        = CSharpDefaultFileExt;
            CompilationOptions options        = s_CSharpDefaultOptions;

            ProjectId projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var defaultReferences = ReferenceAssemblies.NetFramework.Net48.Default;
            var references        = Task.Run(() => defaultReferences.ResolveAsync(LanguageNames.CSharp, CancellationToken.None)).GetAwaiter().GetResult();

#pragma warning disable CA2000 // Dispose objects before losing scope - Current solution/project takes the dispose ownership of the created AdhocWorkspace
            Project project = new AdhocWorkspace().CurrentSolution
#pragma warning restore CA2000 // Dispose objects before losing scope
                              .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
                              .AddMetadataReferences(projectId, references)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.CodeAnalysisReference)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.WorkspacesReference)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemWebReference)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemRuntimeSerialization)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemDirectoryServices)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemXaml)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.PresentationFramework)
                              .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemWebExtensions)
                              .WithProjectCompilationOptions(projectId, options)
                              .WithProjectParseOptions(projectId, null)
                              .GetProject(projectId);

            // Enable Flow-Analysis feature on the project
            var parseOptions = project.ParseOptions.WithFeatures(
                project.ParseOptions.Features.Concat(
                    new[] { new KeyValuePair <string, string>("flow-analysis", "true") }));
            project = project.WithParseOptions(parseOptions);

            MetadataReference symbolsReference = AdditionalMetadataReferences.CSharpSymbolsReference;
            project = project.AddMetadataReference(symbolsReference);

            project = project.AddMetadataReference(AdditionalMetadataReferences.SystemCollectionsImmutableReference);
            project = project.AddMetadataReference(AdditionalMetadataReferences.SystemXmlDataReference);

            int count = 0;
            foreach (FileAndSource source in sources)
            {
                string     newFileName = source.FilePath ?? fileNamePrefix + count++ + "." + fileExt;
                DocumentId documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                project = project.AddDocument(newFileName, SourceText.From(source.Source)).Project;
            }

            return(project);
        }
        public static async Task <string> GenerateAsync(
            DocumentationModel documentationModel,
            DeclarationListOptions options = null,
            IComparer <INamespaceSymbol> namespaceComparer = null,
            IComparer <INamedTypeSymbol> typeComparer      = null,
            IComparer <ISymbol> memberComparer             = null,
            CancellationToken cancellationToken            = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            options = options ?? DeclarationListOptions.Default;

            var builder = new DeclarationListBuilder(
                options: options,
                namespaceComparer: namespaceComparer,
                typeComparer: typeComparer,
                memberComparer: memberComparer);

            builder.Append(documentationModel);

            StringBuilder sb = StringBuilderCache.GetInstance();

            if ((options.IgnoredParts & DeclarationListParts.AutoGeneratedComment) == 0)
            {
                AppendAutoGeneratedComment(documentationModel, sb);
            }

            foreach (INamespaceSymbol namespaceSymbol in builder.Namespaces.OrderBy(f => f, builder.NamespaceComparer))
            {
                cancellationToken.ThrowIfCancellationRequested();

                sb.Append("using ");
                sb.Append(namespaceSymbol.ToDisplayString(SymbolDisplayFormats.TypeNameAndContainingTypesAndNamespaces));
                sb.AppendLine(";");
            }

            if (builder.Namespaces.Count > 0)
            {
                sb.AppendLine();
            }

            sb.Append(builder);

            string content = sb.ToString();

            Project project = new AdhocWorkspace()
                              .CurrentSolution
                              .AddProject("AdHocProject", "AdHocProject", documentationModel.Language)
                              .WithMetadataReferences(documentationModel.Compilation.References);

            if (project.ParseOptions is CSharpParseOptions csharpParseOptions)
            {
                project = project.WithParseOptions(csharpParseOptions.WithLanguageVersion(LanguageVersion.Latest));
            }
            else
            {
                Debug.Fail(project.ParseOptions.GetType().FullName);
            }

            Document document = project.AddDocument("AdHocFile.cs", SourceText.From(content));

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var rewriter = new Rewriter(options, semanticModel, cancellationToken);

            root = rewriter.Visit(root);

            document = document.WithSyntaxRoot(root);

            document = await Simplifier.ReduceAsync(document, cancellationToken : cancellationToken).ConfigureAwait(false);

            root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            return(root.ToFullString());
        }