public void TestCollectFiles()
        {
            var code1    = @"
namespace project1 {
	class A
	{
		private void Method1() { }
		public void Method2() { }
	}
	public class B
	{ }
}";
            var project1 = new UnknownProject {
                FileName = "projectc1.csproj"
            };
            var project2 = new DotNetAssemblyProject {
                FileName = "projectc2.csproj"
            };

            project2.References.Add(new MonoDevelop.Projects.ProjectReference(project1));

            var solution = new Solution();

            solution.RootFolder.AddItem(project1);
            solution.RootFolder.AddItem(project2);
            solution.RootFolder.AddItem(new UnknownProject {
                FileName = "dummy.csproj"
            });

            project1.AddFile(new ProjectFile("dummy.cs"));
            TypeSystemService.LoadProject(project1);
            TypeSystemService.ParseFile(project1, "test.cs", "text/x-csharp", code1);
            var compilation = TypeSystemService.GetCompilation(project1);

            var typeA = compilation.MainAssembly.GetTypeDefinition("project1", "A", 0);

            TestCollectFiles(project1, typeA.GetMembers(m => m.Name == "Method1"),
                             new [] { CreateTestTuple(project1, new [] { (FilePath)"test.cs" }) });
            TestCollectFiles(project1, new [] { typeA }, new [] { CreateTestTuple(project1) });
            TestCollectFiles(project1, typeA.GetMembers(m => m.Name == "Method2"), new [] { CreateTestTuple(project1) });
            TestCollectFiles(project1, typeA.GetMembers(), new [] { CreateTestTuple(project1) });

            TestCollectFiles(solution, typeA.GetMembers(m => m.Name == "Method1"),
                             new [] { CreateTestTuple(project1, new [] { (FilePath)"test.cs" }) });
            TestCollectFiles(solution, typeA.GetMembers(), new [] { CreateTestTuple(project1) });

            var typeB = compilation.MainAssembly.GetTypeDefinition("project1", "B", 0);

            TestCollectFiles(solution, new [] { typeB }, new [] { CreateTestTuple(project1), CreateTestTuple(project2) });
            TestCollectFiles(solution, new [] { typeA, typeB }, new [] { CreateTestTuple(project1), CreateTestTuple(project2) });
        }
        public void TestCollectProjects()
        {
            var code     = @"
namespace project1 {
	class A
	{
		private void Method1() { }
		public void Method2() { }
	}
	public class B
	{
		private void Method1() { }
		protected void Method2() { }
	}
}";
            var project1 = new UnknownProject {
                FileName = "project1.csproj"
            };
            var project2 = new DotNetAssemblyProject {
                FileName = "project2.csproj"
            };
            var solution = new Solution();

            solution.RootFolder.AddItem(project1);
            solution.RootFolder.AddItem(project2);
            solution.RootFolder.AddItem(new UnknownProject {
                FileName = "project3.csproj"
            });

            TypeSystemService.LoadProject(project1);
            TypeSystemService.ParseFile(project1, "test.cs", "text/x-csharp", code);
            var compilation = TypeSystemService.GetCompilation(project1);

            var typeA = compilation.MainAssembly.GetTypeDefinition("project1", "A", 0);

            Assert.IsNotNull(typeA);
            TestCollectProjects(solution, new [] { typeA }, new [] { project1 });
            TestCollectProjects(solution, typeA.GetMembers(), new [] { project1 });
            TestCollectProjects(solution, typeA.GetMembers(m => m.Name == "Method1"), new [] { project1 });
            TestCollectProjects(solution, typeA.GetMembers(m => m.Name == "Method2"), new [] { project1 });

            project2.References.Add(new MonoDevelop.Projects.ProjectReference(project1));
            var typeB = compilation.MainAssembly.GetTypeDefinition("project1", "B", 0);

            Assert.IsNotNull(typeB);
            TestCollectProjects(solution, new [] { typeB }, new Project [] { project1, project2 });
            TestCollectProjects(solution, typeB.GetMembers(), new Project [] { project1, project2 });
            TestCollectProjects(solution, typeB.GetMembers(m => m.Name == "Method1"), new [] { project1 });
            TestCollectProjects(solution, typeB.GetMembers(m => m.Name == "Method2"), new Project [] { project1, project2 });
        }
Example #3
0
        public IType GetCodebehindType(string fileName)
        {
            string typeName = GetCodebehindTypeName(fileName);

            if (typeName != null)
            {
                var dom = TypeSystemService.GetCompilation(this);
                if (dom != null)
                {
                    return(dom.LookupType(typeName));
                }
            }
            return(null);
        }
        protected ITypeResolveContext GetContext(ITreeNavigator treeBuilder)
        {
            var mainAssembly = GetMainAssembly(treeBuilder);

            if (mainAssembly != null)
            {
                var simpleCompilation = new SimpleCompilation(mainAssembly);
                return(new SimpleTypeResolveContext(simpleCompilation.MainAssembly));
            }
            var project     = (Project)treeBuilder.GetParentDataItem(typeof(Project), true);
            var compilation = TypeSystemService.GetCompilation(project);

            return(new SimpleTypeResolveContext(compilation.MainAssembly));
        }
        protected IType Resolve(ITreeNavigator treeBuilder, IUnresolvedTypeDefinition type)
        {
            var mainAssembly = GetMainAssembly(treeBuilder);

            if (mainAssembly != null)
            {
                var simpleCompilation = new SimpleCompilation(mainAssembly);
                return(type.Resolve(new SimpleTypeResolveContext(simpleCompilation.MainAssembly)));
            }
            var project = (Project)treeBuilder.GetParentDataItem(typeof(Project), true);
            var ctx     = TypeSystemService.GetCompilation(project);

            return(ctx.MainAssembly.GetTypeDefinition(type.Namespace, type.Name, type.TypeParameters.Count));
        }
