private async Task<Solution> FixEFModelAsync(Project project, Compilation compilation,
            IEnumerable<IClassAssumption> classAssumptions, IEnumerable<IPropertyAssumption> propertyAssumptions, ObjectTheoremResult objectTheoremResult,
            CancellationToken cancellationToken)
        {
            Trace.WriteLine("FixEFModelAsync");
            try
            {
                var newSolution = project.Solution;

                foreach (var syntaxTree in compilation.SyntaxTrees)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var syntaxRoot = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
                    var semanticModel = compilation.GetSemanticModel(syntaxTree);

                    var rewriter = new AttributeAssumptionsRewriter(semanticModel, classAssumptions, propertyAssumptions, objectTheoremResult, cancellationToken);
                    var newSyntaxRoot = rewriter.Visit(syntaxRoot);

                    cancellationToken.ThrowIfCancellationRequested();

                    var documentId = newSolution.GetDocumentId(syntaxTree);
                    newSolution = newSolution.WithDocumentSyntaxRoot(documentId, newSyntaxRoot);
                }

                return newSolution;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
        }
 internal override AbstractDescriptionBuilder CreateDescriptionBuilder(
     IVsObjectBrowserDescription3 description,
     ObjectListItem listItem,
     Project project)
 {
     return new DescriptionBuilder(description, this, listItem, project);
 }
		public GenerateTypeOptionsResult(
			Accessibility accessibility,
			TypeKind typeKind,
			string typeName,
			Project project,
			bool isNewFile,
			string newFileName,
			IList<string> folders,
			string fullFilePath,
			Document existingDocument,
			bool areFoldersValidIdentifiers,
			bool isCancelled = false)
		{
			this.Accessibility = accessibility;
			this.TypeKind = typeKind;
			this.TypeName = typeName;
			this.Project = project;
			this.IsNewFile = isNewFile;
			this.NewFileName = newFileName;
			this.Folders = folders;
			this.FullFilePath = fullFilePath;
			this.ExistingDocument = existingDocument;
			this.AreFoldersValidIdentifiers = areFoldersValidIdentifiers;
			this.IsCancelled = isCancelled;
		}
예제 #4
0
        private string GetTestRunner(Microsoft.CodeAnalysis.Project testProject, string fileConfigTestRunner)
        {
            var testRunner = fileConfigTestRunner ?? "DotNet";

            Log.Info($"Test runner: {testRunner}");
            return(testRunner);
        }
