Example #1
0
 void UnloadAdhocProject()
 {
     CancelEnsureAnalysisDocumentIsOpen();
     lock (adhocProjectLock) {
         if (adhocProject == null)
         {
             return;
         }
         if (adhocSolution != null)
         {
             TypeSystemService.Unload(adhocSolution);
             adhocSolution.Dispose();
             adhocSolution = null;
         }
         adhocProject = null;
     }
 }
        public async Task CancelledParsedProjectionIsIgnored()
        {
            string solFile = Util.GetSampleProject("console-project", "ConsoleProject.sln");

            var parsers = TypeSystemService.Parsers;

            try {
                var projectionParser = new TypeSystemParserNode();
                projectionParser.BuildActions = new [] { "Compile" };
                projectionParser.MimeType     = "text/csharp";

                var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
                var field = typeof(TypeExtensionNode).GetField("type", flags);
                field.SetValue(projectionParser, typeof(ProjectionParser));

                var newParsers = new List <TypeSystemParserNode> ();
                newParsers.Add(projectionParser);
                TypeSystemService.Parsers = newParsers;

                using (var sol = (Solution)await Services.ProjectService.ReadWorkspaceItem(Util.GetMonitor(), solFile)) {
                    using (var ws = await TypeSystemServiceTestExtensions.LoadSolution(sol)) {
                        var source1 = new CancellationTokenSource();
                        var source2 = new CancellationTokenSource();

                        var options = new ParseOptions {
                            FileName = "first.xaml.cs"
                        };
                        var task1 = TypeSystemService.ParseProjection(options, "text/csharp", source1.Token);
                        source1.Cancel();

                        options = new ParseOptions {
                            FileName = "second.xaml.cs"
                        };
                        var task2 = TypeSystemService.ParseProjection(options, "text/csharp", source2.Token);

                        var result1 = await task1;
                        var result2 = await task2;

                        Assert.IsNotNull(result2);
                        Assert.IsNull(result1);
                    }
                }
            } finally {
                TypeSystemService.Parsers = parsers;
            }
        }
        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);
        }
        public override bool TryGetWorkspace(ITextBuffer textBuffer, out Workspace workspace)
        {
            if (textBuffer == null)
            {
                throw new ArgumentNullException(nameof(textBuffer));
            }

            // We do a best effort approach in this method to get the workspace that belongs to the TextBuffer.
            // Below we try and find the project and then the solution that contains the given text buffer. If
            // we're able to find both the project and solution then we use the solution to look up the corresponding
            // Workspace using MonoDevelops TypeSystemService.

            var hostProject = (DotNetProject)_projectService.GetHostProject(textBuffer);

            if (hostProject == null)
            {
                // Does not have a host project.
                workspace = null;
                return(false);
            }

            var hostSolution = hostProject.ParentSolution;

            if (hostSolution == null)
            {
                // Project does not have a solution
                workspace = null;
                return(false);
            }

            workspace = TypeSystemService.GetWorkspace(hostSolution);

            // Workspace cannot be null at this point. If TypeSystemService.GetWorkspace isn't able to find a corresponding
            // workspace it returns an empty workspace. Therefore, in order to see if we have a valid workspace we need to
            // cross-check it against the list of active non-empty workspaces.

            if (!TypeSystemService.AllWorkspaces.Contains(workspace))
            {
                // We were returned the empty workspace which is equivalent to us not finding a valid workspace for our text buffer.
                workspace = null;
                return(false);
            }

            return(true);
        }
Example #5
0
        void HandleAddition(object sender, ProjectFileEventArgs args)
        {
            foreach (var e in args)
            {
                CheckForBom(e.ProjectFile.Name);

                if (!project.Loading && !project.IsCompileable(e.ProjectFile.Name) &&
                    e.ProjectFile.BuildAction == BuildAction.Compile)
                {
                    e.ProjectFile.BuildAction = BuildAction.None;
                }

                if (!project.Loading && e.ProjectFile.BuildAction == BuildAction.Compile)
                {
                    TypeSystemService.ParseFile(project, e.ProjectFile.Name);
                }
            }
        }