Example #6
0
        void GetCodeBehind(out IType codeBehindClass, out ICompilation projectDatabase)
        {
            codeBehindClass = null;
            projectDatabase = null;

            if (HasDoc && !string.IsNullOrEmpty(aspDoc.Info.InheritedClass))
            {
                projectDatabase = TypeSystemService.GetCompilation(project);
                if (projectDatabase != null)
                {
                    codeBehindClass = projectDatabase.FindType(aspDoc.Info.InheritedClass);
                }
            }
        }
        public IType GetCodebehindType(string fileName)
        {
            string typeName = GetCodebehindTypeName(fileName);

            if (typeName != null)
            {
                var dom = TypeSystemService.GetCompilation(this);
                if (dom != null)
                {
                    return(ReflectionHelper.ParseReflectionName(typeName).Resolve(dom));
                }
            }
            return(null);
        }
Example #8
0
        void GetCodeBehind(out IType codeBehindClass, out ICompilation projectDatabase)
        {
            codeBehindClass = null;
            projectDatabase = null;

            if (HasDoc && !string.IsNullOrEmpty(aspDoc.Info.InheritedClass))
            {
                projectDatabase = TypeSystemService.GetCompilation(project);
                if (projectDatabase != null)
                {
                    codeBehindClass = ReflectionHelper.ParseReflectionName(aspDoc.Info.InheritedClass).Resolve(projectDatabase);
                }
            }
        }
        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));
                        }
                    }
                }
            }
        }
        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);
        }
Example #11
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 #12
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));
        }
Example #13
0
        Task <HashSet <IAssembly> > GetAllAssemblies(Project referencedProject)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;

            return(Task.Factory.StartNew(delegate {
                var assemblies = new HashSet <IAssembly> ();
                foreach (var project in solution.GetAllProjects())
                {
                    if (!IsReferenced(project, referencedProject))
                    {
                        continue;
                    }
                    var comp = TypeSystemService.GetCompilation(project);
                    if (comp == null)
                    {
                        continue;
                    }
                    assemblies.Add(comp.MainAssembly);
                }
                return assemblies;
            }));
        }
Example #14
0
 void FillClasses(MoonlightProject project)
 {
     if (classesFilled)
     {
         return;
     }
     classesFilled = true;
     try {
         var   dom     = TypeSystemService.GetCompilation(project);
         IType appType = dom.LookupType("System.Windows", "Application");
         if (appType == null)
         {
             return;
         }
         foreach (IType type in appType.GetAllBaseTypes())
         {
             classListStore.AppendValues(type.FullName);
         }
     } catch (InvalidOperationException) {
         // Project not found in parser database
     }
 }
Example #15
0
        public override void DoGlobalOperationOn(IEnumerable <IEntity> entities, Action <RefactoringContext, Script, IEnumerable <AstNode> > callback, string operationName = null)
        {
            using (var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(operationName ?? GettextCatalog.GetString("Performing refactoring task..."), null)) {
                var col = entities.SelectMany(entity => ReferenceFinder.FindReferences(entity, true, monitor)).OfType <CSharpReferenceFinder.CSharpMemberReference> ().GroupBy(reference => reference.FileName);

                foreach (var r in col)
                {
                    string filename = r.Key;

                    bool isOpen;
                    System.Text.Encoding encoding;
                    bool hadBom;

                    var data = TextFileProvider.Instance.GetTextEditorData(filename, out hadBom, out encoding, out isOpen);

                    var firstReference = r.First();

                    var project = firstReference.Project;

                    ParsedDocument parsedDocument;
                    using (var reader = new StreamReader(data.OpenStream()))
                        parsedDocument = new MonoDevelop.CSharp.Parser.TypeSystemParser().Parse(true, filename, reader, project);

                    var resolver = new CSharpAstResolver(TypeSystemService.GetCompilation(project), firstReference.SyntaxTree, parsedDocument.ParsedFile as CSharpUnresolvedFile);

                    var ctx    = new MDRefactoringContext(project as DotNetProject, data, parsedDocument, resolver, firstReference.AstNode.StartLocation, this.context.CancellationToken);
                    var script = new MDRefactoringScript(ctx, FormattingOptions);

                    callback(ctx, script, r.Select(reference => reference.AstNode));

                    if (!isOpen)
                    {
                        script.Dispose();
                        Mono.TextEditor.Utils.TextFileUtility.WriteText(filename, data.Text, encoding, hadBom);
                    }
                }
            }
        }