예제 #5
0
        private List <INamedTypeSymbol> AnalyzeProject(Project project)
        {
            var compilation = project.GetCompilationAsync().Result;
            var allTypes    = compilation.GetSymbolsWithName(x => true, SymbolFilter.Type).OfType <ITypeSymbol>().Where(t => t is INamedTypeSymbol).OfType <INamedTypeSymbol>();

            return(allTypes.ToList(  ));
        }
        internal async Task <IEnumerable <ISymbol> > GetMatchingTypesAsync(
            Microsoft.CodeAnalysis.Project project, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
        {
            // Can't be on the right hand side of binary expression (like 'dot').
            cancellationToken.ThrowIfCancellationRequested();
            string name;
            int    arity;

            node.GetNameAndArityOfSimpleName(out name, out arity);

            var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false);

            // also lookup type symbols with the "Attribute" suffix.
            var inAttributeContext = node.IsAttributeName();

            if (inAttributeContext)
            {
                symbols = symbols.Concat(
                    await SymbolFinder.FindDeclarationsAsync(project, name + "Attribute", this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false));
            }

            var accessibleTypeSymbols = symbols
                                        .OfType <INamedTypeSymbol>()
                                        .Where(s => (arity == 0 || s.GetArity() == arity) &&
                                               s.IsAccessibleWithin(semanticModel.Compilation.Assembly) &&
                                               (!inAttributeContext || s.IsAttribute()) &&
                                               HasValidContainer(s))
                                        .ToList();

            return(accessibleTypeSymbols);
        }
        internal async Task <IEnumerable <ISymbol> > GetMatchingNamespacesAsync(
            Microsoft.CodeAnalysis.Project project,
            SemanticModel semanticModel,
            SyntaxNode simpleName,
            CancellationToken cancellationToken)
        {
            if (simpleName.IsAttributeName())
            {
                return(null);
            }

            string name;
            int    arity;

            simpleName.GetNameAndArityOfSimpleName(out name, out arity);
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false);

            var namespaces = symbols
                             .OfType <INamespaceSymbol>()
                             .Where(n => !n.IsGlobalNamespace &&
                                    HasAccessibleTypes(n, semanticModel, cancellationToken));

            return(namespaces);
        }
        private async Task <IEnumerable <INamespaceSymbol> > GetNamespacesForQueryPatternsAsync(
            Microsoft.CodeAnalysis.Project project,
            Diagnostic diagnostic,
            SyntaxNode node,
            SemanticModel semanticModel,
            ISet <INamespaceSymbol> namespacesInScope,
            CancellationToken cancellationToken)
        {
            if (!this.CanAddImportForQuery(diagnostic, ref node))
            {
                return(null);
            }

            ITypeSymbol type = this.GetQueryClauseInfo(semanticModel, node, cancellationToken);

            if (type == null)
            {
                return(null);
            }

            // find extension methods named "Select"
            var symbols = await SymbolFinder.FindDeclarationsAsync(project, "Select", this.IgnoreCase, SymbolFilter.Member, cancellationToken).ConfigureAwait(false);

            var extensionMethodSymbols = symbols
                                         .OfType <IMethodSymbol>()
                                         .Where(s => s.IsExtensionMethod && IsViableExtensionMethod(type, s))
                                         .ToList();

            return(GetProposedNamespaces(
                       extensionMethodSymbols.Select(s => s.ContainingNamespace),
                       semanticModel,
                       namespacesInScope));
        }
        private async Task <IEnumerable <ITypeSymbol> > GetTypeSymbols(
            Microsoft.CodeAnalysis.Project project,
            SyntaxNode node,
            SemanticModel semanticModel,
            string name,
            bool inAttributeContext,
            CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            if (ExpressionBinds(node, semanticModel, cancellationToken))
            {
                return(null);
            }

            var symbols = await SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false);

            // also lookup type symbols with the "Attribute" suffix.
            if (inAttributeContext)
            {
                symbols = symbols.Concat(
                    await SymbolFinder.FindDeclarationsAsync(project, name + "Attribute", this.IgnoreCase, SymbolFilter.Type, cancellationToken).ConfigureAwait(false));
            }

            return(symbols.OfType <ITypeSymbol>());
        }
        private Task <IEnumerable <ISymbol> > GetSymbolsAsync(
            Microsoft.CodeAnalysis.Project project,
            SyntaxNode node,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // See if the name binds.  If it does, there's nothing further we need to do.
            if (ExpressionBinds(node, semanticModel, cancellationToken, checkForExtensionMethods: true))
            {
                return(Task.FromResult(Enumerable.Empty <ISymbol>()));
            }

            string name;
            int    arity;

            node.GetNameAndArityOfSimpleName(out name, out arity);
            if (name == null)
            {
                return(Task.FromResult(Enumerable.Empty <ISymbol>()));
            }

            return(SymbolFinder.FindDeclarationsAsync(project, name, this.IgnoreCase, SymbolFilter.Member, cancellationToken));
        }
        private async Task <IEnumerable <IMethodSymbol> > GetAddMethodsAsync(
            Microsoft.CodeAnalysis.Project project,
            Diagnostic diagnostic,
            SyntaxNode node,
            SemanticModel semanticModel,
            ISet <INamespaceSymbol> namespacesInScope,
            SyntaxNode expression,
            CancellationToken cancellationToken)
        {
            string name;
            int    arity;

            node.GetNameAndArityOfSimpleName(out name, out arity);
            if (name != null)
            {
                return(SpecializedCollections.EmptyEnumerable <IMethodSymbol>());
            }

            if (IsAddMethodContext(node, semanticModel))
            {
                var symbols = await SymbolFinder.FindDeclarationsAsync(project, "Add", this.IgnoreCase, SymbolFilter.Member, cancellationToken).ConfigureAwait(false);

                return(symbols
                       .OfType <IMethodSymbol>()
                       .Where(method => method.IsExtensionMethod &&
                              method.ContainingType?.IsAccessibleWithin(semanticModel.Compilation.Assembly) == true &&
                              IsViableExtensionMethod(method, expression, semanticModel, cancellationToken)));
            }

            return(SpecializedCollections.EmptyEnumerable <IMethodSymbol>());
        }
        private async Task <IEnumerable <INamespaceSymbol> > GetNamespacesForMatchingNamespacesAsync(
            Microsoft.CodeAnalysis.Project project,
            Diagnostic diagnostic,
            SyntaxNode node,
            SemanticModel semanticModel,
            ISet <INamespaceSymbol> namespacesInScope,
            CancellationToken cancellationToken)
        {
            if (!this.CanAddImportForNamespace(diagnostic, ref node))
            {
                return(null);
            }

            string name;
            int    arity;

            node.GetNameAndArityOfSimpleName(out name, out arity);

            if (ExpressionBinds(node, semanticModel, cancellationToken))
            {
                return(null);
            }

            var symbols = await SymbolFinder.FindDeclarationsAsync(
                project, name, this.IgnoreCase, SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false);

            return(GetProposedNamespaces(
                       symbols.OfType <INamespaceSymbol>().Select(n => n.ContainingNamespace),
                       semanticModel,
                       namespacesInScope));
        }
        private async Task <IEnumerable <ITypeSymbol> > GetMatchingTypesAsync(
            Microsoft.CodeAnalysis.Project project,
            Diagnostic diagnostic,
            SyntaxNode node,
            SemanticModel semanticModel,
            ISet <INamespaceSymbol> namespacesInScope,
            CancellationToken cancellationToken)
        {
            if (!this.CanAddImportForType(diagnostic, ref node))
            {
                return(null);
            }

            string name;
            int    arity;
            bool   inAttributeContext, hasIncompleteParentMember;

            CalculateContext(node, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);

            var symbols = await GetTypeSymbols(project, node, semanticModel, name, inAttributeContext, cancellationToken).ConfigureAwait(false);

            if (symbols == null)
            {
                return(null);
            }

            return(GetMatchingTypes(semanticModel, namespacesInScope, name, arity, inAttributeContext, symbols, hasIncompleteParentMember));
        }
예제 #14
0
        public LineCoverage[] RunTest(Project project,
            RewrittenDocument rewrittenDocument,
            MethodDeclarationSyntax method,
            ISemanticModel semanticModel,
            string[] rewrittenAssemblies)
        {
            var testClass = method.GetParentClass();
            var rewrittenTestClass =
                rewrittenDocument.SyntaxTree
                    .GetRoot()
                    .DescendantNodes()
                    .OfType<ClassDeclarationSyntax>().First(x => x.Identifier.ToString() == testClass.Identifier.ToString());

            var fixtureDetails = _testsExtractor.GetTestFixtureDetails(rewrittenTestClass, semanticModel);
            var allReferences = _solutionExplorer.GetAllProjectReferences(project.Name);

            fixtureDetails.Cases.RemoveAll(x => x.MethodName != method.Identifier.ToString());

            if (fixtureDetails.Cases.Count == 0)
                return null;

            var compiledTestInfo = new CompiledTestFixtureInfo
            {
                AllReferences = allReferences.Union(rewrittenAssemblies).ToArray(),
                TestDocumentPath = rewrittenDocument.DocumentPath,
                SemanticModel = semanticModel
            };

            var coverage = RunTestFixture(fixtureDetails, compiledTestInfo, project.Name);

            return coverage;
        }
