public GenerateNamespaceImport GetResult (ProjectDom dom, ICompilationUnit unit, IType type, TextEditorData data)
		{
			GenerateNamespaceImport result;
			if (cache.TryGetValue (type.Namespace, out result))
				return result;
			result = new GenerateNamespaceImport ();
			cache[type.Namespace] = result;
			
			result.InsertNamespace  = false;
			
			DomLocation location = new DomLocation (data.Caret.Line, data.Caret.Column);
			foreach (IUsing u in unit.Usings.Where (u => u.ValidRegion.Contains (location))) {
				if (u.Namespaces.Any (ns => type.Namespace == ns)) {
					result.GenerateUsing = false;
					return result;
				}
			}
			result.GenerateUsing = true;
			string name = type.DecoratedFullName.Substring (type.Namespace.Length + 1);
			
			foreach (IUsing u in unit.Usings.Where (u => u.ValidRegion.Contains (location))) {
				foreach (string ns in u.Namespaces) {
					if (dom.SearchType (unit, unit.GetTypeAt (location), unit.GetMemberAt (location), ns + "." + name) != null) {
						result.GenerateUsing = false;
						result.InsertNamespace = true;
						return result;
					}
				}
			}
			return result;
		}
		public static void Format (TextEditorData data, ProjectDom dom, DomLocation location, bool correctBlankLines)
		{
			PolicyContainer policyParent = dom != null && dom.Project != null? dom.Project.Policies
				: PolicyService.DefaultPolicies;
			var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			Format (policyParent, mimeTypeChain, data, dom, location, correctBlankLines);
		}
		public static void Format (MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR = false)
		{
			PolicyContainer policyParent = dom != null && dom.Project != null ? dom.Project.Policies
 : PolicyService.DefaultPolicies;
			var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			Format (policyParent, mimeTypeChain, data, dom, location, correctBlankLines, runAferCR);
		}
		public RefactorerContext (ProjectDom ctx, ITextFileProvider files, IType cls)
		{
			this.files = files;
			this.ctx = ctx;
			if (cls != null)
				typeResolver = GetTypeNameResolver (cls);
		}
		public override ParsedDocument Parse (ProjectDom dom, string fileName, string fileContent)
		{
			XmlParsedDocument doc = new XmlParsedDocument (fileName);
			doc.Flags |= ParsedDocumentFlags.NonSerializable;
			TextReader tr = new StringReader (fileContent);
			try {
				Parser xmlParser = new Parser (new XmlFreeState (), true);
				xmlParser.Parse (tr);
				doc.XDocument = xmlParser.Nodes.GetRoot ();
				doc.Add (xmlParser.Errors);
				
				if (doc.XDocument != null && doc.XDocument.RootElement != null) {
					if (!doc.XDocument.RootElement.IsEnded)
						doc.XDocument.RootElement.End (xmlParser.Location);
				}
			}
			catch (Exception ex) {
				MonoDevelop.Core.LoggingService.LogError ("Unhandled error parsing xml document", ex);
			}
			finally {
				if (tr != null)
					tr.Dispose ();
			}
			return doc;
		}
		public override IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, IEnumerable<INode> searchedMembers)
		{
			var editor = TextFileProvider.Instance.GetTextEditorData (fileName);
			AspNetAppProject project = dom.Project as AspNetAppProject;
			if (project == null)
				yield break;
			
			var unit = AspNetParserService.GetCompileUnit (project, fileName, true);
			if (unit == null)
				yield break;
			var refman = new DocumentReferenceManager (project);
			
			var parsedAspDocument = (AspNetParsedDocument)new AspNetParser ().Parse (dom, fileName, editor.Text);
			refman.Doc = parsedAspDocument;
			
			var usings = refman.GetUsings ();
			var documentInfo = new DocumentInfo (dom, unit, usings, refman.GetDoms ());
			
			var builder = new AspLanguageBuilder ();
			
			
			var buildDocument = new Mono.TextEditor.Document ();
			var offsetInfos = new List<LocalDocumentInfo.OffsetInfo> ();
			buildDocument.Text = builder.BuildDocumentString (documentInfo, editor, offsetInfos, true);
			var parsedDocument = AspLanguageBuilder.Parse (dom, fileName, buildDocument.Text);
			foreach (var member in searchedMembers) {
				foreach (var reference in SearchMember (member, dom, fileName, editor, buildDocument, offsetInfos, parsedDocument)) {
					yield return reference;
				}
			}
		}
		public InstantiatedParameterType (ProjectDom dom, ITypeParameterMember typeParameterMember, ITypeParameter tp)
		{
			IType outerType = typeParameterMember as IType ?? typeParameterMember.DeclaringType;
			typeparam = tp;
			compilationUnit = outerType.CompilationUnit;
			ClassType = ClassType.Class;
			Modifiers = Modifiers.Public;
			Name = tp.Name;
			Namespace = outerType.DecoratedFullName;
			Location = outerType.Location;
			DeclaringType = outerType;
			
			if (tp.Constraints.Count > 0)
				ClassType = ClassType.Interface;
			foreach (IReturnType rt in tp.Constraints) {
				if (FindCyclicReference (new HashSet<ITypeParameter> () { tp }, outerType, ((DomReturnType)rt).DecoratedFullName))
					continue;
				IType bt = dom.SearchType (typeParameterMember, rt);
				IReturnType resolvedType = rt;
				if (bt != null) {
					resolvedType = new DomReturnType (bt);
					if (bt.ClassType == ClassType.Interface || BaseType != null) {
						AddInterfaceImplementation (resolvedType);
					} else {
						ClassType = bt.ClassType;
						BaseType = resolvedType;
					}
				} else {
					AddInterfaceImplementation (resolvedType);
				}
			}
			if (BaseType == null)
				BaseType = DomReturnType.Object;
		}
		public override IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, IEnumerable<INode> searchedMembers)
		{
			HashSet<int > positions = new HashSet<int> ();
			var editor = TextFileProvider.Instance.GetTextEditorData (fileName);
			FindMemberAstVisitor visitor = new FindMemberAstVisitor (editor.Document);
			visitor.IncludeXmlDocumentation = IncludeDocumentation;
			visitor.Init (searchedMembers);
			if (!visitor.FileContainsMemberName ()) {
				yield break;
			}
			var doc = ProjectDomService.ParseFile (dom, fileName, () => editor.Text);
			if (doc == null || doc.CompilationUnit == null)
				yield break;
			var resolver = new NRefactoryResolver (dom, doc.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, editor, fileName);

			visitor.ParseFile (resolver);
			visitor.RunVisitor (resolver);
			foreach (var reference in visitor.FoundReferences) {
				if (positions.Contains (reference.Position))
					continue;
				positions.Add (reference.Position);
				yield return reference;
			}
			visitor.ClearParsers ();
		}
		public override ParsedDocument Parse (ProjectDom dom, string fileName, string fileContent)
		{
			XmlParsedDocument doc = new XmlParsedDocument (fileName);
			doc.Flags = ParsedDocumentFlags.NonSerializable;
			
			TextReader tr = new StringReader (fileContent);
			try {
				Parser xmlParser = new Parser (
					new XmlFreeState (new HtmlTagState (true), new HtmlClosingTagState (true)),
					true);
				
				xmlParser.Parse (tr);
				doc.XDocument = xmlParser.Nodes.GetRoot ();
				doc.Add (xmlParser.Errors);
				if (doc.XDocument != null)
					doc.Add (Validate (doc.XDocument));
			}
			catch (Exception ex) {
				MonoDevelop.Core.LoggingService.LogError ("Unhandled error parsing HTML document", ex);
			}
			finally {
				if (tr != null)
					tr.Dispose ();
			}
			
			return doc;
		}