Example #16
0
 void LoadExceptions()
 {
     classes.Add("System.Exception");
     if (IdeApp.ProjectOperations.CurrentSelectedProject != null)
     {
         var dom = TypeSystemService.GetCompilation(IdeApp.ProjectOperations.CurrentSelectedProject);
         foreach (var t in dom.FindType(typeof(Exception)).GetSubTypeDefinitions())
         {
             classes.Add(t.ReflectionName);
         }
     }
     else
     {
         // no nead to unload this assembly context, it's not cached.
         var unresolvedAssembly = TypeSystemService.LoadAssemblyContext(Runtime.SystemAssemblyService.CurrentRuntime, MonoDevelop.Core.Assemblies.TargetFramework.Default, typeof(Uri).Assembly.FullName);
         var mscorlib           = TypeSystemService.LoadAssemblyContext(Runtime.SystemAssemblyService.CurrentRuntime, MonoDevelop.Core.Assemblies.TargetFramework.Default, typeof(object).Assembly.FullName);
         var dom = new ICSharpCode.NRefactory.TypeSystem.Implementation.SimpleCompilation(unresolvedAssembly, mscorlib);
         foreach (var t in dom.FindType(typeof(Exception)).GetSubTypeDefinitions())
         {
             classes.Add(t.ReflectionName);
         }
     }
 }
        void TestCreateInterface(string interfacecode, string outputString, string stubString = null)
        {
            var project = new UnknownProject();

            project.FileName = "test.csproj";

            TypeSystemService.LoadProject(project);

            TypeSystemService.ParseFile(project, "program.cs", "text/x-csharp", interfacecode);
            TypeSystemService.ParseFile(project, "stub.cs", "text/x-csharp", "class Stub {\n " + stubString + "}\n");

            var wrapper = TypeSystemService.GetProjectContentWrapper(project);

            wrapper.UpdateContent(c => c.AddAssemblyReferences(new [] { Mscorlib, SystemCore }));

            var pctx = TypeSystemService.GetCompilation(project);

            var stubType = pctx.MainAssembly.GetTypeDefinition("", "Stub", 0);
            var iface    = pctx.MainAssembly.GetTypeDefinition("", "ITest", 0);

            var gen = new CSharpCodeGenerator();

            gen.EolMarker   = "\n";
            gen.Compilation = pctx;
            string generated = gen.CreateInterfaceImplementation(stubType, stubType.Parts.First(), iface, false);

            Assert.IsNotEmpty(generated);
            // crop #region
            generated = generated.Substring(generated.IndexOf("implementation") + "implementation".Length);
            generated = generated.Substring(0, generated.LastIndexOf("#"));
            generated = generated.Trim();
            if (outputString != generated)
            {
                Console.WriteLine(generated);
            }
            Assert.AreEqual(outputString, generated);
        }
Example #18
0
        public string[] GetCompatibleMethodsInCodeBehind(MethodInfo methodInfo)
        {
            if (fullClass == null)
            {
                return(new string[0]);
            }

            ParameterInfo[] reflectionParams = methodInfo.GetParameters();
            List <IMethod>  compatMeth       = new List <IMethod> ();

            IType[]        pars        = new IType[reflectionParams.Length];
            List <IType>[] baseTypes   = new List <IType> [reflectionParams.Length];
            ICompilation   compilation = TypeSystemService.GetCompilation(IdeApp.Workbench.ActiveDocument.Project);

            for (int i = 0; i < reflectionParams.Length; i++)
            {
                pars[i]      = reflectionParams[i].ParameterType.ToTypeReference().Resolve(compilation);
                baseTypes[i] = new List <IType> (pars[i].GetAllBaseTypes());
            }

            var matchMethType = methodInfo.ReturnType.ToTypeReference().Resolve(compilation);

            foreach (IMethod mmethod in fullClass.GetMethods(null, null, GetMemberOptions.IgnoreInheritedMembers))
            {
                if (mmethod.IsPrivate || mmethod.Parameters.Count != pars.Length || mmethod.IsInternal)
                {
                    continue;
                }

                if (mmethod.ReturnType.FullName != matchMethType.FullName)
                {
                    continue;
                }

                bool allCompatible = true;

                //compare each parameter
                for (int i = 0; i < pars.Length; i++)
                {
                    if (pars[i].FullName != mmethod.Parameters[i].Type.FullName)
                    {
                        allCompatible = false;
                        break;
                    }

                    List <IType> insideBTypes = new List <IType> (mmethod.Parameters[i].Type.GetAllBaseTypes());
                    if (insideBTypes.Count != baseTypes[i].Count)
                    {
                        allCompatible = false;
                        break;
                    }
                    for (int j = 0; j < baseTypes[i].Count; j++)
                    {
                        if (baseTypes[i][j].FullName != insideBTypes[j].FullName)
                        {
                            allCompatible = false;
                            break;
                        }
                    }
                }

                if (allCompatible)
                {
                    compatMeth.Add(mmethod);
                }
            }

            string[] names = new string[compatMeth.Count];
            for (int i = 0; i < names.Length; i++)
            {
                names[i] = compatMeth[i].Name;
            }
            return(names);
        }
 public IEnumerable <CompletionData> GetControlCompletionData()
 {
     return(GetControlCompletionData(ReflectionHelper.ParseReflectionName("System.Web.UI.Control").Resolve(TypeSystemService.GetCompilation(Project))));
 }