예제 #15
0
        public void Compile(Microsoft.CodeAnalysis.Project project)
        {
            _project = project;

            foreach (var document in _project.Documents)
            {
                var tree = document.GetSyntaxTreeAsync().Result;
                foreach (var type in tree.GetRoot().DescendantNodes())
                {
                    switch (type)
                    {
                    case ClassDeclarationSyntax syntax:
                        if (syntax.Modifiers.Any(x => CSharpExtensions.IsKind((SyntaxToken)x, SyntaxKind.AbstractKeyword)))
                        {
                            DeclarationManager.Instance.AddAbstractClass(syntax);
                        }
                        else
                        {
                            DeclarationManager.Instance.AddClass(syntax);
                        }

                        break;

                    case InterfaceDeclarationSyntax syntax:
                        DeclarationManager.Instance.AddInterface(syntax);
                        break;

                    case EnumDeclarationSyntax syntax:
                        DeclarationManager.Instance.AddEnum(syntax);
                        break;
                    }
                }
            }
        }
        public RoslynCompiledItem(Project project, CSharpCompilation
            compilation)
        {
            Project = project;

            Compilation = compilation;
        }
예제 #17
0
    static public bool TryCreateCompilation(Options options, out Task<Compilation> cu, out MSBuildWorkspace workspace, out Project project) 
    {
      Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out cu) != null); 
      Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out workspace) != null);

      Output.WriteLine("Opening the solution {0}", options.Solution);

      workspace = MSBuildWorkspace.Create();
      cu = null;
      project = null;
      try
      {
        if (options.Project != null && options.Solution != null)
        {
          return CreateCompilationFromSolution(options, workspace, out cu, out project);
        }
        else
        {
          Output.WriteError("Failed to parse either the Project or Solution");
          // not implemented;
          return false;
        }
      }
      catch(Exception e)
      {
        Output.WriteError("Error while parsing the .csproj file. Exception from Roslyn: {0}", e.ToString());
        cu = null;
        return false;
      }
    }
		private static Project MoveTypeNodes(SemanticModel model, ImmutableArray<TypeToRemove> typesToRemove,
			Func<string, string> typeFolderGenerator, Project project, CancellationToken token)
		{
			var projectName = project.Name;

			foreach (var typeToRemove in typesToRemove)
			{
				token.ThrowIfCancellationRequested();
				var fileName = $"{typeToRemove.Symbol.Name}.cs";

				var containingNamespace = typeToRemove.Symbol.GetContainingNamespace();
				var typeFolder = typeFolderGenerator(containingNamespace).Replace(
					projectName, string.Empty);

				if (typeFolder.StartsWith("\\"))
				{
					typeFolder = typeFolder.Remove(0, 1);
				}

				project = project.AddDocument(fileName,
					typeToRemove.Declaration.GetCompilationUnitForType(model, containingNamespace),
					folders: !string.IsNullOrWhiteSpace(typeFolder) ?
						new[] { typeFolder } : null).Project;
			}

			return project;
		}
        public ProjectAnalysisResult(Project project, ImmutableArray<Diagnostic> diagnostics)
        {
            Contract.Requires(project != null);
            Project = project;

            Diagnostics = diagnostics;
        }
예제 #20
0
 //TODO: Test what happens if multiple instances of VisualStudio run...
 public RoslynIntrospector(Project project)
 {
     if (workspace == null)
     workspace = project.Solution.Workspace;
       if (solution == null)
       {
     solution = workspace.CurrentSolution;
     UpdateProjectCompilations(project);
       } else if (ContainingProject.Equals(project.Id))
       {
     var changes = project.Solution.GetChanges(solution);
     foreach (var removedProject in changes.GetRemovedProjects())
       projectCompilations.Remove(removedProject.Id);
     foreach (var addedProject in changes.GetAddedProjects())
       projectCompilations.Add(addedProject.Id, GetCompilationForProject(addedProject));
     foreach (var projectChanges in changes.GetProjectChanges())
       //Bruteforce way: Just get the new compilation...
       //If that does not scale try adding documents to the compilation (incremental update)
       projectCompilations[projectChanges.ProjectId] = GetCompilationForProject(projectChanges.NewProject);
     solution = project.Solution;
       } else
       {//Solution and workspace does not change but project does and so do the dependencies.
        //We then need different projects in the projectCompilations Dictionary
     UpdateProjectCompilations(project);
     workspace = project.Solution.Workspace;
     solution = workspace.CurrentSolution;
       }
       ContainingProject = project.Id;
 }
        protected async Task<ImmutableArray<Document>> FindDocumentsAsync(Project project, IImmutableSet<Document> scope, Func<Document, CancellationToken, Task<bool>> predicateAsync, CancellationToken cancellationToken)
        {
            // special case for HR
            if (scope != null && scope.Count == 1)
            {
                var document = scope.First();
                if (document.Project == project)
                {
                    return scope.ToImmutableArray();
                }

                return ImmutableArray<Document>.Empty;
            }

            var documents = ArrayBuilder<Document>.GetInstance();
            foreach (var document in project.Documents)
            {
                if (scope != null && !scope.Contains(document))
                {
                    continue;
                }

                if (await predicateAsync(document, cancellationToken).ConfigureAwait(false))
                {
                    documents.Add(document);
                }
            }

            return documents.ToImmutableAndFree();
        }
예제 #22
0
        public LineCoverage[] RunAllTestsInDocument(RewrittenDocument rewrittenDocument,
            ISemanticModel semanticModel,
            Project project,
            string[] rewrittenAssemblies)
        {
            var allReferences = _solutionExplorer.GetAllProjectReferences(project.Name);

            var compiledTestInfo = new CompiledTestFixtureInfo
            {
                AllReferences = allReferences.Union(rewrittenAssemblies).ToArray(),
                TestDocumentPath = rewrittenDocument.DocumentPath,
                SemanticModel = semanticModel
            };

            var coverage = new List<LineCoverage>();

            var testClasses = _testsExtractor.GetTestClasses(rewrittenDocument.SyntaxTree.GetRoot());

            if (testClasses.Length == 0)
                return null;

            foreach (ClassDeclarationSyntax testClass in testClasses)
            {
                compiledTestInfo.TestClass = testClass;

                var partialCoverage = RunAllTestsInFixture(compiledTestInfo, project.Name);
                coverage.AddRange(partialCoverage);
            }

            return coverage.ToArray();
        }
