Beispiel #1
0
        static WorkspaceServices()
        {
            if (Environment.GetEnvironmentVariable("DEBUG_AVATAR") == "1")
                Debugger.Break();

            HostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Concat(new[]
                {
                    // Avatar.dll
                    typeof(IAvatar).Assembly,
                    // Avatar.CodeAnalysis.dll
                    typeof(NamingConvention).Assembly,
                    // Avatar.StaticProxy.dll
                    typeof(AvatarGenerator).Assembly,
                }));
        }
        public async Task CreateSolutionSnapshotId_Full_Asset_Serialization_Desktop()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            using var workspace = new AdhocWorkspace(hostServices);
            var solution = CreateFullSolution(workspace);

            var validator = new SerializationValidator(workspace.Services);

            using var snapshot = await validator.RemotableDataService.CreatePinnedRemotableDataScopeAsync(solution, CancellationToken.None).ConfigureAwait(false);

            var solutionObject = await validator.GetValueAsync <SolutionStateChecksums>(snapshot.SolutionChecksum);

            await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false);
        }
        public async Task RoundTrip_Analyzer_Serailization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var workspace  = new AdhocWorkspace(hostServices);
            var serializer = new Serializer(workspace);

            var reference = new AnalyzerFileReference(typeof(object).Assembly.Location, new MockShadowCopyAnalyzerAssemblyLoader());

            // make sure this doesn't throw
            var assetFromFile    = SolutionAsset.Create(serializer.CreateChecksum(reference, CancellationToken.None), reference, serializer);
            var assetFromStorage = await CloneAssetAsync(serializer, assetFromFile).ConfigureAwait(false);

            var assetFromStorage2 = await CloneAssetAsync(serializer, assetFromStorage).ConfigureAwait(false);
        }
Beispiel #4
0
        public async Task Missing_Analyzer_Serailization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var workspace  = new AdhocWorkspace(hostServices);
            var serializer = workspace.Services.GetService <ISerializerService>();

            var reference = new AnalyzerFileReference("missing_reference", new MissingAnalyzerLoader());

            // make sure this doesn't throw
            var assetFromFile    = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference, serializer);
            var assetFromStorage = await CloneAssetAsync(serializer, assetFromFile).ConfigureAwait(false);

            await CloneAssetAsync(serializer, assetFromStorage).ConfigureAwait(false);
        }
Beispiel #5
0
        protected void CoreInit()
        {
            StaticInit();

            CompositionHost compositionContext =
                new ContainerConfiguration()
                .WithAssemblies(MefHostServices.DefaultAssemblies)
                .CreateContainer();

            _host = MefHostServices.Create(compositionContext);

            TheWorkspace = new RoslynWorkspaceBase(_host, "Generated");
            TheProjId    = ProjectId.CreateNewId(ProjName);

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }
        static WorkspaceHacks()
        {
            var assemblyNames = new[]
            {
                "Microsoft.CodeAnalysis.Workspaces",
                "Microsoft.CodeAnalysis.Workspaces.Desktop",
                "Microsoft.CodeAnalysis.CSharp.Workspaces",
                "Microsoft.CodeAnalysis.VisualBasic.Workspaces",
                "Microsoft.CodeAnalysis.Features",
                "Microsoft.CodeAnalysis.CSharp.Features",
                "Microsoft.CodeAnalysis.VisualBasic.Features"
            };
            var assemblies = assemblyNames
                             .Select(n => Assembly.Load(n));

            Pack = MefHostServices.Create(assemblies);
        }
Beispiel #7
0
        static MefHostServices CreateDefaultServices()
        {
            var asms    = new HashSet <Assembly>(MefHostServices.DefaultAssemblies);
            var version = typeof(Compilation).Assembly.GetName().Version;

            foreach (var asmNameTmp in otherAssemblies)
            {
                var asmName = string.Format(asmNameTmp, version);
                try {
                    asms.Add(Assembly.Load(asmName));
                }
                catch {
                    Debug.Fail($"Couldn't load Roslyn MEF assembly: {asmName}");
                }
            }
            return(MefHostServices.Create(asms));
        }