Example #20
0
        /// Adds a field to the class
        public void BindToField(Stetic.Component obj)
        {
            if (targetObject == null)
            {
                return;
            }

            string name = GetMemberName(obj);
            var    cls  = GetClass();

            if (FindField(cls.Resolve(project), name) != null)
            {
                return;
            }

            Document doc = IdeApp.Workbench.OpenDocument(cls.Region.FileName, true);

            IEditableTextFile editor = doc.GetContent <IEditableTextFile> ();

            if (editor != null)
            {
                var resolvedCls = cls.Resolve(cls.UnresolvedFile.GetTypeResolveContext(TypeSystemService.GetCompilation(project), cls.Region.Begin)).GetDefinition();
                CodeGenerationService.AddNewMember(resolvedCls, cls, GetFieldCode(cls, obj, name));
            }
        }
        static IEnumerable <PossibleNamespace> GetPossibleNamespaces(Document doc, AstNode node, ResolveResult resolveResult, DocumentLocation location)
        {
            var unit = doc.ParsedDocument.GetAst <SyntaxTree> ();

            if (unit == null)
            {
                yield break;
            }
            var project = doc.Project;

            if (project == null)
            {
                yield break;
            }

            int  tc                    = GetTypeParameterCount(node);
            var  attribute             = unit.GetNodeAt <ICSharpCode.NRefactory.CSharp.Attribute> (location);
            bool isInsideAttributeType = attribute != null && attribute.Type.Contains(location);

            var compilations = new List <Tuple <ICompilation, MonoDevelop.Projects.ProjectReference> > ();

            compilations.Add(Tuple.Create(doc.Compilation, (MonoDevelop.Projects.ProjectReference)null));
            var referencedItems = IdeApp.Workspace != null?project.GetReferencedItems(IdeApp.Workspace.ActiveConfiguration).ToList() : (IEnumerable <SolutionItem>) new SolutionItem[0];

            var solution = project != null ? project.ParentSolution : null;

            if (solution != null)
            {
                foreach (var curProject in solution.GetAllProjects())
                {
                    if (curProject == project || referencedItems.Contains(curProject))
                    {
                        continue;
                    }
                    var comp = TypeSystemService.GetCompilation(curProject);
                    if (comp == null)
                    {
                        continue;
                    }
                    compilations.Add(Tuple.Create(comp, new MonoDevelop.Projects.ProjectReference(curProject)));
                }
            }

            var netProject = project as DotNetProject;

            if (netProject == null)
            {
                yield break;
            }
            var frameworkLookup = TypeSystemService.GetFrameworkLookup(netProject);

            if (resolveResult is UnknownMemberResolveResult)
            {
                var umResult = (UnknownMemberResolveResult)resolveResult;
                foreach (var r in frameworkLookup.LookupExtensionMethod(umResult.MemberName))
                {
                    var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName(r.FullName, r.Package, netProject.TargetFramework);
                    if (systemAssembly == null)
                    {
                        continue;
                    }
                    compilations.Add(Tuple.Create(TypeSystemService.GetCompilation(systemAssembly, doc.Compilation), new MonoDevelop.Projects.ProjectReference(systemAssembly)));
                }
            }
            bool foundIdentifier = false;
            var  lookup          = new MemberLookup(null, doc.Compilation.MainAssembly);

            foreach (var comp in compilations)
            {
                var compilation       = comp.Item1;
                var requiredReference = comp.Item2;
                if (resolveResult is AmbiguousTypeResolveResult)
                {
                    if (compilation != doc.Compilation)
                    {
                        continue;
                    }
                    var aResult = resolveResult as AmbiguousTypeResolveResult;
                    var file    = doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile;
                    var scope   = file.GetUsingScope(location).Resolve(compilation);
                    while (scope != null)
                    {
                        foreach (var u in scope.Usings)
                        {
                            foreach (var typeDefinition in u.Types)
                            {
                                if (typeDefinition.Name == aResult.Type.Name &&
                                    typeDefinition.TypeParameterCount == tc &&
                                    lookup.IsAccessible(typeDefinition, false))
                                {
                                    yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));
                                }
                            }
                        }
                        scope = scope.Parent;
                    }
                }

                var allTypes = compilation == doc.Compilation ? compilation.GetAllTypeDefinitions() : compilation.MainAssembly.GetAllTypeDefinitions();
                if (resolveResult is UnknownIdentifierResolveResult)
                {
                    var    uiResult = resolveResult as UnknownIdentifierResolveResult;
                    string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
                    foreach (var typeDefinition in allTypes)
                    {
                        if (typeDefinition.Name == possibleAttributeName && typeDefinition.TypeParameterCount == tc &&
                            lookup.IsAccessible(typeDefinition, false))
                        {
                            if (typeDefinition.DeclaringTypeDefinition != null)
                            {
                                var builder = new TypeSystemAstBuilder(new CSharpResolver(doc.Compilation));
                                foundIdentifier = true;
                                yield return(new PossibleNamespace(builder.ConvertType(typeDefinition.DeclaringTypeDefinition).ToString(), false, requiredReference));
                            }
                            else
                            {
                                foundIdentifier = true;
                                yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));
                            }
                        }
                    }
                }

                if (resolveResult is UnknownMemberResolveResult)
                {
                    var    umResult = (UnknownMemberResolveResult)resolveResult;
                    string possibleAttributeName = isInsideAttributeType ? umResult.MemberName + "Attribute" : umResult.MemberName;
                    foreach (var typeDefinition in allTypes.Where(t => t.HasExtensionMethods))
                    {
                        foreach (var method in typeDefinition.Methods.Where(m => m.IsExtensionMethod && m.Name == possibleAttributeName))
                        {
                            IType[] inferredTypes;
                            if (CSharpResolver.IsEligibleExtensionMethod(
                                    compilation.Import(umResult.TargetType),
                                    method,
                                    true,
                                    out inferredTypes
                                    ))
                            {
                                yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));

                                goto skipType;
                            }
                        }