Example #6
0
        public virtual IProjectContent GetProjectContext()
        {
            if (Project == null)
            {
                if (singleFileContext == null)
                {
                    singleFileContext = new ICSharpCode.NRefactory.CSharp.CSharpProjectContent();
                    singleFileContext = singleFileContext.AddAssemblyReferences(new [] { Mscorlib, System, SystemCore });
                }
                if (parsedDocument != null)
                {
                    return(singleFileContext.AddOrUpdateFiles(parsedDocument.ParsedFile));
                }
                return(singleFileContext);
            }

            return(TypeSystemService.GetProjectContext(Project));
        }
Example #7
0
 void ListenToProjectLoad(Project project)
 {
     if (currentWrapper != null)
     {
         currentWrapper.Loaded -= HandleInLoadChanged;
         currentWrapper         = null;
     }
     if (project != null)
     {
         var wrapper = TypeSystemService.GetProjectContentWrapper(project);
         wrapper.Loaded += HandleInLoadChanged;
         currentWrapper  = wrapper;
         RunWhenLoaded(delegate {
             currentWrapper.RequestLoad();
         });
     }
     StartReparseThread();
 }
Example #8
0
        static async void OnWorkspaceItemClosed(object sender, WorkspaceItemEventArgs args)
        {
            if (args.Item is MonoDevelop.Projects.Solution sol)
            {
                var ws = await TypeSystemService.GetWorkspaceAsync(sol);

                var solId = ws.GetSolutionId(sol);

                lock (lockObject) {
                    if (cachedUntilViewCreated == null)
                    {
                        return;
                    }

                    cachedUntilViewCreated = cachedUntilViewCreated.Where(x => x.Value.Solution.Id != solId).ToDictionary(x => x.Key, x => x.Value);
                }
            }
        }
        void LoadSolutionContents(Solution sln)
        {
            loadedSlns.Add(sln);

            // Load all tags that are stored in pidb files
            foreach (Project p in sln.GetAllProjects())
            {
                var pContext = TypeSystemService.GetProjectContext(p);
                if (pContext == null)
                {
                    continue;
                }
                foreach (ProjectFile file in p.Files)
                {
                    UpdateCommentTags(sln, file.Name, GetSpecialComments(pContext, file.Name));
                }
            }
        }
Example #10
0
        static CSharpFeaturesTextEditorExtension()
        {
            GoToDefinitionService.TryNavigateToSymbol = delegate(ISymbol symbol, Microsoft.CodeAnalysis.Project project, bool usePreviewTab) {
                RefactoringService.RoslynJumpToDeclaration(symbol, TypeSystemService.GetMonoProject(project));
                return(true);
            };

            GoToDefinitionService.TryNavigateToSpan = delegate(Workspace workspace, DocumentId documentId, Microsoft.CodeAnalysis.Text.TextSpan textSpan, bool usePreviewTab) {
                var project = workspace.CurrentSolution.GetProject(documentId.ProjectId);
                if (project == null)
                {
                    return(false);
                }
                var    fileName = project.GetDocument(documentId).FilePath;
                var    offset   = textSpan.Start;
                string projectedName;
                int    projectedOffset;
                if (TypeSystemService.GetWorkspace(TypeSystemService.GetMonoProject(project).ParentSolution).TryGetOriginalFileFromProjection(fileName, offset, out projectedName, out projectedOffset))
                {
                    fileName = projectedName;
                    offset   = projectedOffset;
                }
                IdeApp.Workbench.OpenDocument(new FileOpenInformation(fileName, TypeSystemService.GetMonoProject(project))
                {
                    Offset = offset
                });
                return(true);
            };

            GoToDefinitionService.DisplayMultiple = delegate(IEnumerable <Tuple <Solution, ISymbol, Location> > list) {
                using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true)) {
                    foreach (var part in list)
                    {
                        if (monitor.CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        monitor.ReportResult(GotoDeclarationHandler.GetJumpTypePartSearchResult(part.Item2, part.Item3));
                    }
                }
            };
        }
        public ICompilation ResolveAssemblyDom(string assemblyName)
        {
            var parsed = SystemAssemblyService.ParseAssemblyName(assemblyName);

            if (string.IsNullOrEmpty(parsed.Name))
            {
                return(null);
            }

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

            foreach (var reference in References)
            {
                if (reference.ReferenceType == ReferenceType.Package || reference.ReferenceType == ReferenceType.Assembly)
                {
                    foreach (string refPath in reference.GetReferencedFileNames(null))
                    {
                        if (Path.GetFileName(refPath) == dllName)
                        {
                            return(new ICSharpCode.NRefactory.TypeSystem.Implementation.SimpleCompilation(TypeSystemService.LoadAssemblyContext(TargetRuntime, TargetFramework, refPath)));
                        }
                    }
                }
                else if (reference.ReferenceType == ReferenceType.Project && parsed.Name == reference.Reference)
                {
                    var p = ParentSolution.FindProjectByName(reference.Reference) as DotNetProject;
                    if (p == null)
                    {
                        LoggingService.LogWarning("Project '{0}' referenced from '{1}' could not be found", reference.Reference, this.Name);
                        continue;
                    }
                    return(TypeSystemService.GetCompilation(p));
                }
            }

            string path = GetAssemblyPath(assemblyName);

            if (path != null)
            {
                return(new ICSharpCode.NRefactory.TypeSystem.Implementation.SimpleCompilation(TypeSystemService.LoadAssemblyContext(TargetRuntime, TargetFramework, path)));
            }
            return(null);
        }
        static void HandleDomReferencesUpdated(object sender, ProjectReferenceEventArgs e)
        {
            var project = (DotNetProject)sender;
            var dom     = TypeSystemService.GetProjectContentWrapper(project);

            if (dom == null)
            {
                return;
            }
            NSObjectProjectInfo info;

            lock (infos) {
                if (!infos.TryGetValue(dom, out info))
                {
                    return;
                }
            }
            info.SetNeedsUpdating();
        }