Beispiel #10
0
		public static IMember GetCompatibleMemberInClass (ProjectDom ctx, IType cls, CodeTypeMember member)
		{
			//check for identical property names
			foreach (IProperty prop in cls.Properties) {
				if (string.Compare (prop.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) {
					EnsureClassExists (ctx, prop.ReturnType.FullName, GetValidRegion (prop));
					CodeMemberProperty memProp = member as CodeMemberProperty;
					if (memProp == null || !IsTypeCompatible (ctx, prop.ReturnType.FullName, memProp.Type.BaseType))
						throw new MemberExistsException (cls.FullName, MemberType.Property, member, GetValidRegion (prop), cls.CompilationUnit.FileName);
					return prop;
				}
			}
				
			//check for identical method names
			foreach (IMethod meth in cls.Methods) {
				if (string.Compare (meth.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) {
					EnsureClassExists (ctx, meth.ReturnType.FullName, GetValidRegion (meth));
					CodeMemberMethod memMeth = member as CodeMemberMethod;
					if (memMeth == null || !IsTypeCompatible (ctx, meth.ReturnType.FullName, memMeth.ReturnType.BaseType))
						throw new MemberExistsException (cls.FullName, MemberType.Method, member, GetValidRegion (meth), cls.CompilationUnit.FileName);
					return meth;
				}
			}
			
			//check for identical event names
			foreach (IEvent ev in cls.Events) {
				if (string.Compare (ev.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) {
					EnsureClassExists (ctx, ev.ReturnType.FullName, GetValidRegion (ev));
					CodeMemberEvent memEv = member as CodeMemberEvent;
					if (memEv == null || !IsTypeCompatible (ctx, ev.ReturnType.FullName, memEv.Type.BaseType))
						throw new MemberExistsException (cls.FullName, MemberType.Event, member, GetValidRegion (ev), cls.CompilationUnit.FileName);
					return ev;
				}
			}
				
			//check for identical field names
			foreach (IField field in cls.Fields) {
				if (string.Compare (field.Name, member.Name, StringComparison.OrdinalIgnoreCase) == 0) {
					EnsureClassExists (ctx, field.ReturnType.FullName, GetValidRegion (field));
					CodeMemberField memField = member as CodeMemberField;
					if (memField == null || !IsTypeCompatible (ctx, field.ReturnType.FullName, memField.Type.BaseType))
						throw new MemberExistsException (cls.FullName, MemberType.Field, member, GetValidRegion (field), cls.CompilationUnit.FileName);
					return field;
				}
			}
			
			//walk down into base classes, if any
			foreach (IReturnType baseType in cls.BaseTypes) {
				IType c = ctx.GetType (baseType);
				if (c == null)
					throw new TypeNotFoundException (baseType.FullName, cls.BodyRegion, cls.CompilationUnit.FileName);
				IMember mem = GetCompatibleMemberInClass (ctx, c, member);
				if (mem != null)
					return mem;
			}
			
			//return null if no match
			return null;
		}
		public override IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, IEnumerable<INode> searchedMembers)
		{
			foreach (var member in searchedMembers) {
				foreach (var reference in FindReferences (dom, fileName, member)) {
					yield return reference;
				}
			}
		}
		public static ParsedDocument Parse (ProjectDom dom, string fileName, string text)
		{
			var result = new MonoDevelop.CSharp.Parser.McsParser ().Parse (null, fileName, text);
			foreach (DomType type in result.CompilationUnit.Types) {
				type.SourceProjectDom = dom;
			}
			return result;
		}
		public override IResolver CreateResolver (ProjectDom dom, object editor, string fileName)
		{
			MonoDevelop.Ide.Gui.Document doc = (MonoDevelop.Ide.Gui.Document)editor;
			if (doc.Editor == null)
				return null;
			
			return new NRefactoryResolver (dom, doc.CompilationUnit, ICSharpCode.OldNRefactory.SupportedLanguage.CSharp, doc.Editor, fileName);
		}
		public string OutputNode (ProjectDom dom, INode node, string indent)
		{
			CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor ();
			CSharpFormatter.SetFormatOptions (outputVisitor, dom != null && dom.Project != null ? dom.Project.Policies : null);
			int col = CSharpFormatter.GetColumn (indent, 0, 4);
			outputVisitor.OutputFormatter.IndentationLevel = System.Math.Max (0, col / 4);
			node.AcceptVisitor (outputVisitor, null);
			return outputVisitor.Text;
		}
Beispiel #15
0
		IType GetFullClass (out ProjectDom ctx)
		{
			if (project == null || className == null) {
				ctx = null;
				return null;
			}
			ctx = MonoDevelop.Projects.Dom.Parser.ProjectDomService.GetProjectDom (project);
			return ctx.GetType (className, false, false);
		}
		public override void Initialize ()
		{
			base.Initialize ();
			
			dom = Document.Dom;
			
			textEditorResolver = base.Document.GetContent<ITextEditorResolver> ();
			textEditorData = base.Document.Editor;
			textEditorData.Caret.PositionChanged += HandleTextEditorDataCaretPositionChanged;
			textEditorData.Document.TextReplaced += HandleTextEditorDataDocumentTextReplaced;
		}
		public override void Initialize ()
		{
			base.Initialize ();
			dom = Document.Dom;
			textEditorData = Document.TextEditorData;
			
			InitTracker ();
			IEnumerable<string> types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			if (dom != null && dom.Project != null)
				policy = base.Document.Project.Policies.Get<CSharpFormattingPolicy> (types);
		}
 public string OutputNode(ProjectDom dom, INode node, string indent)
 {
     /* WNH FSharpOutputVisitor FIXME!!!!!		FSharpOutputVisitor outputVisitor = new FSharpOutputVisitor ();
     FSharpFormatter.SetFormatOptions (outputVisitor, dom.Project);
     int col = FSharpFormatter.GetColumn (indent, 0, 4);
     outputVisitor.OutputFormatter.IndentationLevel = System.Math.Max (0, col / 4);
     node.AcceptVisitor (outputVisitor, null);
     return outputVisitor.Text;
     WNH */
     return "Hello World";      // WNH RIP OUT later
 }
Beispiel #19
0
 static IEnumerable <MonoDevelop.Projects.Dom.IProperty> GetAllProperties(
     MonoDevelop.Projects.Dom.Parser.ProjectDom projectDatabase,
     MonoDevelop.Projects.Dom.IType cls)
 {
     foreach (MonoDevelop.Projects.Dom.IType type in projectDatabase.GetInheritanceTree(cls))
     {
         foreach (MonoDevelop.Projects.Dom.IProperty prop in type.Properties)
         {
             yield return(prop);
         }
     }
 }
Beispiel #20
0
 static IEnumerable <MonoDevelop.Projects.Dom.IEvent> GetAllEvents(
     MonoDevelop.Projects.Dom.Parser.ProjectDom projectDatabase,
     MonoDevelop.Projects.Dom.IType cls)
 {
     foreach (MonoDevelop.Projects.Dom.IType type in projectDatabase.GetInheritanceTree(cls))
     {
         foreach (MonoDevelop.Projects.Dom.IEvent ev in type.Events)
         {
             yield return(ev);
         }
     }
 }
		public NewOverrideCompletionData (ProjectDom dom, TextEditorData editor, int declarationBegin, IType type, IMember member) : base (null)
		{
			this.editor = editor;
			this.type   = type;
			this.member = member;
			
			this.declarationBegin = declarationBegin;
			this.GenerateBody = true;
			this.Icon = member.StockIcon;
			this.DisplayText = ambience.GetString (member, OutputFlags.IncludeParameters | OutputFlags.IncludeGenerics | OutputFlags.HideExtensionsParameter);
			this.CompletionText = member.Name;
		}
		static IEnumerable<Tuple<ProjectDom, FilePath>> GetFileNames (Solution solution, ProjectDom dom, ICompilationUnit unit, INode member, IProgressMonitor monitor)
		{
			var scope = GetScope (member);
			int counter = 0;
			switch (scope) {
			case RefactoryScope.File:
			case RefactoryScope.DeclaringType:
				if (dom != null && unit != null)
					yield return Tuple.Create (dom, unit.FileName);
				break;
			case RefactoryScope.Project:
				if (dom == null)
					yield break;
				if (monitor != null)
					monitor.BeginTask (GettextCatalog.GetString ("Finding references in project..."), dom.Project.Files.Count);
				foreach (var file in dom.Project.Files) {
					if (monitor != null && monitor.IsCancelRequested)
						yield break;
					yield return Tuple.Create (dom, file.FilePath);
					if (monitor != null) {
						if (counter % 10 == 0)
							monitor.Step (10);
						counter++;
					}
				}
				if (monitor != null)
					monitor.EndTask ();
				break;
			case RefactoryScope.Solution:
				var allProjects = solution.GetAllProjects ();
				if (monitor != null)
					monitor.BeginTask (GettextCatalog.GetString ("Finding references in solution..."),
						allProjects.Sum (p => p.Files.Count));
				foreach (var project in allProjects) {
					if (monitor != null && monitor.IsCancelRequested)
						yield break;
					var currentDom = ProjectDomService.GetProjectDom (project);
					foreach (var file in project.Files) {
						if (monitor != null && monitor.IsCancelRequested)
							yield break;
						yield return Tuple.Create (currentDom, file.FilePath);
						if (monitor != null) {
							if (counter % 10 == 0)
								monitor.Step (10);
							counter++;
						}
					}
				}
				if (monitor != null)
					monitor.EndTask ();
				break;
			}
		}
		public string OutputNode (ProjectDom dom, AstNode node, string indent)
		{
			StringWriter w = new StringWriter();
			var policyParent = dom != null && dom.Project != null ? dom.Project.Policies : null;
			IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			CSharpFormattingPolicy codePolicy = policyParent != null ? policyParent.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);
			var formatter = new TextWriterOutputFormatter(w);
			int col = GetColumn (indent, 0, 4);
			formatter.Indentation = System.Math.Max (0, col / 4);
			OutputVisitor visitor = new OutputVisitor (formatter, codePolicy.CreateOptions ());
			node.AcceptVisitor (visitor, null);
			return w.ToString();
		}
        public void Deserialize(XElement xml, ProjectDom dom)
        {
            if (xml == null) {
                throw new ArgumentNullException ("xml");
            }

            var textAttr = xml.Attribute ("CommentText");
            if (textAttr != null) {
                Text = textAttr.Value;
            }

            this.DeserializePosition (xml.Element ("Position"));
        }
		public override ParsedDocument Parse (ProjectDom dom, string fileName, string fileContent)
		{
			using (var tr = new StringReader (fileContent)) {
				var info = new PageInfo ();
				var rootNode = new RootNode ();
				var errors = new List<Error> ();
				
				try {
					rootNode.Parse (fileName, tr);
				} catch (Exception ex) {
					LoggingService.LogError ("Unhandled error parsing ASP.NET document '" + (fileName ?? "") + "'", ex);
					errors.Add (new Error (ErrorType.Error, 0, 0, "Unhandled error parsing ASP.NET document: " + ex.Message));
				}
				
				
				foreach (var pe in rootNode.ParseErrors)
					errors.Add (new Error (ErrorType.Error, pe.Location.BeginLine, pe.Location.BeginColumn, pe.Message));
				
				info.Populate (rootNode, errors);
				
				var type = AspNetAppProject.DetermineWebSubtype (fileName);
				if (type != info.Subtype) {
					if (info.Subtype == WebSubtype.None) {
						errors.Add (new Error (ErrorType.Error, 1, 1, "File directive is missing"));
					} else {
						type = info.Subtype;
						errors.Add (new Error (ErrorType.Warning, 1, 1, "File directive does not match page extension"));
					}
				}
				
				var result = new AspNetParsedDocument (fileName, type, rootNode, info);
				result.Add (errors);
								
				/*
				if (MonoDevelop.Core.LoggingService.IsLevelEnabled (MonoDevelop.Core.Logging.LogLevel.Debug)) {
					DebugStringVisitor dbg = new DebugStringVisitor ();
					rootNode.AcceptVisit (dbg);
					System.Text.StringBuilder sb = new System.Text.StringBuilder ();
					sb.AppendLine ("Parsed AspNet file:");
					sb.AppendLine (dbg.DebugString);
					if (errors.Count > 0) {
						sb.AppendLine ("Errors:");
						foreach (ParserException ex in errors)
							sb.AppendLine (ex.ToString ());
					}
					MonoDevelop.Core.LoggingService.LogDebug (sb.ToString ());
				}*/
				
				return result;
			}
		}
		public override void Initialize ()
		{
			base.Initialize ();
			dom = Document.Dom;
			textEditorData = Document.Editor;
			
			IEnumerable<string > types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			if (dom != null && dom.Project != null)
				policy = dom.Project.Policies.Get<CSharpFormattingPolicy> (types);
			InitTracker ();
			UpdatePath (null, null);
			textEditorData.Caret.PositionChanged += UpdatePath;
			Document.DocumentParsed += HandleDocumentDocumentParsed;
		}
		IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, INode member)
		{
			var editor = TextFileProvider.Instance.GetTextEditorData (fileName);
			var doc    = ProjectDomService.GetParsedDocument (dom, fileName);
			
			if (doc == null || doc.CompilationUnit == null)
				return null;
			var resolver = new NRefactoryResolver (dom, doc.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, editor, fileName);
			
			FindMemberAstVisitor visitor = new FindMemberAstVisitor (editor.Document, resolver, member);
			visitor.IncludeXmlDocumentation = IncludeDocumentation;
			visitor.RunVisitor ();
			return visitor.FoundReferences;
		}