Beispiel #8
0
        private async Task <EmitResult> WhenTheSourceCodeIsCompiled(
            string sourceCode,
            string outputAssembly,
            [CallerMemberName] string compilationAssemblyName = "TestCompilation")
        {
            var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);
            var frameworkLocation = Path.GetDirectoryName(typeof(object).Assembly.Location) !;
            var projectInfo       = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                compilationAssemblyName,
                compilationAssemblyName,
                LanguageNames.CSharp
                )
                                    .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                                            .WithNullableContextOptions(NullableContextOptions.Enable))
                                    .WithParseOptions(new CSharpParseOptions(LanguageVersion.Latest))
                                    .WithMetadataReferences(new[]
            {
                //framework assemblies
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(Path.Combine(frameworkLocation, "netstandard.dll")),
                MetadataReference.CreateFromFile(Path.Combine(frameworkLocation, "System.Runtime.dll")),
                //project dependencies assemblies
                MetadataReference.CreateFromFile(typeof(DataContractAttribute).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Cache <,>).Assembly.Location)
            })
                                    .WithAnalyzerReferences(new[] {
                //our generator
                new AnalyzerFileReference(
                    typeof(DbQueryGenerator).Assembly.Location,
                    new DbQueryGeneratorAnalyzerLoader())
            });

            var compilation = await new AdhocWorkspace(host)
                              .CurrentSolution
                              .AddProject(projectInfo)
                              .AddDocument(
                documentId: DocumentId.CreateNewId(projectInfo.Id, compilationAssemblyName + ".cs"),
                name: compilationAssemblyName + ".cs",
                text: SourceText.From(sourceCode, Encoding.UTF8))
                              .GetProject(projectInfo.Id) !
                              .GetCompilationAsync();

            return(compilation !.Emit(outputAssembly));
        }
Beispiel #9
0
        public RoslynHost(NuGetConfiguration nuGetConfiguration = null, IEnumerable <Assembly> additionalAssemblies = null)
        {
            _nuGetConfiguration = nuGetConfiguration;

            _workspaces = new ConcurrentDictionary <DocumentId, RoslynWorkspace>();
            _diagnosticsUpdatedNotifiers = new ConcurrentDictionary <DocumentId, Action <DiagnosticsUpdatedArgs> >();

            var assemblies = new[]
            {
                Assembly.Load("Microsoft.CodeAnalysis"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp"),
                Assembly.Load("Microsoft.CodeAnalysis.Features"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"),
                typeof(RoslynHost).Assembly,
            };

            if (additionalAssemblies != null)
            {
                assemblies = assemblies.Concat(additionalAssemblies).ToArray();
            }

            var partTypes = MefHostServices.DefaultAssemblies.Concat(assemblies)
                            .Distinct()
                            .SelectMany(x => x.GetTypes())
                            .Concat(new[] { typeof(Microsoft.CodeAnalysis.CodeFixes.CodeFixService) })
                            .Concat(new[] { typeof(DocumentationProviderServiceFactory) })
                            .ToArray();

            _compositionContext = new ContainerConfiguration()
                                  .WithParts(partTypes)
                                  .WithDefaultConventions(new AttributeFilterProvider())
                                  .CreateContainer();

            _host = MefHostServices.Create(_compositionContext);

            _parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Script, preprocessorSymbols: PreprocessorSymbols);

            _referenceAssembliesPath      = GetReferenceAssembliesPath();
            _documentationProviderService = new DocumentationProviderServiceFactory.DocumentationProviderService();

            DefaultReferences = _defaultReferenceAssemblies.Select(t => CreateMetadataReference(t.Location)).ToImmutableArray();

            DefaultImports = _defaultReferenceAssemblyTypes.Select(x => x.Namespace).Distinct().ToImmutableArray();

            GetService <IDiagnosticService>().DiagnosticsUpdated += OnDiagnosticsUpdated;
        }
        public async Task <CompletionList> GetCompletions(string code, IEnumerable <string> imports)
        {
            // not sure why but adding extra character at end fixes auto completion when tab complete after '.'
            var extraChar    = code.LastOrDefault();
            var modifiedCode = $"{code}{extraChar}";

            // based on: https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/

            var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);

            var workspace = new AdhocWorkspace(host);

            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                usings: imports);

            var scriptProjectInfo = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Create(),
                "Script",
                "Script",
                LanguageNames.CSharp,
                isSubmission: true)
                                    .WithMetadataReferences(new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
            })
                                    .WithCompilationOptions(compilationOptions);

            var scriptProject = workspace.AddProject(scriptProjectInfo);

            var scriptDocumentInfo = DocumentInfo.Create(
                DocumentId.CreateNewId(scriptProject.Id), "Script",
                sourceCodeKind: SourceCodeKind.Script,
                loader: TextLoader.From(TextAndVersion.Create(SourceText.From(modifiedCode), VersionStamp.Create())));

            var scriptDocument = workspace.AddDocument(scriptDocumentInfo);

            var position = modifiedCode.Length - 1;

            var completionService = CompletionService.GetService(scriptDocument);

            var results = await completionService.GetCompletionsAsync(scriptDocument, position);

            return(results ?? CompletionList.Empty);
        }
