Beispiel #1
0
        public ProjectDom 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(ProjectDomService.GetAssemblyDom(TargetRuntime, 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(ProjectDomService.GetProjectDom(p));
                }
            }

            string path = GetAssemblyPath(assemblyName);

            if (path != null)
            {
                return(ProjectDomService.GetAssemblyDom(TargetRuntime, path));
            }
            return(null);
        }
        protected override SourceCodeLocation GetSourceCodeLocation(string fullClassName, string methodName)
        {
            ProjectDom ctx = ProjectDomService.GetProjectDom(project);
            IType      cls = ctx.GetType(fullClassName);

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

            foreach (IMethod met in cls.Methods)
            {
                if (met.Name == methodName)
                {
                    return(new SourceCodeLocation(cls.CompilationUnit.FileName, met.Location.Line, met.Location.Column));
                }
            }
            return(new SourceCodeLocation(cls.CompilationUnit.FileName, cls.Location.Line, cls.Location.Column));
        }
        public TypeUpdateInformation UpdateFromParseInfo(ICompilationUnit parserInfo, string fileName)
        {
            lock (rwlock) {
                ICompilationUnit cu = parserInfo;

                List <IType>      resolved;
                List <IAttribute> resolvedAtts;

                int unresolvedCount = ResolveTypes(cu, cu.Types, cu.Attributes, out resolved, out resolvedAtts);
                totalUnresolvedCount += unresolvedCount;

                TypeUpdateInformation res = UpdateTypeInformation(resolved, resolvedAtts, parserInfo.FileName);

                FileEntry file;
                if (files.TryGetValue(fileName, out file))
                {
                    if (unresolvedCount > 0)
                    {
                        if (file.ParseErrorRetries != 1)
                        {
                            file.ParseErrorRetries = 1;

                            // Enqueue the file for quickly reparse. Types can't be resolved most probably because
                            // the file that implements them is not yet parsed.
                            ProjectDomService.QueueParseJob(SourceProjectDom,
                                                            delegate { UpdateFromParseInfo(parserInfo, fileName); },
                                                            file.FileName);
                        }
                    }
                    else
                    {
                        file.ParseErrorRetries = 0;
                    }
                }

                if ((++parseCount % MAX_ACTIVE_COUNT) == 0)
                {
                    Flush();
                }
                return(res);
            }
        }
        void CollectTypes()
        {
            lock (types) {
                getTypesTimer.BeginTiming();
                try {
                    foreach (Document doc in IdeApp.Workbench.Documents)
                    {
                        // We only want to check it here if it's not part
                        // of the open combine.  Otherwise, it will get
                        // checked down below.
                        if (doc.Project == null && doc.IsFile)
                        {
                            ICompilationUnit info = doc.CompilationUnit;
                            if (info != null)
                            {
                                foreach (IType c in info.Types)
                                {
                                    types.Add(c);
                                }
                            }
                        }
                    }

                    ReadOnlyCollection <Project> projects = IdeApp.Workspace.GetAllProjects();

                    foreach (Project p in projects)
                    {
                        ProjectDom dom = ProjectDomService.GetProjectDom(p);
                        if (dom == null)
                        {
                            continue;
                        }
                        foreach (IType c in dom.Types)
                        {
                            AddType(c, types);
                        }
                    }
                } finally {
                    getTypesTimer.EndTiming();
                }
            }
        }