skipType:
                        ;
                    }
                }

                if (resolveResult is ErrorResolveResult)
                {
                    var identifier = unit != null?unit.GetNodeAt <Identifier> (location) : null;

                    if (identifier != null)
                    {
                        var uiResult = resolveResult as UnknownIdentifierResolveResult;
                        if (uiResult != null)
                        {
                            string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
                            foreach (var typeDefinition in allTypes)
                            {
                                if ((identifier.Name == possibleAttributeName) &&
                                    typeDefinition.TypeParameterCount == tc &&
                                    lookup.IsAccessible(typeDefinition, false))
                                {
                                    yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));
                                }
                            }
                        }
                    }
                }
            }
            // Try to search framework types
            if (!foundIdentifier && resolveResult is UnknownIdentifierResolveResult)
            {
                var    uiResult = resolveResult as UnknownIdentifierResolveResult;
                string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
                foreach (var r in frameworkLookup.LookupIdentifier(possibleAttributeName, tc))
                {
                    var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName(r.FullName, r.Package, netProject.TargetFramework);
                    if (systemAssembly == null)
                    {
                        continue;
                    }
                    yield return(new PossibleNamespace(r.Namespace, true, new MonoDevelop.Projects.ProjectReference(systemAssembly)));
                }
            }
        }
 public IEnumerable <CompletionData> GetControlCompletionData()
 {
     return(GetControlCompletionData(TypeSystemService.GetCompilation(Project).LookupType("System.Web.UI", "Control")));
 }