Beispiel #28
0
 public override bool IsAccessibleFrom(MonoDevelop.Projects.Dom.Parser.ProjectDom dom, IType calledType, IMember member, bool includeProtected)
 {
     if (calledType != null)
     {
         foreach (IType baseType in dom.GetInheritanceTree(calledType))
         {
             if (baseType.FullName == calledType.FullName)
             {
                 return(true);
             }
         }
     }
     return(base.IsAccessibleFrom(dom, calledType, member, includeProtected));
 }
Beispiel #29
0
 static void RemoveParseJobs(ProjectDom dom)
 {
     lock (parseQueueLock)
     {
         foreach (ParsingJob pj in parseQueue)
         {
             if (pj.Database == dom)
             {
                 pj.ParseCallback = null;
                 parseQueueIndex.Remove(pj.File);
             }
         }
     }
 }
Beispiel #30
0
        // Returns the ParsedDocument object for a file. It will parse
        // the file if it has not been recently parsed
        public static ParsedDocument GetParsedDocument(ProjectDom dom, string fileName)
        {
            if (fileName == null || fileName.Length == 0)
            {
                return(null);
            }

            ParsedDocument info = GetCachedParseInformation(fileName);

            if (info != null)
            {
                return(info);
            }
            return(ParseFile(dom, fileName));
        }