Beispiel #11
0
        public async Task MetadataReference_RoundTrip_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var workspace = new AdhocWorkspace(hostServices);
            var reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            var serializer   = new Serializer(workspace.Services);
            var trees        = new ChecksumTreeCollection();
            var assetBuilder = new AssetBuilder(trees.CreateRootTreeNode(workspace.CurrentSolution.State));

            var assetFromFile    = assetBuilder.Build(reference, CancellationToken.None);
            var assetFromStorage = await CloneAssetAsync(serializer, assetBuilder, assetFromFile).ConfigureAwait(false);

            var assetFromStorage2 = await CloneAssetAsync(serializer, assetBuilder, assetFromStorage).ConfigureAwait(false);
        }
Beispiel #12
0
        public async Task ShadowCopied_Analyzer_Serailization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            using var tempRoot  = new TempRoot();
            using var workspace = new AdhocWorkspace(hostServices);
            var reference = CreateShadowCopiedAnalyzerReference(tempRoot);

            var serializer = workspace.Services.GetService <ISerializerService>();

            // make sure this doesn't throw
            var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference, serializer);

            // this will verify serialized analyzer reference return same checksum as the original one
            var assetFromStorage = await CloneAssetAsync(serializer, assetFromFile).ConfigureAwait(false);
        }
        protected RoslynLanguageBase(
            string name,
            string featuresAssemblyName,
            string workspacesAssemblyName,
            IRoslynLanguageOptions options
            )
        {
            Name          = name;
            _hostServices = CreateHostServices(featuresAssemblyName, workspacesAssemblyName);

            _options = options;
            _codeFixProvidersIndexedByDiagnosticIds = CreateDefaultCodeFixProvidersSlow();
            _analyzers = ImmutableArray.CreateRange(
                _options.AnalyzerReferences.SelectMany(r => r.GetAnalyzers(Name))
                );
            _defaultSignatureHelpProviders = CreateDefaultSignatureHelpProvidersSlow();
        }
Beispiel #14
0
        static async Task Main(string[] args)
        {
            var host        = MefHostServices.Create(MefHostServices.DefaultAssemblies);
            var workspace   = new AdhocWorkspace(host);
            var code        = @"using System;
 
public class MyClass
{
    public static void MyMethod(int value)
    {
        Guid.
    }
}";
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "MyProject", "MyProject", LanguageNames.CSharp).
                              WithMetadataReferences(new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
            });
            var project  = workspace.AddProject(projectInfo);
            var document = workspace.AddDocument(project.Id, "MyFile.cs", SourceText.From(code));

            var position = code.LastIndexOf("Guid.") + 5;

            var completionService = CompletionService.GetService(document);
            var results           = await completionService.GetCompletionsAsync(document, position);

            foreach (var i in results.Items)
            {
                Console.WriteLine(i.DisplayText);

                foreach (var prop in i.Properties)
                {
                    Console.Write($"{prop.Key}:{prop.Value}  ");
                }

                Console.WriteLine();
                foreach (var tag in i.Tags)
                {
                    Console.Write($"{tag}  ");
                }

                Console.WriteLine();
                Console.WriteLine();
            }
        }