Beispiel #5
0
                public ConditinalExpressionEvaluator(Mono.TextEditor.Document doc)
                {
                    var project = IdeApp.ProjectOperations.CurrentSelectedProject;

                    if (project != null)
                    {
                        DotNetProjectConfiguration configuration = project.GetConfiguration(IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration;
                        if (configuration != null)
                        {
                            CSharpCompilerParameters cparams = configuration.CompilationParameters as CSharpCompilerParameters;
                            if (cparams != null)
                            {
                                string[] syms = cparams.DefineSymbols.Split(';', ',', ' ', '\t');
                                foreach (string s in syms)
                                {
                                    string ss = s.Trim();
                                    if (ss.Length > 0 && !symbols.Contains(ss))
                                    {
                                        symbols.Add(ss);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("NO CONFIGURATION");
                        }
                    }

                    ProjectDom     dom            = ProjectDomService.GetProjectDom(project);
                    ParsedDocument parsedDocument = ProjectDomService.GetParsedDocument(dom, doc.FileName);

/*					if (parsedDocument == null)
 *                                              parsedDocument = ProjectDomService.ParseFile (dom, doc.FileName ?? "a.cs", delegate { return doc.Text; });*/
                    if (parsedDocument != null)
                    {
                        foreach (PreProcessorDefine define in parsedDocument.Defines)
                        {
                            symbols.Add(define.Define);
                        }
                    }
                }
Beispiel #6
0
        public static void AddNewMembers(IType type, IEnumerable <IMember> newMembers, string regionName = null, Func <IMember, bool> implementExplicit = null)
        {
            IMember firstNewMember = newMembers.FirstOrDefault();

            if (firstNewMember == null)
            {
                return;
            }
            bool isOpen;
            var  data           = TextFileProvider.Instance.GetTextEditorData(type.CompilationUnit.FileName, out isOpen);
            var  parsedDocument = ProjectDomService.GetParsedDocument(type.SourceProjectDom, type.CompilationUnit.FileName);

            var insertionPoints = GetInsertionPoints(data, parsedDocument, type);


            var suitableInsertionPoint = GetSuitableInsertionPoint(insertionPoints, type, firstNewMember);

            var generator = CreateCodeGenerator(data);

            generator.IndentLevel = CalculateBodyIndentLevel(parsedDocument.CompilationUnit.GetTypeAt(type.Location));
            StringBuilder sb = new StringBuilder();

            foreach (IMember newMember in newMembers)
            {
                if (sb.Length > 0)
                {
                    sb.AppendLine();
                    sb.AppendLine();
                }
                sb.Append(generator.CreateMemberImplementation(type, newMember, implementExplicit != null ? implementExplicit(newMember) : false).Code);
            }
            suitableInsertionPoint.Insert(data, string.IsNullOrEmpty(regionName) ? sb.ToString() : generator.WrapInRegions(regionName, sb.ToString()));
            if (!isOpen)
            {
                try {
                    File.WriteAllText(type.CompilationUnit.FileName, data.Text);
                } catch (Exception e) {
                    LoggingService.LogError(GettextCatalog.GetString("Failed to write file '{0}'.", type.CompilationUnit.FileName), e);
                    MessageService.ShowError(GettextCatalog.GetString("Failed to write file '{0}'.", type.CompilationUnit.FileName));
                }
            }
        }
Beispiel #7
0
        void RunFormatter()
        {
            if (PropertyService.Get("OnTheFlyFormatting", false) && textEditorData != null)
            {
                textEditorData.Paste -= TextEditorDataPaste;
                //		textEditorData.Document.TextReplaced -= TextCut;
                ProjectDom dom = ProjectDomService.GetProjectDom(Document.Project);
                if (dom == null)
                {
                    dom = ProjectDomService.GetFileDom(Document.FileName);
                }

                DomLocation location = new DomLocation(textEditorData.Caret.Location.Line + (lastCharInserted == '\n' ? -1 : 0), textEditorData.Caret.Location.Column);
                //				CSharpFormatter.Format (textEditorData, dom, Document.CompilationUnit, location);
                OnTheFlyFormatter.Format(Document, dom, location, lastCharInserted == '\n');

                //		textEditorData.Document.TextReplaced += TextCut;
                textEditorData.Paste += TextEditorDataPaste;
            }
        }
        protected override void ParseFile(string fileName, IProgressMonitor monitor)
        {
            if (monitor != null)
            {
                monitor.BeginTask(string.Format(GettextCatalog.GetString("Parsing file: {0}"), Path.GetFileName(fileName)), 1);
            }

            try {
                ProjectDomService.Parse(this.project,
                                        fileName,
                                        null,
                                        delegate() { return(File.ReadAllText(fileName)); });
                // The call to ProjectDomService.Parse will call UpdateFromParseInfo when done
            } finally {
                if (monitor != null)
                {
                    monitor.EndTask();
                }
            }
        }
        IMember GetMemberToDocument()
        {
            var   parsedDocument = ProjectDomService.Parse(Document.Project, Document.FileName, Document.TextEditorData.Document.MimeType, Document.TextEditorData.Document.Text);
            IType type           = parsedDocument.CompilationUnit.GetTypeAt(textEditorData.Caret.Line, textEditorData.Caret.Column);

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

            foreach (IMember member in type.Members)
            {
                if (member.Location > new DomLocation(textEditorData.Caret.Line + 1, textEditorData.Caret.Column + 1) && (result == null || member.Location < result.Location))
                {
                    result = member;
                }
            }
            return(result);
        }
        public override IEnumerable <MemberReference> FindMemberReferences(RefactorerContext ctx, string fileName, IType cls, IMember member, bool includeXmlComment)
        {
            var editor = ((Mono.TextEditor.ITextEditorDataProvider)ctx.GetFile(fileName)).GetTextEditorData();

            var doc = ProjectDomService.GetParsedDocument(ctx.ParserContext, fileName);

            if (doc == null || doc.CompilationUnit == null)
            {
                return(null);
            }
            NRefactoryResolver resolver = new NRefactoryResolver(ctx.ParserContext, doc.CompilationUnit, ICSharpCode.OldNRefactory.SupportedLanguage.CSharp, editor, fileName);

            resolver.CallingMember = member;
            FindMemberAstVisitor visitor = new FindMemberAstVisitor(editor.Document, member);

            visitor.IncludeXmlDocumentation = includeXmlComment;
            visitor.RunVisitor(resolver);
            SetContext(visitor.FoundReferences, ctx);
            return(visitor.FoundReferences);
        }
Beispiel #11
0
        public override void Setup()
        {
            base.Setup();
            string solFile = Util.GetSampleProject("completion-db-test", "CompletionDbTest.sln");

            solution = (Solution)Services.ProjectService.ReadWorkspaceItem(Util.GetMonitor(), solFile);
            ProjectDomService.Load(solution);

            Project prj;

            prj  = solution.FindProjectByName("Library2");
            lib2 = ProjectDomService.GetProjectDom(prj);
            lib2.ForceUpdate(true);
            prj  = solution.FindProjectByName("Library1");
            lib1 = ProjectDomService.GetProjectDom(prj);
            lib1.ForceUpdate(true);
            prj         = solution.FindProjectByName("CompletionDbTest");
            mainProject = ProjectDomService.GetProjectDom(prj);
            mainProject.ForceUpdate(true);
        }
Beispiel #12
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)
         {
             return(null);
         }
         string  currentParseText   = editor.Text;
         Project curentParseProject = Project;
         this.parsedDocument = ProjectDomService.Parse(curentParseProject, currentParseFile, currentParseText);
         if (this.parsedDocument != null && !this.parsedDocument.HasErrors)
         {
             this.lastErrorFreeParsedDocument = parsedDocument;
         }
     } finally {
         OnDocumentParsed(EventArgs.Empty);
     }
     return(this.parsedDocument);
 }
Beispiel #13
0
        public string GetExpression(int offset)
        {
            string fileName = View.ContentName;

            if (fileName == null)
            {
                fileName = View.UntitledName;
            }

            IExpressionFinder expressionFinder = ProjectDomService.GetExpressionFinder(fileName);
            string            expression       = expressionFinder == null?GetExpressionBeforeOffset(offset) : expressionFinder.FindFullExpression(Document.Text, offset).Expression;

            if (expression == null)
            {
                return(string.Empty);
            }
            else
            {
                return(expression.Trim());
            }
        }
Beispiel #14
0
        static ProjectDom 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);
            }
            ProjectDom dom = ProjectDomService.GetAssemblyDom(runtime, file);

            if (dom == null)
            {
                throw new Exception("System.Web parse database not found for framework " + targetFramework.Id + " file '" + file + "'");
            }
            return(dom);
        }