Example #23
0
        public void Run()
        {
            var assemblies = new HashSet <IAssembly> ();

            foreach (var project in IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllProjects())
            {
                var comp = TypeSystemService.GetCompilation(project);
                if (comp == null)
                {
                    continue;
                }
                assemblies.Add(comp.MainAssembly);
            }

            TypeGraph tg   = new TypeGraph(assemblies);
            var       node = tg.GetNode(entity.DeclaringTypeDefinition);

            using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true)) {
                Stack <IList <TypeGraphNode> > derivedTypes = new Stack <IList <TypeGraphNode> > ();
                derivedTypes.Push(node.DerivedTypes);
                HashSet <ITypeDefinition> visitedType = new HashSet <ITypeDefinition> ();
                while (derivedTypes.Count > 0)
                {
                    foreach (var derived in derivedTypes.Pop())
                    {
                        if (visitedType.Contains(derived.TypeDefinition))
                        {
                            continue;
                        }
                        derivedTypes.Push(tg.GetNode(derived.TypeDefinition).DerivedTypes);
                        visitedType.Add(derived.TypeDefinition);
                        var impMember = derived.TypeDefinition.Compilation.Import(entity);
                        if (impMember == null)
                        {
                            continue;
                        }
                        IMember derivedMember;
                        if (entity.DeclaringTypeDefinition.Kind == TypeKind.Interface)
                        {
                            derivedMember = derived.TypeDefinition.GetMembers(null, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(
                                m => m.ImplementedInterfaceMembers.Any(im => im.Region == entity.Region)
                                );
                        }
                        else
                        {
                            derivedMember = InheritanceHelper.GetDerivedMember(impMember, derived.TypeDefinition);
                        }
                        if (derivedMember == null)
                        {
                            continue;
                        }
                        var tf    = TextFileProvider.Instance.GetReadOnlyTextEditorData(derivedMember.Region.FileName);
                        var start = tf.LocationToOffset(derivedMember.Region.Begin);
                        tf.SearchRequest.SearchPattern = derivedMember.Name;
                        var sr = tf.SearchForward(start);
                        if (sr != null)
                        {
                            start = sr.Offset;
                        }

                        monitor.ReportResult(new MemberReference(derivedMember, derivedMember.Region, start, derivedMember.Name.Length));
                    }
                }
            }
        }
 static IEnumerable <Project> GetAllReferencingProjects(Solution solution, string assemblyName)
 {
     return(solution.GetAllProjects().Where(
                project => TypeSystemService.GetCompilation(project).Assemblies.Any(a => a.AssemblyName == assemblyName)));
 }
        public override IEnumerable <MemberReference> FindReferences(Project project, IProjectContent content, IEnumerable <FilePath> possibleFiles, IProgressMonitor monitor, IEnumerable <object> members)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content", "Project content not set.");
            }
            SetPossibleFiles(possibleFiles);
            SetSearchedMembers(members);

            var scopes      = searchedMembers.Select(e => e is IEntity ? refFinder.GetSearchScopes((IEntity)e) : refFinder.GetSearchScopes((INamespace)e));
            var compilation = project != null?TypeSystemService.GetCompilation(project) : content.CreateCompilation();

            List <MemberReference> refs = new List <MemberReference> ();

            foreach (var opendoc in openDocuments)
            {
                foreach (var newRef in FindInDocument(opendoc.Item2))
                {
                    if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                    {
                        continue;
                    }
                    refs.Add(newRef);
                }
            }
            foreach (var file in files)
            {
                if (monitor != null)
                {
                    monitor.Step(1);
                }
                string text = Mono.TextEditor.Utils.TextFileUtility.ReadAllText(file);
                if (memberName != null && text.IndexOf(memberName, StringComparison.Ordinal) < 0 &&
                    (keywordName == null || text.IndexOf(keywordName, StringComparison.Ordinal) < 0))
                {
                    continue;
                }
                using (var editor = TextEditorData.CreateImmutable(text)) {
                    editor.Document.FileName = file;
                    var unit = new PlayScriptParser().Parse(editor);
                    if (unit == null)
                    {
                        continue;
                    }

                    var storedFile = content.GetFile(file);
                    var parsedFile = storedFile as CSharpUnresolvedFile;

                    if (parsedFile == null && storedFile is ParsedDocumentDecorator)
                    {
                        parsedFile = ((ParsedDocumentDecorator)storedFile).ParsedFile as CSharpUnresolvedFile;
                    }

                    if (parsedFile == null)
                    {
                        // for fallback purposes - should never happen.
                        parsedFile  = unit.ToTypeSystem();
                        content     = content.AddOrUpdateFiles(parsedFile);
                        compilation = content.CreateCompilation();
                    }
                    foreach (var scope in scopes)
                    {
                        refFinder.FindReferencesInFile(
                            scope,
                            parsedFile,
                            unit,
                            compilation,
                            (astNode, result) => {
                            var newRef = GetReference(project, result, astNode, unit, file, editor);
                            if (newRef == null || refs.Any(r => r.FileName == newRef.FileName && r.Region == newRef.Region))
                            {
                                return;
                            }
                            refs.Add(newRef);
                        },
                            CancellationToken.None
                            );
                    }
                }
            }
            return(refs);
        }
        public static void FindDerivedClasses(ITypeDefinition cls)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;

            if (solution == null)
            {
                return;
            }

            var sourceProject = TypeSystemService.GetProject(cls);

            if (sourceProject == null)
            {
                return;
            }

            var projects = ReferenceFinder.GetAllReferencingProjects(solution, sourceProject);

            ThreadPool.QueueUserWorkItem(delegate
            {
                using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true))
                {
                    var cache = new Dictionary <string, TextEditorData> ();
                    Parallel.ForEach(projects, p =>
                    {
                        var comp = TypeSystemService.GetCompilation(p);
                        if (comp == null)
                        {
                            return;
                        }
                        var importedType = comp.Import(cls);
                        if (importedType == null)
                        {
                            return;
                        }
                        foreach (var type in comp.MainAssembly.GetAllTypeDefinitions())
                        {
                            if (!type.IsDerivedFrom(importedType))
                            {
                                continue;
                            }
                            TextEditorData textFile;
                            if (!cache.TryGetValue(type.Region.FileName, out textFile))
                            {
                                cache [type.Region.FileName] = textFile = TextFileProvider.Instance.GetTextEditorData(type.Region.FileName);
                            }
                            int position = textFile.LocationToOffset(type.Region.Begin);
                            string keyword;
                            switch (type.Kind)
                            {
                            case TypeKind.Interface:
                                keyword = "interface";
                                break;

                            case TypeKind.Struct:
                                keyword = "struct";
                                break;

                            case TypeKind.Delegate:
                                keyword = "delegate";
                                break;

                            case TypeKind.Enum:
                                keyword = "enum";
                                break;

                            default:
                                keyword = "class";
                                break;
                            }
                            while (position < textFile.Length - keyword.Length)
                            {
                                if (textFile.GetTextAt(position, keyword.Length) == keyword)
                                {
                                    position += keyword.Length;
                                    while (position < textFile.Length && textFile.GetCharAt(position) == ' ' || textFile.GetCharAt(position) == '\t')
                                    {
                                        position++;
                                    }
                                    break;
                                }
                                position++;
                            }
                            monitor.ReportResult(new MonoDevelop.Ide.FindInFiles.SearchResult(new FileProvider(type.Region.FileName, p), position, 0));
                        }
                    });
                    foreach (var tf in cache.Values)
                    {
                        if (tf.Parent == null)
                        {
                            tf.Dispose();
                        }
                    }
                }
            });
        }