Beispiel #15
0
        public static async Task <List <string> > Run(string script, int position)
        {
            var assemblies = new[]
            {
                Assembly.Load("Microsoft.CodeAnalysis"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp"),
                Assembly.Load("Microsoft.CodeAnalysis.Features"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"),
            };

            var parts = MefHostServices.DefaultAssemblies.Concat(assemblies)
                        .Distinct()
                        .SelectMany(x => x.GetTypes())
                        .ToArray();

            var ctx = new ContainerConfiguration()
                      .WithParts(parts)
                      .CreateContainer();
            var host      = MefHostServices.Create(ctx);
            var workspace = new AdhocWorkspace(host);

            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary, usings: new[] { "System",
                                                                     "CoreFunctions", "Microsoft.AspNetCore.Http",
                                                                     "System.Net" });
            var scriptProjectInfo = ProjectInfo.Create(ProjectId.CreateNewId(),
                                                       VersionStamp.Create(), "Script", "Script",
                                                       LanguageNames.CSharp, isSubmission: true)
                                    .WithMetadataReferences(new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) })
                                    .WithCompilationOptions(compilationOptions);

            var scriptProject      = workspace.AddProject(scriptProjectInfo);
            var scriptDocumentInfo = DocumentInfo.Create(
                DocumentId.CreateNewId(scriptProject.Id), "Script",
                sourceCodeKind: SourceCodeKind.Script,
                loader: TextLoader.From(
                    TextAndVersion.Create(SourceText.From(script),
                                          VersionStamp.Create())));
            var scriptDocument = workspace.AddDocument(scriptDocumentInfo);
            var compiler       = CompletionService.GetService(scriptDocument);

            return((await compiler.GetCompletionsAsync(scriptDocument, position))
                   .Items
                   .Select(c => c.DisplayText).ToList());
        }