Beispiel #15
0
        public IEnumerable <Tuple <ProjectDom, FilePath> > GetFileNames(Solution solution, ProjectDom dom, ICompilationUnit unit, IProgressMonitor monitor)
        {
            int counter = 0;
            ReadOnlyCollection <Project> allProjects = solution.GetAllProjects();

            if (monitor != null)
            {
                monitor.BeginTask(GettextCatalog.GetString("Finding references in solution..."),
                                  allProjects.Sum <Project>(p => p.Files.Count));
            }
            foreach (Project project in allProjects)
            {
                if (monitor != null && monitor.IsCancelRequested)
                {
                    yield break;
                }
                ProjectDom currentDom = ProjectDomService.GetProjectDom(project);
                foreach (ProjectFile projectFile in (Collection <ProjectFile>)project.Files)
                {
                    if (monitor != null && monitor.IsCancelRequested)
                    {
                        yield break;
                    }
                    yield return(Tuple.Create <ProjectDom, FilePath>(currentDom, projectFile.FilePath));

                    if (monitor != null)
                    {
                        if (counter % 10 == 0)
                        {
                            monitor.Step(10);
                        }
                        ++counter;
                    }
                }
            }
            if (monitor != null)
            {
                monitor.EndTask();
            }
        }
 void FillClasses(MoonlightProject project)
 {
     if (classesFilled)
     {
         return;
     }
     classesFilled = true;
     try {
         ProjectDom dom     = ProjectDomService.GetProjectDom(project);
         IType      appType = dom.GetType("System.Windows.Application", true);
         if (appType == null)
         {
             return;
         }
         foreach (IType type in dom.GetSubclasses(appType, false))
         {
             classListStore.AppendValues(type.FullName);
         }
     } catch (InvalidOperationException) {
         // Project not found in parser database
     }
 }