Beispiel #31
0
        public static ProjectDom GetFileDom(FilePath file)
        {
            if (file.IsNull)
            {
                file = Path.GetTempFileName();
            }

            file = file.CanonicalPath;

            lock (singleDatabases)
            {
                SingleFileCacheEntry entry;
                if (singleDatabases.TryGetValue(file, out entry))
                {
                    entry.AccessTime = DateTime.Now;
                    return(entry.Database);
                }
                else
                {
                    if (singleDatabases.Count >= MAX_SINGLEDB_CACHE_SIZE)
                    {
                        DateTime tim      = DateTime.MaxValue;
                        string   toDelete = null;
                        foreach (KeyValuePair <FilePath, SingleFileCacheEntry> pce in singleDatabases)
                        {
                            DateTime ptim = pce.Value.AccessTime;
                            if (ptim < tim)
                            {
                                tim      = ptim;
                                toDelete = pce.Key;
                            }
                        }
                        singleDatabases.Remove(toDelete);
                    }


                    ProjectDom db = ParserDatabase.LoadSingleFileDom(file);
                    db.Uri = "File:" + file;
                    db.UpdateReferences();
                    entry                  = new SingleFileCacheEntry();
                    entry.Database         = db;
                    entry.AccessTime       = DateTime.Now;
                    singleDatabases [file] = entry;
                    db.ReferenceCount      = 1;
                    return(db);
                }
            }
        }
		public RefactoringPreviewDialog (ProjectDom ctx, List<Change> changes)
		{
			this.Build ();
			this.changes = changes;
			treeviewPreview.Model = store;

			TreeViewColumn column = new TreeViewColumn ();

			// pixbuf column
			var pixbufCellRenderer = new CellRendererPixbuf ();
			column.PackStart (pixbufCellRenderer, false);
			column.SetAttributes (pixbufCellRenderer, "pixbuf", pixbufColumn);
			column.AddAttribute (pixbufCellRenderer, "visible", statusVisibleColumn);
			
			// text column
			CellRendererText cellRendererText = new CellRendererText ();
			column.PackStart (cellRendererText, false);
			column.SetAttributes (cellRendererText, "text", textColumn);
			column.AddAttribute (cellRendererText, "visible", statusVisibleColumn);
			
			// location column
			CellRendererText cellRendererText2 = new CellRendererText ();
			column.PackStart (cellRendererText2, false);
			column.SetCellDataFunc (cellRendererText2, new TreeCellDataFunc (SetLocationTextData));
			
			CellRendererDiff cellRendererDiff = new CellRendererDiff ();
			column.PackStart (cellRendererDiff, true);
			column.SetCellDataFunc (cellRendererDiff, new TreeCellDataFunc (SetDiffCellData));

			treeviewPreview.AppendColumn (column);
			treeviewPreview.HeadersVisible = false;
			
			buttonCancel.Clicked += delegate {
				Destroy ();
			};
			
			buttonOk.Clicked += delegate {
				IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (this.Title, null);
				RefactoringService.AcceptChanges (monitor, ctx, changes);
				
				Destroy ();
			};
			
			FillChanges ();
			Resize (IdeApp.Workbench.ActiveDocument.ActiveView.Control.Allocation.Width,
			        IdeApp.Workbench.ActiveDocument.ActiveView.Control.Allocation.Height);
		}
		IEnumerable<MemberReference> SearchMember (INode member, ProjectDom dom, FilePath fileName, Mono.TextEditor.TextEditorData editor, Mono.TextEditor.Document buildDocument, List<LocalDocumentInfo.OffsetInfo> offsetInfos, ParsedDocument parsedDocument)
		{
			var resolver = new NRefactoryResolver (dom, parsedDocument.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, editor, fileName);
			
			FindMemberAstVisitor visitor = new FindMemberAstVisitor (buildDocument, member);
			visitor.IncludeXmlDocumentation = IncludeDocumentation;
			visitor.RunVisitor (resolver);
			
			foreach (var result in visitor.FoundReferences) {
				var offsetInfo = offsetInfos.FirstOrDefault (info => info.ToOffset <= result.Position && result.Position < info.ToOffset + info.Length);
				if (offsetInfo == null)
					continue;
				var offset = offsetInfo.FromOffset + result.Position - offsetInfo.ToOffset;
				var loc = editor.OffsetToLocation (offset);
				yield return new MemberReference (null, fileName, offset, loc.Line, loc.Column, result.Name, null);
			}
		}