Beispiel #16
0
        public void TestEncodingSerialization()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var workspace  = new AdhocWorkspace(hostServices);
            var serializer = new Serializer(workspace);

            // test with right serializable encoding
            var sourceText = SourceText.From("Hello", Encoding.UTF8);

            using (var stream = SerializableBytes.CreateWritableStream())
            {
                using (var objectWriter = new ObjectWriter(stream))
                {
                    serializer.Serialize(sourceText, objectWriter, CancellationToken.None);
                }

                stream.Position = 0;

                using (var objectReader = ObjectReader.TryGetReader(stream))
                {
                    var newText = serializer.Deserialize <SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
                    Assert.Equal(sourceText.ToString(), newText.ToString());
                }
            }

            // test with wrong encoding that doesn't support serialization
            sourceText = SourceText.From("Hello", new NotSerializableEncoding());
            using (var stream = SerializableBytes.CreateWritableStream())
            {
                using (var objectWriter = new ObjectWriter(stream))
                {
                    serializer.Serialize(sourceText, objectWriter, CancellationToken.None);
                }

                stream.Position = 0;

                using (var objectReader = ObjectReader.TryGetReader(stream))
                {
                    var newText = serializer.Deserialize <SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None);
                    Assert.Equal(sourceText.ToString(), newText.ToString());
                }
            }
        }
        async static Task Main(string[] args)
        {
            var code = @"using System;

            public class MyClass
            {
                public static void MyMethod(int value)
                {
                }
            }";

            var host      = MefHostServices.Create(MefHostServices.DefaultAssemblies);
            var workspace = new AdhocWorkspace(host);

            var souceText = SourceText.From(code);

            // with a project
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "MyProject", "MyProject", LanguageNames.CSharp).
                              WithMetadataReferences(new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) });
            var project  = workspace.AddProject(projectInfo);
            var document = workspace.AddDocument(project.Id, "MyFile.cs", souceText);

            var classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, new TextSpan(0, code.Length));

            foreach (var classifiedSpan in classifiedSpans.Where(s => !ClassificationTypeNames.AdditiveTypeNames.Contains(s.ClassificationType)))
            {
                var position = souceText.Lines.GetLinePositionSpan(classifiedSpan.TextSpan);
                Console.WriteLine($"{souceText.ToString(classifiedSpan.TextSpan)} - {classifiedSpan.ClassificationType} - {position.Start}:{position.End}");
            }

            // with semantic model
            var syntaxTree    = CSharpSyntaxTree.ParseText(souceText);
            var compilation   = CSharpCompilation.Create("Dummy").AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)).AddSyntaxTrees(syntaxTree);
            var semanticModel = compilation.GetSemanticModel(syntaxTree);

            classifiedSpans = Classifier.GetClassifiedSpans(semanticModel, new TextSpan(0, code.Length), workspace);

            foreach (var classifiedSpan in classifiedSpans.Where(s => !ClassificationTypeNames.AdditiveTypeNames.Contains(s.ClassificationType)))
            {
                var position = souceText.Lines.GetLinePositionSpan(classifiedSpan.TextSpan);
                Console.WriteLine($"{souceText.ToString(classifiedSpan.TextSpan)} - {classifiedSpan.ClassificationType} - {position.Start}:{position.End}");
            }

            Console.ReadLine();
        }
        public CompletionProvider(ScriptCs.ScriptServices service, ICSharpCode.AvalonEdit.Document.TextDocument text)
        {
            _simp = new SimpleCompletionProvider(service, text);

            var currentPath = Assembly.GetExecutingAssembly().Location;

            currentPath = Path.GetDirectoryName(currentPath);
            var f1 = Path.Combine(currentPath, "Microsoft.CodeAnalysis.Features.dll");
            var f2 = Path.Combine(currentPath, "Microsoft.CodeAnalysis.CSharp.Features");
            var f3 = Path.Combine(currentPath, "Microsoft.CodeAnalysis.Workspaces.Desktop");

            if (!File.Exists(f1))
            {
                File.WriteAllBytes(f1, Resources.Microsoft_CodeAnalysis_Features);
            }
            if (!File.Exists(f2))
            {
                File.WriteAllBytes(f2, Resources.Microsoft_CodeAnalysis_CSharp_Features);
            }
            if (!File.Exists(f3))
            {
                File.WriteAllBytes(f3, Resources.Microsoft_CodeAnalysis_Workspaces_Desktop);
            }

            _host = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(new[]
            {
                Assembly.LoadFrom(f1),
                Assembly.LoadFrom(f2)
            }));

            _ws = new InteractiveWorkspace(_host);


            _parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Interactive);

            _references = _assemblyTypes.Select(t =>
                                                MetadataReference.CreateFromAssembly(t.Assembly)).ToArray();
            _compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                               usings: _assemblyTypes.Select(x => x.Namespace).ToImmutableArray());

            var container = new CompositionContainer(new AssemblyCatalog(typeof(ISignatureHelpProvider).Assembly),
                                                     CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            _signatureHelpProviders = container.GetExportedValues <ISignatureHelpProvider>().ToArray();
        }
Beispiel #19
0
        public async Task Missing_Analyzer_Serailization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var workspace = new AdhocWorkspace(hostServices);
            var reference = new AnalyzerFileReference("missing_reference", new MissingAnalyzerLoader());

            var serializer   = new Serializer(workspace.Services);
            var trees        = new ChecksumTreeCollection();
            var assetBuilder = new AssetBuilder(trees.CreateRootTreeNode(workspace.CurrentSolution.State));

            // make sure this doesn't throw
            var assetFromFile    = assetBuilder.Build(reference, CancellationToken.None);
            var assetFromStorage = await CloneAssetAsync(serializer, assetBuilder, assetFromFile).ConfigureAwait(false);

            var assetFromStorage2 = await CloneAssetAsync(serializer, assetBuilder, assetFromStorage).ConfigureAwait(false);
        }
Beispiel #20
0
    static WorkspaceServices()
    {
        if (Environment.GetEnvironmentVariable("DEBUG_MOQ") == "1")
        {
            Debugger.Break();
        }

        HostServices = MefHostServices.Create(
            MefHostServices.DefaultAssemblies.Concat(new[]
        {
            // Moq.Sdk.dll
            typeof(IMock).Assembly,
            // Moq.CodeAnalysis.dll
            typeof(MockNamingConvention).Assembly,
            // Moq.dll
            typeof(IMoq).Assembly,
        }));
    }