Example #13
0
			public override async void Activate ()
			{
				var filePath = result.NavigableItem.Document.FilePath;
				var offset = result.NavigableItem.SourceSpan.Start;

				var proj = TypeSystemService.GetMonoProject (result.NavigableItem.Document.Project);
				if (proj?.ParentSolution != null) {
					string projectedName;
					int projectedOffset;
					if (TypeSystemService.GetWorkspace (proj.ParentSolution).TryGetOriginalFileFromProjection (filePath, offset, out projectedName, out projectedOffset)) {
						filePath = projectedName;
						offset = projectedOffset;
					}
				}

				await IdeApp.Workbench.OpenDocument (new FileOpenInformation (filePath, proj) {
					Offset = offset
				});
			}
        public void Run()
        {
            using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true)) {
                foreach (var project in IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllProjects())
                {
                    var comp = TypeSystemService.GetCompilation(project);
                    foreach (var type in comp.MainAssembly.GetAllTypeDefinitions())
                    {
                        if (!type.IsStatic)
                        {
                            continue;
                        }
                        foreach (var method in type.GetMethods(m => m.IsStatic))
                        {
                            if (!method.IsExtensionMethod)
                            {
                                continue;
                            }
                            IType[] ifTypes;
                            var     typeDef = comp.Import(entity);
                            if (typeDef == null)
                            {
                                continue;
                            }
                            if (!CSharpResolver.IsEligibleExtensionMethod(typeDef, method, true, out ifTypes))
                            {
                                continue;
                            }

                            var tf    = TextFileProvider.Instance.GetReadOnlyTextEditorData(method.Region.FileName);
                            var start = tf.LocationToOffset(method.Region.Begin);
                            tf.SearchRequest.SearchPattern = method.Name;
                            var sr = tf.SearchForward(start);
                            if (sr != null)
                            {
                                start = sr.Offset;
                            }
                            monitor.ReportResult(new MemberReference(method, method.Region, start, method.Name.Length));
                        }
                    }
                }
            }
        }