Beispiel #34
0
		public override ParsedDocument Parse (ProjectDom dom, string fileName, string content)
		{
			ParsedTemplate template = new ParsedTemplate (fileName);
			try {
				Tokeniser tk = new Tokeniser (fileName, content);
				template.ParseWithoutIncludes (tk);
			} catch (ParserException ex) {
				template.LogError (ex.Message, ex.Location);
			}
			
			T4ParsedDocument doc = new T4ParsedDocument (fileName, template.RawSegments);
			doc.Flags |= ParsedDocumentFlags.NonSerializable;
			foreach (System.CodeDom.Compiler.CompilerError err in template.Errors)
				doc.Errors.Add (new Error (err.IsWarning? ErrorType.Warning : ErrorType.Error,
				                           err.Line, err.Column, err.ErrorText)); 
			
			return doc;
		}
		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 #36
0
		public static void Format (TextEditorData data, ProjectDom dom)
		{
			CSharp.Dom.CompilationUnit compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			CSharpFormattingPolicy policy = dom.Project.Policies != null ? dom.Project.Policies.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);
			DomSpacingVisitor domSpacingVisitor = new DomSpacingVisitor (policy, data);
			domSpacingVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			DomIndentationVisitor domIndentationVisitor = new DomIndentationVisitor (policy, data);
			domIndentationVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);
			
			List<Change> changes = new List<Change> ();
			changes.AddRange (domSpacingVisitor.Changes);
			changes.AddRange (domIndentationVisitor.Changes);
			RefactoringService.AcceptChanges (null, null, changes);
		}