Beispiel #21
0
        // Re-run this method with TD.NET AdHoc runner to regenerate CodeFixNames.g.cs as needed.
        public void GenerateCodeFixNames()
        {
            var host                 = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(new[] { typeof(CodeFixNamesGenerator).Assembly }));
            var codeFixProviders     = host.GetExports <CodeFixProvider, IDictionary <string, object> >().Select(x => x.Metadata);
            var refactoringProviders = MefHostServices.DefaultAssemblies.Select(asm => asm.GetTypes())
                                       .SelectMany(types => types.Select(type => type.GetCustomAttribute <ExportCodeRefactoringProviderAttribute>()))
                                       .Where(attr => attr != null)
                                       .Select(attr => new Dictionary <string, object>
            {
                { nameof(ExportCodeRefactoringProviderAttribute.Name), attr.Name },
                { nameof(ExportCodeRefactoringProviderAttribute.Languages), attr.Languages },
            });

            var allFixes  = new HashSet <string>();
            var codeFixes = new Dictionary <string, HashSet <string> >
            {
                { "All", allFixes }
            };

            var allRefactorings  = new HashSet <string>();
            var codeRefactorings = new Dictionary <string, HashSet <string> >
            {
                { "All", allFixes }
            };

            GroupActions(codeFixProviders, allFixes, codeFixes);
            GroupActions(refactoringProviders, allRefactorings, codeRefactorings);

            var ns = NamespaceDeclaration(ParseName("Avatars.CodeActions"))
                     .AddMembers(GetConstants("CodeFixes", codeFixes))
                     .AddMembers(GetConstants("CodeRefactorings", codeRefactorings));

            var file = Path.GetFullPath(@$ "{ThisAssembly.Project.MSBuildProjectDirectory}\..\Avatar.StaticProxy\CodeActions.g.cs");

            using (var output = new StreamWriter(file, false))
            {
                output.WriteLine("#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member");
                ns.NormalizeWhitespace().WriteTo(output);
                output.WriteLine();
                output.WriteLine("#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member");
            }

            Console.WriteLine(file);
        }
        public async Task Workspace_RoundTrip_Test_Desktop()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            using var workspace = new AdhocWorkspace(hostServices);
            var solution = CreateFullSolution(workspace);

            var validator = new SerializationValidator(workspace.Services);

            using var snapshot1 = await validator.RemotableDataService.CreatePinnedRemotableDataScopeAsync(solution, CancellationToken.None).ConfigureAwait(false);

            // recover solution from given snapshot
            var recovered = await validator.GetSolutionAsync(snapshot1).ConfigureAwait(false);

            var solutionObject1 = await validator.GetValueAsync <SolutionStateChecksums>(snapshot1.SolutionChecksum).ConfigureAwait(false);

            // create new snapshot from recovered solution
            using var snapshot2 = await validator.RemotableDataService.CreatePinnedRemotableDataScopeAsync(recovered, CancellationToken.None).ConfigureAwait(false);

            // verify asset created by recovered solution is good
            var solutionObject2 = await validator.GetValueAsync <SolutionStateChecksums>(snapshot2.SolutionChecksum).ConfigureAwait(false);

            await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false);

            // verify snapshots created from original solution and recovered solution are same
            validator.SolutionStateEqual(solutionObject1, solutionObject2);
            snapshot1.Dispose();

            // recover new solution from recovered solution
            var roundtrip = await validator.GetSolutionAsync(snapshot2).ConfigureAwait(false);

            // create new snapshot from round tripped solution
            using var snapshot3 = await validator.RemotableDataService.CreatePinnedRemotableDataScopeAsync(roundtrip, CancellationToken.None).ConfigureAwait(false);

            // verify asset created by rount trip solution is good
            var solutionObject3 = await validator.GetValueAsync <SolutionStateChecksums>(snapshot3.SolutionChecksum).ConfigureAwait(false);

            await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false);

            // verify snapshots created from original solution and round trip solution are same.
            validator.SolutionStateEqual(solutionObject2, solutionObject3);
            snapshot2.Dispose();
        }