Example #15
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);
        }
        public async Task DiagnosticEnableSourceAnalysisChanged()
        {
            var old = IdeApp.Preferences.EnableSourceAnalysis;

            Projects.Solution sol = null;
            try {
                int expectedUpdates = 5;
                IdeApp.Preferences.EnableSourceAnalysis.Value = true;

                var tuple = await GatherDiagnosticsNoDispose <bool> (OneFromEach, (ext, tcs) => {
                    --expectedUpdates;
                    if (expectedUpdates == 4)
                    {
                        Assert.AreEqual(0, ext.QuickTasks.Length);
                    }

                    if (expectedUpdates == 1)
                    {
                        IdeApp.Preferences.EnableSourceAnalysis.Value = false;

                        Assert.AreEqual(3, ext.QuickTasks.Length);
                        for (int i = 0; i < 3; ++i)
                        {
                            AssertExpectedDiagnostic(OneFromEachDiagnostics [i], ext.QuickTasks [i]);
                        }
                    }
                    if (expectedUpdates == 0)
                    {
                        Assert.AreEqual(0, ext.QuickTasks.Length);
                        tcs.SetResult(true);
                    }
                });

                sol = tuple.Item2;
            } finally {
                IdeApp.Preferences.EnableSourceAnalysis.Value = old;
                if (sol != null)
                {
                    TypeSystemService.Unload(sol);
                }
            }
        }
        static Document Setup(string input)
        {
            var tww     = new TestWorkbenchWindow();
            var content = new TestViewContent();

            var project = new DotNetAssemblyProject("C#");

            project.Name = "test";
            project.References.Add(new ProjectReference(ReferenceType.Package, "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
            project.References.Add(new ProjectReference(ReferenceType.Package, "System.Core"));

            project.FileName = "test.csproj";

            var wrapper = TypeSystemService.LoadProject(project);

            wrapper.EnsureReferencesAreLoaded();
            wrapper.ReconnectAssemblyReferences();
            content.Project = project;

            tww.ViewContent     = content;
            content.ContentName = "a.cs";
            content.GetTextEditorData().Document.MimeType = "text/x-csharp";
            var doc = new Document(tww);

            var text   = input;
            int endPos = text.IndexOf('$');

            if (endPos >= 0)
            {
                text = text.Substring(0, endPos) + text.Substring(endPos + 1);
            }

            content.Text           = text;
            content.CursorPosition = Math.Max(0, endPos);

            var compExt = new CSharpCompletionTextEditorExtension();

            compExt.Initialize(doc);
            content.Contents.Add(compExt);
            doc.UpdateParseDocument();
            return(doc);
        }
Example #18
0
        public async Task TestWorkspaceImmediatelyAvailable()
        {
            //Initialize IdeApp so IdeApp.Workspace is not null
            if (!IdeApp.IsInitialized)
            {
                IdeApp.Initialize(new ProgressMonitor());
            }
            string solFile = Util.GetSampleProject("console-project", "ConsoleProject.sln");
            var    tcs     = new TaskCompletionSource <bool> ();

            IdeApp.Workspace.SolutionLoaded += (s, e) => {
                var workspace = TypeSystemService.GetWorkspace(e.Solution);
                Assert.IsNotNull(workspace);
                Assert.AreNotSame(workspace, TypeSystemService.emptyWorkspace);
                tcs.SetResult(true);
            };
            await IdeApp.Workspace.OpenWorkspaceItem(solFile);

            await tcs.Task;
        }
Example #19
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));
        }
 IEnumerable <Project> CollectProjects()
 {
     projectOnly = true;
     foreach (var o in entities)
     {
         var entity = o as IEntity;
         if (entity != null)
         {
             Collect(TypeSystemService.GetProject(entity), entity);
             continue;
         }
         var par = o as IParameter;
         if (par != null)
         {
             Collect(TypeSystemService.GetProject(par.Owner), par.Owner);
             continue;
         }
     }
     return(collectedProjects);
 }
Example #21
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 csc = new CancellationTokenSource();
            var ctx = await TypeSystemService.GetCompilationAsync(project, csc.Token).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().OfType <IMethodSymbol> ())
                {
                    if (met.Name == testName)
                    {
                        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().OfType <IMethodSymbol> ())
                    {
                        if (met.Name == testName)
                        {
                            var loc = met.Locations.FirstOrDefault(l => l.IsInSource);
                            return(ConvertToSourceCodeLocation(loc));
                        }
                    }
                }
            }
            var classLoc = cls.Locations.FirstOrDefault(l => l.IsInSource);

            return(ConvertToSourceCodeLocation(classLoc));
        }