Example #27
0
        /*public override void RunParameterCompletionCommand ()
         * {
         *      if (localDocumentInfo == null) {
         *              base.RunParameterCompletionCommand ();
         *              return;
         *      }
         *      var doc = document;
         *      document = localDocumentInfo.HiddenDocument;
         *      var cw = CompletionWidget;
         *      CompletionWidget = documentBuilder.CreateCompletionWidget (localDocumentInfo);
         *      try {
         *              base.RunParameterCompletionCommand ();
         *      } finally {
         *              document = doc;
         *              CompletionWidget = cw;
         *      }
         * }*/

        protected override void GetElementCompletions(CompletionDataList list)
        {
            S.XName parentName = GetParentElementName(0);

            //fallback
            if (!HasDoc)
            {
                AddAspBeginExpressions(list);
                string aspPrefix = "asp:";
                var    type      = ReflectionHelper.ParseReflectionName("System.Web.UI.Control").Resolve(TypeSystemService.GetCompilation(project));
                foreach (var cls in WebTypeContext.ListSystemControlClasses(type, project))
                {
                    list.Add(new AspTagCompletionData(aspPrefix, cls));
                }

                base.GetElementCompletions(list);
                return;
            }

            IType controlClass = null;

            if (parentName.HasPrefix)
            {
                controlClass = refman.GetControlType(parentName.Prefix, parentName.Name);
            }
            else
            {
                S.XName grandparentName = GetParentElementName(1);
                if (grandparentName.IsValid && grandparentName.HasPrefix)
                {
                    controlClass = refman.GetControlType(grandparentName.Prefix, grandparentName.Name);
                }
            }

            //we're just in HTML
            if (controlClass == null)
            {
                //root element?
                if (!parentName.IsValid)
                {
                    if (aspDoc.Info.Subtype == WebSubtype.WebControl)
                    {
                        AddHtmlTagCompletionData(list, Schema, new S.XName("div"));
                        AddAspBeginExpressions(list);
                        list.AddRange(refman.GetControlCompletionData());
                        AddMiscBeginTags(list);
                    }
                    else if (!string.IsNullOrEmpty(aspDoc.Info.MasterPageFile))
                    {
                        //FIXME: add the actual region names
                        list.Add(new CompletionData("asp:Content"));
                    }
                }
                else
                {
                    AddAspBeginExpressions(list);
                    list.AddRange(refman.GetControlCompletionData());
                    base.GetElementCompletions(list);
                }
                return;
            }

            string defaultProp;
            bool   childrenAsProperties = AreChildrenAsProperties(controlClass, out defaultProp);

            if (defaultProp != null && defaultProp.Length == 0)
            {
                defaultProp = null;
            }

            //parent permits child controls directly
            if (!childrenAsProperties)
            {
                AddAspBeginExpressions(list);
                list.AddRange(refman.GetControlCompletionData());
                AddMiscBeginTags(list);
                //TODO: get correct parent for Content tags
                AddHtmlTagCompletionData(list, Schema, new S.XName("body"));
                return;
            }

            //children of properties
            if (childrenAsProperties && (!parentName.HasPrefix || defaultProp != null))
            {
                if (controlClass.GetProjectContent() == null)
                {
                    LoggingService.LogWarning("IType {0} does not have a SourceProjectDom", controlClass);
                    return;
                }

                string    propName = defaultProp ?? parentName.Name;
                IProperty property =
                    controlClass.GetProperties()
                    .Where(x => string.Compare(propName, x.Name, StringComparison.OrdinalIgnoreCase) == 0)
                    .FirstOrDefault();

                if (property == null)
                {
                    return;
                }

                //sanity checks on attributes
                switch (GetPersistenceMode(property))
                {
                case System.Web.UI.PersistenceMode.Attribute:
                case System.Web.UI.PersistenceMode.EncodedInnerDefaultProperty:
                    return;

                case System.Web.UI.PersistenceMode.InnerDefaultProperty:
                    if (!parentName.HasPrefix)
                    {
                        return;
                    }
                    break;

                case System.Web.UI.PersistenceMode.InnerProperty:
                    if (parentName.HasPrefix)
                    {
                        return;
                    }
                    break;
                }

                //check if allows freeform ASP/HTML content
                if (property.ReturnType.ToString() == "System.Web.UI.ITemplate")
                {
                    AddAspBeginExpressions(list);
                    AddMiscBeginTags(list);
                    AddHtmlTagCompletionData(list, Schema, new S.XName("body"));
                    list.AddRange(refman.GetControlCompletionData());
                    return;
                }

                //FIXME:unfortunately ASP.NET doesn't seem to have enough type information / attributes
                //to be able to resolve the correct child types here
                //so we assume it's a list and have a quick hack to find arguments of strongly typed ILists

                IType collectionType = property.ReturnType;
                if (collectionType == null)
                {
                    list.AddRange(refman.GetControlCompletionData());
                    return;
                }

                string  addStr = "Add";
                IMethod meth   = collectionType.GetMethods()
                                 .Where(m => m.Parameters.Count == 1 && m.Name == addStr).FirstOrDefault();

                if (meth != null)
                {
                    IType argType = meth.Parameters [0].Type;
                    var   type    = ReflectionHelper.ParseReflectionName("System.Web.UI.Control").Resolve(argType.GetDefinition().Compilation);
                    if (argType != null && argType.IsBaseType(type))
                    {
                        list.AddRange(refman.GetControlCompletionData(argType));
                        return;
                    }
                }

                list.AddRange(refman.GetControlCompletionData());
                return;
            }

            //properties as children of controls
            if (parentName.HasPrefix && childrenAsProperties)
            {
                if (controlClass.GetProjectContent() == null)
                {
                    LoggingService.LogWarning("IType {0} does not have a SourceProjectDom", controlClass);
                }

                foreach (IProperty prop in GetUniqueMembers <IProperty> (controlClass.GetProperties()))
                {
                    if (GetPersistenceMode(prop) != System.Web.UI.PersistenceMode.Attribute)
                    {
                        list.Add(prop.Name, prop.GetStockIcon(), AmbienceService.GetSummaryMarkup(prop));
                    }
                }
                return;
            }
        }