Beispiel #23
0
        public static RoslynWorkspace GetWorkspace(AvalonStudio.Projects.ISolution solution)
        {
            if (!s_solutionWorkspaces.ContainsKey(solution))
            {
                //await PackageManager.EnsurePackage("AvalonStudio.Languages.CSharp", IoC.Get<IConsole>());

                //var dotnetDirectory = Path.Combine(PackageManager.GetPackageDirectory("AvalonStudio.Languages.CSharp"), "content");

                var currentDir = AvalonStudio.Platforms.Platform.ExecutionPath;

                var loadedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();

                var assemblies = new[]
                {
                    // Microsoft.CodeAnalysis.Workspaces
                    typeof(WorkspacesResources).GetTypeInfo().Assembly,
                    // Microsoft.CodeAnalysis.CSharp.Workspaces
                    typeof(CSharpWorkspaceResources).GetTypeInfo().Assembly,
                    // Microsoft.CodeAnalysis.Features
                    typeof(FeaturesResources).GetTypeInfo().Assembly,
                    // Microsoft.CodeAnalysis.CSharp.Features
                    typeof(CSharpFeaturesResources).GetTypeInfo().Assembly,
                    typeof(RoslynWorkspace).Assembly,
                };

                var partTypes = MefHostServices.DefaultAssemblies.Concat(assemblies)
                                .Distinct()
                                .SelectMany(x => x.GetTypes())
                                .ToArray();

                var compositionContext = new ContainerConfiguration()
                                         .WithParts(partTypes)
                                         .CreateContainer();

                var host = MefHostServices.Create(compositionContext);

                var workspace = new RoslynWorkspace(host, null, compositionContext, DotNetCliService.Instance.Info.Executable, DotNetCliService.Instance.Info.BasePath);

                workspace.RegisterWorkspace(solution);
            }

            return(s_solutionWorkspaces[solution]);
        }
            static ImmutableHashSet <IOption> ComputeSerializableOptionsFromProviders(ImmutableArray <Lazy <IOptionProvider, LanguageMetadata> > lazyProvidersAndMetadata)
            {
                var builder = ImmutableHashSet.CreateBuilder <IOption>();

                foreach (var lazyProviderAndMetadata in lazyProvidersAndMetadata)
                {
                    // We only consider the options defined in the the DefaultAssemblies (Workspaces and Features) as serializable.
                    // This is due to the fact that other layers above are VS specific and do not execute in OOP.
                    var provider = lazyProviderAndMetadata.Value;
                    if (!MefHostServices.IsDefaultAssembly(provider.GetType().Assembly))
                    {
                        continue;
                    }

                    builder.AddRange(provider.Options);
                }

                return(builder.ToImmutable());
            }
        public RoslynSession(
            SourceText sourceText,
            ProjectInfo projectInfo,
            MefHostServices hostServices,
            ImmutableArray <DiagnosticAnalyzer> analyzers,
            ImmutableDictionary <string, ImmutableArray <CodeFixProvider> > codeFixProviders,
            ImmutableArray <ISignatureHelpProviderWrapper> signatureHelpProviders
            )
        {
            _workspace         = new CustomWorkspace(hostServices);
            _sourceText        = sourceText;
            _document          = CreateProjectAndOpenNewDocument(_workspace, projectInfo, sourceText);
            QuickInfoService   = QuickInfoService.GetService(_document);
            _completionService = CompletionService.GetService(_document);

            Analyzers = analyzers;
            SignatureHelpProviders = signatureHelpProviders;
            CodeFixProviders       = codeFixProviders;
        }
Beispiel #26
0
        public async Task SnapshotWithMissingReferencesTest()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            var project = new AdhocWorkspace(hostServices).CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            var metadata = new MissingMetadataReference();
            var analyzer = new AnalyzerFileReference("missing_reference", new MissingAnalyzerLoader());

            project = project.AddMetadataReference(metadata);
            project = project.AddAnalyzerReference(analyzer);

            var snapshotService = (new RemotableDataServiceFactory()).CreateService(project.Solution.Workspace.Services) as IRemotableDataService;

            using var snapshot = await snapshotService.CreatePinnedRemotableDataScopeAsync(project.Solution, CancellationToken.None).ConfigureAwait(false);

            // this shouldn't throw
            var recovered = await GetSolutionAsync(snapshotService, snapshot).ConfigureAwait(false);
        }