예제 #23
0
파일: CSharpTask.cs 프로젝트: kzu/clide
		public override bool Execute()
		{
			if (Language != CSharp)
			{
				Log.LogError("Unsupported language {0}.", Language);
				return false;
			}

			Project = this.GetOrAddProject(ProjectFullPath);
			if (cancellation.IsCancellationRequested)
			{
				Log.LogWarning("Cancellation was requested. Aborting task.");
				return false;
			}

			Compilation = Project.GetCompilationAsync(cancellation.Token).Result;

			var logWarnings = false;
			if (!string.IsNullOrEmpty(LogWarnings) && bool.TryParse(LogWarnings, out logWarnings) && logWarnings)
			{
				var diagnostics = Compilation.GetDiagnostics(cancellation.Token);
				if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
					Log.LogWarning("Code generation may not be complete, since there are compilation errors: " +
						string.Join(Environment.NewLine, diagnostics.Select(d => d.GetMessage())));
			}

			return true;
		}
        private async Task<DiagnosticAnalysisResultMap<DiagnosticAnalyzer, DiagnosticAnalysisResult>> AnalyzeOutOfProcAsync(
            RemoteHostClient client, CompilationWithAnalyzers analyzerDriver, Project project, CancellationToken cancellationToken)
        {
            var solution = project.Solution;

            var snapshotService = solution.Workspace.Services.GetService<ISolutionChecksumService>();

            // TODO: this should be moved out
            var hostChecksums = GetHostAnalyzerReferences(snapshotService, _analyzerService.GetHostAnalyzerReferences(), cancellationToken);
            var analyzerMap = CreateAnalyzerMap(analyzerDriver.Analyzers.Where(a => !a.MustRunInProcess()));
            if (analyzerMap.Count == 0)
            {
                return DiagnosticAnalysisResultMap.Create(ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty, ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo>.Empty);
            }

            // TODO: send telemetry on session
            using (var session = await client.CreateCodeAnalysisServiceSessionAsync(solution, cancellationToken).ConfigureAwait(false))
            {
                var argument = new DiagnosticArguments(
                    analyzerDriver.AnalysisOptions.ReportSuppressedDiagnostics,
                    analyzerDriver.AnalysisOptions.LogAnalyzerExecutionTime,
                    project.Id, hostChecksums, analyzerMap.Keys.ToArray());

                var result = await session.InvokeAsync(
                    WellKnownServiceHubServices.CodeAnalysisService_CalculateDiagnosticsAsync,
                    new object[] { argument },
                    (s, c) => GetCompilerAnalysisResultAsync(s, analyzerMap, project, c)).ConfigureAwait(false);

                ReportAnalyzerExceptions(project, result.Exceptions);

                return result;
            }
        }
        public async Task<DiagnosticAnalysisResultMap<DiagnosticAnalyzer, DiagnosticAnalysisResult>> AnalyzeAsync(CompilationWithAnalyzers analyzerDriver, Project project, CancellationToken cancellationToken)
        {
            var remoteHostClient = await project.Solution.Workspace.Services.GetService<IRemoteHostClientService>().GetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false);
            if (remoteHostClient == null)
            {
                // remote host is not running. this can happen if remote host is disabled.
                return await AnalyzeInProcAsync(analyzerDriver, project, cancellationToken).ConfigureAwait(false);
            }

            // TODO: later, make sure we can run all analyzer on remote host. 
            //       for now, we will check whether built in analyzer can run on remote host and only those run on remote host.
            var inProcResultTask = AnalyzeInProcAsync(CreateAnalyzerDriver(analyzerDriver, a => a.MustRunInProcess()), project, cancellationToken);
            var outOfProcResultTask = AnalyzeOutOfProcAsync(remoteHostClient, analyzerDriver, project, cancellationToken);

            // run them concurrently in vs and remote host
            await Task.WhenAll(inProcResultTask, outOfProcResultTask).ConfigureAwait(false);

            // make sure things are not cancelled
            cancellationToken.ThrowIfCancellationRequested();

            // merge 2 results
            return DiagnosticAnalysisResultMap.Create(
                inProcResultTask.Result.AnalysisResult.AddRange(outOfProcResultTask.Result.AnalysisResult),
                inProcResultTask.Result.TelemetryInfo.AddRange(outOfProcResultTask.Result.TelemetryInfo));
        }
예제 #26
0
        public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
        {
            if (project.Language == LanguageNames.VisualBasic)
            {
                return("");
            }

            IVisualStudioHostProject ivisualStudioHostProject;
            IVsHierarchy             hierarchy;

            EnvDTE.Project envDTEProject;

            var folders          = new List <string>();
            var defaultNamespace = "";

            if (workspace is VisualStudioWorkspaceImpl)
            {
                ((VisualStudioWorkspaceImpl)workspace).GetProjectData(project.Id, out ivisualStudioHostProject, out hierarchy, out envDTEProject);

                try
                {
                    defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
                }
                catch (ArgumentException)
                {
                    // DefaultNamespace does not exist for this project.
                }
            }

            return(defaultNamespace);
        }