Beispiel #17
0
        /// Synchronizes the bindings between the object and the source code
        public void UpdateBindings(string fileName)
        {
            if (targetObject == null)
            {
                return;
            }

            ParsedDocument doc = ProjectDomService.Parse(project, fileName, null);

            classFile = fileName;

            if (doc != null && doc.CompilationUnit != null)
            {
                IType cls = GetClass();
                UpdateBindings(targetObject, cls);

                if (cls != null)
                {
                    targetObject.GeneratePublic = cls.IsPublic;
                }
            }
        }
Beispiel #18
0
        public override void BuildChildNodes(ITreeBuilder treeBuilder,
                                             object dataObject)
        {
            PackageNode          packageNode = dataObject as PackageNode;
            PythonParsedDocument parsed      = ProjectDomService.ParseFile(null, packageNode.ProjectFile.Name) as PythonParsedDocument;

            if (parsed != null && parsed.Module != null)
            {
                foreach (PythonClass pyClass in parsed.Module.Classes)
                {
                    treeBuilder.AddChild(pyClass);
                }
                foreach (PythonAttribute pyAttr in parsed.Module.Attributes)
                {
                    treeBuilder.AddChild(pyAttr);
                }
                foreach (PythonFunction pyFunc in parsed.Module.Functions)
                {
                    treeBuilder.AddChild(pyFunc);
                }
            }
        }
Beispiel #19
0
        bool AnalyzeTargetExpression(RefactoringOptions options, MonoDevelop.CSharp.Ast.CompilationUnit unit)
        {
            var data   = options.GetTextEditorData();
            var target = unit.GetNodeAt(data.Caret.Line, data.Caret.Column);

            if (target == null)
            {
                return(false);
            }
            if (target.Parent is MemberReferenceExpression && ((MemberReferenceExpression)target.Parent).GetChildByRole(MemberReferenceExpression.Roles.Identifier) == target)
            {
                var memberReference = (MemberReferenceExpression)target.Parent;
                target = memberReference.Target;
                var targetResult = options.GetResolver().Resolve(new ExpressionResult(data.GetTextBetween(target.StartLocation.Line, target.StartLocation.Column, target.EndLocation.Line, target.EndLocation.Column)), resolvePosition);
                if (targetResult.StaticResolve)
                {
                    modifiers = MonoDevelop.Projects.Dom.Modifiers.Static;
                }
                declaringType = options.Dom.GetType(targetResult.ResolvedType);
                methodName    = memberReference.MemberName;
            }
            else if (target is Identifier)
            {
                declaringType = options.ResolveResult.CallingType;
                methodName    = data.GetTextBetween(target.StartLocation.Line, target.StartLocation.Column, target.EndLocation.Line, target.EndLocation.Column);
            }

            if (declaringType != null && !HasCompatibleMethod(declaringType, methodName, invocation))
            {
                if (declaringType.HasParts)
                {
                    declaringType = declaringType.Parts.FirstOrDefault(t => t.CompilationUnit.FileName == options.Document.FileName) ?? declaringType;
                }
                var doc = ProjectDomService.GetParsedDocument(declaringType.SourceProjectDom, declaringType.CompilationUnit.FileName);
                declaringType = doc.CompilationUnit.GetTypeAt(declaringType.Location) ?? declaringType;
                return(true);
            }
            return(false);
        }