Beispiel #37
0
        public static void Load(WorkspaceItem item)
        {
            if (IncLoadCount(item) != 1)
            {
                return;
            }

            lock (databases) {
                if (item is Workspace)
                {
                    Workspace ws = (Workspace)item;
                    foreach (WorkspaceItem it in ws.Items)
                    {
                        Load(it);
                    }
                    ws.ItemAdded   += OnWorkspaceItemAdded;
                    ws.ItemRemoved += OnWorkspaceItemRemoved;
                }
                else if (item is Solution)
                {
                    Solution solution = (Solution)item;
                    foreach (Project project in solution.GetAllProjects())
                    {
                        Load(project);
                    }
                    // Refresh the references of all projects. This is necessary because
                    // some project may have been loaded before the projects their reference,
                    // in which case those references are not properly registered.
                    foreach (Project project in solution.GetAllProjects())
                    {
                        ProjectDom dom = GetProjectDom(project);
                        // referenced by main project - prevents the removal if a project is referenced one time inside the solution
                        // and the project that references it is reloaded.
                        dom.ReferenceCount++;
                        if (dom != null)
                        {
                            dom.UpdateReferences();
                        }
                    }
                    solution.SolutionItemAdded   += OnSolutionItemAdded;
                    solution.SolutionItemRemoved += OnSolutionItemRemoved;
                }
            }
        }
Beispiel #38
0
        public static void QueueParseJob(ProjectDom db, Action <string, IProgressMonitor> callback, string file)
        {
            ParsingJob job = new ParsingJob();

            job.ParseCallback = callback;
            job.File          = file;
            job.Database      = db;
            lock (parseQueueLock)
            {
                RemoveParseJob(file);
                parseQueueIndex [file] = job;
                parseQueue.Enqueue(job);
                parseEvent.Set();

                if (parseQueueIndex.Count == 1)
                {
                    queueEmptied.Reset();
                }
            }
        }