예제 #27
0
        private string GetTestRunner(Microsoft.CodeAnalysis.Project testProject, string fileConfigTestRunner)
        {
            //This is a bit hackish but it's until I fix so you can specify test runner in file config.
            LogTo.Info($"Looking for test runner for {testProject.Name}..");
            if (!string.IsNullOrEmpty(fileConfigTestRunner))
            {
                LogTo.Info($"..found {fileConfigTestRunner} in config.");
                return(fileConfigTestRunner);
            }

            if (testProject.ParseOptions.PreprocessorSymbolNames.Any(p => p.ToUpper().Contains("NETCOREAPP")))
            {
                LogTo.Info("..found .core in symbol names so will use dotnet.");
                return("dotnet");
            }

            if (testProject.MetadataReferences.Any(m => m.Display.ToLower().Contains("nunit")))
            {
                LogTo.Info("..found nunit in references so will use that.");
                return("nunit");
            }

            if (testProject.MetadataReferences.Any(m => m.Display.ToLower().Contains("xunit")))
            {
                LogTo.Info("..found xunit in references so will use that.");
                return("xunit");
            }

            throw new OpenProjectException($"Could not determine test runner for {testProject.Name}. Please specify test runner in config");
        }
 internal IVsNavInfo GetProjectNavInfo(Project project)
 {
     return new NavInfo(
         this.LibraryGuid,
         this.SymbolToolLanguage,
         project.GetProjectNavInfoName());
 }
		internal static async Task<ImmutableArray<Diagnostic>> GetDiagnostics (Project project, List<DiagnosticAnalyzer> providers, CancellationToken token)
		{
			var analyzers = ImmutableArray<DiagnosticAnalyzer>.Empty.AddRange (providers);
			try {
				var compilation = await project.GetCompilationAsync (token).ConfigureAwait (false);
				CompilationWithAnalyzers compilationWithAnalyzer;
				var options = new CompilationWithAnalyzersOptions (
					null,
					delegate (Exception exception, DiagnosticAnalyzer analyzer, Diagnostic diag) {
						LoggingService.LogError ("Exception in diagnostic analyzer " + diag.Id + ":" + diag.GetMessage (), exception);
					},
					true,
					false
				);

				compilationWithAnalyzer = compilation.WithAnalyzers (analyzers, options);
				if (token.IsCancellationRequested)
					return ImmutableArray<Diagnostic>.Empty;

				return await compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync ().ConfigureAwait (false);
			} catch (Exception) {
				return ImmutableArray<Diagnostic>.Empty;
			} finally {
				CompilationWithAnalyzers.ClearAnalyzerState (analyzers);
			}
		}
예제 #30
0
 public AssemblyChangedEvent(PackageLoadedAssembly assembly, AssemblyChangeType changeType, string changedFile, Project project)
 {
     Assembly    = assembly;
     ChangeType  = changeType;
     ChangedFile = changedFile;
     Project     = project;
 }
예제 #31
0
        private async Task<GraphNode> AddLinkedNodeForType(Project project, INamedTypeSymbol namedType, GraphBuilder graphBuilder, IEnumerable<SyntaxTree> syntaxTrees)
        {
            // If this named type is contained in a parent type, then just link farther up
            if (namedType.ContainingType != null)
            {
                var parentTypeNode = await AddLinkedNodeForType(project, namedType.ContainingType, graphBuilder, syntaxTrees).ConfigureAwait(false);
                var typeNode = await graphBuilder.AddNodeForSymbolAsync(namedType, relatedNode: parentTypeNode).ConfigureAwait(false);
                graphBuilder.AddLink(parentTypeNode, GraphCommonSchema.Contains, typeNode);

                return typeNode;
            }
            else
            {
                // From here, we can link back up to the containing project item
                var typeNode = await graphBuilder.AddNodeForSymbolAsync(namedType, contextProject: project, contextDocument: null).ConfigureAwait(false);

                foreach (var tree in syntaxTrees)
                {
                    var document = project.Solution.GetDocument(tree);
                    Contract.ThrowIfNull(document);

                    var documentNode = graphBuilder.AddNodeForDocument(document);
                    graphBuilder.AddLink(documentNode, GraphCommonSchema.Contains, typeNode);
                }

                return typeNode;
            }
        }
예제 #32
0
        public async Task Initialize()
        {
            if (initializedTaskSource == null)
            {
                initializedTaskSource = new TaskCompletionSource <bool>();

                // Track all packages
                foreach (var package in session.LocalPackages)
                {
                    await TrackPackage(package);
                }

                // Locate current package's game executable
                // TODO: Handle current package changes. Detect this as part of the package solution.
                var gameExecutableViewModel = (session.CurrentProject as ProjectViewModel)?.Type == ProjectType.Executable ? session.CurrentProject : null;
                if (gameExecutableViewModel != null && gameExecutableViewModel.IsLoaded)
                {
                    gameExecutable = await OpenProject(gameExecutableViewModel.ProjectPath);
                }

                initializedTaskSource.SetResult(true);
            }
            else
            {
                await initializedTaskSource.Task;
            }
        }
        public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
        {
            this.AssertIsForeground();

            if (project.Language == LanguageNames.VisualBasic)
            {
                return("");
            }

            var folders          = new List <string>();
            var defaultNamespace = "";

            if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
            {
                vsWorkspace.GetProjectData(project.Id,
                                           out var hierarchy, out var envDTEProject);

                try
                {
                    defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
                }
                catch (ArgumentException)
                {
                    // DefaultNamespace does not exist for this project.
                }
            }

            return(defaultNamespace);
        }
예제 #34
0
        private async Task ProcessProjectAsync(Project project, GraphBuilder graphBuilder, CancellationToken cancellationToken)
        {
            var cacheService = project.Solution.Services.CacheService;
            if (cacheService != null)
            {
                using (cacheService.EnableCaching(project.Id))
                {
                    var results = await FindNavigableSourceSymbolsAsync(project, cancellationToken).ConfigureAwait(false);

                    foreach (var result in results)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        var symbol = result.Item1;

                        if (symbol is INamedTypeSymbol)
                        {
                            await AddLinkedNodeForType(project, (INamedTypeSymbol)symbol, graphBuilder, symbol.DeclaringSyntaxReferences.Select(d => d.SyntaxTree)).ConfigureAwait(false);
                        }
                        else
                        {
                            await AddLinkedNodeForMemberAsync(project, symbol, graphBuilder).ConfigureAwait(false);
                        }
                    }
                }
            }
        }
예제 #35
0
 public ProjectViewModel(FolderViewModel parent, DirectoryInfo dir)
     : base(parent, dir)
 {
     var tuple = Workspace.Add(this);
     _id = tuple.Item1;
     _project = tuple.Item2;
 }