Beispiel #20
0
        void LoadSolutionContents(Solution sln)
        {
            loadedSlns.Add(sln);

            // Load all tags that are stored in pidb files
            foreach (Project p in sln.GetAllProjects())
            {
                ProjectDom pContext = ProjectDomService.GetProjectDom(p);
                if (pContext == null)
                {
                    continue;
                }
                foreach (ProjectFile file in p.Files)
                {
                    IList <Tag> tags = pContext.GetSpecialComments(file.Name);
                    if (tags != null && tags.Count > 0)
                    {
                        UpdateCommentTags(sln, file.Name, tags);
                    }
                }
            }
        }
Beispiel #21
0
        public Gtk.Window CreateTooltipWindow(Mono.TextEditor.TextEditor editor, int offset, Gdk.ModifierType modifierState, TooltipItem item)
        {
            ExtensibleTextEditor ed  = (ExtensibleTextEditor)editor;
            ParsedDocument       doc = ProjectDomService.GetParsedDocument(null, ed.Document.FileName);

            ResolveResult resolveResult = (ResolveResult)item.Item;

            if (lastResult != null && lastResult.ResolvedExpression != null && lastWindow.IsRealized &&
                resolveResult != null && resolveResult.ResolvedExpression != null && lastResult.ResolvedExpression.Expression == resolveResult.ResolvedExpression.Expression)
            {
                return(lastWindow);
            }
            LanguageItemWindow result = new LanguageItemWindow(ed, modifierState, resolveResult, null, doc != null ? doc.CompilationUnit : null);

            lastWindow = result;
            lastResult = resolveResult;
            if (result.IsEmpty)
            {
                return(null);
            }
            return(result);
        }
Beispiel #22
0
        void OnFileRemoved(object sender, ProjectFileEventArgs args)
        {
            ArrayList toDelete       = new ArrayList();
            ArrayList toDeleteGroups = new ArrayList();

            ParsedDocument doc = ProjectDomService.GetParsedDocument(ProjectDomService.GetProjectDom(args.Project), args.ProjectFile.Name);

            if (doc == null || doc.CompilationUnit == null)
            {
                return;
            }

            foreach (IType t in doc.CompilationUnit.Types)
            {
                GuiBuilderWindow win = GetWindowForClass(t.FullName);
                if (win != null)
                {
                    toDelete.Add(win);
                    continue;
                }

                Stetic.ActionGroupInfo group = GetActionGroup(t.FullName);
                if (group != null)
                {
                    toDeleteGroups.Add(group);
                }
            }

            foreach (GuiBuilderWindow win in toDelete)
            {
                Remove(win);
            }

            foreach (Stetic.ActionGroupInfo group in toDeleteGroups)
            {
                RemoveActionGroup(group);
            }
        }