Beispiel #39
0
        internal static int ResolveTypes(ProjectDom db, ICompilationUnit unit, IEnumerable <IType> types, IEnumerable <IAttribute> attributes, out List <IType> result, out List <IAttribute> resultAtrtibutes)
        {
            TypeResolverVisitor tr = new TypeResolverVisitor(db, unit);

            int unresolvedCount = 0;

            result = new List <IType> ();
            foreach (IType c in types)
            {
                tr.UnresolvedCount = 0;
                DomType rc = (DomType)c.AcceptVisitor(tr, null);
                if (rc.CompilationUnit != null)
                {
                    rc.CompilationUnit = new CompilationUnit(rc.CompilationUnit.FileName);
                }
                rc.Resolved = true;
                // no need to set the base type here - the completion db handles that
                // (setting to system.object is wrong for enums & structs - and interfaces may never have a base)

/*
 *                              if (tr.UnresolvedCount == 0 && c.FullName != "System.Object") {
 *                                      // If the class has no base classes, make sure it subclasses System.Object
 *                                      if (rc.BaseType == null)
 *                                              rc.BaseType = new DomReturnType ("System.Object");
 *                              }*/

                result.Add(rc);
                unresolvedCount += tr.UnresolvedCount;
            }

            resultAtrtibutes = new List <IAttribute> ();
            foreach (IAttribute a in attributes)
            {
                tr.UnresolvedCount = 0;
                DomAttribute ra = (DomAttribute)a.AcceptVisitor(tr, null);
                resultAtrtibutes.Add(ra);
                unresolvedCount += tr.UnresolvedCount;
            }

            return(unresolvedCount);
        }
        static ParsedDocument DoParseFile(ProjectDom dom, string fileName, string fileContent)
        {
            using (Counters.FileParse.BeginTiming()) {
                IParser parser = GetParser(fileName);
                if (parser == null)
                {
                    return(null);
                }

                ParsedDocument parserOutput = null;

                if (fileContent == null)
                {
                    try {
                        if (!File.Exists(fileName))
                        {
                            return(null);
                        }
                        using (StreamReader sr = File.OpenText(fileName)) {
                            fileContent = sr.ReadToEnd();
                        }
                    } catch (Exception e) {
                        LoggingService.LogError("Got exception while reading file", e);
                        return(null);
                    }
                }

                parserOutput = parser.Parse(dom, fileName, fileContent);

                if (parserOutput != null)
                {
                    AddToCache(parserOutput);
                    OnParsedDocumentUpdated(new ParsedDocumentEventArgs(parserOutput));
                }

                return(parserOutput);
            }
        }
        public static void Load(Project project)
        {
            if (IncLoadCount(project) != 1)
            {
                return;
            }

            lock (databases)
            {
                string uri = "Project:" + project.FileName;
                if (databases.ContainsKey(uri))
                {
                    return;
                }

                try {
                    ProjectDom db = ParserDatabase.LoadProjectDom(project);
                    RegisterDom(db, uri);
                    project.Modified += HandleModified;
                } catch (Exception ex) {
                    LoggingService.LogError("Parser database for project '" + project.Name + " could not be loaded", ex);
                }
            }
        }
Beispiel #42
0
 public ProjectDomDecorator(ProjectDom decorated)
 {
     this.decorated = decorated;
 }
