コード例 #1
0
 async Task LoadExceptionList()
 {
     classes.Add("System.Exception");
     try {
         Microsoft.CodeAnalysis.Compilation compilation    = null;
         Microsoft.CodeAnalysis.ProjectId   dummyProjectId = null;
         if (IdeApp.ProjectOperations.CurrentSelectedProject != null)
         {
             compilation = await TypeSystemService.GetCompilationAsync(IdeApp.ProjectOperations.CurrentSelectedProject);
         }
         if (compilation == null)
         {
             //no need to unload this assembly context, it's not cached.
             dummyProjectId = Microsoft.CodeAnalysis.ProjectId.CreateNewId("GetExceptionsProject");
             compilation    = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("GetExceptions")
                              .AddReferences(MetadataReferenceCache.LoadReference(dummyProjectId, System.Reflection.Assembly.GetAssembly(typeof(object)).Location))                                                        //corlib
                              .AddReferences(MetadataReferenceCache.LoadReference(dummyProjectId, System.Reflection.Assembly.GetAssembly(typeof(Uri)).Location));                                                          //System.dll
         }
         var exceptionClass = compilation.GetTypeByMetadataName("System.Exception");
         foreach (var t in compilation.GlobalNamespace.GetAllTypes().Where((arg) => arg.IsDerivedFromClass(exceptionClass)))
         {
             classes.Add(t.GetFullMetadataName());
         }
         if (dummyProjectId != null)
         {
             MetadataReferenceCache.RemoveReferences(dummyProjectId);
         }
     } catch (Exception e) {
         LoggingService.LogError("Failed to obtain exceptions list in breakpoint dialog.", e);
     }
     await Runtime.RunInMainThread(() => {
         entryExceptionType.SetCodeCompletionList(classes.ToList());
     });
 }
コード例 #2
0
        public override async System.Threading.Tasks.Task <SourceCodeLocation> GetSourceCodeLocationAsync(MonoDevelop.Projects.Project project, string fixtureTypeNamespace, string fixtureTypeName, string testName, System.Threading.CancellationToken cancellationToken)
        {
            var ctx = await TypeSystemService.GetCompilationAsync(project, cancellationToken).ConfigureAwait(false);

            var cls = ctx?.Assembly?.GetTypeByMetadataName(string.IsNullOrEmpty(fixtureTypeNamespace) ? fixtureTypeName : fixtureTypeNamespace + "." + fixtureTypeName);

            if (cls == null)
            {
                return(null);
            }
            if (cls.Name != testName)
            {
                foreach (var met in cls.GetMembers(testName).OfType <IMethodSymbol> ())
                {
                    var loc = met.Locations.FirstOrDefault(l => l.IsInSource);
                    return(ConvertToSourceCodeLocation(loc));
                }

                int idx = testName != null?testName.IndexOf('(') : -1;

                if (idx > 0)
                {
                    testName = testName.Substring(0, idx);
                    foreach (var met in cls.GetMembers(testName).OfType <IMethodSymbol> ())
                    {
                        var loc = met.Locations.FirstOrDefault(l => l.IsInSource);
                        return(ConvertToSourceCodeLocation(loc));
                    }
                }
            }
            var classLoc = cls.Locations.FirstOrDefault(l => l.IsInSource);

            return(ConvertToSourceCodeLocation(classLoc));
        }
        void LoadExceptionList()
        {
            classes.Add("System.Exception");
            if (IdeApp.ProjectOperations.CurrentSelectedProject != null)
            {
                var compilation    = TypeSystemService.GetCompilationAsync(IdeApp.ProjectOperations.CurrentSelectedProject).Result;
                var exceptionClass = compilation.GetTypeByMetadataName("System.Exception");
                foreach (var t in compilation.GlobalNamespace.GetAllTypes().Where((arg) => arg.IsDerivedFromClass(exceptionClass)))
                {
                    classes.Add(t.GetFullMetadataName());
                }
            }
            else
            {
                //no need to unload this assembly context, it's not cached.
                var dummyProjectId = Microsoft.CodeAnalysis.ProjectId.CreateNewId("GetExceptionsProject");
                var compilation    = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("GetExceptions")
                                     .AddReferences(MetadataReferenceCache.LoadReference(dummyProjectId, System.Reflection.Assembly.GetAssembly(typeof(object)).Location))                                               //corlib
                                     .AddReferences(MetadataReferenceCache.LoadReference(dummyProjectId, System.Reflection.Assembly.GetAssembly(typeof(Uri)).Location));                                                 //System.dll

                var exceptionClass = compilation.GetTypeByMetadataName("System.Exception");
                foreach (var t in compilation.GlobalNamespace.GetAllTypes().Where((arg) => arg.IsDerivedFromClass(exceptionClass)))
                {
                    classes.Add(t.GetFullMetadataName());
                }
                MetadataReferenceCache.RemoveReferences(dummyProjectId);
            }
            entryExceptionType.SetCodeCompletionList(classes.ToList());
        }