Beispiel #23
0
//		public bool RenameVariable (IProgressMonitor monitor, LocalVariable var, string newName)
//		{
//			try {
//				MemberReferenceCollection refs = new MemberReferenceCollection ();
//				Refactor (monitor, var, new RefactorDelegate (new RefactorFindVariableReferences (var, refs).Refactor));
//				refs.RenameAll (newName);
//
//				RefactorerContext gctx = GetGeneratorContext (var);
//				IRefactorer r = GetGeneratorForVariable (var);
//				bool rv = r.RenameVariable (gctx, var, newName);
//				gctx.Save ();
//
//				return rv;
//			} catch (Exception e) {
//				LoggingService.LogError (GettextCatalog.GetString ("Error while renaming {0} to {1}: {2}",  var, newName, e.ToString ()));
//				return false;
//			}
//		}
//
//		public bool RenameParameter (IProgressMonitor monitor, IParameter param, string newName)
//		{
//			try {
//				MemberReferenceCollection refs = new MemberReferenceCollection ();
//				Refactor (monitor, param, new RefactorDelegate (new RefactorFindParameterReferences (param, refs, false).Refactor));
//				refs.RenameAll (newName);
//
//				IMember member = param.DeclaringMember;
//				RefactorerContext gctx = GetGeneratorContext (member.DeclaringType);
//				IRefactorer r = GetGeneratorForClass (member.DeclaringType);
//				bool rv = r.RenameParameter (gctx, param, newName);
//				gctx.Save ();
//
//				return rv;
//			} catch (Exception e) {
//				LoggingService.LogError (GettextCatalog.GetString ("Error while renaming {0} to {1}: {2}",  param, newName, e.ToString ()));
//				return false;
//			}
//		}

        public IType[] FindDerivedClasses(IType baseClass)
        {
            ArrayList list = new ArrayList();

            if (solution != null)
            {
                foreach (Project p in solution.GetAllProjects())
                {
                    ProjectDom ctx = ProjectDomService.GetProjectDom(p);
                    if (ctx == null)
                    {
                        continue;
                    }
                    foreach (IType cls in ctx.Types)
                    {
                        if (IsSubclass(ctx, baseClass, cls))
                        {
                            list.Add(cls);
                        }
                    }
                }
            }
            else
            {
                ProjectDom ctx = GetParserContext(baseClass);
                if (ctx != null)
                {
                    foreach (IType cls in ctx.Types)
                    {
                        if (IsSubclass(ctx, baseClass, cls))
                        {
                            list.Add(cls);
                        }
                    }
                }
            }
            return((IType[])list.ToArray(typeof(IType)));
        }
        void ParseCallback(object ob, IProgressMonitor monitor)
        {
            string fileName = (string)ob;

            ProjectDomService.Parse(Project,
                                    fileName,
                                    null,
                                    delegate() {
                return(File.ReadAllText(fileName));
            });


            /*
             * ParseFile (fileName, monitor);
             * lock (rwlock) {
             *      FileEntry file = GetFile (fileName);
             *      if (file != null) {
             *              file.InParseQueue = false;
             *              FileInfo fi = new FileInfo (fileName);
             *              file.LastParseTime = fi.LastWriteTime;
             *      }
             * }*/
        }
Beispiel #25
0
        public CodeTemplateContext GetTemplateContext()
        {
            if (IsSomethingSelected)
            {
                string  fileName = view.ContentName ?? view.UntitledName;
                IParser parser   = ProjectDomService.GetParser(fileName, Document.MimeType);
                if (parser == null)
                {
                    return(CodeTemplateContext.Standard);
                }

                IExpressionFinder expressionFinder = parser.CreateExpressionFinder(ProjectDom);
                if (expressionFinder == null)
                {
                    return(CodeTemplateContext.Standard);
                }
                if (expressionFinder.IsExpression(Document.GetTextAt(SelectionRange)))
                {
                    return(CodeTemplateContext.InExpression);
                }
            }
            return(CodeTemplateContext.Standard);
        }