예제 #36
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="project">Project</param>
 public PSharpProject(Project project)
 {
     this.Project = project;
     this.PSharpPrograms = new List<PSharpProgram>();
     this.PPrograms = new List<PProgram>();
     this.ProgramMap = new Dictionary<IPSharpProgram, SyntaxTree>();
 }
        public RewrittenDocument RewriteDocumentWithAssemblyInfo(Project currentProject, Project[] allProjects, string documentPath, string documentContent)
        {
            var attrs = CreateInternalVisibleToAttributeList(currentProject, allProjects);
            var rewrittenDocument = RewriteDocument(currentProject, documentPath, documentContent, attrs);

            return rewrittenDocument;
        }
 public MemberTarget(SourceTextContainer textContainer, ISymbol memberIdentifier, Project project, Solution solution)
 {
     _textContainer = textContainer;
     _memberIdentifier = memberIdentifier;
     _project = project;
     _solution = solution;
 }
예제 #39
0
 public IList<ResourceDescription> GetResources(Project project)
 {
     return Directory.EnumerateFiles(project.ProjectDirectory, "*.resx", SearchOption.AllDirectories)
                     .Select(resxFilePath =>
                         new ResourceDescription(GetResourceName(project.Name, resxFilePath),
                                                 () => GetResourceStream(resxFilePath),
                                                 isPublic: true)).ToList();
 }
예제 #40
0
 private async Task AddDocuments(MSProject msProject, Project project)
 {
     // Handle all documents in project
     foreach (var msDocument in msProject.Documents)
     {
         await AddNamespaces(project, msDocument);
     }
 }
예제 #41
0
        private static async Task<IEnumerable<string>> GetThrownExceptionTypeNames(Project project)
        {
            var compilation = await project.GetCompilationAsync();

            return compilation.SyntaxTrees
                              .SelectMany(tree => GetThrownExceptionTypeNames(compilation, tree))
                              .Distinct();
        }
        protected override Project ExtendProject(Project project)
        {
            var newFileName = DefaultFilePathPrefix + project.Documents.Count() + "." + CSharpDefaultFileExt;

            return project.AddMetadataReference(IListSourceReference)
                          .AddMetadataReference(EntityFrameworkReference)
                          .AddDocument(newFileName, SourceText.From(Properties.Resources.Model)).Project;
        }
예제 #43
0
파일: Document.cs 프로젝트: vslsnap/roslyn
        internal Document(Project project, DocumentState state)
        {
            Contract.ThrowIfNull(project);
            Contract.ThrowIfNull(state);

            this.Project = project;
            _state = state;
        }
예제 #44
0
 private Document SetSubmissionDocument(SourceTextContainer textContainer, Project project)
 {
     var id = DocumentId.CreateNewId(project.Id);
     var solution = project.Solution.AddDocument(id, project.Name, textContainer.CurrentText);
     _workspace.SetCurrentSolution(solution);
     _workspace.OpenDocument(id, textContainer);
     return solution.GetDocument(id);
 }
예제 #45
0
 public DescriptionBuilder(
     IVsObjectBrowserDescription3 description,
     ObjectBrowserLibraryManager librayManager,
     ObjectListItem listItem,
     Project project)
     : base(description, librayManager, listItem, project)
 {
 }
예제 #46
0
        public static Task<ImmutableArray<PatternSearchResult>> RunAsync(Project project, ImmutableArray<PatternSearch> searches)
        {
            if (project == null)
                throw new ArgumentNullException(nameof(project));

            var documents = project.Documents;
            return RunAsync(documents, searches);
        }
예제 #47
0
            public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
            {
                var sum = await GetProjectSizeAsync(project, cancellationToken).ConfigureAwait(false);

                _map.AddOrUpdate(project.Id, sum, (id, existing) => sum);

                _size = _map.Values.Sum();
            }
 private static IEnumerable <DocumentId> GetSupportedDocumentIds(RoslynProject project)
 {
     return(project.Documents
            .Where(document => document.SupportsSemanticModel &&
                   document.SupportsSyntaxTree &&
                   document.SourceCodeKind == SourceCodeKind.Regular)
            .Select(d => d.Id));
 }