コード例 #4
0
        MetadataReference GetProjectReference(AssemblyName parsed)
        {
            if (project == null)
            {
                return(null);
            }

            var dllName = parsed.Name + ".dll";

            foreach (var reference in project.References)
            {
                if (reference.ReferenceType == ReferenceType.Package || reference.ReferenceType == ReferenceType.Assembly)
                {
                    foreach (string refPath in reference.GetReferencedFileNames(null))
                    {
                        if (Path.GetFileName(refPath) == dllName)
                        {
                            return(LoadMetadataReference(refPath));
                        }
                    }
                }
                else
                if (reference.ReferenceType == ReferenceType.Project && parsed.Name == reference.Reference)
                {
                    var p = reference.ResolveProject(project.ParentSolution) as DotNetProject;
                    if (p == null)
                    {
                        continue;
                    }
                    return(TypeSystemService.GetCompilationAsync(p).Result.ToMetadataReference());
                }
            }

            return(null);
        }
コード例 #5
0
        IEnumerable <MetadataReference> GetReferencedAssemblies()
        {
            var references = new HashSet <MetadataReference> ();

            if (project != null)
            {
                var task = TypeSystemService.GetCompilationAsync(project);
                if (task.Result != null)
                {
                    references.Add(task.Result.ToMetadataReference());
                }
            }
            if (doc != null)
            {
                foreach (var asm in doc.Info.Assemblies.Select(a => a.Name).Select(name => GetReferencedAssembly(name)))
                {
                    references.Add(asm);
                }
            }

            foreach (var asm in GetRegisteredAssemblies().Select(name => GetReferencedAssembly(name)))
            {
                references.Add(asm);
            }

            references.Remove(null);

            return(references);
        }
コード例 #6
0
        public static void BuildChildNodes(ITreeBuilder builder, Project project)
        {
            if (project is DotNetProject)
            {
                builder.AddChild(((DotNetProject)project).References);
            }
            bool publicOnly = builder.Options ["PublicApiOnly"];
            var  dom        = TypeSystemService.GetCompilationAsync(project).Result;

            if (dom == null)
            {
                return;
            }
            bool             nestedNamespaces = builder.Options ["NestedNamespaces"];
            HashSet <string> addedNames       = new HashSet <string> ();

            foreach (var ns in dom.Assembly.GlobalNamespace.GetNamespaceMembers())
            {
                if (nestedNamespaces)
                {
                    if (!addedNames.Contains(ns.Name))
                    {
                        builder.AddChild(new ProjectNamespaceData(project, ns));
                        addedNames.Add(ns.Name);
                    }
                }
                else
                {
                    FillNamespaces(builder, project, ns);
                }
            }
            builder.AddChildren(dom.Assembly.GlobalNamespace.GetTypeMembers()
                                .Where(type => !publicOnly || type.DeclaredAccessibility == Accessibility.Public)
                                .Select(type => new ClassData(project, type)));
        }