Example #22
0
        IEnumerable <FileList> CollectFiles()
        {
            projectOnly = false;
            foreach (var o in entities)
            {
                if (o is INamespace)
                {
                    Collect(null, null);
                    continue;
                }

                var par = o as IParameter;
                if (par != null)
                {
                    Collect(TypeSystemService.GetProject(par.Owner), par.Owner);
                }
                else
                {
                    var entity = o as IEntity;
                    if (entity == null)
                    {
                        continue;
                    }
                    Collect(TypeSystemService.GetProject(entity), entity);
                }

                if (searchProjectAdded)
                {
                    break;
                }
            }
            foreach (var project in collectedProjects)
            {
                yield return(new FileList(project, TypeSystemService.GetProjectContext(project), project.Files.Select(f => f.FilePath)));
            }

            foreach (var files in collectedFiles)
            {
                yield return(new FileList(files.Key, TypeSystemService.GetProjectContext(files.Key), files.Value.Select(f => (FilePath)f)));
            }
        }
        async Task <MetadataReference> GetProjectReference(AssemblyName parsed, CancellationToken token)
        {
            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;
                    }
                    var result = await TypeSystemService.GetCompilationAsync(p);

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

            return(null);
        }
Example #24
0
        void OnFileAdded(object sender, ProjectFileEventArgs e)
        {
            foreach (ProjectFileEventInfo args in e)
            {
                var docId = TypeSystemService.GetDocumentId(args.Project, args.ProjectFile.Name);
                if (docId == null)
                {
                    continue;
                }
                var doc = TypeSystemService.GetCodeAnalysisDocument(docId);
                if (doc == null)
                {
                    continue;
                }

                string dir = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "stetic"), "deleted-designs");
                if (!Directory.Exists(dir) || Directory.GetFiles(dir).Length == 0)
                {
                    continue;
                }
                var semanticModel = doc.GetSemanticModelAsync().Result;
                if (semanticModel == null)
                {
                    continue;
                }

                foreach (var classDeclaration in semanticModel.SyntaxTree.GetRoot().DescendantNodesAndSelf(child => !(child is BaseTypeDeclarationSyntax)).OfType <ClassDeclarationSyntax> ())
                {
                    var    c    = semanticModel.GetDeclaredSymbol(classDeclaration);
                    string path = Path.Combine(dir, c.ToDisplayString(Microsoft.CodeAnalysis.SymbolDisplayFormat.CSharpErrorMessageFormat) + ".xml");
                    if (!System.IO.File.Exists(path))
                    {
                        continue;
                    }
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(path);
                    AddNewComponent(xmldoc.DocumentElement);
                    System.IO.File.Delete(path);
                }
            }
        }
        async Task LoadExceptionList()
        {
            classes.Add("System.Exception");
            try {
                Microsoft.CodeAnalysis.Compilation compilation = null;
                MonoDevelopWorkspace workspace = null;

                var project = IdeApp.ProjectOperations.CurrentSelectedProject;
                if (project != null)
                {
                    var roslynProj = TypeSystemService.GetProject(project);
                    if (roslynProj != null)
                    {
                        workspace   = (MonoDevelopWorkspace)roslynProj.Solution.Workspace;
                        compilation = await roslynProj.GetCompilationAsync();
                    }
                }

                if (compilation == null)
                {
                    var service = workspace.MetadataReferenceManager;
                    var corlib  = service.GetOrCreateMetadataReferenceSnapshot(System.Reflection.Assembly.GetAssembly(typeof(object)).Location, MetadataReferenceProperties.Assembly);
                    var system  = service.GetOrCreateMetadataReferenceSnapshot(System.Reflection.Assembly.GetAssembly(typeof(Uri)).Location, MetadataReferenceProperties.Assembly);

                    //no need to unload this assembly context, it's not cached.
                    compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("GetExceptions")
                                  .AddReferences(corlib)
                                  .AddReferences(system);
                }
                var exceptionClass = compilation.GetTypeByMetadataName("System.Exception");
                foreach (var t in compilation.GlobalNamespace.GetAllTypes().Where((arg) => arg.IsDerivedFromClass(exceptionClass)))
                {
                    classes.Add(t.GetFullMetadataName());
                }
            } catch (Exception e) {
                LoggingService.LogError("Failed to obtain exceptions list in breakpoint dialog.", e);
            }
            await Runtime.RunInMainThread(() => {
                entryExceptionType.SetCodeCompletionList(classes.ToList());
            });
        }