Beispiel #43
0
        static ParsedDocument UpdateFile(Project[] projects, string fileName, Func <string> getContent)
        {
            try {
                if (GetParser(fileName) == null)
                {
                    return(null);
                }

                ParsedDocument parseInformation = null;
                string         fileContent;
                if (getContent == null)
                {
                    if (!System.IO.File.Exists(fileName))
                    {
                        fileContent = "";
                    }
                    else
                    {
                        try {
                            fileContent = System.IO.File.ReadAllText(fileName);
                        } catch (Exception e) {
                            LoggingService.LogError("Error reading file {0} for ProjectDomService: {1}", fileName, e);
                            fileContent = "";
                        }
                    }
                }
                else
                {
                    fileContent = getContent();
                }

                // Remove any pending jobs for this file
                RemoveParseJob(fileName);
                ProjectDom dom = projects != null && projects.Length > 0 ? GetProjectDom(projects [0]) : null;
                parseInformation = DoParseFile(dom, fileName, fileContent);
                if (parseInformation == null)
                {
                    return(null);
                }
                // don't update project dom with incorrect parse informations, they may not contain all
                // information.
                if (projects != null && projects.Length > 0 && parseInformation.CompilationUnit != null)
                {
                    SetSourceProject(parseInformation.CompilationUnit, dom);
                }

//				if (parseInformation.Errors.Any ()) {
//					Console.WriteLine (fileName + "-- Errors:");
//					foreach (var e in parseInformation.Errors) {
//						Console.WriteLine (e);
//					}
//				}

                if (parseInformation.CompilationUnit != null &&
                    (parseInformation.Flags & ParsedDocumentFlags.NonSerializable) == 0)
                {
                    if (projects != null && projects.Length > 0)
                    {
                        foreach (Project project in projects)
                        {
                            ProjectDom db = GetProjectDom(project);
                            if (db != null)
                            {
                                try {
                                    if (parseInformation.HasErrors)
                                    {
                                        db.UpdateTemporaryCompilationUnit(parseInformation.CompilationUnit);
                                    }
                                    else
                                    {
                                        db.UpdateTagComments(fileName, parseInformation.TagComments);
                                        db.RemoveTemporaryCompilationUnit(parseInformation.CompilationUnit);
                                        TypeUpdateInformation res = db.UpdateFromParseInfo(parseInformation.CompilationUnit, getContent == null);
                                        if (res != null)
                                        {
                                            NotifyTypeUpdate(project, fileName, res);
                                        }
                                        UpdatedCommentTasks(fileName, parseInformation.TagComments, project);
                                    }
                                } catch (Exception e) {
                                    LoggingService.LogError(e.ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        ProjectDom db = GetFileDom(fileName);
                        db.UpdateFromParseInfo(parseInformation.CompilationUnit, getContent == null);
                    }
                }

                return(parseInformation);
            } catch (Exception e) {
                LoggingService.LogError(e.ToString());
                return(null);
            }
        }
Beispiel #44
0
        static void CheckModifiedFiles()
        {
            // Check databases following a bottom-up strategy in the dependency
            // tree. This will help resolving parsed classes.

            Set <ProjectDom> list = new Set <ProjectDom> ();

            lock (databases) {
                // There may be several uris for the same db
                foreach (ProjectDom ob in databases.Values)
                {
                    list.Add(ob);
                }
            }

            Set <ProjectDom> done = new Set <ProjectDom> ();

            while (list.Count > 0)
            {
                ProjectDom readydb      = null;
                ProjectDom bestdb       = null;
                int        bestRefCount = int.MaxValue;

                // Look for a db with all references resolved
                foreach (ProjectDom db in list)
                {
                    bool allDone = true;
                    foreach (ProjectDom refdb in db.References)
                    {
                        if (!done.Contains(refdb))
                        {
                            allDone = false;
                            break;
                        }
                    }

                    if (allDone)
                    {
                        readydb = db;
                        break;
                    }
                    else if (db.References.Count < bestRefCount)
                    {
                        bestdb       = db;
                        bestRefCount = db.References.Count;
                        break;
                    }
                }

                // It may not find any db without resolved references if there
                // are circular dependencies. In this case, take the one with
                // less references

                if (readydb == null)
                {
                    readydb = bestdb;
                }

                readydb.CheckModifiedFiles();
                list.Remove(readydb);
                done.Add(readydb);
            }
        }
Beispiel #45
0
 // Parses a file. It does not update the parser database
 public static ParsedDocument ParseFile(ProjectDom dom, string fileName)
 {
     return(ParseFile(dom, fileName, null));
 }
Beispiel #46
0
        // Parses a file. It does not update the parser database
        public static ParsedDocument ParseFile(ProjectDom dom, string fileName, Func <string> getContent)
        {
            string fileContent = getContent != null?getContent() : null;

            return(DoParseFile(dom, fileName, fileContent));
        }
        static ParsedDocument UpdateFile(Project[] projects, string fileName, string mimeType, ContentDelegate getContent)
        {
            try {
                if (GetParser(fileName, mimeType) == null)
                {
                    return(null);
                }

                ParsedDocument parseInformation = null;
                string         fileContent;
                if (getContent == null)
                {
                    StreamReader sr = new StreamReader(fileName);
                    fileContent = sr.ReadToEnd();
                    sr.Close();
                }
                else
                {
                    fileContent = getContent();
                }

                // Remove any pending jobs for this file
                RemoveParseJob(fileName);
                ProjectDom dom = projects != null && projects.Length > 0 ? GetProjectDom(projects [0]) : null;
                parseInformation = DoParseFile(dom, fileName, fileContent);
                if (parseInformation == null)
                {
                    return(null);
                }
                // don't update project dom with incorrect parse informations, they may not contain all
                // information.
                if (projects != null && projects.Length > 0 && parseInformation.CompilationUnit != null)
                {
                    SetSourceProject(parseInformation.CompilationUnit, dom);
                }
                if (parseInformation.CompilationUnit != null &&
                    (parseInformation.Flags & ParsedDocumentFlags.NonSerializable) == 0)
                {
                    if (projects != null && projects.Length > 0)
                    {
                        foreach (Project project in projects)
                        {
                            ProjectDom db = GetProjectDom(project);
                            if (db != null)
                            {
                                try {
                                    if (parseInformation.HasErrors)
                                    {
                                        db.UpdateTemporaryCompilationUnit(parseInformation.CompilationUnit);
                                    }
                                    else
                                    {
                                        db.UpdateTagComments(fileName, parseInformation.TagComments);
                                        db.RemoveTemporaryCompilationUnit(parseInformation.CompilationUnit);
                                        TypeUpdateInformation res = db.UpdateFromParseInfo(parseInformation.CompilationUnit);
                                        if (res != null)
                                        {
                                            NotifyTypeUpdate(project, fileName, res);
                                        }
                                        UpdatedCommentTasks(fileName, parseInformation.TagComments, project);
                                    }
                                } catch (Exception e) {
                                    LoggingService.LogError(e.ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        ProjectDom db = GetFileDom(fileName);
                        db.UpdateFromParseInfo(parseInformation.CompilationUnit);
                    }
                }

                return(parseInformation);
            } catch (Exception e) {
                LoggingService.LogError(e.ToString());
                return(null);
            }
        }
 public ProjectDomEventArgs(ProjectDom dom)
 {
     this.dom = dom;
 }
 public static void RegisterDom(ProjectDom dom, string uri)
 {
     dom.Uri         = uri;
     databases [uri] = dom;
     dom.UpdateReferences();
 }
 public TypeResolverVisitor(ProjectDom db, ICompilationUnit unit)
 {
     this.db   = db;
     this.unit = unit;
 }
 public virtual ParsedDocument Parse(ProjectDom dom, string fileName, TextReader content)
 {
     return(Parse(dom, fileName, content.ReadToEnd()));
 }
 public abstract ParsedDocument Parse(ProjectDom dom, string fileName, string content);
 public virtual IResolver CreateResolver(ProjectDom dom, object editor, string fileName)
 {
     return(null);
 }
 public virtual IExpressionFinder CreateExpressionFinder(ProjectDom dom)
 {
     return(null);
 }
 public ParsedDocument Parse(ProjectDom dom, string fileName)
 {
     return(Parse(dom, fileName, System.IO.File.ReadAllText(fileName)));
 }