コード例 #7
0
            public TypeDataProvider(MonoDevelop.Projects.DotNetProject project)
            {
                TypeNamesList = new List <string> ();
                var ctx = TypeSystemService.GetCompilationAsync(project).Result;

                TypesList = new List <INamedTypeSymbol> (ctx.GetAllTypesInMainAssembly());
                foreach (var typeDef in TypesList)
                {
                    TypeNamesList.Add(Ambience.EscapeText(typeDef.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
                }
            }
コード例 #8
0
        protected override SourceCodeLocation GetSourceCodeLocation(string fixtureTypeNamespace, string fixtureTypeName, string methodName)
        {
            if (string.IsNullOrEmpty(fixtureTypeName) || string.IsNullOrEmpty(fixtureTypeName))
            {
                return(null);
            }
            var csc  = new CancellationTokenSource();
            var task = TypeSystemService.GetCompilationAsync(project, csc.Token);

            task.Wait(2000);
            if (!task.IsCompleted)
            {
                csc.Cancel();
                return(null);
            }
            var ctx = task.Result;
            var cls = ctx?.Assembly?.GetTypeByMetadataName(string.IsNullOrEmpty(fixtureTypeNamespace) ? fixtureTypeName : fixtureTypeNamespace + "." + fixtureTypeName);

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

            if (cls.Name != methodName)
            {
                foreach (var met in cls.GetMembers().OfType <IMethodSymbol> ())
                {
                    if (met.Name == methodName)
                    {
                        var loc = met.Locations.FirstOrDefault(l => l.IsInSource);
                        return(ConvertToSourceCodeLocation(loc));
                    }
                }

                int idx = methodName != null?methodName.IndexOf('(') : -1;

                if (idx > 0)
                {
                    methodName = methodName.Substring(0, idx);
                    foreach (var met in cls.GetMembers().OfType <IMethodSymbol> ())
                    {
                        if (met.Name == methodName)
                        {
                            var loc = met.Locations.FirstOrDefault(l => l.IsInSource);
                            return(ConvertToSourceCodeLocation(loc));
                        }
                    }
                }
            }
            var classLoc = cls.Locations.FirstOrDefault(l => l.IsInSource);

            return(ConvertToSourceCodeLocation(classLoc));
        }
コード例 #9
0
        async Task <INamedTypeSymbol> FindController(MonoDevelop.Projects.Project project, string name)
        {
            var compilation = await TypeSystemService.GetCompilationAsync(project);

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

            return(compilation.GetAllTypesInMainAssembly()
                   .FirstOrDefault(symbol => symbol.Name == name + "Controller"));
        }
コード例 #10
0
        public async Task TestLoadingSolution()
        {
            string solFile = Util.GetSampleProject("console-project", "ConsoleProject.sln");
            var    sol     = (Projects.Solution) await Services.ProjectService.ReadWorkspaceItem(Util.GetMonitor(), solFile);

            await TypeSystemServiceTestExtensions.LoadSolution(sol);

            var compilation = await TypeSystemService.GetCompilationAsync(sol.GetAllProjects().First());

            var programType = compilation.GetTypeByMetadataName("ConsoleProject.Program");

            Assert.IsNotNull(programType);
        }
コード例 #11
0
        public Compilation GetParserContext()
        {
            System.Threading.Tasks.Task <Compilation> task;
            do
            {
                task = TypeSystemService.GetCompilationAsync(Project);
                task.Wait(500);
            } while (!task.IsCompleted);

            var dom = task.Result;

            if (dom != null && needsUpdate)
            {
                needsUpdate = false;
            }
            return(dom);
        }
コード例 #12
0
        /// <summary>
        /// Adds the dependency to the project and returns true if the dependency was added to the project
        /// </summary>
        protected sealed override async Task <bool> OnAddToProject(CancellationToken token)
        {
            int  tryCount   = 1;
            bool keepTrying = true;

            while (keepTrying)
            {
                try {
                    if (tryCount > 1)
                    {
                        LoggingService.LogInfo("Retrying to add code dependency...");
                    }
                    else
                    {
                        LoggingService.LogInfo("Adding code dependency '{0}' to '{1}'...", this, this.Service.Project.Name);
                    }

                    this.compilation = await TypeSystemService.GetCompilationAsync(this.Service.Project).ConfigureAwait(false);

                    if (this.compilation == null)
                    {
                        LoggingService.LogInternalError("Could not get compilation object.", null);
                        return(false);
                    }

                    this.InitLookupTypes(token, this.lookupTypes.Keys.ToArray());

                    var result = await Runtime.RunInMainThread <bool> (
                        () => this.AddCodeToProject (token)
                        );

                    LoggingService.LogInfo(result ? "Code dependency added." : "Code dependency was not added.");
                    return(result);
                } catch (SolutionVersionMismatchException) {
                    tryCount++;
                }

                keepTrying = tryCount <= 3;
            }

            return(false);
        }
コード例 #13
0
        public override void BuildChildNodes(ITreeBuilder builder, object dataObject)
        {
            Project project    = (Project)dataObject;
            bool    publicOnly = Widget.PublicApiOnly;
            var     dom        = TypeSystemService.GetCompilationAsync(project).Result;

            if (dom == null)
            {
                return;
            }
            bool             nestedNamespaces = builder.Options ["NestedNamespaces"];
            HashSet <string> addedNames       = new HashSet <string> ();

            foreach (var ns in dom.Assembly.GlobalNamespace.GetNamespaceMembers())
            {
                FillNamespaces(builder, project, ns);
            }
            builder.AddChildren(dom.Assembly.GlobalNamespace.GetTypeMembers()
                                .Where(type => !publicOnly || type.DeclaredAccessibility == Microsoft.CodeAnalysis.Accessibility.Public));
        }
コード例 #14
0
        async Task <IEnumerable <MetadataReference> > GetReferencedAssemblies(CancellationToken token)
        {
            var references = new HashSet <MetadataReference> ();

            if (project != null)
            {
                var result = await TypeSystemService.GetCompilationAsync(project, token);

                if (result != null)
                {
                    references.Add(result.ToMetadataReference());
                }
            }

            var tasks = new List <Task <MetadataReference> > ();

            if (doc != null)
            {
                foreach (var t in doc.Info.Assemblies.Select(a => a.Name).Select(name => GetReferencedAssembly(name, token)))
                {
                    tasks.Add(t);
                }
            }

            foreach (var t in GetRegisteredAssemblies().Select(name => GetReferencedAssembly(name, token)))
            {
                tasks.Add(t);
            }

            MetadataReference[] assemblies = await Task.WhenAll(tasks);

            foreach (var asm in assemblies)
            {
                references.Add(asm);
            }

            references.Remove(null);

            return(references);
        }
コード例 #15
0
        /// <summary>
        /// Removes the dependency from the project and returns true if the dependency was removed
        /// </summary>
        protected sealed override async Task <bool> OnRemoveFromProject(CancellationToken token)
        {
            int  tryCount   = 1;
            bool keepTrying = true;

            while (keepTrying)
            {
                try {
                    if (tryCount > 1)
                    {
                        LoggingService.LogInfo("Retrying to remove code dependency...");
                    }
                    else
                    {
                        LoggingService.LogInfo("Removing code dependency '{0}' from '{1}'...", this, this.Service.Project.Name);
                    }

                    var compilation = await TypeSystemService.GetCompilationAsync(this.Service.Project).ConfigureAwait(false);

                    if (compilation == null)
                    {
                        LoggingService.LogInternalError("Could not get compilation object.", null);
                        return(false);
                    }

                    this.InitLookupTypes(compilation, token, this.lookupTypes.Keys.ToArray());

                    var result = await this.RemoveCodeFromProject(token).ConfigureAwait(false);

                    LoggingService.LogInfo(result ? "Code dependency removed." : "Code dependency was not removed.");
                    return(result);
                } catch (SolutionVersionMismatchException) {
                    tryCount++;
                }

                keepTrying = tryCount <= 3;
            }

            return(false);
        }
コード例 #16
0
 void FillClasses()
 {
     try {
         var ctx = TypeSystemService.GetCompilationAsync(project).Result;
         if (ctx == null)
         {
             // Project not found in parser database
             return;
         }
         foreach (var c in ctx.Assembly.GlobalNamespace.GetTypeMembers())
         {
             foreach (var m in c.GetMembers().OfType <IMethodSymbol> ())
             {
                 if (m.IsStatic && m.Name == "Main")
                 {
                     classListStore.AppendValues(c.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat));
                 }
             }
         }
         classListFilled = true;
     } catch (InvalidOperationException) {
         // Project not found in parser database
     }
 }
コード例 #17
0
        public async Task <List <ClassDefinition> > ProcessAsync(MonoDevelop.Projects.Project project, IProgress <TreeBuilderProgress> progress = null)
        {
            var classes     = new Dictionary <ITypeSymbol, ClassDefinition>();
            var compilation = await TypeSystemService.GetCompilationAsync(project);

            var types = compilation.GetAllTypesInMainAssembly();

            progress?.Report(new TreeBuilderProgress {
                totalClasses = types.Count()
            });

            for (int i = 0; i < types.Count(); i++)
            {
                var type       = types.ElementAt(i);
                var definition = GetValueOrCreate(type, classes);

                if (type.IsAbstract && definition.ClassType == ClassType.Class)
                {
                    definition.ClassType = ClassType.Abstract;
                }

                foreach (var iface in type.Interfaces)
                {
                    var interfaceDefinition = GetValueOrCreate(iface, classes);
                    interfaceDefinition.ClassType = ClassType.Interface;
                    definition.Interfaces.Add(interfaceDefinition);
                }

                foreach (var baseClass in type.GetAllBaseClasses())
                {
                    if (!baseClass.IsDefinedInSource())
                    {
                        continue;
                    }

                    var baseDefinition = GetValueOrCreate(baseClass, classes);
                    definition.BaseClasses.Add(baseDefinition);
                }

                HashSet <ClassDefinition> dependencies = new HashSet <ClassDefinition>();
                var syntaxDeclarations = type.GetDeclarations();
                foreach (var declaration in syntaxDeclarations)
                {
                    var semanticModel = compilation.GetSemanticModel(declaration.SyntaxTree);
                    var descendants   = declaration.GetSyntax().DescendantNodes();
                    foreach (var descendant in descendants)
                    {
                        ITypeSymbol usedType = semanticModel.GetTypeInfo(descendant).Type;
                        usedType = usedType as INamedTypeSymbol;
                        if (usedType != null && usedType.IsDefinedInSource())
                        {
                            var def = GetValueOrCreate(usedType, classes);
                            if (def != definition && !definition.Interfaces.Contains(def) && !definition.BaseClasses.Contains(def))
                            {
                                dependencies.Add(def);
                            }
                        }
                    }
                }
                definition.Dependencies.AddRange(dependencies);

                progress?.Report(new TreeBuilderProgress {
                    totalClasses = types.Count(), doneClasses = i + 1
                });
            }

            return(classes.Values.ToList());
        }
コード例 #18
0
        void Init()
        {
            TestId = test.Id.ToString();
            TestSourceCodeDocumentId = test.FullyQualifiedName;
            if (!string.IsNullOrEmpty(test.CodeFilePath))
            {
                sourceCodeLocation = new SourceCodeLocation(test.CodeFilePath, test.LineNumber, 0);
            }
            else
            {
                TypeSystemService.GetCompilationAsync(Project).ContinueWith((t) => {
                    var dotIndex     = test.FullyQualifiedName.LastIndexOf(".", StringComparison.Ordinal);
                    var className    = test.FullyQualifiedName.Remove(dotIndex);
                    var methodName   = test.FullyQualifiedName.Substring(dotIndex + 1);
                    var bracketIndex = methodName.IndexOf('(');
                    if (bracketIndex != -1)
                    {
                        methodName = methodName.Remove(bracketIndex).Trim();
                    }
                    var compilation = t.Result;
                    if (compilation == null)
                    {
                        return;
                    }
                    var cls = compilation.GetTypeByMetadataName(className);
                    if (cls == null)
                    {
                        return;
                    }
                    IMethodSymbol method = null;
                    while ((method = cls.GetMembers(methodName).OfType <IMethodSymbol> ().FirstOrDefault()) == null)
                    {
                        cls = cls.BaseType;
                        if (cls == null)
                        {
                            return;
                        }
                    }
                    if (method == null)
                    {
                        return;
                    }
                    var source = method.Locations.FirstOrDefault(l => l.IsInSource);
                    if (source == null)
                    {
                        return;
                    }
                    var line           = source.GetLineSpan();
                    sourceCodeLocation = new SourceCodeLocation(source.SourceTree.FilePath, line.StartLinePosition.Line, line.StartLinePosition.Character);
                }).Ignore();
            }
            int index = test.FullyQualifiedName.LastIndexOf('.');

            if (index > 0)
            {
                FixtureTypeName = test.FullyQualifiedName.Substring(0, index);

                index = FixtureTypeName.LastIndexOf('.');
                if (index > 0)
                {
                    FixtureTypeNamespace = FixtureTypeName.Substring(0, index);
                    FixtureTypeName      = FixtureTypeName.Substring(index + 1);
                }
                else
                {
                    FixtureTypeNamespace = string.Empty;
                }
            }
            else
            {
                FixtureTypeNamespace = string.Empty;
                FixtureTypeName      = string.Empty;
            }
            name = test.DisplayName;
            var obsoletePrefix = string.IsNullOrEmpty(FixtureTypeNamespace) ? FixtureTypeName : FixtureTypeNamespace + "." + FixtureTypeName;

            if (test.DisplayName.StartsWith(obsoletePrefix, StringComparison.Ordinal) && test.DisplayName [obsoletePrefix.Length] == '.')
            {
                name = test.DisplayName.Substring(obsoletePrefix.Length + 1);
            }
        }