Example #26
0
 /// <summary>
 /// This method can take some time to finish. It's not threaded
 /// </summary>
 /// <returns>
 /// A <see cref="ParsedDocument"/> that contains the current dom.
 /// </returns>
 public ParsedDocument UpdateParseDocument()
 {
     try {
         string currentParseFile = FileName;
         var    editor           = Editor;
         if (editor == null || string.IsNullOrEmpty(currentParseFile))
         {
             return(null);
         }
         TypeSystemService.AddSkippedFile(currentParseFile);
         string currentParseText = editor.Text;
         this.parsedDocument = TypeSystemService.ParseFile(Project, currentParseFile, editor.Document.MimeType, currentParseText);
         if (Project == null && this.parsedDocument != null)
         {
             singleFileContext = GetProjectContext().AddOrUpdateFiles(parsedDocument.ParsedFile);
         }
     } finally {
         OnDocumentParsed(EventArgs.Empty);
     }
     return(this.parsedDocument);
 }
Example #27
0
        Task <HashSet <IAssembly> > GetAllAssemblies()
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;

            return(Task.Factory.StartNew(delegate {
                var assemblies = new HashSet <IAssembly> ();
                foreach (var project in solution.GetAllProjects())
                {
                    var comp = TypeSystemService.GetCompilation(project);
                    if (comp == null)
                    {
                        continue;
                    }
                    foreach (var asm in comp.Assemblies)
                    {
                        assemblies.Add(asm);
                    }
                }
                return assemblies;
            }));
        }
Example #28
0
        static ICompilation GetSystemWebDom(TargetRuntime runtime, TargetFramework targetFramework)
        {
            string file = runtime.AssemblyContext.GetAssemblyNameForVersion(sysWebAssemblyName, targetFramework);

            if (string.IsNullOrEmpty(file))
            {
                throw new Exception("System.Web assembly name not found for framework " + targetFramework.Id);
            }
            file = runtime.AssemblyContext.GetAssemblyLocation(file, targetFramework);
            if (string.IsNullOrEmpty(file))
            {
                throw new Exception("System.Web assembly file not found for framework " + targetFramework.Id);
            }
            var dom = new SimpleCompilation(TypeSystemService.LoadAssemblyContext(runtime, targetFramework, file));

            if (dom == null)
            {
                throw new Exception("System.Web parse database not found for framework " + targetFramework.Id + " file '" + file + "'");
            }
            return(dom);
        }
        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);
        }
Example #30
0
        protected override SourceCodeLocation GetSourceCodeLocation(string fixtureTypeNamespace, string fixtureTypeName, string methodName)
        {
            if (fixtureTypeName == null)
            {
                return(null);
            }
            var ctx = TypeSystemService.GetCompilation(project);
            var cls = ctx.MainAssembly.GetTypeDefinition(fixtureTypeNamespace, fixtureTypeName, 0);

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

            if (cls.Name != methodName)
            {
                foreach (var met in cls.GetMethods())
                {
                    if (met.Name == methodName)
                    {
                        return(new SourceCodeLocation(met.Region.FileName, met.Region.BeginLine, met.Region.BeginColumn));
                    }
                }

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

                if (idx > 0)
                {
                    methodName = methodName.Substring(0, idx);
                    foreach (var met in cls.GetMethods())
                    {
                        if (met.Name == methodName)
                        {
                            return(new SourceCodeLocation(met.Region.FileName, met.Region.BeginLine, met.Region.BeginColumn));
                        }
                    }
                }
            }
            return(new SourceCodeLocation(cls.Region.FileName, cls.Region.BeginLine, cls.Region.BeginColumn));
        }