Example #28
0
        void StartAnalyzation(object sender, EventArgs e)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;

            if (solution == null)
            {
                return;
            }
            runButton.Sensitive = false;
            store.Clear();
            var rootNode = store.AddNode();

            rootNode.SetValue(text, "Analyzing...");
            ThreadPool.QueueUserWorkItem(delegate {
                using (var monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor("Analyzing solution", null, false)) {
                    int work = 0;
                    foreach (var project in solution.GetAllProjects())
                    {
                        work += project.Files.Count(f => f.BuildAction == BuildAction.Compile);
                    }
                    monitor.BeginTask("Analyzing solution", work);
                    int allIssues           = 0;
                    TypeSystemParser parser = null;
                    string lastMime         = null;
                    CodeIssueProvider[] codeIssueProvider = null;
                    foreach (var project in solution.GetAllProjects())
                    {
                        var compilation             = TypeSystemService.GetCompilation(project);
                        List <CodeIssue> codeIssues = new List <CodeIssue> ();
                        Parallel.ForEach(project.Files, file => {
                            if (file.BuildAction != BuildAction.Compile)
                            {
                                return;
                            }

                            var editor = TextFileProvider.Instance.GetReadOnlyTextEditorData(file.FilePath);

                            if (lastMime != editor.MimeType || parser == null)
                            {
                                parser = TypeSystemService.GetParser(editor.MimeType);
                            }
                            if (parser == null)
                            {
                                return;
                            }
                            var reader   = new StreamReader(editor.OpenStream());
                            var document = parser.Parse(true, editor.FileName, reader, project);
                            reader.Close();
                            if (document == null)
                            {
                                return;
                            }

                            var resolver = new CSharpAstResolver(compilation, document.GetAst <SyntaxTree> (), document.ParsedFile as CSharpUnresolvedFile);
                            var context  = document.CreateRefactoringContextWithEditor(editor, resolver, CancellationToken.None);

                            if (lastMime != editor.MimeType || codeIssueProvider == null)
                            {
                                codeIssueProvider = RefactoringService.GetInspectors(editor.MimeType).ToArray();
                            }
                            Parallel.ForEach(codeIssueProvider, (provider) => {
                                var severity = provider.GetSeverity();
                                if (severity == Severity.None)
                                {
                                    return;
                                }
                                try {
                                    foreach (var r in provider.GetIssues(context, CancellationToken.None))
                                    {
                                        lock (codeIssues) {
                                            codeIssues.Add(r);
                                        }
                                    }
                                } catch (Exception ex) {
                                    LoggingService.LogError("Error while running code issue on:" + editor.FileName, ex);
                                }
                            });
                            lastMime = editor.MimeType;
                            monitor.Step(1);
                        });
                        Application.Invoke(delegate {
                            var projectNode = store.AddNode();
                            projectNode.SetValue(text, project.Name + "( " + codeIssues.Count + " issues)");
                            foreach (var issue in codeIssues)
                            {
                                var child = projectNode.AddChild();
                                child.SetValue(text, issue.Description + " - " + issue.Region);
                                child.SetValue(region, issue.Region);
                                child.MoveToParent();
                            }
                            projectNode.MoveToParent();
                            allIssues += codeIssues.Count;
                        });
                    }
                    Application.Invoke(delegate {
                        rootNode.SetValue(text, "Found issues :" + allIssues);
                        runButton.Sensitive = true;
                    });
                    monitor.EndTask();
                }
            });
        }