Beispiel #26
0
        void OnDocumentChanged(object o, EventArgs a)
        {
            // Don't directly parse the document because doing it at every key press is
            // very inefficient. Do it after a small delay instead, so several changes can
            // be parsed at the same time.

            if (parsing)
            {
                return;
            }

            parsing = true;
            string currentParseFile = FileName;
            string mime             = DesktopService.GetMimeTypeForUri(currentParseFile);

            GLib.Timeout.Add(ParseDelay, delegate {
                if (closed)
                {
                    return(false);
                }
                parsing = false;
                string currentParseText    = TextEditor.Text;
                Project curentParseProject = Project;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                    // Don't access Document properties from the thread
                    this.parsedDocument = ProjectDomService.Parse(curentParseProject, currentParseFile, mime, currentParseText);
                    if (this.parsedDocument != null && !this.parsedDocument.HasErrors)
                    {
                        this.lastErrorFreeParsedDocument = parsedDocument;
                    }
                    DispatchService.GuiSyncDispatch(delegate {
                        OnDocumentParsed(EventArgs.Empty);
                    });
                });
                return(false);
            });
        }
        void LoadExceptions()
        {
            ProjectDom dom;

            if (IdeApp.ProjectOperations.CurrentSelectedProject != null)
            {
                dom = ProjectDomService.GetProjectDom(IdeApp.ProjectOperations.CurrentSelectedProject);
            }
            else
            {
                string asm = typeof(Uri).Assembly.Location;
                if (!systemLoaded)
                {
                    ProjectDomService.LoadAssembly(Runtime.SystemAssemblyService.CurrentRuntime, asm);
                    systemLoaded = true;
                }
                dom = ProjectDomService.GetAssemblyDom(Runtime.SystemAssemblyService.CurrentRuntime, asm);
            }
            classes.Add("System.Exception");
            foreach (IType t in dom.GetSubclasses(dom.GetType("System.Exception", true)))
            {
                classes.Add(t.FullName);
            }
        }
        public static void AddNewMember(IType type, IMember newMember, bool implementExplicit = false)
        {
            bool isOpen;
            var  data           = TextFileProvider.Instance.GetTextEditorData(type.CompilationUnit.FileName, out isOpen);
            var  parsedDocument = ProjectDomService.GetParsedDocument(type.SourceProjectDom, type.CompilationUnit.FileName);

            var insertionPoints = GetInsertionPoints(data, parsedDocument, type);

            var suitableInsertionPoint = GetSuitableInsertionPoint(insertionPoints, type, newMember);

            var generator     = CreateCodeGenerator(data);
            var generatedCode = generator.CreateMemberImplementation(type, newMember, implementExplicit);

            suitableInsertionPoint.Insert(data, generatedCode.Code);
            if (!isOpen)
            {
                try {
                    File.WriteAllText(type.CompilationUnit.FileName, data.Text);
                } catch (Exception e) {
                    LoggingService.LogError(GettextCatalog.GetString("Failed to write file '{0}'.", type.CompilationUnit.FileName), e);
                    MessageService.ShowError(GettextCatalog.GetString("Failed to write file '{0}'.", type.CompilationUnit.FileName));
                }
            }
        }
        ITypeNameResolver GetTypeNameResolver(IType cls)
        {
            if (cls.CompilationUnit == null || cls.CompilationUnit.FileName == FilePath.Null)
            {
                return(null);
            }
            string         file = cls.CompilationUnit.FileName;
            ParsedDocument pi   = ProjectDomService.GetParsedDocument(cls.SourceProjectDom, file);

            if (pi == null)
            {
                return(null);
            }
            ICompilationUnit unit = pi.CompilationUnit;

            if (unit != null)
            {
                return(new TypeNameResolver(unit, cls));
            }
            else
            {
                return(null);
            }
        }
Beispiel #30
0
        //	string expression;