Beispiel #27
0
        public void WorkspaceAnalyzer_Serialization_Desktop_Test()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Add(typeof(Host.TemporaryStorageServiceFactory.TemporaryStorageService).Assembly));

            using var tempRoot  = new TempRoot();
            using var workspace = new AdhocWorkspace(hostServices);
            var reference = CreateShadowCopiedAnalyzerReference(tempRoot);

            var serializer = workspace.Services.GetService <ISerializerService>();

            var asset = WorkspaceAnalyzerReferenceAsset.Create(reference, serializer, CancellationToken.None);

            // verify checksum from custom asset builder uses different checksum than regular one
            var expectedChecksum = Checksum.Create(
                WellKnownSynchronizationKind.AnalyzerReference,
                serializer.CreateChecksum(reference, CancellationToken.None));

            Assert.Equal(expectedChecksum, asset.Checksum);
        }
        static MefHostServices CreateDefaultServices()
        {
            var asms    = new HashSet <Assembly>(MefHostServices.DefaultAssemblies);
            var version = typeof(Compilation).Assembly.GetName().Version;

            foreach (var asmNameTmp in otherAssemblies)
            {
                var asmName = string.Format(asmNameTmp, version);
                try {
                    asms.Add(Assembly.Load(asmName));
                }
                catch {
                    Debug.Fail($"Couldn't load Roslyn MEF assembly: {asmName}");
                }
            }
            // dnSpy.Roslyn.Internal exports some stuff too
            asms.Add(typeof(SignatureHelpService).Assembly);
            asms.Add(typeof(Microsoft.CodeAnalysis.Editor.VisualBasic.QuickInfo.SemanticQuickInfoProvider).Assembly);
            return(MefHostServices.Create(asms));
        }
        public void AcquireCompletionService()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Concat(
                    new[]
            {
                typeof(CompletionService).Assembly,
                typeof(CSharpCompletionService).Assembly
            }));

            var workspace = new AdhocWorkspace(hostServices);

            var document = workspace
                           .AddProject("TestProject", LanguageNames.CSharp)
                           .AddDocument("TestDocument.cs", "");

            var service = CompletionService.GetService(document);

            Assert.NotNull(service);
        }
Beispiel #30
0
        public RoslynHost(IEnumerable <Assembly> additionalAssemblies = null,
                          RoslynHostReferences references             = null,
                          ImmutableArray <string>?disabledDiagnostics = null)
        {
            if (references == null)
            {
                references = RoslynHostReferences.Empty;
            }

            _workspaces = new ConcurrentDictionary <DocumentId, RoslynWorkspace>();
            _diagnosticsUpdatedNotifiers = new ConcurrentDictionary <DocumentId, Action <DiagnosticsUpdatedArgs> >();

            // ReSharper disable once VirtualMemberCallInConstructor
            var assemblies = GetDefaultCompositionAssemblies();

            if (additionalAssemblies != null)
            {
                assemblies = assemblies.Concat(additionalAssemblies);
            }

            var partTypes = assemblies
                            .SelectMany(x => x.DefinedTypes)
                            .Select(x => x.AsType());

            _compositionContext = new ContainerConfiguration()
                                  .WithParts(partTypes)
                                  .CreateContainer();

            HostServices = MefHostServices.Create(_compositionContext);

            // ReSharper disable once VirtualMemberCallInConstructor
            _parseOptions = CreateDefaultParseOptions();

            _documentationProviderService = GetService <IDocumentationProviderService>();

            DefaultReferences = references.GetReferences(DocumentationProviderFactory);
            DefaultImports    = references.Imports;

            DisabledDiagnostics = disabledDiagnostics ?? ImmutableArray <string> .Empty;
            GetService <IDiagnosticService>().DiagnosticsUpdated += OnDiagnosticsUpdated;
        }
 public OmnisharpWorkspace(MefHostServices hostServices) : base(hostServices, "Custom")
 {
     BufferManager = new BufferManager(this);
 }