예제 #49
0
        public void PinvokeMethodReferences_VB()
        {
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            Microsoft.CodeAnalysis.Solution sln = new CustomWorkspace().CurrentSolution
                                                  .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                                                  .AddMetadataReference(prj1Id, MscorlibRef)
                                                  .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod  = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
예제 #50
0
        public static IEnumerable <Document> FilterDocuments(Project project, Filter filter)
        {
            if (filter.Documents.Count == 0)
            {
                return(project.Documents);
            }

            return((from existingDocuments in project.Documents
                    join selectedDocuments in filter.Documents on existingDocuments.Name.Split(".")[0] equals selectedDocuments
                    select(existingDocuments)).Distinct());
        }
예제 #51
0
        static async Task <LookupResult> TryLookupSymbolInProject(Microsoft.CodeAnalysis.Project prj, string documentationCommentId, CancellationToken token)
        {
            if (string.IsNullOrEmpty(documentationCommentId))
            {
                return(LookupResult.Failure);
            }
            bool searchNs      = documentationCommentId[0] == 'N';
            bool searchType    = documentationCommentId[0] == 'T';
            int  reminderIndex = 2;
            var  comp          = await prj.GetCompilationAsync(token).ConfigureAwait(false);

            var current = LookupNamespace(documentationCommentId, ref reminderIndex, comp.GlobalNamespace);

            if (current == null)
            {
                return(LookupResult.Failure);
            }
            if (searchNs)
            {
                if (current.GetDocumentationCommentId() == documentationCommentId)
                {
                    return(new LookupResult(current, prj.Solution, comp));
                }
                return(LookupResult.Failure);
            }

            INamedTypeSymbol type = null;

            foreach (var t in current.GetAllTypes())
            {
                type = LookupType(documentationCommentId, reminderIndex, t);
                if (type != null)
                {
                    if (searchType)
                    {
                        return(new LookupResult(type, prj.Solution, comp));
                    }
                    break;
                }
            }
            if (type == null)
            {
                return(LookupResult.Failure);
            }
            foreach (var member in type.GetMembers())
            {
                if (member.GetDocumentationCommentId() == documentationCommentId)
                {
                    return(new LookupResult(member, prj.Solution, comp));
                }
            }
            return(LookupResult.Failure);
        }
예제 #52
0
        public static SymbolNameMap CompileSymbolNames(Microsoft.CodeAnalysis.Project project, Compilation compilation)
        {
/*
 *          var assemblyInfoByAssemblySymbol = project.MetadataReferences
 *              .ToDictionary(x => compilation.GetReferencedAssemblySymbol(x), x => Assembly.ReflectionOnlyLoadFrom(x.Display));
 *          var referencedAssembliesByAssemblySymbol = assemblyInfoByAssemblySymbol
 *              .ToDictionary(x => x.Key, x => x.Value.GetReferencedAssemblies().Select(y => y.Name));
 */

/*
 *          foreach (var metadataReference in project.MetadataReferences)
 *          {
 *              var assemblyLocation = metadataReference.Display;
 *              var assemblySymbol = compilation.GetReferencedAssemblySymbol(metadataReference);
 *              var reflectionAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyLocation);
 *              var referencedAssemblies = reflectionAssembly.GetReferencedAssemblies();
 *          }
 */

            var mainAssembly = Tuple.Create(compilation.Assembly, (IAssemblySymbol[])null); //compilation.References.Select(x => compilation.GetReferencedAssemblySymbol(x)).ToArray());
//            var referencedAssemblies = mainAssembly.Item2.Select(x => Tuple.Create(x, AssembliesSorter.GetReferencedAssemblies(x).ToArray()));
            var assemblies = new[] { mainAssembly };                                        //.Concat(referencedAssemblies).ToArray();

            var sortedAssemblies = AssembliesSorter.Sort(assemblies);

            var names = new Dictionary <ISymbol, string>();

            foreach (var assembly in sortedAssemblies)
            {
                var collector = new SymbolCollector();
                assembly.Accept(collector);

                var counter = 1;
//                var types = collector.Symbols.Where(x => x.Kind == SymbolKind.NamedType).OrderBy(x => x.DeclaredAccessibility == Accessibility.Public ? -1 : 1);
//                foreach (var type in types)
//                {
//                    names[type] = "$" + counter++;
//                }

/*
 *              var namespaces = collector.Symbols.Where(x => x.Kind == SymbolKind.Namespace);
 *              foreach (var ns in namespaces)
 *              {
 *                  names[ns] = "$" + counter++;
 *              }
 */
            }
            var map = new SymbolNameMap(names);

            return(map);
        }
        public async void UpdatePreview(string text)
        {
            var workspace = new PreviewWorkspace(Ide.Composition.CompositionManager.Instance.HostServices);
            var fileName  = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj");

            project = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language);

            // use the mscorlib, system, and system.core that are loaded in the current process.
            string [] references =
            {
                "mscorlib",
                "System",
                "System.Core"
            };

            var metadataService = workspace.Services.GetService <IMetadataService> ();

            var referenceAssemblies = Thread.GetDomain().GetAssemblies()
                                      .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase))
                                      .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly));

            project = project.WithMetadataReferences(referenceAssemblies);

            var document  = project.AddDocument("document.cs", SourceText.From(text, Encoding.UTF8));
            var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None);

            workspace.TryApplyChanges(project.Solution);

            TextViewHost.MimeType        = "text/x-csharp";
            TextViewHost.Text            = (await document.GetTextAsync()).ToString();
            TextViewHost.DocumentContext = new MyDocumentContext(workspace, document);

            TextViewHost.IsReadOnly = false;
            for (int i = 1; i <= TextViewHost.LineCount; i++)
            {
                var txt = TextViewHost.GetLineText(i);
                if (txt == "//[" || txt == "//]")
                {
                    var line = TextViewHost.GetLine(i);
                    TextViewHost.RemoveText(line.Offset, line.LengthIncludingDelimiter);
                    i--;
                }
            }
            TextViewHost.IsReadOnly = true;
            if (curWorkspace != null)
            {
                curWorkspace.Dispose();
            }

            this.curWorkspace = workspace;
        }
예제 #54
0
 private List <INamedTypeSymbol> AnalyzeProject(Project project)
 {
     try
     {
         var compilation = project.GetCompilationAsync().Result;
         var allTypes    = compilation.GetSymbolsWithName(x => true, SymbolFilter.Type).OfType <ITypeSymbol>().Where(t => t is INamedTypeSymbol).OfType <INamedTypeSymbol>();
         return(allTypes.ToList(  ));
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error getting types from '" + project.Name + "': " + ex.Message);
         return(new List <INamedTypeSymbol>());
     }
 }
예제 #55
0
        private void _buildEvents_OnBuildProjConfigDone(string project, string projectConfig, string platform, string solutionConfig, bool success)
        {
            if (!WorkspaceHasBitConfigV1JsonFile())
            {
                return;
            }

            thereWasAnErrorInLastBuild = thereWasAnErrorInLastBuild && success;

            Project proj = _visualStudioWorkspace.CurrentSolution.Projects.Where(p => p.Language == LanguageNames.CSharp)
                           .ExtendedSingle($"Lookin for {project} in [ {(string.Join(",", _visualStudioWorkspace.CurrentSolution.Projects.Where(p => p.Language == LanguageNames.CSharp).Select(prj => prj.Name)))} ]", prj => Path.GetFileName(prj.FilePath) == project.Split('\\').Last());

            _shouldGeneratedProjectNames.Add(proj.Name);
        }