/*		IMember GetLanguageItem (Mono.TextEditor.Document document, LineSegment line, int offset, string expression)
 *              {
 *                      string txt = document.Text;
 *                      ExpressionResult expressionResult = new ExpressionResult (expression);
 * //			ExpressionResult expressionResult = expressionFinder.FindFullExpression (txt, offset);
 *                      int lineNumber = document.OffsetToLineNumber (offset);
 *                      expressionResult.Region = new DomRegion (lineNumber, offset - line.Offset, lineNumber, offset + expression.Length - line.Offset);
 *                      expressionResult.ExpressionContext = ExpressionContext.IdentifierExpected;
 *
 *                      resolver = new NRefactoryResolver (ctx, doc.CompilationUnit, doc.TextEditor, document.FileName);
 *                      ResolveResult result = resolver.Resolve (expressionResult, expressionResult.Region.Start);
 *
 *                      if (result is MemberResolveResult)
 *                              return ((MemberResolveResult)result).ResolvedMember;
 *                      return null;
 *              }*/

        public override void Analyze(Mono.TextEditor.Document doc, LineSegment line, Chunk startChunk, int startOffset, int endOffset)
        {
            if (!MonoDevelop.Core.PropertyService.Get("EnableSemanticHighlighting", false) || doc == null || line == null || startChunk == null)
            {
                return;
            }
            ctx = GetParserContext(doc);
            int              lineNumber     = doc.OffsetToLineNumber(line.Offset);
            ParsedDocument   parsedDocument = ProjectDomService.GetParsedDocument(ctx, doc.FileName);
            ICompilationUnit unit           = parsedDocument != null ? parsedDocument.CompilationUnit : null;

            if (unit == null)
            {
                return;
            }
            for (Chunk chunk = startChunk; chunk != null; chunk = chunk.Next)
            {
                if (chunk.Style != "text")
                {
                    continue;
                }
                for (int i = chunk.Offset; i < chunk.EndOffset; i++)
                {
                    char charBefore = i > 0 ? doc.GetCharAt(i - 1) : '}';
                    if (Char.IsLetter(doc.GetCharAt(i)) && !Char.IsLetterOrDigit(charBefore))
                    {
                    }
                    else
                    {
                        continue;
                    }

                    int  start         = i;
                    bool wasWhitespace = false;
                    bool wasDot        = false;
                    int  bracketCount  = 0;
                    while (start > 0)
                    {
                        char ch = doc.GetCharAt(start);
                        if (ch == '\n' || ch == '\r')
                        {
                            break;
                        }
                        if (wasWhitespace && IsNamePart(ch))
                        {
                            start++;
                            if (start < chunk.Offset)
                            {
                                start = Int32.MaxValue;
                            }
                            break;
                        }
                        if (ch == '<')
                        {
                            bracketCount--;
                            if (bracketCount < 0)
                            {
                                start++;
                                break;
                            }
                            start--;
                            wasWhitespace = false;
                            continue;
                        }
                        if (ch == '>')
                        {
                            if (wasWhitespace && !wasDot)
                            {
                                break;
                            }
                            bracketCount++;
                            start--;
                            wasWhitespace = false;
                            continue;
                        }
                        if (!IsNamePart(ch) && !Char.IsWhiteSpace(ch) && ch != '.')
                        {
                            start++;
                            break;
                        }
                        wasWhitespace = Char.IsWhiteSpace(ch);
                        wasDot        = ch == '.' || wasDot && wasWhitespace;
                        start--;
                    }

                    int end          = i;
                    int genericCount = 0;
                    wasWhitespace = false;
                    List <Segment> nameSegments = new List <Segment> ();
                    while (end < chunk.EndOffset)
                    {
                        char ch = doc.GetCharAt(end);
                        if (wasWhitespace && IsNamePart(ch))
                        {
                            break;
                        }
                        if (ch == '<')
                        {
                            genericCount = 1;
                            while (end < doc.Length)
                            {
                                ch = doc.GetCharAt(end);
                                if (ch == ',')
                                {
                                    genericCount++;
                                }
                                if (ch == '>')
                                {
                                    nameSegments.Add(new Segment(end, 1));
                                    break;
                                }
                                end++;
                            }
                            break;
                        }
                        if (!IsNamePart(ch) && !Char.IsWhiteSpace(ch))
                        {
                            break;
                        }
                        wasWhitespace = Char.IsWhiteSpace(ch);
                        end++;
                    }
                    if (start >= end)
                    {
                        continue;
                    }
                    string      typeString = doc.GetTextBetween(start, end);
                    IReturnType returnType = NRefactoryResolver.ParseReturnType(new ExpressionResult(typeString));

                    int nameEndOffset = start;
                    for (; nameEndOffset < end; nameEndOffset++)
                    {
                        char ch = doc.GetCharAt(nameEndOffset);
                        if (nameEndOffset >= i && ch == '<')
                        {
                            nameEndOffset++;
                            break;
                        }
                    }
                    nameSegments.Add(new Segment(i, nameEndOffset - i));

                    int   column      = i - line.Offset;
                    IType callingType = unit.GetTypeAt(lineNumber, column);
                    List <IReturnType> genericParams = null;
                    if (genericCount > 0)
                    {
                        genericParams = new List <IReturnType> ();
                        for (int n = 0; n < genericCount; n++)
                        {
                            genericParams.Add(new DomReturnType("A"));
                        }
                    }

                    IType type = null;
                    if (ctx != null)
                    {
                        type = ctx.SearchType((MonoDevelop.Projects.Dom.INode)callingType ?? unit, returnType);
                    }
                    if (type == null && unit != null && returnType != null)
                    {
                        type = unit.GetType(returnType.FullName, returnType.GenericArguments.Count);
                    }
                    if (ctx != null && type == null && returnType != null)
                    {
                        returnType.Name += "Attribute";
                        type             = ctx.SearchType((MonoDevelop.Projects.Dom.INode)callingType ?? unit, returnType);
                    }
                    if (type != null)
                    {
                        nameSegments.ForEach(segment => HighlightSegment(startChunk, segment, "keyword.semantic.type"));
                    }
                }
            }
        }