예제 #56
0
파일: Form1.cs 프로젝트: VE-2016/VE-2016
        public async void CompileSolution()
        {
            var _ = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);

            string solutionFileName = "C:\\MSBuildProjects-beta\\VStudio.sln";


            VSSolutionLoader rw = new VSSolutionLoader();

            System.Windows.Forms.TreeView vv = rw.LoadProject(solutionFileName);

            VSSolution vs = vv.Tag as VSSolution;

            MessageBox.Show("VSolution loaded.." + vs.Name);

            comp = new Dictionary <string, Compilation>();

            named = new Dictionary <string, List <INamespaceOrTypeSymbol> >();

            workspace = null;

            ProjectDependencyGraph projectGraph = null;

            Microsoft.CodeAnalysis.Solution solution = null;
            workspace = MSBuildWorkspace.Create();
            solution  = await workspace.OpenSolutionAsync(solutionFileName);

            projectGraph = solution.GetProjectDependencyGraph();

            foreach (ProjectId projectId in projectGraph.GetTopologicallySortedProjects())
            {
                Stopwatch sw = Stopwatch.StartNew();

                Compilation projectCompilation = solution.GetProject(projectId).GetCompilationAsync().Result;

                sw.Stop();

                System.Diagnostics.Debug.WriteLine("Time taken compilation creation: {0}ms", sw.Elapsed.TotalMilliseconds);

                Microsoft.CodeAnalysis.Project project = solution.GetProject(projectId);

                comp.Add(project.FilePath, projectCompilation);

                // List<INamespaceOrTypeSymbol> ns = GetAllTypes(project.FilePath);

                // named.Add(project.FilePath, ns);
            }
        }
예제 #57
0
        private Microsoft.CodeAnalysis.Project GetRoslynProject(GenProject genProject)
        {
            string proj        = genProject.GenProjSetting.Project;
            var    analyzerKey = _analyzerManager.Projects.Keys
                                 .FirstOrDefault(key => key.Contains($"{proj}.csproj"));

            if (analyzerKey == null)
            {
                throw new InvalidOperationException($"Project: {proj} not found.");
            }

            ProjectAnalyzer analyzer = _analyzerManager.Projects[analyzerKey];

            Microsoft.CodeAnalysis.Project roslynProject = analyzer.AddToWorkspace(_workspace);
            return(roslynProject);
        }
        internal static async Task <LookupResult> TryLookupSymbol(string documentationCommentId, MonoDevelop.Projects.Project hintProject, CancellationToken token)
        {
            Microsoft.CodeAnalysis.Project codeAnalysisHintProject = null;
            LookupResult result = LookupResult.Failure;

            if (hintProject != null)
            {
                codeAnalysisHintProject = TypeSystemService.GetCodeAnalysisProject(hintProject);
                if (codeAnalysisHintProject != null)
                {
                    var curResult = await TryLookupSymbolInProject(codeAnalysisHintProject, documentationCommentId, token);

                    if (curResult.Success)
                    {
                        curResult.MonoDevelopProject = hintProject;
                        result = curResult;
                    }
                }
            }
            if (result.Success && result.Symbol.IsDefinedInSource())
            {
                return(result);
            }
            foreach (var ws in TypeSystemService.AllWorkspaces)
            {
                foreach (var prj in ws.CurrentSolution.Projects)
                {
                    if (prj == codeAnalysisHintProject)
                    {
                        continue;
                    }
                    var curResult = await TryLookupSymbolInProject(prj, documentationCommentId, token);

                    if (curResult.Success)
                    {
                        curResult.MonoDevelopProject = TypeSystemService.GetMonoProject(prj);
                        if (curResult.Symbol.IsDefinedInSource())
                        {
                            return(curResult);
                        }
                        result = curResult;
                    }
                }
            }

            return(result);
        }
예제 #59
0
        public async Task <Microsoft.CodeAnalysis.Project> GetCodeAnalysisProjectAsync(MonoDevelop.Projects.Project project, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parentSolution = project.ParentSolution;
            var workspace      = await GetWorkspaceAsync(parentSolution, cancellationToken);

            var projectId = workspace.GetProjectId(project);

            Microsoft.CodeAnalysis.Project proj = null;
            if (projectId != null)
            {
                proj = workspace.CurrentSolution.GetProject(projectId);
                if (proj != null)
                {
                    return(proj);
                }
            }
            //We assume that since we have projectId and project is not found in solution
            //project is being loaded(waiting MSBuild to return list of source files)
            var taskSource   = new TaskCompletionSource <Microsoft.CodeAnalysis.Project> ();
            var registration = cancellationToken.Register(() => taskSource.TrySetCanceled());
            EventHandler <WorkspaceChangeEventArgs> del = (s, e) => {
                if (e.Kind == WorkspaceChangeKind.SolutionAdded || e.Kind == WorkspaceChangeKind.SolutionReloaded)
                {
                    projectId = workspace.GetProjectId(project);
                    if (projectId == null)
                    {
                        return;
                    }
                    var proj = workspace.CurrentSolution.GetProject(projectId);
                    if (proj != null)
                    {
                        registration.Dispose();
                        taskSource.TrySetResult(proj);
                    }
                }
            };

            workspace.WorkspaceChanged += del;
            try {
                proj = await taskSource.Task;
            } finally {
                workspace.WorkspaceChanged -= del;
            }
            return(proj);
        }
예제 #60
0
        internal Project(Solution solution, RoslynProject roslynProject)
        {
            this.solution      = solution;
            this.roslynProject = roslynProject;
            isCoreLib          = roslynProject.AllProjectReferences.Count == 0;

            // validate compiler options
            var compilationOptions = roslynProject.CompilationOptions;

            if (compilationOptions.Platform != Platform.AnyCpu)
            {
                throw new Exception("Project platform must be AnyCpu: " + roslynProject.FilePath);
            }

            // get project type
            var kind = compilationOptions.OutputKind;

            if (kind == OutputKind.DynamicallyLinkedLibrary)
            {
                type    = ProjectType.Dll;
                exeType = ProjectExeType.NA;
            }
            else if (kind == OutputKind.ConsoleApplication)
            {
                type    = ProjectType.Exe;
                exeType = ProjectExeType.Console;
            }
            else if (kind == OutputKind.WindowsApplication)
            {
                type    = ProjectType.Exe;
                exeType = ProjectExeType.Windows;
            }
            else
            {
                throw new Exception("Unsuported project kind: " + roslynProject.FilePath);
            }

            // check optimization level
            optimizationLevel = compilationOptions.OptimizationLevel;
        }