diff options
author | Mike Krüger <mkrueger@novell.com> | 2011-06-15 12:39:08 +0400 |
---|---|---|
committer | Mike Krüger <mkrueger@novell.com> | 2011-06-17 17:04:17 +0400 |
commit | 6c23dcfdadba0611ed60e99bf981a884b14e2428 (patch) | |
tree | babb2b3d2042440cc6d5c9dc73f8b61c4e3c5cd7 /main | |
parent | e4d0233abe14e785d46383d991cd30a04b29ee32 (diff) |
Converted MonoDevelop.Ide to use the new type system.
There are still some todos: code generation, class pad.
Diffstat (limited to 'main')
68 files changed, 3908 insertions, 648 deletions
diff --git a/main/src/core/MonoDevelop.Ide/ChangeLog b/main/src/core/MonoDevelop.Ide/ChangeLog index 277235dc26..ea589b1d82 100644 --- a/main/src/core/MonoDevelop.Ide/ChangeLog +++ b/main/src/core/MonoDevelop.Ide/ChangeLog @@ -8968,7 +8968,7 @@ MonoDevelop.Ide.Dom.Parser/ProjectParserService.cs, MonoDevelop.Ide.Dom.Parser/IParser.cs, MonoDevelop.Ide.Dom.Parser/ProjectDomEventArgs.cs, - MonoDevelop.Ide.Dom.Parser/ProjectDom.cs, + MonoDevelop.Ide.Dom.Parser/ITypeResolveContext.cs, MonoDevelop.Ide.Dom.Output, MonoDevelop.Ide.Dom.Output/OutputFlags.cs, MonoDevelop.Ide.Dom.Output/Ambience.cs, @@ -8999,7 +8999,7 @@ MonoDevelop.Ide.Dom/IReturnType.cs, MonoDevelop.Ide.Dom/IEvent.cs, MonoDevelop.Ide.Dom/AbstractMember.cs, MonoDevelop.Ide.Dom/IField.cs, MonoDevelop.Ide.Dom/CommentType.cs, - MonoDevelop.Ide.Dom/DomLocation.cs, + MonoDevelop.Ide.Dom/AstLocation.cs, MonoDevelop.Ide.Dom/AttributeTarget.cs: Removed dead code. 2008-09-18 Lluis Sanchez Gual <lluis@novell.com> @@ -10320,7 +10320,7 @@ MonoDevelop.Ide.Gui.Pads.ClassBrowser/ProjectNamespaceBuilder.cs, MonoDevelop.Ide.Dom.Parser/ProjectParserService.cs, MonoDevelop.Ide.Dom.Parser/ProjectDomEventArgs.cs, - MonoDevelop.Ide.Dom.Parser/ProjectDom.cs, + MonoDevelop.Ide.Dom.Parser/ITypeResolveContext.cs, MonoDevelop.Ide.Dom/IMember.cs, MonoDevelop.Ide.Dom/DomReturnType.cs, MonoDevelop.Ide.Dom/DomType.cs, MonoDevelop.Ide.Dom/DomMethod.cs, @@ -10328,7 +10328,7 @@ MonoDevelop.Ide.Dom/DomEvent.cs, MonoDevelop.Ide.Dom/DomField.cs, MonoDevelop.Ide.Dom/DomProperty.cs, MonoDevelop.Ide.Dom/IType.cs, MonoDevelop.Ide.Dom/AbstractMember.cs, - MonoDevelop.Ide.Dom/DomLocation.cs, MonoDevelop.Ide.mdp, + MonoDevelop.Ide.Dom/AstLocation.cs, MonoDevelop.Ide.mdp, gtk-gui/MonoDevelop.Ide.Gui.Pads.ClassBrowser.ClassBrowserPadWidget.cs: Worked on mcs integration/class browser @@ -10358,7 +10358,7 @@ 2008-04-14 Mike Krüger <mkrueger@novell.com> - * MonoDevelop.Ide.Dom/DomRegion.cs, MonoDevelop.Ide.Dom/DomLocation.cs: + * MonoDevelop.Ide.Dom/DomRegion.cs, MonoDevelop.Ide.Dom/AstLocation.cs: Changed the region/location model. 2008-04-14 Mike Krüger <mkrueger@novell.com> @@ -11120,7 +11120,7 @@ * MonoDevelop.Dom.Parser/AbstractParser.cs, MonoDevelop.Dom.Parser/ProjectParserService.cs, - MonoDevelop.Dom.Parser/IParser.cs, MonoDevelop.Dom.Parser/ProjectDom.cs, + MonoDevelop.Dom.Parser/IParser.cs, MonoDevelop.Dom.Parser/ITypeResolveContext.cs, MonoDevelop.Dom.Output/Ambience.cs, MonoDevelop.Dom.Output/NetAmbience.cs, MonoDevelop.Dom/IMember.cs, MonoDevelop.Dom/DomReturnType.cs, MonoDevelop.Dom/DomType.cs, @@ -11160,7 +11160,7 @@ * MonoDevelop.Dom.Parser, MonoDevelop.Dom.Parser/AbstractParser.cs, MonoDevelop.Dom.Parser/ProjectParserService.cs, - MonoDevelop.Dom.Parser/IParser.cs, MonoDevelop.Dom.Parser/ProjectDom.cs, + MonoDevelop.Dom.Parser/IParser.cs, MonoDevelop.Dom.Parser/ITypeResolveContext.cs, MonoDevelop.Dom.Output, MonoDevelop.Dom.Output/Ambience.cs, MonoDevelop.Dom.Output/NetAmbience.cs, MonoDevelop.Dom/DomType.cs, MonoDevelop.Dom/ClassType.cs, MonoDevelop.Dom/ICompilationUnit.cs, diff --git a/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml b/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml index 6b10bde5f5..d29ae969f1 100644 --- a/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml +++ b/main/src/core/MonoDevelop.Ide/ExtensionModel/MonoDevelop.Ide.addin.xml @@ -160,6 +160,11 @@ <ExtensionNode name="Provider" type="MonoDevelop.TypeSystem.TypeSystemProviderNode"/> </ExtensionPoint> + <ExtensionPoint path = "/MonoDevelop/ProjectModel/Ambiences" name = "Language ambiences"> + <Description>Language ambiences. Specified classes must implement IAmbience.</Description> + <ExtensionNode name="Ambience" type="MonoDevelop.Core.AddIns.MimeTypeExtensionNode" /> + </ExtensionPoint> + <!-- Extensions --> <Extension path = "/MonoDevelop/Core/Applications"> diff --git a/main/src/core/MonoDevelop.Ide/Makefile.am b/main/src/core/MonoDevelop.Ide/Makefile.am index a4ba040ac9..b7ba5c7e65 100644 --- a/main/src/core/MonoDevelop.Ide/Makefile.am +++ b/main/src/core/MonoDevelop.Ide/Makefile.am @@ -1,6 +1,5 @@ DEPS = \ - $(top_builddir)/build/bin/ICSharpCode.Decompiler.dll \ $(top_builddir)/build/bin/ICSharpCode.NRefactory.dll \ $(top_builddir)/build/bin/Mono.Cecil.dll \ $(top_builddir)/build/bin/Mono.TextEditor.dll \ @@ -492,22 +491,6 @@ FILES = \ MonoDevelop.Ide.Gui.OptionPanels/MonoRuntimePanel.cs \ MonoDevelop.Ide.Gui.OptionPanels/TasksOptionsPanel.cs \ MonoDevelop.Ide.Gui.OptionPanels/TextStylePolicyPanel.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ClassBrowserPad.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ClassBrowserPadWidget.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ClassData.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ClassNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/CombineNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/EventNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/FieldNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeCommandHandler.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/MethodNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ProjectNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/PropertyNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ReferenceNodeBuilder.cs \ - MonoDevelop.Ide.Gui.Pads.ClassPad/SolutionNodeBuilder.cs \ MonoDevelop.Ide.Gui.Pads.ProjectPad/FileOperationsBuilderExtension.cs \ MonoDevelop.Ide.Gui.Pads.ProjectPad/FolderNodeBuilder.cs \ MonoDevelop.Ide.Gui.Pads.ProjectPad/ProjectFileNodeBuilder.cs \ @@ -646,8 +629,11 @@ FILES = \ MonoDevelop.Ide.Projects/TemplatePickerWidget.cs \ MonoDevelop.Ide.StandardHeader/StandardHeaderPolicyPanel.cs \ MonoDevelop.Ide.StandardHeader/StandardHeaderService.cs \ + MonoDevelop.Ide.Tasks/CommentTag.cs \ + MonoDevelop.Ide.Tasks/CommentTasksChangedEventHandler.cs \ MonoDevelop.Ide.Tasks/CommentTasksView.cs \ MonoDevelop.Ide.Tasks/ITaskListView.cs \ + MonoDevelop.Ide.Tasks/Tag.cs \ MonoDevelop.Ide.Tasks/Task.cs \ MonoDevelop.Ide.Tasks/TaskPriority.cs \ MonoDevelop.Ide.Tasks/TaskService.cs \ @@ -689,6 +675,7 @@ FILES = \ MonoDevelop.Ide.WebBrowser/TitleChangedEventArgs.cs \ MonoDevelop.Ide/AddEntryEventHandler.cs \ MonoDevelop.Ide/CodeGenerationService.cs \ + MonoDevelop.Ide/CodeGenerator.cs \ MonoDevelop.Ide/DesktopService.cs \ MonoDevelop.Ide/DispatchService.cs \ MonoDevelop.Ide/ExitEventHandler.cs \ @@ -703,8 +690,21 @@ FILES = \ MonoDevelop.Ide/RootWorkspace.cs \ MonoDevelop.Ide/Services.cs \ MonoDevelop.Ide/WebBrowserService.cs \ + MonoDevelop.TypeSystem/Ambience.cs \ + MonoDevelop.TypeSystem/AmbienceService.cs \ + MonoDevelop.TypeSystem/Comment.cs \ + MonoDevelop.TypeSystem/ConditionalRegion.cs \ + MonoDevelop.TypeSystem/FoldingRegion.cs \ MonoDevelop.TypeSystem/ITypeSystemProvider.cs \ + MonoDevelop.TypeSystem/MarkupUtilities.cs \ + MonoDevelop.TypeSystem/NetAmbience.cs \ + MonoDevelop.TypeSystem/OutputFlags.cs \ + MonoDevelop.TypeSystem/OutputSettings.cs \ + MonoDevelop.TypeSystem/ParsedDocument.cs \ + MonoDevelop.TypeSystem/PreProcessorDefine.cs \ MonoDevelop.TypeSystem/ProjectContentEventArgs.cs \ + MonoDevelop.TypeSystem/StockIcons.cs \ + MonoDevelop.TypeSystem/Tag.cs \ MonoDevelop.TypeSystem/TypeSystemProviderNode.cs \ MonoDevelop.TypeSystem/TypeSystemService.cs @@ -912,7 +912,6 @@ RES = \ MonoDevelop.Ide.CodeFormatting/MonoTextStylePolicy.xml \ MonoDevelop.Ide.CodeFormatting/VisualStudioTextStylePolicy.xml \ MonoDevelop.Ide.CodeTemplates/MonoDevelop-templates.xml \ - MonoDevelop.Ide.Gui.Pads.ClassPad/ClassPadContextMenu.addin.xml \ MonoDevelop.Ide.Gui.Pads.ProjectPad/ProjectPadContextMenu.addin.xml \ MonoDevelop.Ide.StandardHeader/Apache2LicencePolicy.xml \ MonoDevelop.Ide.StandardHeader/GPL2LicencePolicy.xml \ diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MemberCompletionData.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MemberCompletionData.cs index 7617542ab1..2f65d1f996 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MemberCompletionData.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MemberCompletionData.cs @@ -25,13 +25,13 @@ // THE SOFTWARE. using System; -using MonoDevelop.Projects.Dom; +using ICSharpCode.NRefactory.TypeSystem; namespace MonoDevelop.Ide.CodeCompletion { public class MemberCompletionData : CompletionData { - public INode Member { + public IEntity Member { get; set; } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MutableCompletionDataList.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MutableCompletionDataList.cs index 9321156e15..fca438b9dd 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MutableCompletionDataList.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeCompletion/MutableCompletionDataList.cs @@ -27,8 +27,7 @@ // using System; - -using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide.CodeCompletion { @@ -63,31 +62,31 @@ namespace MonoDevelop.Ide.CodeCompletion public event EventHandler Changing { add { if (changing == null) - ProjectDomService.ParseOperationStarted += HandleParseOperationStarted; + TypeSystemService.ParseOperationStarted += HandleParseOperationStarted; changing += value; } remove { changing -= value; if (changing == null) - ProjectDomService.ParseOperationStarted -= HandleParseOperationStarted; + TypeSystemService.ParseOperationStarted -= HandleParseOperationStarted; } } public event EventHandler Changed { add { if (changed == null) - ProjectDomService.ParseOperationFinished += HandleParseOperationFinished; + TypeSystemService.ParseOperationFinished += HandleParseOperationFinished; changed += value; } remove { changed -= value; if (changed == null) - ProjectDomService.ParseOperationFinished -= HandleParseOperationFinished; + TypeSystemService.ParseOperationFinished -= HandleParseOperationFinished; } } public bool IsChanging { - get { return ProjectDomService.IsParsing; } + get { return TypeSystemService.IsParsing; } } protected virtual void OnChanging () @@ -119,9 +118,9 @@ namespace MonoDevelop.Ide.CodeCompletion if (!disposed) { disposed = true; if (changing != null) - ProjectDomService.ParseOperationStarted -= HandleParseOperationStarted; + TypeSystemService.ParseOperationStarted -= HandleParseOperationStarted; if (changed != null) - ProjectDomService.ParseOperationFinished -= HandleParseOperationFinished; + TypeSystemService.ParseOperationFinished -= HandleParseOperationFinished; } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/CodeFormatter.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/CodeFormatter.cs index d0817f959e..250bbe0e5e 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/CodeFormatter.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/CodeFormatter.cs @@ -26,10 +26,10 @@ using System; using MonoDevelop.Projects.Policies; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using Mono.TextEditor; using System.Collections.Generic; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.CSharp; namespace MonoDevelop.Ide.CodeFormatting { @@ -84,17 +84,17 @@ namespace MonoDevelop.Ide.CodeFormatting /// A <see cref="System.Object"/> that must be from type Mono.TextEditorData. /// </param> /// <param name="dom"> - /// A <see cref="ProjectDom"/> + /// A <see cref="ITypeResolveContext"/> /// </param> /// <param name="unit"> - /// A <see cref="ICompilationUnit"/> + /// A <see cref="IParsedFile"/> /// </param> /// <param name="caretLocation"> - /// A <see cref="DomLocation"/> that should be the end location to which the parsing should occur. + /// A <see cref="AstLocation"/> that should be the end location to which the parsing should occur. /// </param> public void OnTheFlyFormat (PolicyContainer policyParent, TextEditorData data, - IType callingType, IMember callingMember, ProjectDom dom, ICompilationUnit unit, - DomLocation endLocation) + IType callingType, IMember callingMember, ITypeResolveContext dom, IParsedFile unit, + AstLocation endLocation) { var adv = formatter as IAdvancedCodeFormatter; if (adv == null || !adv.SupportsOnTheFlyFormatting) diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/IAdvancedCodeFormatter.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/IAdvancedCodeFormatter.cs index ee3c88b6dd..9f84d22f4d 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/IAdvancedCodeFormatter.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeFormatting/IAdvancedCodeFormatter.cs @@ -27,10 +27,9 @@ using System; using System.Collections.Generic; using Mono.TextEditor; - -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Projects.Policies; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.CSharp; namespace MonoDevelop.Ide.CodeFormatting { @@ -49,17 +48,17 @@ namespace MonoDevelop.Ide.CodeFormatting /// A <see cref="System.Object"/> that must be from type Mono.TextEditorData. /// </param> /// <param name="dom"> - /// A <see cref="ProjectDom"/> + /// A <see cref="ITypeResolveContext"/> /// </param> /// <param name="unit"> - /// A <see cref="ICompilationUnit"/> + /// A <see cref="IParsedFile"/> /// </param> /// <param name="caretLocation"> - /// A <see cref="DomLocation"/> that should be the end location to which the parsing should occur. + /// A <see cref="AstLocation"/> that should be the end location to which the parsing should occur. /// </param> void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, - TextEditorData textEditorData, IType callingType, IMember callingMember, ProjectDom dom, - ICompilationUnit unit, DomLocation endLocation); + TextEditorData textEditorData, IType callingType, IMember callingMember, ITypeResolveContext dom, + IParsedFile unit, AstLocation endLocation); void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, TextEditorData textEditorData, int startOffset, int endOffset); @@ -71,8 +70,8 @@ namespace MonoDevelop.Ide.CodeFormatting public virtual bool SupportsCorrectingIndent { get { return false; } } public virtual void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, - TextEditorData data, IType callingType, IMember callingMember, ProjectDom dom, - ICompilationUnit unit, DomLocation endLocation) + TextEditorData data, IType callingType, IMember callingMember, ITypeResolveContext dom, + IParsedFile unit, AstLocation endLocation) { throw new NotSupportedException (); } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplate.cs index e17cc730d5..aed1170c77 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplate.cs @@ -33,11 +33,10 @@ using System.Text; using System.Text.RegularExpressions; using System.Xml; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using Mono.TextEditor; using Mono.TextEditor.PopupWindow; using MonoDevelop.Ide.CodeFormatting; +using ICSharpCode.NRefactory.TypeSystem; namespace MonoDevelop.Ide.CodeTemplates { @@ -382,17 +381,17 @@ namespace MonoDevelop.Ide.CodeTemplates /// </summary> public TemplateResult InsertTemplateContents (MonoDevelop.Ide.Gui.Document document) { - ProjectDom dom = document.Dom; - ParsedDocument doc = document.ParsedDocument ?? MonoDevelop.Projects.Dom.Parser.ProjectDomService.GetParsedDocument (dom, document.FileName); + var dom = document.TypeResolveContext; + var doc = document.ParsedFile; Mono.TextEditor.TextEditorData data = document.Editor; - + int offset = data.Caret.Offset; // string leadingWhiteSpace = GetLeadingWhiteSpace (editor, editor.CursorLine); TemplateContext context = new TemplateContext { Template = this, Document = document, - ProjectDom = dom, + ITypeResolveContext = dom, ParsedDocument = doc, InsertPosition = data.Caret.Location, LineIndent = data.Document.GetLineIndent (data.Caret.Line), diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplateCompletionData.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplateCompletionData.cs index 7de6f3b904..3f19b81ce7 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplateCompletionData.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/CodeTemplateCompletionData.cs @@ -26,7 +26,6 @@ using System; using MonoDevelop.Ide.Gui; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Ide.CodeCompletion; using MonoDevelop.Core; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/ExpansionObject.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/ExpansionObject.cs index 4433af16cd..390f31d95c 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/ExpansionObject.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.CodeTemplates/ExpansionObject.cs @@ -30,11 +30,9 @@ using System.Text; using System.Text.RegularExpressions; using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; -using MonoDevelop.Projects.Dom.Output; using Mono.TextEditor.PopupWindow; using Mono.TextEditor; +using ICSharpCode.NRefactory.TypeSystem; namespace MonoDevelop.Ide.CodeTemplates { @@ -44,12 +42,12 @@ namespace MonoDevelop.Ide.CodeTemplates get; set; } - public ProjectDom ProjectDom { + public ITypeResolveContext ITypeResolveContext { get; set; } - public ParsedDocument ParsedDocument { + public IParsedFile ParsedDocument { get; set; } @@ -91,7 +89,7 @@ namespace MonoDevelop.Ide.CodeTemplates { if (CurrentContext.ParsedDocument == null) return null; - IType type = CurrentContext.ParsedDocument.CompilationUnit.GetTypeAt (CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column); + var type = CurrentContext.ParsedDocument.GetTypeDefinition (CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column); if (type == null) return null; return type.Name; @@ -101,7 +99,7 @@ namespace MonoDevelop.Ide.CodeTemplates { if (CurrentContext.ParsedDocument == null) return null; - IType type = CurrentContext.ParsedDocument.CompilationUnit.GetTypeAt (CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column); + var type = CurrentContext.ParsedDocument.GetTypeDefinition (CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column); if (type == null) return ""; return type.IsStatic ? "static " : "public "; @@ -116,8 +114,8 @@ namespace MonoDevelop.Ide.CodeTemplates ITextEditorResolver textEditorResolver = CurrentContext.Document.GetContent <ITextEditorResolver> (); if (textEditorResolver != null) { - ResolveResult result = textEditorResolver.GetLanguageItem (CurrentContext.Document.Editor.Document.LocationToOffset (CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column), var); - if (result != null && result.ResolvedType != null && (result.ResolvedType.ArrayDimensions > 0 || result.ResolvedType.FullName == DomReturnType.String.FullName)) + var result = textEditorResolver.GetLanguageItem (CurrentContext.Document.Editor.Document.LocationToOffset (CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column), var); + if (!result.Type.IsReferenceType.Value) return "Length"; } return "Count"; @@ -131,13 +129,14 @@ namespace MonoDevelop.Ide.CodeTemplates string var = callback (varName); ITextEditorResolver textEditorResolver = CurrentContext.Document.GetContent <ITextEditorResolver> (); if (textEditorResolver != null) { - ResolveResult result = textEditorResolver.GetLanguageItem (CurrentContext.Document.Editor.Caret.Offset, var); + var result = textEditorResolver.GetLanguageItem (CurrentContext.Document.Editor.Caret.Offset, var); if (result != null) { - IReturnType componentType = DomType.GetComponentType (CurrentContext.ProjectDom, result.ResolvedType); + // TODO: Type system conversion. +/* var componentType = DomType.GetComponentType (CurrentContext.ITypeResolveContext, result.ResolvedType); if (componentType != null) { Ambience ambience = AmbienceService.GetAmbience (CurrentContext.Template.MimeType); - return ambience != null ? ambience.GetString (componentType, OutputFlags.IncludeGenerics) : componentType.ToInvariantString (); - } + return ambience != null ? ambience.GetString (componentType, OutputFlags.IncludeGenerics) : componentType.ToInvariantString (); + }*/ } } @@ -159,8 +158,8 @@ namespace MonoDevelop.Ide.CodeTemplates if (data.Member is IMember) { IMember m = data.Member as IMember; - if (DomType.GetComponentType (CurrentContext.ProjectDom, m.ReturnType) != null) - result.Add (new CodeTemplateVariableValue (m.Name, data.Icon)); +// if (DomType.GetComponentType (CurrentContext.ITypeResolveContext, m.ReturnType) != null) +// result.Add (new CodeTemplateVariableValue (m.Name, data.Icon)); } } @@ -170,8 +169,8 @@ namespace MonoDevelop.Ide.CodeTemplates continue; if (data.Member is IParameter) { IParameter m = data.Member as IParameter; - if (DomType.GetComponentType (CurrentContext.ProjectDom, m.ReturnType) != null) - result.Add (new CodeTemplateVariableValue (m.Name, data.Icon)); +// if (DomType.GetComponentType (CurrentContext.ITypeResolveContext, m.ReturnType) != null) +// result.Add (new CodeTemplateVariableValue (m.Name, data.Icon)); } } @@ -179,11 +178,11 @@ namespace MonoDevelop.Ide.CodeTemplates MonoDevelop.Ide.CodeCompletion.MemberCompletionData data = o as MonoDevelop.Ide.CodeCompletion.MemberCompletionData; if (data == null) continue; - if (data.Member is LocalVariable) { +/* if (data.Member is LocalVariable) { LocalVariable m = data.Member as LocalVariable; - if (DomType.GetComponentType (CurrentContext.ProjectDom, m.ReturnType) != null) + if (DomType.GetComponentType (CurrentContext.ITypeResolveContext, m.ReturnType) != null) result.Add (new CodeTemplateVariableValue (m.Name, data.Icon)); - } + }*/ } } return new CodeTemplateListDataProvider (result); @@ -191,16 +190,17 @@ namespace MonoDevelop.Ide.CodeTemplates public string GetSimpleTypeName (string fullTypeName) { - if (CurrentContext.ParsedDocument == null) - return fullTypeName; - DomReturnType returnType; - int idx = fullTypeName.IndexOf ('#'); - if (idx < 0) { - returnType = new DomReturnType (fullTypeName); - } else { - returnType = new DomReturnType (fullTypeName.Substring (0, idx), fullTypeName.Substring (idx + 1)); - } - return CurrentContext.ParsedDocument.CompilationUnit.ShortenTypeName (returnType, CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column).FullName; + return fullTypeName; +// if (CurrentContext.ParsedDocument == null) +// return fullTypeName; +// ITypeReference returnType; +// int idx = fullTypeName.IndexOf ('#'); +// if (idx < 0) { +// returnType = new DomReturnType (fullTypeName); +// } else { +// returnType = new DomReturnType (fullTypeName.Substring (0, idx), fullTypeName.Substring (idx + 1)); +// } +// return CurrentContext.ParsedDocument.CompilationUnit.ShortenTypeName (returnType, CurrentContext.InsertPosition.Line, CurrentContext.InsertPosition.Column).FullName; } static Regex functionRegEx = new Regex ("([^(]*)\\(([^(]*)\\)", RegexOptions.Compiled); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.FindInFiles/ReferencesFinder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.FindInFiles/ReferencesFinder.cs index 51ce4c595c..bd0c443fb6 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.FindInFiles/ReferencesFinder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.FindInFiles/ReferencesFinder.cs @@ -25,14 +25,13 @@ // THE SOFTWARE. using System; -using MonoDevelop.Projects.Dom; using System.Collections.Generic; using System.Linq; using Mono.Addins; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom.Parser; -using MonoDevelop.Projects.CodeGeneration; using MonoDevelop.Projects; +using ICSharpCode.NRefactory.TypeSystem; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide.FindInFiles { @@ -67,31 +66,31 @@ namespace MonoDevelop.Ide.FindInFiles } - public static IEnumerable<MemberReference> FindReferences (INode member, IProgressMonitor monitor = null) + public static IEnumerable<DomRegion> FindReferences (IEntity member, IProgressMonitor monitor = null) { return FindReferences (IdeApp.ProjectOperations.CurrentSelectedSolution, member, monitor); } - static IEnumerable<Tuple<ProjectDom, FilePath>> GetFileNames (Solution solution, ProjectDom dom, ICompilationUnit unit, INode member, IProgressMonitor monitor) + static IEnumerable<Tuple<ITypeResolveContext, FilePath>> GetFileNames (Solution solution, IProjectContent dom, IParsedFile unit, IEntity member, IProgressMonitor monitor) { var scope = GetScope (member); switch (scope) { case RefactoryScope.File: case RefactoryScope.DeclaringType: if (dom != null && unit != null) - yield return Tuple.Create (dom, unit.FileName); + yield return Tuple.Create<ITypeResolveContext, FilePath> (dom, unit.FileName); break; case RefactoryScope.Project: if (dom == null) yield break; if (monitor != null) - monitor.BeginTask (GettextCatalog.GetString ("Search reference in project..."), dom.Project.Files.Count); + monitor.BeginTask (GettextCatalog.GetString ("Search reference in project..."), dom.GetProject ().Files.Count); int counter = 0; - foreach (var file in dom.Project.Files) { + foreach (var file in dom.GetProject ().Files) { if (monitor != null && monitor.IsCancelRequested) yield break; - yield return Tuple.Create (dom, file.FilePath); + yield return Tuple.Create<ITypeResolveContext, FilePath> (dom, file.FilePath); if (monitor != null) { if (counter % 10 == 0) monitor.Step (10); @@ -107,11 +106,11 @@ namespace MonoDevelop.Ide.FindInFiles foreach (var project in solution.GetAllProjects ()) { if (monitor != null && monitor.IsCancelRequested) yield break; - var currentDom = ProjectDomService.GetProjectDom (project); + var currentDom = TypeSystemService.GetProjectContext (project); foreach (var file in project.Files) { if (monitor != null && monitor.IsCancelRequested) yield break; - yield return Tuple.Create (currentDom, file.FilePath); + yield return Tuple.Create<ITypeResolveContext, FilePath> (currentDom, file.FilePath); } if (monitor != null) monitor.Step (1); @@ -122,26 +121,28 @@ namespace MonoDevelop.Ide.FindInFiles } } - public static IEnumerable<MemberReference> FindReferences (Solution solution, INode member, IProgressMonitor monitor = null) + public static IEnumerable<DomRegion> FindReferences (Solution solution, IEntity member, IProgressMonitor monitor = null) { - ProjectDom dom = null; - ICompilationUnit unit = null; - IEnumerable<INode > searchNodes = new INode[] { member }; - if (member is LocalVariable) { - dom = ((LocalVariable)member).DeclaringMember.DeclaringType.SourceProjectDom; - unit = ((LocalVariable)member).CompilationUnit; + ITypeResolveContext dom = null; + IParsedFile unit = null; + IEnumerable<IEntity> searchNodes = new IEntity[] { member }; + // TODO: Type system conversion. + /*if (member is IVariable) { + dom = ((IVariable)member).DeclaringMember.DeclaringTyp + e.GetProjectContent (); + unit = ((IVariable)member).CompilationUnit; } else if (member is IParameter) { - dom = ((IParameter)member).DeclaringMember.DeclaringType.SourceProjectDom; + dom = ((IParameter)member).DeclaringMember.DeclaringType.GetProjectContent (); unit = ((IParameter)member).DeclaringMember.DeclaringType.CompilationUnit; } else if (member is IType) { - dom = ((IType)member).SourceProjectDom; + dom = ((IType)member).GetDefinition ().ProjectContent; unit = ((IType)member).CompilationUnit; } else if (member is IMember) { - dom = ((IMember)member).DeclaringType.SourceProjectDom; + dom = ((IMember)member).DeclaringType.GetProjectContent (); unit = ((IMember)member).DeclaringType.CompilationUnit; searchNodes = CollectMembers (dom, (IMember)member); } - + string currentMime = null; ReferenceFinder finder = null; @@ -160,31 +161,34 @@ namespace MonoDevelop.Ide.FindInFiles yield break; yield return foundReference; } - } + } */ + yield break; } - public abstract IEnumerable<MemberReference> FindReferences (ProjectDom dom, FilePath fileName, IEnumerable<INode> searchedMembers); + public abstract IEnumerable<DomRegion> FindReferences (ITypeResolveContext dom, FilePath fileName, IEnumerable<IEntity> searchedMembers); - internal static IEnumerable<INode> CollectMembers (ProjectDom dom, IMember member) + internal static IEnumerable<IEntity> CollectMembers (ITypeResolveContext dom, IMember member) { - if (member is IMethod && ((IMethod)member).IsConstructor) { + yield break; + // TODO: Type system conversion. + /* if (member is IMethod && ((IMethod)member).IsConstructor) { yield return member; } else { - bool isOverrideable = member.DeclaringType.ClassType == ClassType.Interface || member.IsOverride || member.IsVirtual || member.IsAbstract; + bool isOverrideable = member.DeclaringType.GetDefinition ().ClassType == ClassType.Interface || member.IsOverride || member.IsVirtual || member.IsAbstract; bool isLastMember = false; // for members we need to collect the whole 'class' of members (overloads & implementing types) HashSet<string> alreadyVisitedTypes = new HashSet<string> (); - foreach (IType type in dom.GetInheritanceTree (member.DeclaringType)) { - if (type.ClassType == ClassType.Interface || isOverrideable || type.DecoratedFullName == member.DeclaringType.DecoratedFullName) { + foreach (var type in member.DeclaringType.GetAllBaseTypes (dom)) { + if (type.GetDefinition ().ClassType == ClassType.Interface || isOverrideable || type.Equals (member.DeclaringType)) { // search in the class for the member - foreach (IMember interfaceMember in type.SearchMember (member.Name, true)) { + foreach (var interfaceMember in type.SearchMember (member.Name, true)) { if (interfaceMember.MemberType == member.MemberType) yield return interfaceMember; } // now search in all subclasses of this class for the member isLastMember = !member.IsOverride; - foreach (IType implementingType in dom.GetSubclasses (type)) { + foreach (var implementingType in dom.GetSubclasses (type)) { string name = implementingType.DecoratedFullName; if (alreadyVisitedTypes.Contains (name)) continue; @@ -202,22 +206,25 @@ namespace MonoDevelop.Ide.FindInFiles break; } } - } + }*/ } - - static RefactoryScope GetScope (INode node) + public enum RefactoryScope{ File, DeclaringType, Solution, Project} + static RefactoryScope GetScope (IEntity node) { IMember member = node as IMember; if (member == null) return RefactoryScope.DeclaringType; - if (member.DeclaringType != null && member.DeclaringType.ClassType == ClassType.Interface) - return GetScope (member.DeclaringType); + if (node.DeclaringTypeDefinition != null && node.DeclaringTypeDefinition.ClassType == ClassType.Interface) + return GetScope (member.DeclaringTypeDefinition); - if (member.IsPublic) + if ((member.Accessibility & Accessibility.Public) == Accessibility.Public) return RefactoryScope.Solution; - if (member.IsProtected || member.IsInternal || member.DeclaringType == null) + // TODO: RefactoringsScope.Hierarchy + if ((member.Accessibility & Accessibility.Protected) == Accessibility.Protected) + return RefactoryScope.Solution; + if ((member.Accessibility & Accessibility.Internal) == Accessibility.Protected) return RefactoryScope.Project; return RefactoryScope.DeclaringType; } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/CompletionTextEditorExtension.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/CompletionTextEditorExtension.cs index 563fd118bd..9856a99ab6 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/CompletionTextEditorExtension.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/CompletionTextEditorExtension.cs @@ -29,9 +29,6 @@ using System; using MonoDevelop.Projects; using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Commands; using MonoDevelop.Core; @@ -373,9 +370,9 @@ namespace MonoDevelop.Ide.Gui.Content } // If there is a parser context, try resolving by calling CtrlSpace. - ProjectDom ctx = GetParserContext(); + var ctx = GetParserContext(); if (ctx != null) { -// TODO: +// TODO: Type system conversion. //CodeCompletionDataProvider completionProvider = new CodeCompletionDataProvider (ctx, GetAmbience ()); //completionProvider.AddResolveResults (ctx.CtrlSpace (completionContext.TriggerLine + 1, // completionContext.TriggerLineOffset + 1, FileName), true, SimpleTypeNameResolver.Instance); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/ITextEditorResolver.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/ITextEditorResolver.cs index 25bb60f2be..ab198f3689 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/ITextEditorResolver.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/ITextEditorResolver.cs @@ -27,13 +27,13 @@ // using System; -using MonoDevelop.Projects.Dom; using System.Collections.Generic; using System.Linq; using Mono.TextEditor; using Mono.Addins; -using MonoDevelop.Projects.Dom.Parser; -using MonoDevelop.Projects.Dom.Output; +using ICSharpCode.NRefactory.CSharp.Resolver; +using ICSharpCode.NRefactory.TypeSystem; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide.Gui.Content { @@ -45,10 +45,10 @@ namespace MonoDevelop.Ide.Gui.Content public interface ITextEditorResolverProvider { - ResolveResult GetLanguageItem (ProjectDom dom, TextEditorData data, int offset); - ResolveResult GetLanguageItem (ProjectDom dom, TextEditorData data, int offset, string expression); + ResolveResult GetLanguageItem (ITypeResolveContext dom, TextEditorData data, int offset); + ResolveResult GetLanguageItem (ITypeResolveContext dom, TextEditorData data, int offset, string expression); - string CreateTooltip (ProjectDom dom, ICompilationUnit unit, ResolveResult result, string errorInformations, Ambience ambience, Gdk.ModifierType modifierState); + string CreateTooltip (ITypeResolveContext dom, IParsedFile unit, ResolveResult result, string errorInformations, Ambience ambience, Gdk.ModifierType modifierState); } public static class TextEditorResolverService diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/TextEditorExtension.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/TextEditorExtension.cs index 0e9347bcd2..fd17394f91 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/TextEditorExtension.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Content/TextEditorExtension.cs @@ -29,13 +29,12 @@ using System; using MonoDevelop.Projects; using MonoDevelop.Ide.CodeCompletion; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Commands;
using MonoDevelop.Core; using Mono.TextEditor; +using ICSharpCode.NRefactory.TypeSystem; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide.Gui.Content { @@ -69,7 +68,7 @@ namespace MonoDevelop.Ide.Gui.Content } } - protected ProjectDom GetParserContext () + protected ITypeResolveContext GetParserContext () { CheckInitialized (); @@ -78,9 +77,8 @@ namespace MonoDevelop.Ide.Gui.Content Project project = view.Project; if (project != null) - return ProjectDomService.GetProjectDom (project); - else - return ProjectDomService.GetFileDom (file); + return TypeSystemService.GetContext (project); + return TypeSystemService.GetContext (file, Document.Editor.Document.MimeType, Document.Editor.Text); } protected Ambience GetAmbience () @@ -88,14 +86,8 @@ namespace MonoDevelop.Ide.Gui.Content CheckInitialized (); IViewContent view = document.Window.ViewContent; - Project project = view.Project; - - if (project != null) - return project.Ambience; - else { - string file = view.IsUntitled ? view.UntitledName : view.ContentName; - return AmbienceService.GetAmbienceForFile (file); - } + string file = view.IsUntitled ? view.UntitledName : view.ContentName; + return AmbienceService.GetAmbienceForFile (file); } public virtual bool ExtendsEditor (Document doc, IEditableTextBuffer editor) diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.OptionPanels/TasksOptionsPanel.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.OptionPanels/TasksOptionsPanel.cs index e5db3ad7de..a17789ecb5 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.OptionPanels/TasksOptionsPanel.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.OptionPanels/TasksOptionsPanel.cs @@ -34,7 +34,6 @@ using MonoDevelop.Core; using MonoDevelop.Ide.Gui.Dialogs; using MonoDevelop.Components; using MonoDevelop.Ide.Tasks; -using MonoDevelop.Projects.Dom.Parser; using Gtk; namespace MonoDevelop.Ide.Gui.OptionPanels @@ -166,7 +165,7 @@ namespace MonoDevelop.Ide.Gui.OptionPanels public void Load () { - foreach (CommentTag ctag in ProjectDomService.SpecialCommentTags) + foreach (var ctag in TaskService.SpecialCommentTags) tokensStore.AppendValues (ctag.Tag, ctag.Priority); colorbuttonHighPrio.Color = StringToColor ((string)PropertyService.Get ("Monodevelop.UserTasksHighPrioColor", "")); @@ -180,7 +179,7 @@ namespace MonoDevelop.Ide.Gui.OptionPanels foreach (object[] row in tokensStore) tags.Add (new CommentTag ((string)row[0], (int)row[1])); - ProjectDomService.SpecialCommentTags = new CommentTagSet (tags); + TaskService.SpecialCommentTags = tags; PropertyService.Set ("Monodevelop.UserTasksHighPrioColor", ColorToString (colorbuttonHighPrio.Color)); PropertyService.Set ("Monodevelop.UserTasksNormalPrioColor", ColorToString (colorbuttonNormalPrio.Color)); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassBrowserPadWidget.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassBrowserPadWidget.cs index d1414c7563..14efdec50d 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassBrowserPadWidget.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassBrowserPadWidget.cs @@ -33,8 +33,6 @@ using System.Collections.Generic; using Gdk; using Gtk; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Projects; using MonoDevelop.Core; using MonoDevelop.Ide.Gui; @@ -187,7 +185,7 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassBrowser if (!IdeApp.Workspace.IsOpen) return; foreach (Project project in IdeApp.Workspace.GetAllProjects ()) { - ProjectDom dom = ProjectDomService.GetProjectDom (project); + ITypeResolveContext dom = TypeSystemService.GetProjectDom (project); if (dom == null) continue; foreach (IType type in dom.Types) { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassData.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassData.cs index 47e49e90d5..07aded100f 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassData.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassData.cs @@ -32,7 +32,7 @@ using System.Collections; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; +using ICSharpCode.NRefactory.TypeSystem; namespace MonoDevelop.Ide.Gui.Pads.ClassPad { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassNodeBuilder.cs index 7d65c12534..a8099beca0 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ClassNodeBuilder.cs @@ -32,8 +32,6 @@ using System.Text; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/EventNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/EventNodeBuilder.cs index 06001d882c..e88bca6968 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/EventNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/EventNodeBuilder.cs @@ -31,8 +31,6 @@ using System.Collections; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.Ide.Gui.Pads.ClassPad diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/FieldNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/FieldNodeBuilder.cs index d39a6be406..414ca870f3 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/FieldNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/FieldNodeBuilder.cs @@ -31,8 +31,6 @@ using System.Collections; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.Ide.Gui.Pads.ClassPad diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeBuilder.cs index a202ee20a4..21e71f27d9 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeBuilder.cs @@ -31,8 +31,6 @@ using System.Collections; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.Ide.Gui.Pads.ClassPad diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeCommandHandler.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeCommandHandler.cs index cd250a504b..0f23f8b115 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeCommandHandler.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MemberNodeCommandHandler.cs @@ -29,7 +29,6 @@ using System; using System.IO; -using MonoDevelop.Projects.Dom; using MonoDevelop.Core; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MethodNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MethodNodeBuilder.cs index b7ec0e68f9..a3465747a4 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MethodNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/MethodNodeBuilder.cs @@ -31,8 +31,6 @@ using System.Collections; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.Ide.Gui.Pads.ClassPad diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs index 08f88f3525..eead8a0325 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceData.cs @@ -32,10 +32,9 @@ using System.Collections.Generic; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; +using ICSharpCode.NRefactory.TypeSystem; namespace MonoDevelop.Ide.Gui.Pads.ClassPad { @@ -95,11 +94,11 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad public override void AddProjectContent (ITreeBuilder builder) { if (project != null) { - ProjectDom dom = ProjectDomService.GetProjectDom (Project); + ITypeResolveContext dom = TypeSystemService.GetProjectDom (Project); AddProjectContent (builder, dom.GetNamespaceContents (FullName, false, false)); } else { foreach (Project p in IdeApp.Workspace.GetAllProjects ()) { - ProjectDom dom = ProjectDomService.GetProjectDom (p); + ITypeResolveContext dom = TypeSystemService.GetProjectDom (p); AddProjectContent (builder, dom.GetNamespaceContents (FullName, false, false)); } } @@ -144,9 +143,9 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad public class CompilationUnitNamespaceData : NamespaceData { - ICompilationUnit unit; + IParsedFile unit; - public CompilationUnitNamespaceData (ICompilationUnit unit, string fullNamespace) : base (fullNamespace) + public CompilationUnitNamespaceData (IParsedFile unit, string fullNamespace) : base (fullNamespace) { this.unit = unit; } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceNodeBuilder.cs index 46ad65b4a5..a43af8d32a 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/NamespaceNodeBuilder.cs @@ -32,8 +32,6 @@ using System.Collections.Generic; using MonoDevelop.Projects; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ProjectNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ProjectNodeBuilder.cs index 1d72409def..865c178cb6 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ProjectNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ProjectNodeBuilder.cs @@ -33,8 +33,6 @@ using System.Collections.Generic; using System.Text; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Core; using MonoDevelop.Ide.Gui.Components; @@ -53,11 +51,11 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad protected override void Initialize () { compilationUnitUpdated = (EventHandler<TypeUpdateInformationEventArgs>) DispatchService.GuiDispatch (new EventHandler<TypeUpdateInformationEventArgs> (OnClassInformationChanged)); - ProjectDomService.TypesUpdated += compilationUnitUpdated; + TypeSystemService.TypesUpdated += compilationUnitUpdated; } public override void Dispose () { - ProjectDomService.TypesUpdated -= compilationUnitUpdated; + TypeSystemService.TypesUpdated -= compilationUnitUpdated; } public override Type NodeDataType { @@ -104,7 +102,7 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad builder.AddChild (((DotNetProject)project).References); } bool publicOnly = builder.Options ["PublicApiOnly"]; - ProjectDom dom = ProjectDomService.GetProjectDom (project); + ITypeResolveContext dom = TypeSystemService.GetProjectDom (project); //IParserContext ctx = IdeApp.Workspace.ParserDatabase.GetProjectParserContext (project); foreach (IMember ob in dom.GetNamespaceContents ("", false, false)) { if (ob is Namespace) { @@ -121,7 +119,7 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad public static void FillNamespaces (ITreeBuilder builder, Project project, string ns) { - ProjectDom dom = ProjectDomService.GetProjectDom (project); + ITypeResolveContext dom = TypeSystemService.GetProjectDom (project); List<IMember> members = dom.GetNamespaceContents (ns, false, false); //IParserContext ctx = IdeApp.Workspace.ParserDatabase.GetProjectParserContext (project); if (members.Count > 0) { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ReferenceNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ReferenceNodeBuilder.cs index e3cebf2af9..a7de6771e6 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ReferenceNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ClassPad/ReferenceNodeBuilder.cs @@ -1,4 +1,4 @@ -//
+// // ReferenceNodeBuilder.cs // // Author: @@ -26,15 +26,13 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -using System;
-using System.Collections.Generic;
-using System.IO;
+using System; +using System.Collections.Generic; +using System.IO; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Core; -using MonoDevelop.Ide.Gui.Components;
+using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.Ide.Gui.Pads.ClassPad { @@ -47,7 +45,7 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad public override string ContextMenuAddinPath { get { return "/MonoDevelop/Ide/ContextMenu/ClassPad/References"; } } -
+ public override Type CommandHandlerType { get { return typeof(ReferenceNodeCommandHandler); } } @@ -55,12 +53,12 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad public override string GetNodeName (ITreeNavigator thisNode, object dataObject) { return ((ProjectReference)dataObject).Reference; - }
+ } public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, ref string label, ref Gdk.Pixbuf icon, ref Gdk.Pixbuf closedIcon) { ProjectReference pref = (ProjectReference) dataObject; -
+ switch (pref.ReferenceType) { case ReferenceType.Project: label = pref.Reference; @@ -77,45 +75,45 @@ namespace MonoDevelop.Ide.Gui.Pads.ClassPad } icon = Context.GetIcon (Stock.Reference); - }
-
+ } + public override void BuildChildNodes (ITreeBuilder builder, object dataObject) { - ProjectReference pref = (ProjectReference) dataObject;
- Dictionary<string, bool> namespaces = new Dictionary<string, bool> ();
- bool nestedNs = builder.Options ["NestedNamespaces"];
- foreach (string fileName in pref.GetReferencedFileNames (IdeApp.Workspace.ActiveConfiguration)) {
- ICompilationUnit unit = DomCecilCompilationUnit.Load (fileName, false, true);
- if (unit == null)
- continue;
- foreach (IType type in unit.Types) {
- if (type.IsSpecialName || type.Name.Contains ("<") || type.Name.Contains (">") || type.Name.Contains ("$"))
- continue;
- if (String.IsNullOrEmpty (type.Namespace)) {
- builder.AddChild (new ClassData (null, type));
- continue;
- }
- string ns = type.Namespace;
+ ProjectReference pref = (ProjectReference) dataObject; + Dictionary<string, bool> namespaces = new Dictionary<string, bool> (); + bool nestedNs = builder.Options ["NestedNamespaces"]; + foreach (string fileName in pref.GetReferencedFileNames (IdeApp.Workspace.ActiveConfiguration)) { + IParsedFile unit = DomCecilCompilationUnit.Load (fileName, false, true); + if (unit == null) + continue; + foreach (IType type in unit.Types) { + if (type.IsSpecialName || type.Name.Contains ("<") || type.Name.Contains (">") || type.Name.Contains ("$")) + continue; + if (String.IsNullOrEmpty (type.Namespace)) { + builder.AddChild (new ClassData (null, type)); + continue; + } + string ns = type.Namespace; if (nestedNs) { - int idx = ns.IndexOf ('.');
+ int idx = ns.IndexOf ('.'); if (idx >= 0) - ns = ns.Substring (0, idx);
- }
- if (namespaces.ContainsKey (ns))
- continue;
- namespaces[ns] = true;
+ ns = ns.Substring (0, idx); + } + if (namespaces.ContainsKey (ns)) + continue; + namespaces[ns] = true; builder.AddChild (new CompilationUnitNamespaceData (unit, ns)); } - }
+ } } -
+ public override bool HasChildNodes (ITreeBuilder builder, object dataObject) - {
- ProjectReference pref = (ProjectReference)dataObject;
+ { + ProjectReference pref = (ProjectReference)dataObject; return pref.ReferenceType != ReferenceType.Project; } - }
-
+ } + public class ReferenceNodeCommandHandler : NodeCommandHandler { public override void ActivateItem () diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads/MonodocTreePad.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads/MonodocTreePad.cs index 3bbc515b4e..c401884b88 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads/MonodocTreePad.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads/MonodocTreePad.cs @@ -34,7 +34,7 @@ using Monodoc; using MonoDevelop.Core; using MonoDevelop.Ide.Gui; -using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.Projects; namespace MonoDevelop.Ide.Gui.Pads { @@ -62,8 +62,8 @@ namespace MonoDevelop.Ide.Gui.Pads scroller.ShadowType = Gtk.ShadowType.None; scroller.Add (tree_view); - if (ProjectDomService.HelpTree != null) { - root_iter = store.AppendValues (GettextCatalog.GetString ("Mono Documentation"), ProjectDomService.HelpTree); + if (HelpService.HelpTree != null) { + root_iter = store.AppendValues (GettextCatalog.GetString ("Mono Documentation"), HelpService.HelpTree); PopulateNode (root_iter); tree_view.ExpandRow (new TreePath ("0"), false); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Document.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Document.cs index 2323fd08b2..aa110d2a99 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Document.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Document.cs @@ -41,12 +41,14 @@ using MonoDevelop.Projects; using MonoDevelop.Projects.Text; using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Ide.Gui.Dialogs; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Ide.Tasks; using Mono.Addins; using MonoDevelop.Ide.Extensions; using System.Linq; +using System.Threading; +using MonoDevelop.TypeSystem; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.TypeSystem.Implementation; namespace MonoDevelop.Ide.Gui { @@ -130,17 +132,17 @@ namespace MonoDevelop.Ide.Gui window.ActiveViewContentChanged += OnActiveViewContentChanged; if (IdeApp.Workspace != null) IdeApp.Workspace.ItemRemovedFromSolution += OnEntryRemoved; - ProjectDomService.DomRegistered += UpdateRegisteredDom; +// TypeSystemService.DomRegistered += UpdateRegisteredDom; } - void UpdateRegisteredDom (object sender, ProjectDomEventArgs e) +/* void UpdateRegisteredDom (object sender, ProjectDomEventArgs e) { if (dom == null || dom.Project == null) return; - var project = e.ProjectDom != null ? e.ProjectDom.Project : null; + var project = e.ITypeResolveContext != null ? e.ITypeResolveContext.Project : null; if (project != null && project.FileName == dom.Project.FileName) - dom = e.ProjectDom; - } + dom = e.ITypeResolveContext; + }*/ public FilePath FileName { get { @@ -167,26 +169,6 @@ namespace MonoDevelop.Ide.Gui get { return Window.ViewContent.Project; } set { Window.ViewContent.Project = value; - dom = null; - } - } - - ProjectDom dom; - bool isFileDom; - public ProjectDom Dom { - get { - if (dom == null) { - isFileDom = false; - dom = ProjectDomService.GetProjectDom (Project); - if (dom == null) { - dom = ProjectDomService.GetFileDom (FileName); - isFileDom = true; - } - } - return dom ?? ProjectDom.Empty; - } - set { - dom = value; } } @@ -196,9 +178,10 @@ namespace MonoDevelop.Ide.Gui } } - public ICSharpCode.NRefactory.TypeSystem.IParsedFile ParsedFile { + ParsedDocument parsedFile; + public ParsedDocument ParsedFile { get { - return MonoDevelop.TypeSystem.TypeSystemService.ParseFile (MonoDevelop.TypeSystem.TypeSystemService.GetProjectContext (Project), FileName, Editor.Document.MimeType, Editor.Document.Text); + return parsedFile; } } @@ -431,7 +414,7 @@ namespace MonoDevelop.Ide.Gui void OnClosed (object s, EventArgs a) { isClosed = true; - ProjectDomService.DomRegistered -= UpdateRegisteredDom; +// TypeSystemService.DomRegistered -= UpdateRegisteredDom; CancelParseTimeout (); ClearTasks (); @@ -463,48 +446,21 @@ namespace MonoDevelop.Ide.Gui // Parse the file when the document is closed. In this way if the document // is closed without saving the changes, the saved compilation unit // information will be restored - if (currentParseFile != null) { - ProjectDomService.QueueParseJob (dom, delegate (string name, IProgressMonitor monitor) { - ProjectDomService.Parse (curentParseProject, currentParseFile); +/* if (currentParseFile != null) { + TypeSystemService.QueueParseJob (dom, delegate (string name, IProgressMonitor monitor) { + TypeSystemService.Parse (curentParseProject, currentParseFile); }, FileName); } if (isFileDom) { - ProjectDomService.RemoveFileDom (FileName); + TypeSystemService.RemoveFileDom (FileName); dom = null; - } + }*/ Counters.OpenDocuments--; } #region document tasks object lockObj = new object (); - ParsedDocument lastErrorFreeParsedDocument; - - ParsedDocument parsedDocument; - public ParsedDocument ParsedDocument { - get { - return parsedDocument; - } - set { - // for unit testing purposes - parsedDocument = value; - } - } - - public ICompilationUnit CompilationUnit { - get { - if (parsedDocument == null) - return null; - var unit = parsedDocument.CompilationUnit; - if (unit == null) - return null; - // HACK: The parser sometimes doesn't send back >any< info on the file on certain errors, this code detects if the last error free parsed document is the better best-fit. - if (parsedDocument.HasErrors && !unit.Types.Any () && lastErrorFreeParsedDocument != null && lastErrorFreeParsedDocument.CompilationUnit.Types.Any ()) - return lastErrorFreeParsedDocument.CompilationUnit; - return unit; - } - } - void ClearTasks () { lock (lockObj) { @@ -639,7 +595,7 @@ namespace MonoDevelop.Ide.Gui /// <returns> /// A <see cref="ParsedDocument"/> that contains the current dom. /// </returns> - public ParsedDocument UpdateParseDocument () + public IParsedFile UpdateParseDocument () { try { string currentParseFile = FileName; @@ -647,14 +603,14 @@ namespace MonoDevelop.Ide.Gui 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; + var ctx = TypeSystemService.GetProjectContext (Project); + if (ctx == null) + ctx = new SimpleProjectContent (); + this.parsedFile = TypeSystemService.ParseFile (ctx, currentParseFile, editor.Document.MimeType, currentParseText); } finally { OnDocumentParsed (EventArgs.Empty); } - return this.parsedDocument; + return this.parsedFile; } uint parseTimeout = 0; @@ -667,20 +623,22 @@ namespace MonoDevelop.Ide.Gui CancelParseTimeout (); parseTimeout = GLib.Timeout.Add (ParseDelay, delegate { string currentParseText = Editor.Text; + string mimeType = Editor.Document.MimeType; Project curentParseProject = Project; - // parser revice queue takes care of the locking - ProjectDomService.QueueParseJob (dom, delegate (string name, IProgressMonitor monitor) { - var currentParsedDocument = ProjectDomService.Parse (curentParseProject, currentParseFile, currentParseText); + + ThreadPool.QueueUserWorkItem (delegate { + var currentParsedDocument = TypeSystemService.ParseFile (TypeSystemService.GetProjectContext (Project), currentParseFile, mimeType, currentParseText); Application.Invoke (delegate { // this may be called after the document has closed, in that case the OnDocumentParsed event shouldn't be invoked. if (isClosed) return; - this.parsedDocument = currentParsedDocument; - if (this.parsedDocument != null && !this.parsedDocument.HasErrors) - this.lastErrorFreeParsedDocument = parsedDocument; + this.parsedFile = currentParsedDocument; +// this.parsedDocument = currentParsedDocument; +// if (this.parsedDocument != null && !this.parsedDocument.HasErrors) +// this.lastErrorFreeParsedDocument = parsedDocument; OnDocumentParsed (EventArgs.Empty); }); - }, FileName); + }); parseTimeout = 0; return false; }); @@ -695,12 +653,6 @@ namespace MonoDevelop.Ide.Gui } } - public ParsedDocument LastErrorFreeParsedDocument { - get { - return lastErrorFreeParsedDocument; - } - } - void OnEntryRemoved (object sender, SolutionItemEventArgs args) { if (args.SolutionItem == window.ViewContent.Project) @@ -756,11 +708,11 @@ namespace MonoDevelop.Ide.Gui return null; } - public MonoDevelop.Projects.CodeGeneration.CodeGenerator CreateCodeGenerator () - { - return MonoDevelop.Projects.CodeGeneration.CodeGenerator.CreateGenerator (Editor.Document.MimeType, - Editor.Options.TabsToSpaces, Editor.Options.TabSize, Editor.EolMarker); - } +// public MonoDevelop.Projects.CodeGeneration.CodeGenerator CreateCodeGenerator () +// { +// return MonoDevelop.Projects.CodeGeneration.CodeGenerator.CreateGenerator (Editor.Document.MimeType, +// Editor.Options.TabsToSpaces, Editor.Options.TabSize, Editor.EolMarker); +// } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Workbench.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Workbench.cs index 79e4ace647..bdef18fe39 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Workbench.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Workbench.cs @@ -966,7 +966,7 @@ namespace MonoDevelop.Ide.Gui public void ReparseOpenDocuments () { foreach (var doc in Documents) { - if (doc.ParsedDocument != null) + if (doc.ParsedFile != null) doc.UpdateParseDocument (); } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/NavigateToDialog.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/NavigateToDialog.cs index ac9a2ab004..c1e49fc0b9 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/NavigateToDialog.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/NavigateToDialog.cs @@ -42,8 +42,8 @@ using MonoDevelop.Core.Instrumentation; using MonoDevelop.Core.Text; using MonoDevelop.Ide.Gui; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; +using ICSharpCode.NRefactory.TypeSystem; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide.NavigateToDialog { @@ -178,7 +178,7 @@ namespace MonoDevelop.Ide.NavigateToDialog void StartCollectThreads () { members = new List<IMember> (); - types = new List<IType> (); + types = new List<Tuple<ITypeResolveContext, IType>> (); StartCollectFiles (); StartCollectTypes (); @@ -195,10 +195,22 @@ namespace MonoDevelop.Ide.NavigateToDialog getMembersTimer.BeginTiming (); try { lock (members) { - foreach (IType type in types) { - foreach (IMember m in type.Members) { - if (m is IType) - continue; + foreach (var pair in types) { + var ctx = pair.Item1; + var type = pair.Item2; + foreach (var m in type.GetMethods (ctx)) { + members.Add (m); + } + + foreach (var m in type.GetFields (ctx)) { + members.Add (m); + } + + foreach (var m in type.GetProperties (ctx)) { + members.Add (m); + } + + foreach (var m in type.GetEvents (ctx)) { members.Add (m); } } @@ -310,7 +322,7 @@ namespace MonoDevelop.Ide.NavigateToDialog class WorkerResult { public List<ProjectFile> filteredFiles = null; - public List<IType> filteredTypes = null; + public List<Tuple<ITypeResolveContext, IType>> filteredTypes = null; public List<IMember> filteredMembers = null; public string pattern = null; @@ -359,7 +371,7 @@ namespace MonoDevelop.Ide.NavigateToDialog internal SearchResult CheckMember (IMember member) { int rank; - bool useDeclaringTypeName = member is IMethod && (((IMethod)member).IsConstructor || ((IMethod)member).IsFinalizer); + bool useDeclaringTypeName = member is IMethod && (((IMethod)member).IsConstructor || ((IMethod)member).IsDestructor); string memberName = useDeclaringTypeName ? member.DeclaringType.Name : member.Name; if (MatchName (memberName, out rank)) return new MemberSearchResult (pattern, memberName, rank, member, false); @@ -386,7 +398,7 @@ namespace MonoDevelop.Ide.NavigateToDialog } IEnumerable<ProjectFile> files; - List<IType> types; + List<Tuple<ITypeResolveContext, IType>> types; List<IMember> members; WorkerResult lastResult; @@ -450,14 +462,14 @@ namespace MonoDevelop.Ide.NavigateToDialog // Search Types if (newResult.IncludeTypes) { - newResult.filteredTypes = new List<IType> (); + newResult.filteredTypes = new List<Tuple<ITypeResolveContext, IType>> (); lock (types) { bool startsWithLastFilter = lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern) && lastResult.filteredTypes != null; - List<IType> allTypes = startsWithLastFilter ? lastResult.filteredTypes : types; - foreach (IType type in allTypes) { + List<Tuple<ITypeResolveContext, IType>> allTypes = startsWithLastFilter ? lastResult.filteredTypes : types; + foreach (var type in allTypes) { if (worker.CancellationPending) yield break; - SearchResult curResult = newResult.CheckType (type); + SearchResult curResult = newResult.CheckType (type.Item2); if (curResult != null) { newResult.filteredTypes.Add (type); yield return curResult; @@ -547,10 +559,10 @@ namespace MonoDevelop.Ide.NavigateToDialog // of the open combine. Otherwise, it will get // checked down below. if (doc.Project == null && doc.IsFile) { - ICompilationUnit info = doc.CompilationUnit; + var info = doc.ParsedFile; if (info != null) { - foreach (IType c in info.Types) { - types.Add (c); + foreach (var c in info.TopLevelTypeDefinitions) { + types.Add (Tuple.Create (doc.TypeResolveContext, (IType)c)); } } } @@ -559,11 +571,11 @@ namespace MonoDevelop.Ide.NavigateToDialog ReadOnlyCollection<Project> projects = IdeApp.Workspace.GetAllProjects (); foreach (Project p in projects) { - ProjectDom dom = ProjectDomService.GetProjectDom (p); + var dom = TypeSystemService.GetProjectContext (p); if (dom == null) continue; - foreach (IType c in dom.Types) - AddType (c, types); + foreach (var c in dom.GetClasses ()) + AddType (c, dom, types); } } finally { getTypesTimer.EndTiming (); @@ -571,11 +583,11 @@ namespace MonoDevelop.Ide.NavigateToDialog } } - void AddType (IType c, List<IType> list) + void AddType (IType c, ITypeResolveContext ctx, List<Tuple<ITypeResolveContext, IType>> list) { - list.Add (c); - foreach (IType ct in c.InnerTypes) - AddType (ct, list); + list.Add (Tuple.Create (ctx, c)); + foreach (var ct in c.GetNestedTypes (ctx)) + AddType (ct, ctx, list); } struct MatchResult diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/ResultsDataSource.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/ResultsDataSource.cs index 7701d5b48f..8266233b5c 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/ResultsDataSource.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/ResultsDataSource.cs @@ -33,13 +33,10 @@ using System.Threading; using Gdk; using Gtk; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Components; using MonoDevelop.Core; using MonoDevelop.Core.Instrumentation; using MonoDevelop.Ide.Gui; -using MonoDevelop.Projects.Dom.Output; using MonoDevelop.Ide.CodeCompletion; namespace MonoDevelop.Ide.NavigateToDialog diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/SearchResult.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/SearchResult.cs index a8a24610e2..bb7573584d 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/SearchResult.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.NavigateToDialog/SearchResult.cs @@ -31,8 +31,8 @@ using Gtk; using MonoDevelop.Core; using MonoDevelop.Core.Text; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Output; +using ICSharpCode.NRefactory.TypeSystem; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide.NavigateToDialog { @@ -95,24 +95,63 @@ namespace MonoDevelop.Ide.NavigateToDialog class TypeSearchResult : MemberSearchResult { + IType type; + public override string File { - get { return ((IType)member).CompilationUnit.FileName; } + get { return type.GetDefinition ().Region.FileName; } + } + + public override Gdk.Pixbuf Icon { + get { + return ImageService.GetPixbuf (type.GetStockIcon (), IconSize.Menu); + } + } + + public override int Row { + get { return type.GetDefinition ().Region.BeginLine; } + } + + public override int Column { + get { return type.GetDefinition ().Region.BeginColumn; } + } + + public override string PlainText { + get { + return Ambience.GetString (type.GetDefinition (), Flags); + } } public override string Description { get { - IType type = (IType)member; - if (useFullName) - return type.SourceProject != null ? String.Format (GettextCatalog.GetString ("from Project \"{0}\""), type.SourceProject.Name ?? "") : String.Format (GettextCatalog.GetString ("from \"{0}\""), (string)type.CompilationUnit.FileName ?? ""); - if (type.SourceProject != null) - return String.Format (GettextCatalog.GetString ("from Project \"{0} in {1}\""), type.SourceProject.Name ?? "", type.Namespace ?? ""); - return String.Format (GettextCatalog.GetString ("from \"{0} in {1}\""), (string)type.CompilationUnit.FileName ?? "", type.Namespace ?? ""); + // if (useFullName) + // return type.GetSourceProject () != null ? String.Format (GettextCatalog.GetString ("from Project \"{0}\""), type.GetSourceProject ().Name ?? "") : String.Format (GettextCatalog.GetString ("from \"{0}\""), (string)type.GetDefinition ().Region.FileName ?? ""); + // if (type.GetSourceProject () != null) + // return String.Format (GettextCatalog.GetString ("from Project \"{0} in {1}\""), type.GetSourceProject ().Name ?? "", type.Namespace ?? ""); + return String.Format (GettextCatalog.GetString ("from \"{0} in {1}\""), File ?? "", type.Namespace ?? ""); } } + public override string GetMarkupText (Widget widget) + { + if (useFullName) + return HighlightMatch (widget, Ambience.GetString (member, Flags), match); + OutputSettings settings = new OutputSettings (Flags | OutputFlags.IncludeMarkup); + settings.EmitNameCallback = delegate (object domVisitable, ref string outString) { + if (type == domVisitable) + outString = HighlightMatch (widget, outString, match); + }; + return Ambience.GetString (type, settings); + } - public TypeSearchResult (string match, string matchedString, int rank, IType type, bool useFullName) : base (match, matchedString, rank, type, useFullName) + public TypeSearchResult (string match, string matchedString, int rank, IType type, bool useFullName) : base (match, matchedString, rank, null, useFullName) { + this.type = type; + } + + protected override Ambience Ambience { + get { + return AmbienceService.GetAmbienceForFile (type.GetDefinition ().Region.FileName); + } } } @@ -174,18 +213,6 @@ namespace MonoDevelop.Ide.NavigateToDialog } } - public override string GetMarkupText (Widget widget) - { - if (useFullName) - return HighlightMatch (widget, Ambience.GetString (member, Flags), match); - OutputSettings settings = new OutputSettings (Flags | OutputFlags.IncludeMarkup); - settings.EmitNameCallback = delegate (INode domVisitable, ref string outString) { - if (domVisitable == member) - outString = HighlightMatch (widget, outString, match); - }; - return Ambience.GetString (member, settings); - } - /* public override string MarkupText { get { @@ -201,21 +228,21 @@ namespace MonoDevelop.Ide.NavigateToDialog } public override string File { - get { return member.DeclaringType.CompilationUnit.FileName; } + get { return member.DeclaringType.GetDefinition ().Region.FileName; } } public override Gdk.Pixbuf Icon { get { - return ImageService.GetPixbuf (member.StockIcon, IconSize.Menu); + return ImageService.GetPixbuf (member.GetStockIcon (), IconSize.Menu); } } public override int Row { - get { return member.Location.Line; } + get { return member.Region.BeginLine; } } public override int Column { - get { return member.Location.Column; } + get { return member.Region.BeginColumn; } } public override string Description { @@ -230,12 +257,21 @@ namespace MonoDevelop.Ide.NavigateToDialog this.useFullName = useFullName; } - protected Ambience Ambience { + public override string GetMarkupText (Widget widget) + { + if (useFullName) + return HighlightMatch (widget, Ambience.GetString (member, Flags), match); + OutputSettings settings = new OutputSettings (Flags | OutputFlags.IncludeMarkup); + settings.EmitNameCallback = delegate (object domVisitable, ref string outString) { + if (member == domVisitable) + outString = HighlightMatch (widget, outString, match); + }; + return Ambience.GetString (member, settings); + } + + protected virtual Ambience Ambience { get { - IType type = member is IType ? (IType)member : member.DeclaringType; - if (type.SourceProject is DotNetProject) - return ((DotNetProject)type.SourceProject).Ambience; - return AmbienceService.DefaultAmbience; + return AmbienceService.GetAmbienceForFile (member.DeclaringType.GetDefinition ().Region.FileName); } } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTag.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTag.cs new file mode 100644 index 0000000000..0af7adbe1d --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTag.cs @@ -0,0 +1,43 @@ +// +// CommentTag.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; + +namespace MonoDevelop.Ide.Tasks +{ + public class CommentTag + { + public CommentTag (string tag, int priority) + { + Tag = tag; + Priority = priority; + } + + public string Tag { get; internal set; } + + public int Priority { get; internal set; } + } +} + diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksChangedEventHandler.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksChangedEventHandler.cs new file mode 100644 index 0000000000..f7f3552300 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksChangedEventHandler.cs @@ -0,0 +1,52 @@ +// CommentTasksChangedEventHandler.cs +// +// Author: +// David Makovský <yakeen@sannyas-on.net> +// +// Copyright (c) 2007 David Makovský +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// +using System; +using System.Collections.Generic; +using MonoDevelop.Projects; + +namespace MonoDevelop.Ide.Tasks +{ + public class CommentTasksChangedEventArgs : EventArgs + { + string filename; + IList<Tag> tagComments; + Project project; + + public CommentTasksChangedEventArgs (string filename, IList<Tag> tagComments, Project project) + { + this.filename = filename; + this.tagComments = tagComments; + this.project = project; + } + + public string FileName { get { return filename; } } + + public IList<Tag> TagComments { get { return tagComments; } } + + public Project Project { get { return project; } } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksView.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksView.cs index 178bcb1db0..f7dbf4b945 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksView.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/CommentTasksView.cs @@ -37,8 +37,6 @@ using MonoDevelop.Projects; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui; using MonoDevelop.Projects.Text; -using MonoDevelop.Projects.Dom.Parser; -using MonoDevelop.Projects.Dom; namespace MonoDevelop.Ide.Tasks { @@ -80,8 +78,8 @@ namespace MonoDevelop.Ide.Tasks ReloadPriorities (); - ProjectDomService.CommentTasksChanged += OnCommentTasksChanged; - ProjectDomService.SpecialCommentTagsChanged += OnCommentTagsChanged; + TaskService.CommentTasksChanged += OnCommentTasksChanged; + TaskService.SpecialCommentTagsChanged += OnCommentTagsChanged; IdeApp.Workspace.WorkspaceItemLoaded += OnWorkspaceItemLoaded; IdeApp.Workspace.WorkspaceItemUnloaded += OnWorkspaceItemUnloaded; @@ -198,11 +196,11 @@ namespace MonoDevelop.Ide.Tasks // Load all tags that are stored in pidb files foreach (Project p in sln.GetAllProjects ()) { - ProjectDom pContext = ProjectDomService.GetProjectDom (p); - if (pContext == null) - continue; +// ITypeResolveContext pContext = TypeSystemService. (p); +// if (pContext == null) +// continue; foreach (ProjectFile file in p.Files) { - IList<Tag> tags = pContext.GetSpecialComments (file.Name); + IList<Tag> tags = TaskService.GetSpecialComments (file.Name); if (tags != null && tags.Count > 0) UpdateCommentTags (sln, file.Name, tags); } @@ -254,7 +252,7 @@ namespace MonoDevelop.Ide.Tasks desc = tag.Key + ": " + desc; } - Task t = new Task (fileName, desc, tag.Region.Start.Column, tag.Region.Start.Line, + Task t = new Task (fileName, desc, tag.Region.BeginColumn, tag.Region.BeginLine, TaskSeverity.Information, priorities[tag.Key], wob); newTasks.Add (t); } @@ -290,7 +288,7 @@ namespace MonoDevelop.Ide.Tasks void ReloadPriorities () { priorities.Clear (); - foreach (CommentTag tag in ProjectDomService.SpecialCommentTags) + foreach (var tag in TaskService.SpecialCommentTags) priorities.Add (tag.Tag, (TaskPriority) tag.Priority); } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/Tag.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/Tag.cs new file mode 100644 index 0000000000..d386ad147d --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/Tag.cs @@ -0,0 +1,72 @@ +// +// TypeParameter.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +using System; +using ICSharpCode.NRefactory.TypeSystem; + +namespace MonoDevelop.Ide.Tasks +{ + [Serializable] + public class Tag + { + string key; + + public string Key { + get { + return key; + } + } + + public DomRegion Region { + get; + private set; + } + + public string Comment { + get; + private set; + } + + public string Text { + get; + set; + } + + public Tag (string key, DomRegion region) + { + this.key = key; + this.Region = region; + } + + public Tag (string key, string comment, DomRegion region) + { + this.key = key; + this.Region = region; + this.Comment = comment; + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/TaskService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/TaskService.cs index a3415ed784..5aa412fa2d 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/TaskService.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Tasks/TaskService.cs @@ -32,8 +32,6 @@ using System.Xml.Serialization; using MonoDevelop.Core; using MonoDevelop.Core.Serialization; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Ide.Gui; namespace MonoDevelop.Ide.Tasks @@ -185,6 +183,71 @@ namespace MonoDevelop.Ide.Tasks if (handler != null) handler (null, new TaskEventArgs (task)); } + + #region Special comment tags + public static event EventHandler SpecialCommentTagsChanged; + + const string defaultTags = "FIXME:2;TODO:1;HACK:1;UNDONE:0"; + static List<CommentTag> specialCommentTags; + + static List<CommentTag> CreateCommentTags (string tagListString) + { + var list = new List<CommentTag> (); + if (string.IsNullOrEmpty (tagListString)) + return list; + + string[] tags = tagListString.Split (';'); + for (int n=0; n<tags.Length; n++) { + string[] split = tags [n].Split (':'); + int priority; + if (split.Length == 2 && int.TryParse (split [1], out priority)) + list.Add (new CommentTag (split [0], priority)); + else + MonoDevelop.Core.LoggingService.LogWarning ("Invalid tag list in CommentTagSet: '{0}'", tagListString); + } + return list; + } + + static string ToString (List<CommentTag> list) + { + string res = ""; + for (int n=0; n<list.Count; n++) { + if (n > 0) + res += ";"; + res += list [n].Tag + ":" + list [n].Priority; + } + return res; + } + + public static List<CommentTag> SpecialCommentTags { + get { + if (specialCommentTags == null) { + string tags = PropertyService.Get ("Monodevelop.TaskListTokens", defaultTags); + specialCommentTags = CreateCommentTags (tags); + } + return specialCommentTags; + } + set { + if (!SpecialCommentTags.Equals (value)) { + specialCommentTags = value; + PropertyService.Set ("Monodevelop.TaskListTokens", ToString (specialCommentTags)); + if (SpecialCommentTagsChanged != null) + SpecialCommentTagsChanged (null, EventArgs.Empty); + } + } + } + + public static IList<Tag> GetSpecialComments (string name) + { + var result = new List<Tag> (); + // TODO: Type system conversion. + return result; + } + #endregion + + #region Comment tasks + public static event EventHandler<CommentTasksChangedEventArgs> CommentTasksChanged; + #endregion } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeDomFileDescriptionTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeDomFileDescriptionTemplate.cs index 729668d9bf..3823171a1b 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeDomFileDescriptionTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeDomFileDescriptionTemplate.cs @@ -34,7 +34,6 @@ using System.CodeDom; using System.CodeDom.Compiler; using MonoDevelop.Projects; -using MonoDevelop.Projects.CodeGeneration; using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Core; @@ -59,33 +58,34 @@ namespace MonoDevelop.Ide.Templates public override string CreateContent (Project project, Dictionary<string, string> tags, string language) { - if (language == null || language == "") - throw new InvalidOperationException ("Language not defined in CodeDom based template."); - - IDotNetLanguageBinding binding = GetLanguageBinding (language) as IDotNetLanguageBinding; - - CodeDomProvider provider = null; - if (binding != null) - provider = binding.GetCodeDomProvider (); - - if (provider == null) - throw new InvalidOperationException ("The language '" + language + "' does not have support for CodeDom."); - - XmlCodeDomReader xcd = new XmlCodeDomReader (); - CodeCompileUnit cu = xcd.ReadCompileUnit (domContent); - - foreach (CodeNamespace cns in cu.Namespaces) - cns.Name = StripImplicitNamespace (project, tags, cns.Name); - - CodeGeneratorOptions options = new CodeGeneratorOptions (); - options.IndentString = TextEditorProperties.IndentString; - options.BracingStyle = "C"; - - StringWriter sw = new StringWriter (); - provider.GenerateCodeFromCompileUnit (cu, sw, options); - sw.Close (); - - return StripHeaderAndBlankLines (sw.ToString (), provider); +// if (language == null || language == "") +// throw new InvalidOperationException ("Language not defined in CodeDom based template."); +// +// IDotNetLanguageBinding binding = GetLanguageBinding (language) as IDotNetLanguageBinding; +// +// CodeDomProvider provider = null; +// if (binding != null) +// provider = binding.GetCodeDomProvider (); +// +// if (provider == null) +// throw new InvalidOperationException ("The language '" + language + "' does not have support for CodeDom."); +// +// var xcd = new XmlCodeDomReader (); +// var cu = xcd.ReadCompileUnit (domContent); +// +// foreach (CodeNamespace cns in cu.Namespaces) +// cns.Name = StripImplicitNamespace (project, tags, cns.Name); +// +// CodeGeneratorOptions options = new CodeGeneratorOptions (); +// options.IndentString = TextEditorProperties.IndentString; +// options.BracingStyle = "C"; +// +// StringWriter sw = new StringWriter (); +// provider.GenerateCodeFromCompileUnit (cu, sw, options); +// sw.Close (); +// +// return StripHeaderAndBlankLines (sw.ToString (), provider); + return "Todo: CodeDomFileDescriptionTemplate"; } static string StripHeaderAndBlankLines (string text, CodeDomProvider provider) diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeTranslationFileDescriptionTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeTranslationFileDescriptionTemplate.cs index 1fcbdaae1d..f641faee66 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeTranslationFileDescriptionTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/CodeTranslationFileDescriptionTemplate.cs @@ -41,7 +41,6 @@ using System.IO; using MonoDevelop.Core; using MonoDevelop.Ide.Templates; using MonoDevelop.Projects; -using MonoDevelop.Projects.CodeGeneration; namespace MonoDevelop.Ide.Templates { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileDescriptionTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileDescriptionTemplate.cs index ecbe84dacd..9c7e7c8a51 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileDescriptionTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileDescriptionTemplate.cs @@ -39,7 +39,6 @@ using MonoDevelop.Core; using Mono.Addins; using MonoDevelop.Ide.Gui; using MonoDevelop.Projects; -using MonoDevelop.Projects.CodeGeneration; using MonoDevelop.Ide.Codons; namespace MonoDevelop.Ide.Templates diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileTemplate.cs index 15ee78b013..8b18b08dec 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/FileTemplate.cs @@ -487,7 +487,7 @@ namespace MonoDevelop.Ide.Templates { //Template can match all CodeDom .NET languages with a "*" if (list.Contains ("*")) { - foreach (ILanguageBinding lb in LanguageBindingService.LanguageBindings) { + foreach (var lb in LanguageBindingService.LanguageBindings) { IDotNetLanguageBinding dnlang = lb as IDotNetLanguageBinding; if (dnlang != null && dnlang.GetCodeDomProvider () != null) list.Add (dnlang.Language); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/ProjectTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/ProjectTemplate.cs index fcdb3d02c4..ced36b286c 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/ProjectTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/ProjectTemplate.cs @@ -45,7 +45,6 @@ using Mono.Addins; using MonoDevelop.Ide.Codons; using MonoDevelop.Projects; using MonoDevelop.Ide.Gui; -using MonoDevelop.Projects.CodeGeneration; namespace MonoDevelop.Ide.Templates { @@ -287,7 +286,7 @@ namespace MonoDevelop.Ide.Templates { //Template can match all CodeDom .NET languages with a "*" if (list.Contains ("*")) { - foreach (ILanguageBinding lb in LanguageBindingService.LanguageBindings) { + foreach (var lb in LanguageBindingService.LanguageBindings) { IDotNetLanguageBinding dnlang = lb as IDotNetLanguageBinding; if (dnlang != null && dnlang.GetCodeDomProvider () != null) list.Add (dnlang.Language); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs index 85f3757947..2679d8abf9 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Templates/SingleFileDescriptionTemplate.cs @@ -223,7 +223,7 @@ namespace MonoDevelop.Ide.Templates fileName = fileName + defaultExtension; } else if (!string.IsNullOrEmpty (language)) { - ILanguageBinding languageBinding = GetLanguageBinding (language); + var languageBinding = GetLanguageBinding (language); fileName = languageBinding.GetFileName (fileName); } } @@ -382,7 +382,7 @@ namespace MonoDevelop.Ide.Templates protected ILanguageBinding GetLanguageBinding (string language) { - ILanguageBinding binding = LanguageBindingService.GetBindingPerLanguageName (language); + var binding = LanguageBindingService.GetBindingPerLanguageName (language); if (binding == null) throw new InvalidOperationException ("Language '" + language + "' not found"); return binding; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj index 1afa21633e..d5bf307206 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.csproj @@ -94,10 +94,6 @@ <Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project> <Name>ICSharpCode.NRefactory</Name> </ProjectReference> - <ProjectReference Include="..\..\..\contrib\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj"> - <Project>{984CC812-9470-4A13-AFF9-CC44068D666C}</Project> - <Name>ICSharpCode.Decompiler</Name> - </ProjectReference> <ProjectReference Include="..\..\..\contrib\Mono.Cecil\Mono.Cecil.csproj"> <Project>{3EC06433-F168-4C5B-A885-99CE4AB617E1}</Project> <Name>Mono.Cecil</Name> @@ -740,9 +736,6 @@ <EmbeddedResource Include="MonoDevelop.Ide.Gui.Pads.ProjectPad\ProjectPadContextMenu.addin.xml"> <LogicalName>ProjectPadContextMenu.addin.xml</LogicalName> </EmbeddedResource> - <EmbeddedResource Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassPadContextMenu.addin.xml"> - <LogicalName>ClassPadContextMenu.addin.xml</LogicalName> - </EmbeddedResource> <EmbeddedResource Include="ExtensionModel\Commands.addin.xml"> <LogicalName>Commands.addin.xml</LogicalName> </EmbeddedResource> @@ -948,19 +941,6 @@ <Compile Include="MonoDevelop.Ide.Gui.Content\DocumentStateTracker.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Content\IPathedDocument.cs" /> <Compile Include="MonoDevelop.Ide.Codons\CategoryNode.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassData.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\CombineNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\EventNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\FieldNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\MemberNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\MemberNodeCommandHandler.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\MethodNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\NamespaceData.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\NamespaceNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ProjectNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\PropertyNodeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\SolutionNodeBuilder.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Components\ExtensibleTreeView.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Components\ITreeBuilder.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Components\ITreeBuilderContext.cs" /> @@ -979,9 +959,6 @@ <Compile Include="MonoDevelop.Ide.Gui.Components\TreeBuilder.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Components\TreeOptions.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Components\TransactedTreeBuilder.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassBrowserPad.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassBrowserPadWidget.cs" /> - <Compile Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ReferenceNodeBuilder.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Content\INavigable.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Content\IUrlHandler.cs" /> <Compile Include="MonoDevelop.Ide.Gui.Content\ISmartIndenter.cs" /> @@ -1469,6 +1446,23 @@ <Compile Include="MonoDevelop.TypeSystem\ProjectContentEventArgs.cs" /> <Compile Include="MonoDevelop.TypeSystem\TypeSystemProviderNode.cs" /> <Compile Include="MonoDevelop.TypeSystem\TypeSystemService.cs" /> + <Compile Include="MonoDevelop.TypeSystem\Ambience.cs" /> + <Compile Include="MonoDevelop.TypeSystem\AmbienceService.cs" /> + <Compile Include="MonoDevelop.TypeSystem\NetAmbience.cs" /> + <Compile Include="MonoDevelop.TypeSystem\OutputFlags.cs" /> + <Compile Include="MonoDevelop.TypeSystem\OutputSettings.cs" /> + <Compile Include="MonoDevelop.Ide.Tasks\CommentTag.cs" /> + <Compile Include="MonoDevelop.Ide.Tasks\CommentTasksChangedEventHandler.cs" /> + <Compile Include="MonoDevelop.Ide.Tasks\Tag.cs" /> + <Compile Include="MonoDevelop.TypeSystem\StockIcons.cs" /> + <Compile Include="MonoDevelop.Ide\CodeGenerator.cs" /> + <Compile Include="MonoDevelop.TypeSystem\FoldingRegion.cs" /> + <Compile Include="MonoDevelop.TypeSystem\ParsedDocument.cs" /> + <Compile Include="MonoDevelop.TypeSystem\Comment.cs" /> + <Compile Include="MonoDevelop.TypeSystem\Tag.cs" /> + <Compile Include="MonoDevelop.TypeSystem\PreProcessorDefine.cs" /> + <Compile Include="MonoDevelop.TypeSystem\ConditionalRegion.cs" /> + <Compile Include="MonoDevelop.TypeSystem\MarkupUtilities.cs" /> </ItemGroup> <ItemGroup> <None Include="ChangeLog" /> @@ -1494,6 +1488,23 @@ <None Include="MonoDevelop.Ide.dll.config"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassPadContextMenu.addin.xml" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassData.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\CombineNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\EventNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\FieldNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\MemberNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\MemberNodeCommandHandler.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\MethodNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\NamespaceData.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\NamespaceNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ProjectNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\PropertyNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\SolutionNodeBuilder.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassBrowserPad.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ClassBrowserPadWidget.cs" /> + <None Include="MonoDevelop.Ide.Gui.Pads.ClassPad\ReferenceNodeBuilder.cs" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <ProjectExtensions> diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerationService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerationService.cs index ec60bf47c5..054933a82e 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerationService.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerationService.cs @@ -30,11 +30,12 @@ using System.Linq; using System.Text; using Mono.TextEditor; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using System.CodeDom; using MonoDevelop.Projects; using System.CodeDom.Compiler; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.CSharp; +using MonoDevelop.TypeSystem; namespace MonoDevelop.Ide { @@ -43,14 +44,14 @@ namespace MonoDevelop.Ide public static IMember AddCodeDomMember (IType type, CodeTypeMember newMember) { bool isOpen; - var data = TextFileProvider.Instance.GetTextEditorData (type.CompilationUnit.FileName, out isOpen); - var parsedDocument = ProjectDomService.GetParsedDocument (type.SourceProjectDom, type.CompilationUnit.FileName); + var data = TextFileProvider.Instance.GetTextEditorData (type.GetDefinition ().Region.FileName, out isOpen); + var parsedDocument = TypeSystemService.ParseFile (type.GetDefinition ().ProjectContent, data.Document.FileName, data.Document.MimeType, data.Text); var insertionPoints = GetInsertionPoints (data, parsedDocument, type); var suitableInsertionPoint = GetSuitableInsertionPoint (insertionPoints, type, newMember); - var dotNetProject = type.SourceProject as DotNetProject; + var dotNetProject = type.GetSourceProject () as DotNetProject; if (dotNetProject == null) { LoggingService.LogError ("Only .NET projects are supported."); return null; @@ -59,7 +60,7 @@ namespace MonoDevelop.Ide var generator = dotNetProject.LanguageBinding.GetCodeDomProvider (); StringWriter sw = new StringWriter (); var options = new CodeGeneratorOptions (); - options.IndentString = data.GetLineIndent (type.Location.Line) + "\t"; + options.IndentString = data.GetLineIndent (type.GetDefinition ().Region.BeginLine) + "\t"; if (newMember is CodeMemberMethod) options.BracingStyle = "C"; generator.GenerateCodeFromMember (newMember, sw, options); @@ -67,21 +68,21 @@ namespace MonoDevelop.Ide suitableInsertionPoint.Insert (data, sw.ToString ()); if (!isOpen) { try { - File.WriteAllText (type.CompilationUnit.FileName, data.Text); + File.WriteAllText (type.GetDefinition ().Region.FileName, data.Text); } catch (Exception e) { - LoggingService.LogError (string.Format ("Failed to write file '{0}'.", type.CompilationUnit.FileName), e); - MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.CompilationUnit.FileName)); + LoggingService.LogError (string.Format ("Failed to write file '{0}'.", type.GetDefinition ().Region.FileName), e); + MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.GetDefinition ().Region.FileName)); } } - var newDocument = ProjectDomService.Parse (type.SourceProject as Project, type.CompilationUnit.FileName, data.Text); - return newDocument.CompilationUnit.GetMemberAt (suitableInsertionPoint.Location.Line, int.MaxValue); + var newDocument = TypeSystemService.ParseFile (type.GetProjectContent (), data.FileName, data.MimeType, data.Text); + return newDocument.GetMember (suitableInsertionPoint.Location.Line, int.MaxValue); } 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 data = TextFileProvider.Instance.GetTextEditorData (type.GetDefinition ().Region.FileName, out isOpen); + var parsedDocument = TypeSystemService.ParseFile (type.GetProjectContent (), data.FileName, data.MimeType, data.Text); var insertionPoints = GetInsertionPoints (data, parsedDocument, type); @@ -89,15 +90,15 @@ namespace MonoDevelop.Ide var generator = CreateCodeGenerator (data); - generator.IndentLevel = CalculateBodyIndentLevel (parsedDocument.CompilationUnit.GetTypeAt (type.Location)); + generator.IndentLevel = CalculateBodyIndentLevel (parsedDocument.GetTypeDefinition (type.GetLocation ())); var generatedCode = generator.CreateMemberImplementation (type, newMember, implementExplicit); suitableInsertionPoint.Insert (data, generatedCode.Code); if (!isOpen) { try { - File.WriteAllText (type.CompilationUnit.FileName, data.Text); + File.WriteAllText (type.GetDefinition ().Region.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)); + LoggingService.LogError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.GetDefinition ().Region.FileName), e); + MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.GetDefinition ().Region.FileName)); } } } @@ -105,18 +106,19 @@ namespace MonoDevelop.Ide public static int CalculateBodyIndentLevel (IType declaringType) { int indentLevel = 0; - IType t = declaringType; + // TODO: Type system conversion. + /* IType t = declaringType; do { indentLevel++; t = t.DeclaringType; } while (t != null); - DomLocation lastLoc = DomLocation.Empty; + AstLocation lastLoc = AstLocation.Empty; foreach (IUsing us in declaringType.CompilationUnit.Usings.Where (u => u.IsFromNamespace && u.ValidRegion.Contains (declaringType.Location))) { if (lastLoc == us.Region.Start) continue; lastLoc = us.Region.Start; indentLevel++; - } + }*/ return indentLevel; } @@ -126,8 +128,8 @@ namespace MonoDevelop.Ide 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 data = TextFileProvider.Instance.GetTextEditorData (type.GetDefinition ().Region.FileName, out isOpen); + var parsedDocument = TypeSystemService.ParseFile (type.GetProjectContent (), data); var insertionPoints = GetInsertionPoints (data, parsedDocument, type); @@ -135,7 +137,7 @@ namespace MonoDevelop.Ide var suitableInsertionPoint = GetSuitableInsertionPoint (insertionPoints, type, firstNewMember); var generator = CreateCodeGenerator (data); - generator.IndentLevel = CalculateBodyIndentLevel (parsedDocument.CompilationUnit.GetTypeAt (type.Location)); + generator.IndentLevel = CalculateBodyIndentLevel (parsedDocument.GetTypeDefinition (type.GetLocation ())); StringBuilder sb = new StringBuilder (); foreach (IMember newMember in newMembers) { if (sb.Length > 0) { @@ -147,23 +149,22 @@ namespace MonoDevelop.Ide suitableInsertionPoint.Insert (data, string.IsNullOrEmpty (regionName) ? sb.ToString () : generator.WrapInRegions (regionName, sb.ToString ())); if (!isOpen) { try { - File.WriteAllText (type.CompilationUnit.FileName, data.Text); + File.WriteAllText (type.GetDefinition ().Region.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)); + LoggingService.LogError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.GetDefinition ().Region.FileName), e); + MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.GetDefinition ().Region.FileName)); } } } - static MonoDevelop.Projects.CodeGeneration.CodeGenerator CreateCodeGenerator (TextEditorData data) + static CodeGenerator CreateCodeGenerator (TextEditorData data) { - return MonoDevelop.Projects.CodeGeneration.CodeGenerator.CreateGenerator (data.Document.MimeType, - data.Options.TabsToSpaces, data.Options.TabSize, data.EolMarker); + return CodeGenerator.CreateGenerator (data); } protected static IType GetMainPart (IType t) { - return t.HasParts ? t.Parts.First () : t; + return t.GetDefinition ().GetParts ().First (); } #region Insertion Points @@ -171,10 +172,10 @@ namespace MonoDevelop.Ide { if (document == null) throw new ArgumentNullException ("document"); - return GetInsertionPoints (document.Editor, document.ParsedDocument, type); + return GetInsertionPoints (document.Editor, document.ParsedFile, type); } - public static List<InsertionPoint> GetInsertionPoints (TextEditorData data, ParsedDocument parsedDocument, IType type) + public static List<InsertionPoint> GetInsertionPoints (TextEditorData data, IParsedFile parsedDocument, IType type) { if (data == null) throw new ArgumentNullException ("data"); @@ -184,10 +185,10 @@ namespace MonoDevelop.Ide throw new ArgumentNullException ("type"); // update type from parsed document, since this is always newer. - type = parsedDocument.CompilationUnit.GetTypeAt (type.Location) ?? type; + type = parsedDocument.GetTypeDefinition (type.GetLocation ()) ?? type; - List<InsertionPoint> result = new List<InsertionPoint> (); - int offset = data.LocationToOffset (type.BodyRegion.Start.Line, type.BodyRegion.Start.Column); + List<InsertionPoint > result = new List<InsertionPoint> (); + int offset = data.LocationToOffset (type.GetDefinition ().Region.BeginLine, type.GetDefinition ().Region.BeginColumn); if (offset < 0) return result; while (offset < data.Length && data.GetCharAt (offset) != '{') { @@ -196,43 +197,44 @@ namespace MonoDevelop.Ide var realStartLocation = data.OffsetToLocation (offset); result.Add (GetInsertionPosition (data.Document, realStartLocation.Line, realStartLocation.Column)); - result[0].LineBefore = NewLineInsertion.None; - foreach (IMember member in type.Members) { - DomLocation domLocation = member.BodyRegion.End; - if (domLocation.Line <= 0) { - LineSegment lineSegment = data.GetLine (member.Location.Line); - if (lineSegment == null) - continue; - domLocation = new DomLocation (member.Location.Line, lineSegment.EditableLength + 1); - } - result.Add (GetInsertionPosition (data.Document, domLocation.Line, domLocation.Column)); - } - result[result.Count - 1].LineAfter = NewLineInsertion.None; - CheckStartPoint (data.Document, result[0], result.Count == 1); - if (result.Count > 1) { - result.RemoveAt (result.Count - 1); - NewLineInsertion insertLine; - var lineBefore = data.GetLine (type.BodyRegion.End.Line - 1); - if (lineBefore != null && lineBefore.EditableLength == lineBefore.GetIndentation (data.Document).Length) { - insertLine = NewLineInsertion.None; - } else { - insertLine = NewLineInsertion.Eol; - } - // search for line start - var line = data.GetLine (type.BodyRegion.End.Line); - int col = type.BodyRegion.End.Column - 1; - while (col > 1 && char.IsWhiteSpace (data.GetCharAt (line.Offset + col - 2))) - col--; - result.Add (new InsertionPoint (new DocumentLocation (type.BodyRegion.End.Line, col), insertLine, NewLineInsertion.Eol)); - CheckEndPoint (data.Document, result[result.Count - 1], result.Count == 1); - } - - foreach (var region in parsedDocument.UserRegions.Where (r => type.BodyRegion.Contains (r.Region))) { - result.Add (new InsertionPoint (new DocumentLocation (region.Region.Start.Line + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol)); - result.Add (new InsertionPoint (new DocumentLocation (region.Region.End.Line, 1), NewLineInsertion.Eol, NewLineInsertion.Eol)); - result.Add (new InsertionPoint (new DocumentLocation (region.Region.End.Line + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol)); - } - result.Sort ((left, right) => left.Location.CompareTo (right.Location)); + result [0].LineBefore = NewLineInsertion.None; + // TODO: Type system conversion. +// foreach (IMember member in type.Members) { +// AstLocation domLocation = member.BodyRegion.End; +// if (domLocation.Line <= 0) { +// LineSegment lineSegment = data.GetLine (member.Location.Line); +// if (lineSegment == null) +// continue; +// domLocation = new AstLocation (member.Location.Line, lineSegment.EditableLength + 1); +// } +// result.Add (GetInsertionPosition (data.Document, domLocation.Line, domLocation.Column)); +// } +// result[result.Count - 1].LineAfter = NewLineInsertion.None; +// CheckStartPoint (data.Document, result[0], result.Count == 1); +// if (result.Count > 1) { +// result.RemoveAt (result.Count - 1); +// NewLineInsertion insertLine; +// var lineBefore = data.GetLine (type.BodyRegion.EndLine - 1); +// if (lineBefore != null && lineBefore.EditableLength == lineBefore.GetIndentation (data.Document).Length) { +// insertLine = NewLineInsertion.None; +// } else { +// insertLine = NewLineInsertion.Eol; +// } +// // search for line start +// var line = data.GetLine (type.BodyRegion.EndLine); +// int col = type.BodyRegion.EndColumn - 1; +// while (col > 1 && char.IsWhiteSpace (data.GetCharAt (line.Offset + col - 2))) +// col--; +// result.Add (new InsertionPoint (new DocumentLocation (type.BodyRegion.EndLine, col), insertLine, NewLineInsertion.Eol)); +// CheckEndPoint (data.Document, result[result.Count - 1], result.Count == 1); +// } +// +// foreach (var region in parsedDocument.UserRegions.Where (r => type.BodyRegion.Contains (r.Region))) { +// result.Add (new InsertionPoint (new DocumentLocation (region.Region.BeginLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol)); +// result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine, 1), NewLineInsertion.Eol, NewLineInsertion.Eol)); +// result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol)); +// } +// result.Sort ((left, right) => left.Location.CompareTo (right.Location)); return result; } @@ -298,17 +300,20 @@ namespace MonoDevelop.Ide static InsertionPoint GetSuitableInsertionPoint (IEnumerable<InsertionPoint> points, IType cls, IMember member) { var mainPart = GetMainPart (cls); - switch (member.MemberType) { - case MemberType.Field: + switch (member.EntityType) { + case EntityType.Field: return GetNewFieldPosition (points, mainPart); - case MemberType.Method: + case EntityType.Method: + case EntityType.Constructor: + case EntityType.Destructor: + case EntityType.Operator: return GetNewMethodPosition (points, mainPart); - case MemberType.Event: + case EntityType.Event: return GetNewEventPosition (points, mainPart); - case MemberType.Property: + case EntityType.Property: return GetNewPropertyPosition (points, mainPart); } - throw new InvalidOperationException ("Invalid member type: " + member.MemberType); + throw new InvalidOperationException ("Invalid member type: " + member.EntityType); } static InsertionPoint GetSuitableInsertionPoint (IEnumerable<InsertionPoint> points, IType cls, CodeTypeMember mem) @@ -327,43 +332,47 @@ namespace MonoDevelop.Ide static InsertionPoint GetNewFieldPosition (IEnumerable<InsertionPoint> points, IType cls) { - if (cls.FieldCount == 0) - return points.FirstOrDefault (); - var lastField = cls.Fields.Last (); - return points.FirstOrDefault (p => p.Location.Convert () > lastField.Location); + throw new NotImplementedException (); +// if (cls.GetDefinition ().Fields.Count == 0) +// return points.FirstOrDefault (); +// var lastField = cls.Fields.Last (); +// return points.FirstOrDefault (p => p.Location.Convert () > lastField.Location); } static InsertionPoint GetNewMethodPosition (IEnumerable<InsertionPoint> points, IType cls) { - if (cls.MethodCount + cls.ConstructorCount == 0) - return GetNewPropertyPosition (points, cls); - var lastMember = cls.Members.Last (); - return points.FirstOrDefault (p => p.Location.Convert () > lastMember.Location); + throw new NotImplementedException (); +// if (cls.MethodCount + cls.ConstructorCount == 0) +// return GetNewPropertyPosition (points, cls); +// var lastMember = cls.Members.Last (); +// return points.FirstOrDefault (p => p.Location.Convert () > lastMember.Location); } static InsertionPoint GetNewPropertyPosition (IEnumerable<InsertionPoint> points, IType cls) { - if (cls.PropertyCount == 0) + throw new NotImplementedException (); +// if (cls.PropertyCount == 0) +// IProperty lastProperty = cls.Properties.Last (); return GetNewFieldPosition (points, cls); - IProperty lastProperty = cls.Properties.Last (); - return points.FirstOrDefault (p => p.Location.Convert () > lastProperty.Location); +// return points.FirstOrDefault (p => p.Location.Convert () > lastProperty.Location); } static InsertionPoint GetNewEventPosition (IEnumerable<InsertionPoint> points, IType cls) { - if (cls.EventCount == 0) - return GetNewMethodPosition (points, cls); - IEvent lastEvent = cls.Events.Last (); - return points.FirstOrDefault (p => p.Location.Convert () > lastEvent.Location); + throw new NotImplementedException (); +// if (cls.EventCount == 0) +// return GetNewMethodPosition (points, cls); +// IEvent lastEvent = cls.Events.Last (); +// return points.FirstOrDefault (p => p.Location.Convert () > lastEvent.Location); } #endregion } public static class HelperMethods { - public static DomLocation Convert (this DocumentLocation location) + public static AstLocation Convert (this DocumentLocation location) { - return new DomLocation (location.Line, location.Column); + return new AstLocation (location.Line, location.Column); } } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerator.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerator.cs new file mode 100644 index 0000000000..15d29a85ad --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/CodeGenerator.cs @@ -0,0 +1,338 @@ +// +// CodeGenerator.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2010 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using System.Text; +using System.Collections.Generic; +using System.Linq; +using Mono.Addins; +using ICSharpCode.NRefactory.TypeSystem; +using Mono.TextEditor; +using MonoDevelop.Core.AddIns; +using MonoDevelop.TypeSystem; +using ICSharpCode.NRefactory.CSharp; + +namespace MonoDevelop.Ide +{ + public abstract class CodeGenerator + { + static Dictionary<string, MimeTypeExtensionNode> generators = new Dictionary<string, MimeTypeExtensionNode> (); + + public bool UseSpaceIndent { + get; + set; + } + + public string EolMarker { + get; + set; + } + + public int TabSize { + get; + set; + } + + public static CodeGenerator CreateGenerator (TextEditorData data) + { + MimeTypeExtensionNode node; + if (!generators.TryGetValue (data.MimeType, out node)) + return null; + + var result = (CodeGenerator)node.CreateInstance (); + result.UseSpaceIndent = data.Options.TabsToSpaces; + result.EolMarker = data.EolMarker; + result.TabSize = data.Options.TabSize; + return result; + } + + protected void AppendLine (StringBuilder sb) + { + sb.Append (EolMarker); + } + + protected string GetIndent (int indentLevel) + { + if (UseSpaceIndent) + return new string (' ', indentLevel * TabSize); + + return new string ('\t', indentLevel); + } + + public static bool HasGenerator (string mimeType) + { + return generators.ContainsKey (mimeType); + } + + static CodeGenerator () + { + AddinManager.AddExtensionNodeHandler ("/MonoDevelop/ProjectModel/CodeGenerators", delegate (object sender, ExtensionNodeEventArgs args) { + var node = (MimeTypeExtensionNode)args.ExtensionNode; + switch (args.Change) { + case ExtensionChange.Add: + AddGenerator (node); + break; + case ExtensionChange.Remove: + RemoveGenerator (node); + break; + } + }); + } + + public int IndentLevel { + get; + set; + } + + public CodeGenerator () + { + IndentLevel = -1; + } + + public static void AddGenerator (MimeTypeExtensionNode node) + { + generators [node.MimeType] = node; + } + + public static void RemoveGenerator (MimeTypeExtensionNode node) + { + generators.Remove (node.MimeType); + } + + static int CalculateBodyIndentLevel (IType declaringType) + { + int indentLevel = 0; + // TODO: Type system conversion. +/* IType t = declaringType; + do { + indentLevel++; + t = t.DeclaringType; + } while (t != null); + DomLocation lastLoc = DomLocation.Empty; + foreach (IUsing us in declaringType.CompilationUnit.Usings.Where (u => u.IsFromNamespace && u.ValidRegion.Contains (declaringType.Location))) { + if (lastLoc == us.Region.Start) + continue; + lastLoc = us.Region.Start; + indentLevel++; + }*/ + return indentLevel; + } + + protected void SetIndentTo (IType implementingType) + { + if (IndentLevel < 0) + IndentLevel = CalculateBodyIndentLevel (implementingType); + } + + public string CreateInterfaceImplementation (IType implementingType, IType interfaceType, bool explicitly, bool wrapRegions = true) + { + SetIndentTo (implementingType); + StringBuilder result = new StringBuilder (); + List<IMember > implementedMembers = new List<IMember> (); + foreach (var baseInterface in interfaceType.GetAllBaseTypes (interfaceType.GetDefinition ().ProjectContent)) { + if (baseInterface.GetDefinition ().ClassType != ClassType.Interface) + continue; + if (result.Length > 0) { + AppendLine (result); + AppendLine (result); + } + string implementation = InternalCreateInterfaceImplementation (implementingType, baseInterface, explicitly, implementedMembers); + if (wrapRegions) { + result.Append (WrapInRegions (baseInterface.Name + " implementation", implementation)); + } else { + result.Append (implementation); + } + } + return result.ToString (); + } + + protected string InternalCreateInterfaceImplementation (IType implementingType, IType interfaceType, bool explicitly, List<IMember> implementedMembers) + { + StringBuilder result = new StringBuilder (); + + var dom = implementingType.GetProjectContent (); + + List<KeyValuePair<IMember, bool >> toImplement = new List<KeyValuePair<IMember, bool>> (); + bool alreadyImplemented; + + // Stub out non-implemented events defined by @iface + foreach (var ev in interfaceType.GetEvents (dom)) { + if (ev.IsSynthetic) + continue; + bool needsExplicitly = explicitly; + + alreadyImplemented = implementingType.GetAllBaseTypes (dom).Any (x => x.GetDefinition ().ClassType != ClassType.Interface && x.GetEvents (dom).Any (y => y.Name == ev.Name)); + + if (!alreadyImplemented) + toImplement.Add (new KeyValuePair<IMember, bool> (ev, needsExplicitly)); + } + + // Stub out non-implemented methods defined by @iface + foreach (var method in interfaceType.GetMethods (dom)) { + if (method.IsSynthetic) + continue; + bool needsExplicitly = explicitly; + alreadyImplemented = false; + foreach (var t in implementingType.GetAllBaseTypes (dom)) { + if (t.GetDefinition ().ClassType == ClassType.Interface) + continue; + foreach (var cmet in t.GetMethods (dom)) { + if (cmet.Name == method.Name && Equals (cmet.Parameters, method.Parameters)) { + if (!needsExplicitly && !cmet.ReturnType.Equals (method.ReturnType)) + needsExplicitly = true; +// TODO: Type system conversion. +// else +// alreadyImplemented |= !needsExplicitly || (interfaceType.FullName == GetExplicitPrefix (cmet.InterfaceImplementations.FirstOrDefault ())); + } + } + } + if (!alreadyImplemented) + toImplement.Add (new KeyValuePair<IMember, bool> (method, needsExplicitly)); + } + + // Stub out non-implemented properties defined by @iface + foreach (var prop in interfaceType.GetProperties (dom)) { + if (prop.IsSynthetic) + continue; + bool needsExplicitly = explicitly; + alreadyImplemented = false; + foreach (IType t in implementingType.GetBaseTypes (dom)) { + if (t.GetDefinition ().ClassType == ClassType.Interface) + continue; + foreach (IProperty cprop in t.GetProperties (dom)) { + if (cprop.Name == prop.Name) { + if (!needsExplicitly && !cprop.ReturnType.Equals (prop.ReturnType)) + needsExplicitly = true; +// TODO: Type system conversion. +// else +// alreadyImplemented |= !needsExplicitly || (interfaceType.FullName == GetExplicitPrefix (cprop.ExplicitInterfaces)); + } + } + } + if (!alreadyImplemented) + toImplement.Add (new KeyValuePair<IMember, bool> (prop, needsExplicitly)); + } + bool first = true; + foreach (var pair in toImplement) { + if (!first) { + AppendLine (result); + AppendLine (result); + } else { + first = false; + } + bool isExplicit = pair.Value; + foreach (var member in implementedMembers.Where (m => m.Name == pair.Key.Name && m.EntityType == pair.Key.EntityType)) { + if (member is IMethod && pair.Key is IMethod) { + var method = (IMethod)member; + var othermethod = (IMethod)pair.Key; + isExplicit = member.ReturnType.Equals (othermethod.ReturnType); + if (method.Parameters.Count == othermethod.Parameters.Count && othermethod.Parameters.Count > 0) { + for (int i = 0; i < method.Parameters.Count; i++) { + if (!method.Parameters [i].Type.Equals (othermethod.Parameters [i].Type)) { + isExplicit = true; + break; + } + } + } + } else { + isExplicit = true; + } + } + + result.Append (CreateMemberImplementation (implementingType, pair.Key, isExplicit).Code); + implementedMembers.Add (pair.Key); + } + + return result.ToString (); + } + + static string GetExplicitPrefix (IEnumerable<ITypeReference> explicitInterfaces) + { + if (explicitInterfaces != null) { + foreach (var retType in explicitInterfaces) { + // TODO: Type system conversion. + return retType.ToString (); + } + } + return null; + } + + public abstract string WrapInRegions (string regionName, string text) +; + public abstract CodeGeneratorMemberResult CreateMemberImplementation (IType implementingType, IMember member, bool explicitDeclaration) +; + public abstract string CreateFieldEncapsulation (IType implementingType, IField field, string propertyName, Modifiers modifiers, bool readOnly); + } + + public class CodeGeneratorMemberResult + { + public CodeGeneratorMemberResult (string code) : this (code, null) + { + } + + public CodeGeneratorMemberResult (string code, int bodyStartOffset, int bodyEndOffset) + { + this.Code = code; + this.BodyRegions = new CodeGeneratorBodyRegion[] { + new CodeGeneratorBodyRegion (bodyStartOffset, bodyEndOffset) + }; + } + + public CodeGeneratorMemberResult (string code, IList<CodeGeneratorBodyRegion> bodyRegions) + { + this.Code = code; + this.BodyRegions = bodyRegions ?? new CodeGeneratorBodyRegion[0]; + } + + public string Code { get; private set; } + + public IList<CodeGeneratorBodyRegion> BodyRegions { get; private set; } + } + + public class CodeGeneratorBodyRegion + { + public CodeGeneratorBodyRegion (int startOffset, int endOffset) + { + this.StartOffset = startOffset; + this.EndOffset = endOffset; + } + + public int StartOffset { get; private set; } + + public int EndOffset { get; private set; } + + public int Length { + get { + return EndOffset - StartOffset; + } + } + + public bool IsValid { + get { + return StartOffset >= 0 && Length >= 0; + } + } + } +}
\ No newline at end of file diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/HelpOperations.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/HelpOperations.cs index e2908e0852..a7a4ab20be 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/HelpOperations.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/HelpOperations.cs @@ -33,9 +33,8 @@ using Monodoc; using MonoDevelop.Core.Execution; using System.IO; using MonoDevelop.Core; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Projects; +using ICSharpCode.NRefactory.CSharp.Resolver; namespace MonoDevelop.Ide { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs index b5aeb70ffa..d31cd15d9d 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs @@ -197,8 +197,8 @@ namespace MonoDevelop.Ide }; // Perser service initialization - MonoDevelop.Projects.Dom.Parser.ProjectDomService.TrackFileChanges = true; - MonoDevelop.Projects.Dom.Parser.ProjectDomService.ParseProgressMonitorFactory = new ParseProgressMonitorFactory (); +// TypeSystemService.TrackFileChanges = true; +// TypeSystemService.ParseProgressMonitorFactory = new ParseProgressMonitorFactory (); // Startup commands @@ -445,7 +445,7 @@ namespace MonoDevelop.Ide IdeApp.Workbench.CurrentLayout = "Default"; IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ProjectPad.ProjectSolutionPad> ().Visible = false; IdeApp.Workbench.GetPad<FileScout> ().Visible = false; - IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ClassBrowser.ClassBrowserPad> ().Visible = false; +// IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ClassBrowser.ClassBrowserPad> ().Visible = false; foreach (Pad p in IdeApp.Workbench.Pads) { if (p.Visible) p.AutoHide = true; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs index 35b6a45cf1..91c2b33cce 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs @@ -35,8 +35,6 @@ using System.IO; using MonoDevelop.Projects; using MonoDevelop.Projects.Text; -using MonoDevelop.Projects.Dom; -using MonoDevelop.Projects.Dom.Parser; using MonoDevelop.Components; using MonoDevelop.Core; using MonoDevelop.Core.Execution; @@ -50,6 +48,7 @@ using MonoDevelop.Core.Assemblies; using MonoDevelop.Core.Instrumentation; using Mono.TextEditor; using System.Diagnostics; +using ICSharpCode.NRefactory.TypeSystem; namespace MonoDevelop.Ide { @@ -213,84 +212,17 @@ namespace MonoDevelop.Ide return (GetDeclaredFile(item) != null); }*/ - public bool CanJumpToDeclaration (MonoDevelop.Projects.Dom.INode visitable) + public bool CanJumpToDeclaration (IEntity visitable) { - if (visitable is MonoDevelop.Projects.Dom.IType) - return ((MonoDevelop.Projects.Dom.IType)visitable).CompilationUnit != null; - if (visitable is LocalVariable) - return true; - if (visitable is IParameter) - return true; - IMember member = visitable as MonoDevelop.Projects.Dom.IMember; - if (member == null || member.DeclaringType == null) - return false ; - return member.DeclaringType.CompilationUnit != null; + return visitable != null && !visitable.Region.IsEmpty; } - public void JumpToDeclaration (MonoDevelop.Projects.Dom.INode visitable) + public void JumpToDeclaration (IEntity visitable) { - if (visitable is LocalVariable) { - LocalVariable localVar = (LocalVariable)visitable; - IdeApp.Workbench.OpenDocument (localVar.FileName, - localVar.Region.Start.Line, - localVar.Region.Start.Column); - return; - } - - if (visitable is IParameter) { - IParameter para = (IParameter)visitable; - IdeApp.Workbench.OpenDocument (para.DeclaringMember.DeclaringType.CompilationUnit.FileName, - para.Location.Line, - para.Location.Column); - return; - } - - IMember member = visitable as MonoDevelop.Projects.Dom.IMember; - if (member == null) - return; - string fileName; - if (member is MonoDevelop.Projects.Dom.IType) { - try { - fileName = ((MonoDevelop.Projects.Dom.IType)member).CompilationUnit.FileName; - } catch (Exception e) { - LoggingService.LogError ("Can't get file name for type:" + member + ". Try to restart monodevelop.", e); - fileName = null; - } - } else { - if (member.DeclaringType == null) - return; - IType declaringType = SearchContainingPart (member); - fileName = declaringType.CompilationUnit.FileName; - } - var doc = IdeApp.Workbench.OpenDocument (fileName, member.Location.Line, member.Location.Column); - if (doc != null) { - doc.RunWhenLoaded (delegate { - MonoDevelop.Ide.Gui.Content.IUrlHandler handler = doc.ActiveView as MonoDevelop.Ide.Gui.Content.IUrlHandler; - if (handler != null) - handler.Open (member.HelpUrl); - }); - } + IdeApp.Workbench.OpenDocument (visitable.Region.FileName, + visitable.Region.BeginLine, + visitable.Region.BeginColumn); } - - static IType SearchContainingPart (IMember member) - { - IType declaringType = member.DeclaringType; - if (member is ExtensionMethod) - declaringType = ((ExtensionMethod)member).OriginalMethod.DeclaringType; - - if (declaringType is InstantiatedType) - declaringType = ((InstantiatedType)declaringType).UninstantiatedType; - if (declaringType.HasParts) { - foreach (IType part in declaringType.Parts) { - IMember searchedMember = part.SearchMember (member.Name, true).FirstOrDefault (m => m.Location == member.Location); - if (searchedMember != null) - return part; - } - } - - return declaringType; - } - public void RenameItem (IWorkspaceFileObject item, string newName) { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/RootWorkspace.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/RootWorkspace.cs index 758e2272ba..90f4e23e5c 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/RootWorkspace.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/RootWorkspace.cs @@ -36,7 +36,6 @@ using MonoDevelop.Projects; using MonoDevelop.Core; using MonoDevelop.Core.Assemblies; using MonoDevelop.Core.Serialization; -using MonoDevelop.Projects.CodeGeneration; using MonoDevelop.Ide.Gui.Dialogs; using MonoDevelop.Ide.Gui.Content; using System.Runtime.CompilerServices; @@ -160,13 +159,6 @@ namespace MonoDevelop.Ide get { return Items.Count > 0; } } - public CodeRefactorer GetCodeRefactorer (Solution solution) - { - CodeRefactorer refactorer = new CodeRefactorer (solution); - refactorer.TextFileProvider = TextFileProvider.Instance; - return refactorer; - } - IDictionary IExtendedDataItem.ExtendedProperties { get { throw new NotSupportedException ("Root namespace can't have extended properties."); @@ -1007,7 +999,6 @@ namespace MonoDevelop.Ide { try { // Mono.Profiler.RuntimeControls.EnableProfiler (); - MonoDevelop.Projects.Dom.Parser.ProjectDomService.Load (item); MonoDevelop.TypeSystem.TypeSystemService.Load (item); // Mono.Profiler.RuntimeControls.DisableProfiler (); // Console.WriteLine ("PARSE LOAD: " + (DateTime.Now - t).TotalMilliseconds); @@ -1066,7 +1057,6 @@ namespace MonoDevelop.Ide if (WorkspaceItemClosed != null) WorkspaceItemClosed (this, args); - MonoDevelop.Projects.Dom.Parser.ProjectDomService.Unload (item); MonoDevelop.TypeSystem.TypeSystemService.Unload (item); // ParserDatabase.Unload (item); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Services.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Services.cs index 0d627cdb14..2abb36b48c 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Services.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Services.cs @@ -31,7 +31,6 @@ using MonoDevelop.Core.Execution; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Tasks; using MonoDevelop.Projects; -using MonoDevelop.Projects.Dom; using MonoDevelop.Core.Instrumentation; namespace MonoDevelop.Ide diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Ambience.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Ambience.cs new file mode 100644 index 0000000000..a76bcb4767 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Ambience.cs @@ -0,0 +1,169 @@ +// +// Ambience.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Text; +using System.Collections.Generic; +using MonoDevelop.Core; +using ICSharpCode.NRefactory.TypeSystem; +using Mono.Cecil; +using System.Linq; + +namespace MonoDevelop.TypeSystem +{ + public abstract class Ambience + { + public string Name { + get; + private set; + } + + + public Ambience (string name) + { + this.Name = name; + } + + #region To implement + public abstract string GetIntrinsicTypeName (string reflectionName); + + public abstract string SingleLineComment (string text); + public abstract string GetString (string nameSpace, OutputSettings settings); + + protected abstract string GetTypeReferenceString (ITypeReference reference, OutputSettings settings); + protected abstract string GetTypeString (ITypeDefinition type, OutputSettings settings); + protected abstract string GetMethodString (IMethod method, OutputSettings settings); + protected abstract string GetConstructorString (IMethod constructor, OutputSettings settings); + protected abstract string GetDestructorString (IMethod destructor, OutputSettings settings); + protected abstract string GetOperatorString (IMethod op, OutputSettings settings); + + protected abstract string GetFieldString (IField field, OutputSettings settings); + protected abstract string GetEventString (IEvent evt, OutputSettings settings); + protected abstract string GetPropertyString (IProperty property, OutputSettings settings); + protected abstract string GetIndexerString (IProperty property, OutputSettings settings); + + protected abstract string GetParameterString (IParameterizedMember member, IParameter parameter, OutputSettings settings); + #endregion + + public static string Format (string str) + { + if (String.IsNullOrEmpty (str)) + return string.Empty; + + StringBuilder sb = new StringBuilder (str.Length); + MarkupUtilities.AppendEscapedString (sb, str); + return sb.ToString (); + } + + protected static OutputFlags GetFlags (object settings) + { + if (settings is OutputFlags) + return (OutputFlags)settings; + return ((OutputSettings)settings).OutputFlags; + } + + protected static OutputSettings GetSettings (object settings) + { + if (settings is OutputFlags) + return new OutputSettings ((OutputFlags)settings); + return (OutputSettings)settings; + } + + public string GetString (string nameSpace, OutputFlags flags) + { + return GetString (nameSpace, new OutputSettings (flags)); + } + + public string GetString (IEntity entity, OutputSettings settings) + { + if (entity == null) { + string[] trace = Environment.StackTrace.Split (new [] { Environment.NewLine }, StringSplitOptions.None); + return "null entity: " + (trace != null && trace.Length > 2 ? trace [2] : "unknown location"); + } + string result = null; + switch (entity.EntityType) { + case EntityType.Constructor: + result = GetConstructorString ((IMethod)entity, settings); + break; + case EntityType.Destructor: + result = GetDestructorString ((IMethod)entity, settings); + break; + case EntityType.Event: + result = GetEventString ((IEvent)entity, settings); + break; + case EntityType.Field: + result = GetFieldString ((IField)entity, settings); + break; + case EntityType.Indexer: + result = GetPropertyString ((IProperty)entity, settings); + break; + case EntityType.Method: + result = GetMethodString ((IMethod)entity, settings); + break; + case EntityType.Operator: + result = GetMethodString ((IMethod)entity, settings); + break; + case EntityType.Property: + result = GetPropertyString ((IProperty)entity, settings); + break; + case EntityType.TypeDefinition: + result = GetTypeString ((ITypeDefinition)entity, settings); + break; + default: + throw new ArgumentOutOfRangeException ("EntityType", "Unknown entity type:" + entity.EntityType); + } + if (settings is OutputSettings) + ((OutputSettings)settings).PostProcess (entity, ref result); + return result; + } + + public string GetString (ITypeResolveContext ctx, IEntity entity, OutputFlags flags) + { + return GetString (entity, new OutputSettings (flags) { Context = ctx }); + } + + public string GetString (IEntity entity, OutputFlags flags) + { + var ctx = entity.ProjectContent; + return GetString (entity, new OutputSettings (flags) { Context = ctx }); + } + + public string GetString (IType type, OutputSettings settings) + { + var result = GetString ((IEntity)type.GetDefinition (), settings); + if (settings is OutputSettings) + ((OutputSettings)settings).PostProcess (type, ref result); + return result; + } + + public string GetString (ITypeResolveContext ctx, IType type, OutputFlags flags) + { + return GetString (type, new OutputSettings (flags) { Context = ctx }); + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/AmbienceService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/AmbienceService.cs new file mode 100644 index 0000000000..21dff0c62a --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/AmbienceService.cs @@ -0,0 +1,482 @@ +// +// AmbienceService.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Collections.Generic; + +using Mono.Addins; +using System.Xml; +using System.Text; +using ICSharpCode.NRefactory.TypeSystem; +using MonoDevelop.Ide; + +namespace MonoDevelop.TypeSystem +{ + public static class AmbienceService + { + static Dictionary <string, Ambience> ambiences = new Dictionary <string, Ambience> (); + + static AmbienceService () + { + // may not have been initialized in testing environment. + if (AddinManager.IsInitialized) { + AddinManager.AddExtensionNodeHandler ("/MonoDevelop/ProjectModel/Ambiences", delegate(object sender, ExtensionNodeEventArgs args) { + var ambience = args.ExtensionNode as MonoDevelop.Core.AddIns.MimeTypeExtensionNode; + switch (args.Change) { + case ExtensionChange.Add: + ambiences[ambience.MimeType] = (Ambience) ambience.CreateInstance (); + break; + case ExtensionChange.Remove: + ambiences.Remove (ambience.MimeType); + break; + } + }); + } + } + + public static Ambience GetAmbience (IMember member) + { + return GetAmbienceForFile (member.DeclaringTypeDefinition.Region.FileName) ?? new NetAmbience (); + } + + public static Ambience GetAmbienceForFile (string fileName) + { + return GetAmbience (DesktopService.GetMimeTypeForUri (fileName)); + } + + public static Ambience GetAmbience (string mimeType) + { + Ambience result; + if (!string.IsNullOrEmpty (mimeType) && ambiences.TryGetValue (mimeType, out result)) + return result; + return defaultAmbience; + } + + static Ambience defaultAmbience = new NetAmbience (); + + public static Ambience DefaultAmbience { get { return defaultAmbience; } } + #region Documentation + + public class DocumentationFormatOptions + { + public static readonly DocumentationFormatOptions Empty = new DocumentationFormatOptions (); + public string HighlightParameter { + get; + set; + } + + public int MaxLineLength { + get; + set; + } + + public bool BigHeadings { + get; + set; + } + + public bool SmallText { + get; + set; + } + + public Ambience Ambience { + get; + set; + } + + public string FormatHeading (string heading) + { + return BigHeadings ? "<b><big>" + heading + "</big></b>" : "<b>" + heading + "</b>"; + } + + public string FormatBody (string body) + { + return SmallText ? "<small>" + body.Trim () + Environment.NewLine + "</small>" : body.Trim () + Environment.NewLine; + } + } + + public static string GetSummaryMarkup (IMember member) + { + return GetDocumentationMarkup (GetDocumentationSummary (member)); + } + + public static string GetDocumentationSummary (IMember member) + { + /* if (member == null) + return null; + string documentation = member.GetProjectContent ().GetDocumentation (member); + + if (!string.IsNullOrEmpty (documentation)) { + int idx1 = documentation.IndexOf ("<summary>"); + int idx2 = documentation.IndexOf ("</summary>"); + string result; + if (idx2 >= 0 && idx1 >= 0) { + result = documentation.Substring (idx1 + "<summary>".Length, idx2 - idx1 - "<summary>".Length); + } else if (idx1 >= 0) { + result = documentation.Substring (idx1 + "<summary>".Length); + } else if (idx2 >= 0) { + result = documentation.Substring (0, idx2 - 1); + } else { + result = documentation; + } + + return CleanEmpty (result); + } + + XmlElement node = (XmlElement)member.GetMonodocDocumentation (); + if (node != null) { + string innerXml = (node["summary"].InnerXml ?? "").Trim (); + StringBuilder sb = new StringBuilder (); + bool wasWhiteSpace = false; + for (int i = 0; i < innerXml.Length; i++) { + char ch = innerXml[i]; + switch (ch) { + case '\n': + case '\r': + break; + default: + bool isWhiteSpace = Char.IsWhiteSpace (ch); + if (isWhiteSpace && wasWhiteSpace) + continue; + wasWhiteSpace = isWhiteSpace; + sb.Append (ch); + break; + } + } + + + return CleanEmpty (sb.ToString ()); + } + return CleanEmpty (documentation);*/ + return "TODO"; + } + + static string CleanEmpty (string doc) + { + return IsEmptyDocumentation (doc)? null : doc; + } + + static bool IsEmptyDocumentation (string documentation) + { + return string.IsNullOrEmpty (documentation) || documentation.StartsWith ("To be added") || documentation == "we have not entered docs yet"; + } + + public static string GetDocumentation (IMember member) + {// TODO: Type system conversion. + /* if (member == null) + return null; + if (!string.IsNullOrEmpty (member.Documentation)) + return CleanEmpty (member.Documentation); + XmlElement node = (XmlElement)member.GetMonodocDocumentation (); + if (node != null) { + string result = (node.InnerXml ?? "").Trim (); + return CleanEmpty (result); + }*/ + return null; + } + + static string GetCref (string cref) + { + if (cref == null) + return ""; + + if (cref.Length < 2) + return cref; + + if (cref.Substring (1, 1) == ":") + return cref.Substring (2, cref.Length - 2); + + return cref; + } + + static bool IsSpecialChar (int charValue) + { + return + 0x01 <= charValue && charValue <= 0x08 || + 0x0B <= charValue && charValue <= 0x0C || + 0x0E <= charValue && charValue <= 0x1F || + 0x7F <= charValue && charValue <= 0x84 || + 0x86 <= charValue && charValue <= 0x9F; + } + + public static string BreakLines (string text, int maxLineLength) + { + if (maxLineLength <= 0) + return text; + StringBuilder result = new StringBuilder (); + int lineLength = 0; + bool inTag = false; + bool inAmp = false; + foreach (char ch in text) { + switch (ch) { + case '<': + inTag = true; + break; + case '>': + inTag = false; + break; + case '&': + inAmp = true; + break; + case ';': + inAmp = false; + break; + case '\n': + lineLength = 0; + break; + case '\r': + lineLength = 0; + break; + } + + result.Append (ch); + if (!inTag && !inAmp) + lineLength++; + if (!Char.IsLetterOrDigit (ch) && lineLength > maxLineLength) { + result.AppendLine (); + lineLength = 0; + } + } + return result.ToString (); + } + + public static string EscapeText (string text) + { + StringBuilder result = new StringBuilder (); + foreach (char ch in text) { + switch (ch) { + case '<': + result.Append ("<"); + break; + case '>': + result.Append (">"); + break; + case '&': + result.Append ("&"); + break; + case '\'': + result.Append ("'"); + break; + case '"': + result.Append ("""); + break; + default: + int charValue = (int)ch; + if (IsSpecialChar (charValue)) { + result.AppendFormat ("&#x{0:X};", charValue); + } else { + result.Append (ch); + } + break; + } + } + return result.ToString (); + } + + public static string GetDocumentationMarkup (string doc) + { + return GetDocumentationMarkup (doc, DocumentationFormatOptions.Empty); + } + + static string ParseBody (XmlTextReader xml, string endTagName, DocumentationFormatOptions options) + { + StringBuilder result = new StringBuilder (); + while (xml.Read ()) { + switch (xml.NodeType) { + case XmlNodeType.EndElement: + if (xml.Name == endTagName) + return result.ToString (); + break; + case XmlNodeType.Element: + switch (xml.Name.ToLower ()) { + case "para": + result.AppendLine (ParseBody (xml, xml.Name, options)); + break; + case "see": + result.Append (' '); + result.Append ("<i>"); + string name = (GetCref (xml["cref"]) + xml["langword"]).Trim (); + if (options.Ambience != null) + name = options.Ambience.GetIntrinsicTypeName (name); + result.Append (EscapeText (name)); + result.Append ("</i>"); + break; + case "paramref": + result.Append (' '); + result.Append ("<i>"); + result.Append (EscapeText (xml["name"].Trim ())); + result.Append ("</i>"); + break; + } + break; + case XmlNodeType.Text: + StringBuilder textBuilder = new StringBuilder (); + bool wasWhiteSpace = true; + if (IsEmptyDocumentation (xml.Value)) + break; + foreach (char ch in xml.Value) { + if (Char.IsWhiteSpace (ch)) { + if (!wasWhiteSpace) + textBuilder.Append (' '); + wasWhiteSpace = true; + continue; + } + wasWhiteSpace = false; + textBuilder.Append (ch); + } + string text = BreakLines (EscapeText (textBuilder.ToString ()), options.MaxLineLength); + text = text.Trim (); + if (text.Length > 0 && char.IsLetter (text[0])) + result.Append (" "); + result.Append (text.Trim ()); + break; + } + } + return result.ToString (); + } + + public static string GetDocumentationMarkup (string doc, DocumentationFormatOptions options) + { + if (string.IsNullOrEmpty (doc)) + return null; + System.IO.StringReader reader = new System.IO.StringReader ("<docroot>" + doc + "</docroot>"); + XmlTextReader xml = new XmlTextReader (reader); + StringBuilder ret = new StringBuilder (70); + StringBuilder parameters = new StringBuilder (); + StringBuilder exceptions = new StringBuilder (); + parameters.AppendLine (options.FormatHeading ("Parameters:")); + + exceptions.AppendLine (options.FormatHeading ("Exceptions:")); + // ret.Append ("<small>"); + int paramCount = 0, exceptionCount = 0, summaryEnd = -1; + try { + xml.Read (); + do { + if (xml.NodeType == XmlNodeType.Element) { + switch (xml.Name.ToLower ()) { + case "para": + ret.Append (options.FormatBody (ParseBody (xml, xml.Name, options))); + if (summaryEnd < 0) + summaryEnd = ret.Length; + break; + case "summary": +// ret.AppendLine (GetHeading ("Summary:", options)); + ret.Append (options.FormatBody (ParseBody (xml, xml.Name, options))); + if (summaryEnd < 0) + summaryEnd = ret.Length; + break; + case "remarks": + if (string.IsNullOrEmpty (options.HighlightParameter)) { + ret.AppendLine (options.FormatHeading ("Remarks:")); + ret.Append (options.FormatBody (ParseBody (xml, xml.Name, options))); + if (summaryEnd < 0) + summaryEnd = ret.Length; + } else { + options.FormatBody (ParseBody (xml, xml.Name, options)); + } + break; + // skip <example>-nodes + case "example": + xml.Skip (); + xml.Skip (); + break; + case "exception": + exceptionCount++; + if (options.SmallText) + exceptions.Append ("<small>"); + exceptions.Append ("<b>"); + exceptions.Append (EscapeText (GetCref (xml["cref"]))); + exceptions.Append (": "); + exceptions.Append ("</b>"); + if (options.SmallText) + exceptions.Append ("</small>"); + + exceptions.AppendLine (options.FormatBody (ParseBody (xml, xml.Name, options))); + break; + case "returns": + if (string.IsNullOrEmpty (options.HighlightParameter)) { + ret.AppendLine (options.FormatHeading ("Returns:")); + ret.Append (options.FormatBody (ParseBody (xml, xml.Name, options))); + } else { + options.FormatBody (ParseBody (xml, xml.Name, options)); + } + break; + case "param": + paramCount++; + string paramName = xml["name"].Trim (); + parameters.Append ("<i>"); + if (options.HighlightParameter == paramName) + parameters.Append ("<b>"); + if (options.SmallText) + parameters.Append ("<small>"); + parameters.Append (EscapeText (paramName)); + if (options.SmallText) + parameters.Append ("</small>"); + if (options.HighlightParameter == paramName) + parameters.Append ("</b>"); + parameters.Append (":</i> "); + parameters.Append (options.FormatBody (ParseBody (xml, xml.Name, options))); + break; + case "value": + ret.AppendLine (options.FormatHeading ("Value:")); + ret.AppendLine (options.FormatBody (ParseBody (xml, xml.Name, options))); + break; + case "seealso": + if (string.IsNullOrEmpty (options.HighlightParameter)) { + ret.Append (options.FormatHeading ("See also:")); + ret.Append (" " + EscapeText (GetCref (xml["cref"]) + xml["langword"])); + } + break; + } + } + } while (xml.Read ()); + + } catch (Exception ex) { + MonoDevelop.Core.LoggingService.LogError (ex.ToString ()); + return EscapeText (doc); + } + if (IsEmptyDocumentation (ret.ToString ())) + return null; + if (string.IsNullOrEmpty (options.HighlightParameter) && exceptionCount > 0) + ret.Append (exceptions.ToString ()); + + string result = ret.ToString (); + if (summaryEnd < 0) + summaryEnd = result.Length; + if (paramCount > 0) + result = result.Insert (summaryEnd, parameters.ToString ()); + + result = result.Trim (); + if (result.EndsWith (Environment.NewLine +"</small>")) + result = result.Substring (0, result.Length - (Environment.NewLine +"</small>").Length) + "</small>"; + return result; + } + #endregion + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Comment.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Comment.cs new file mode 100644 index 0000000000..185233644e --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Comment.cs @@ -0,0 +1,81 @@ +// +// Comment.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +using System; +using ICSharpCode.NRefactory.CSharp; +using ICSharpCode.NRefactory.TypeSystem; + +namespace MonoDevelop.TypeSystem +{ + [Serializable] + public class Comment + { + public string OpenTag { + get; + set; + } + + public string ClosingTag { + get; + set; + } + + public string Text { + get; + set; + } + + public DomRegion Region { + get; + set; + } + + public bool IsDocumentation { + get; + set; + } + + public bool CommentStartsLine { + get; + set; + } + + public CommentType CommentType { + get; + set; + } + + public Comment () + { + } + + public Comment (string text) + { + this.Text = text; + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ConditionalRegion.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ConditionalRegion.cs new file mode 100644 index 0000000000..6fba3e7099 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ConditionalRegion.cs @@ -0,0 +1,86 @@ +// ConditionalRegion.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +using System; +using System.Collections.Generic; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.CSharp; + +namespace MonoDevelop.TypeSystem +{ + public class ConditionBlock + { + public string Flag { + get; + set; + } + + public DomRegion Region { + get; + set; + } + + public AstLocation Start { + get; + set; + } + + public AstLocation End { + get; + set; + } + + public ConditionBlock (string flag) : this (flag, AstLocation.Empty) + { + } + + public ConditionBlock (string flag, AstLocation start) + { + this.Flag = flag; + this.Start = start; + this.Region = DomRegion.Empty; + } + } + + public class ConditionalRegion : ConditionBlock + { + public DomRegion ElseBlock { + get; + set; + } + + List<ConditionBlock> conditionBlocks = new List<ConditionBlock> (); + + public List<ConditionBlock> ConditionBlocks { + get { + return conditionBlocks; + } + } + + public ConditionalRegion (string flag) : base (flag) + { + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/FoldingRegion.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/FoldingRegion.cs new file mode 100644 index 0000000000..0059f5ccc1 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/FoldingRegion.cs @@ -0,0 +1,85 @@ +// FoldingRegion.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +using System; +using ICSharpCode.NRefactory.TypeSystem; + +namespace MonoDevelop.TypeSystem +{ + public class FoldingRegion + { + static string defaultName = "..."; + + public string Name { get; set; } + + //NOTE: thsi is only respected if the FoldType is set to "Undefined" + public bool IsFoldedByDefault { get; set; } + + public DomRegion Region { get; set; } + + public FoldType Type { get; set; } + + public FoldingRegion (DomRegion region) : this (null, region) + { + } + + public FoldingRegion (string name, DomRegion region) + { + this.Name = name ?? defaultName; + this.Region = region; + } + + public FoldingRegion (string name, DomRegion region, bool isFoldedByDefault) : this (name, region) + { + this.IsFoldedByDefault = isFoldedByDefault; + } + + public FoldingRegion (string name, DomRegion region, FoldType type) : this (name, region) + { + this.Type = type; + } + + public FoldingRegion (string name, DomRegion region, FoldType type, bool isFoldedByDefault) : this (name, region) + { + this.Type = type; + this.IsFoldedByDefault = isFoldedByDefault; + } + + public FoldingRegion (DomRegion region, FoldType type) : this (null, region, type) + { + } + } + + public enum FoldType + { + Undefined = 0, + ConditionalDefine, + Comment, + CommentInsideMember, + UserRegion, + Type, + Member + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ITypeSystemProvider.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ITypeSystemProvider.cs index 44b33a29b4..5f8b1c58e1 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ITypeSystemProvider.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ITypeSystemProvider.cs @@ -31,7 +31,15 @@ namespace MonoDevelop.TypeSystem { public interface ITypeSystemProvider { - IParsedFile Parse (IProjectContent projectContent, string fileName, TextReader content); + ParsedDocument Parse (IProjectContent projectContent, bool storeAst, string fileName, TextReader content); + } + + public abstract class AbstractTypeSystemProvider : ITypeSystemProvider + { + public virtual ParsedDocument Parse (IProjectContent projectContent, bool storeAst, string fileName, TextReader content) + { + return null; + } } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/MarkupUtilities.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/MarkupUtilities.cs new file mode 100644 index 0000000000..782e4da062 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/MarkupUtilities.cs @@ -0,0 +1,72 @@ +// +// DocumentationService.cs +// +// Author: +// Michael Hutchinson <mhutchinson@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Text; + +namespace MonoDevelop.TypeSystem +{ + internal static class MarkupUtilities + { + static string EscapedLessThan = "<"; + static string EscapedGreaterThan = ">"; + static string EscapedAmpersand = "&"; + static string EscapedApostrophe = "'"; + static string EscapedQuote = """; + + public static void AppendEscapedString (StringBuilder builder, string toEscape) + { + if (toEscape == null) + return; + + for (int i = 0; i < toEscape.Length; i++) { + char c = toEscape[i]; + switch (c) { + case '<': + builder.Append (EscapedLessThan); + break; + case '>': + builder.Append (EscapedGreaterThan); + break; + case '&': + builder.Append (EscapedAmpersand); + break; + case '\'': + builder.Append (EscapedApostrophe); + break; + case '"': + builder.Append (EscapedQuote); + break; + default: + builder.Append (c); + break; + } + } + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/NetAmbience.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/NetAmbience.cs new file mode 100644 index 0000000000..93582acad9 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/NetAmbience.cs @@ -0,0 +1,366 @@ +// +// NetAmbience.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Linq; +using System.Text; +using ICSharpCode.NRefactory.TypeSystem; +using System.Collections.Generic; + +namespace MonoDevelop.TypeSystem +{ + public class NetAmbience : Ambience + { + public NetAmbience () : base ("NET") + { + classTypes [ClassType.Class] = "Class"; + classTypes [ClassType.Enum] = "Enumeration"; + classTypes [ClassType.Interface] = "Interface"; + classTypes [ClassType.Struct] = "Structure"; + classTypes [ClassType.Delegate] = "Delegate"; + } + + public override string SingleLineComment (string text) + { + return "// " + text; + } + + #region Type system output + public override string GetIntrinsicTypeName (string reflectionName) + { + return reflectionName; + } + + protected override string GetTypeReferenceString (ITypeReference reference, OutputSettings settings) + { + return reference.ToString (); + } + + protected override string GetTypeString (ITypeDefinition type, OutputSettings settings) + { + var result = new StringBuilder (); + if (settings.IncludeModifiers) + AppendModifiers (result, settings, type); + if (settings.IncludeKeywords) + result.Append (settings.EmitKeyword (GetString (type.ClassType))); + + result.Append (settings.EmitName (type, settings.UseFullName ? type.FullName : type.Name)); + + int parameterCount = type.TypeParameters.Count; + + if (settings.IncludeGenerics && parameterCount > 0) { + result.Append (settings.Markup ("<")); + if (!settings.HideGenericParameterNames) { + for (int i = 0; i < parameterCount; i++) { + if (i > 0) + result.Append (settings.Markup (", ")); + result.Append (type.TypeParameters [i].Name); + } + } + result.Append (settings.Markup (">")); + } + + if (settings.IncludeBaseTypes && type.BaseTypes.Any ()) { + result.Append (settings.Markup (" : ")); + bool first = true; + foreach (var baseType in type.BaseTypes) { + if (baseType.Resolve (settings.Context).Equals (settings.Context.GetClass (typeof (object)))) + continue; + if (!first) + result.Append (settings.Markup (", ")); + first = false; + result.Append (GetTypeReferenceString (baseType, settings)); + } + + } + return result.ToString (); + } + + protected override string GetMethodString (IMethod method, OutputSettings settings) + { + var result = new StringBuilder (); + + if (settings.IncludeModifiers) + AppendModifiers (result, settings, method); + + result.Append (settings.EmitKeyword ("Method")); + result.Append (settings.EmitName (method, settings.UseFullName ? method.FullName : method.Name)); + + if (settings.IncludeParameters) { + result.Append (settings.Markup ("(")); + bool first = true; + foreach (var parameter in method.Parameters) { + if (!first) + result.Append (settings.Markup (", ")); + result.Append (GetParameterString (method, parameter, settings)); + first = false; + } + result.Append (settings.Markup (")")); + } + + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (method.ReturnType, settings)); + } + return result.ToString (); + } + + protected override string GetConstructorString (IMethod method, OutputSettings settings) + { + var result = new StringBuilder (); + + if (settings.IncludeModifiers) + AppendModifiers (result, settings, method); + + result.Append (settings.EmitKeyword ("Constructor")); + result.Append (settings.EmitName (method, method.DeclaringType.Name)); + + if (settings.IncludeParameters) { + result.Append (settings.Markup ("(")); + bool first = true; + foreach (var parameter in method.Parameters) { + if (!first) + result.Append (settings.Markup (", ")); + result.Append (GetParameterString (method, parameter, settings)); + first = false; + } + result.Append (settings.Markup (")")); + } + return result.ToString (); + } + + protected override string GetDestructorString (IMethod method, OutputSettings settings) + { + var result = new StringBuilder (); + result.Append (settings.EmitKeyword ("Destructor")); + result.Append (settings.EmitName (method, method.DeclaringType.Name)); + return result.ToString (); + } + + protected override string GetOperatorString (IMethod method, OutputSettings settings) + { + var result = new StringBuilder (); + + if (settings.IncludeModifiers) + AppendModifiers (result, settings, method); + + result.Append (settings.EmitKeyword ("Operator")); + result.Append (settings.EmitName (method, settings.UseFullName ? method.FullName : method.Name)); + + if (settings.IncludeParameters) { + result.Append (settings.Markup ("(")); + bool first = true; + foreach (var parameter in method.Parameters) { + if (!first) + result.Append (settings.Markup (", ")); + result.Append (GetParameterString (method, parameter, settings)); + first = false; + } + result.Append (settings.Markup (")")); + } + + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (method.ReturnType, settings)); + } + return result.ToString (); + } + + protected override string GetFieldString (IField field, OutputSettings settings) + { + var result = new StringBuilder (); + + if (settings.IncludeModifiers) + AppendModifiers (result, settings, field); + + result.Append (settings.EmitKeyword ("Field")); + result.Append (settings.EmitName (field, field.Name)); + + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (field.ReturnType, settings)); + } + return result.ToString (); + } + + protected override string GetEventString (IEvent evt, OutputSettings settings) + { + var result = new StringBuilder (); + + if (settings.IncludeModifiers) + AppendModifiers (result, settings, evt); + + result.Append (settings.EmitKeyword ("Event")); + result.Append (settings.EmitName (evt, evt.Name)); + + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (evt.ReturnType, settings)); + } + return result.ToString (); + } + + protected override string GetPropertyString (IProperty property, OutputSettings settings) + { + var result = new StringBuilder (); + if (settings.IncludeModifiers) + AppendModifiers (result, settings, property); + result.Append (settings.EmitKeyword ("Property")); + result.Append (settings.EmitName (property, property.Name)); + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (property.ReturnType, settings)); + } + return result.ToString (); + } + + protected override string GetIndexerString (IProperty property, OutputSettings settings) + { + var result = new StringBuilder (); + if (settings.IncludeModifiers) + AppendModifiers (result, settings, property); + result.Append (settings.EmitKeyword ("Indexer")); + result.Append (settings.EmitName (property, property.Name)); + + if (settings.IncludeParameters && property.Parameters.Count > 0) { + result.Append (settings.Markup ("(")); + bool first = true; + foreach (var parameter in property.Parameters) { + if (!first) + result.Append (settings.Markup (", ")); + result.Append (GetParameterString (property, parameter, settings)); + first = false; + } + result.Append (settings.Markup (")")); + } + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (property.ReturnType, settings)); + } + return result.ToString (); + } + + protected override string GetParameterString (IParameterizedMember member, IParameter parameter, OutputSettings settings) + { + var result = new StringBuilder (); + if (settings.IncludeParameterName) { + result.Append (Format (parameter.Name)); + if (settings.IncludeReturnType) { + result.Append (settings.Markup (" : ")); + result.Append (GetTypeReferenceString (parameter.Type, settings)); + } + } else { + result.Append (GetTypeReferenceString (parameter.Type, settings)); + } + if (parameter.IsRef || parameter.IsOut) + result.Append (settings.Markup ("&")); + return result.ToString (); + } + #endregion + + void AppendModifiers (StringBuilder result, OutputSettings settings, IEntity entity) + { + if (entity.IsStatic) + result.Append (settings.EmitModifiers ("Static")); + if (entity.IsSealed) + result.Append (settings.EmitModifiers ("Sealed")); + if (entity.IsAbstract) + result.Append (settings.EmitModifiers ("Abstract")); + if (entity.IsShadowing) + result.Append (settings.EmitModifiers ("Shadows")); + if (entity.IsSynthetic) + result.Append (settings.EmitModifiers ("Synthetic")); + + switch (entity.Accessibility) { + case Accessibility.Internal: + result.Append (settings.EmitModifiers ("Internal")); + break; + case Accessibility.ProtectedAndInternal: + result.Append (settings.EmitModifiers ("Protected And Internal")); + break; + case Accessibility.ProtectedOrInternal: + result.Append (settings.EmitModifiers ("Protected Or Internal")); + break; + case Accessibility.Protected: + result.Append (settings.EmitModifiers ("Protected")); + break; + case Accessibility.Private: + result.Append (settings.EmitModifiers ("Private")); + break; + case Accessibility.Public: + result.Append (settings.EmitModifiers ("Public")); + break; + } + } + + public override string GetString (string nameSpace, OutputSettings settings) + { + var result = new StringBuilder (); + result.Append (settings.EmitKeyword ("Namespace")); + result.Append (Format (nameSpace)); + return result.ToString (); + } + + Dictionary<ClassType, string> classTypes = new Dictionary<ClassType, string> (); + + string GetString (ClassType classType) + { + string res; + if (classTypes.TryGetValue (classType, out res)) + return res; + return string.Empty; + } +// public string Visit (IAttribute attribute, OutputSettings settings) +// { +// StringBuilder result = new StringBuilder (); +// result.Append (settings.Markup ("[")); +// result.Append (GetString (attribute.AttributeType, settings)); +// result.Append (settings.Markup ("(")); +// bool first = true; +// if (attribute.PositionalArguments != null) { +// foreach (object o in attribute.PositionalArguments) { +// if (!first) +// result.Append (settings.Markup (", ")); +// first = false; +// if (o is string) { +// result.Append (settings.Markup ("\"")); +// result.Append (o); +// result.Append (settings.Markup ("\"")); +// } else if (o is char) { +// result.Append (settings.Markup ("\"")); +// result.Append (o); +// result.Append (settings.Markup ("\"")); +// } else +// result.Append (o); +// } +// } +// result.Append (settings.Markup (")]")); +// return result.ToString (); +// } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/OutputFlags.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/OutputFlags.cs new file mode 100644 index 0000000000..2e99ef052e --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/OutputFlags.cs @@ -0,0 +1,62 @@ +// +// OutputFlags.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; + +namespace MonoDevelop.TypeSystem +{ + [Flags] + public enum OutputFlags { + None = 0, + + // Flags + UseFullName = 0x0001, + IncludeReturnType = 0x0002, + IncludeParameters = 0x0004, + IncludeParameterName = 0x0008, + IncludeMarkup = 0x0010, + IncludeKeywords = 0x0020, + IncludeModifiers = 0x0040, + IncludeBaseTypes = 0x0080, + IncludeGenerics = 0x0100, + UseIntrinsicTypeNames = 0x0200, + HighlightName = 0x0400, + HideExtensionsParameter = 0x0800, + HideGenericParameterNames= 0x1000, + HideArrayBrackets = 0x2000, + UseNETTypeNames = 0x4000, // print 'System.Int32' intead of 'int' + UseFullInnerTypeName = 0x8000, + ReformatDelegates = 0x10000, + GeneralizeGenerics = 0x20000, + StaticUsage = 0x40000, // to distinguish static usage for extension methods. + IncludeConstraints = 0x80000, + + ClassBrowserEntries = IncludeReturnType | IncludeParameters | IncludeGenerics, + AssemblyBrowserDescription = IncludeGenerics | IncludeBaseTypes | IncludeReturnType | IncludeParameters | IncludeParameterName | IncludeMarkup | IncludeKeywords | IncludeModifiers + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/OutputSettings.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/OutputSettings.cs new file mode 100644 index 0000000000..624ce981e0 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/OutputSettings.cs @@ -0,0 +1,257 @@ +// OutputSettings.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +using System; +using System.Text; +using MonoDevelop.Projects.Policies; +using System.Collections.Generic; +using ICSharpCode.NRefactory.TypeSystem; + +namespace MonoDevelop.TypeSystem +{ + public class OutputSettings + { + public OutputFlags OutputFlags { + get; + set; + } + + public PolicyContainer PolicyParent { + get; + set; + } + + public ITypeResolveContext Context { + get; + set; + } + + public OutputSettings (OutputFlags outputFlags) + { + this.OutputFlags = outputFlags; + } + + public string Markup (string text) + { + if (MarkupCallback != null) + return MarkupCallback (text); + return IncludeMarkup ? PangoFormat (text) : text; + } + + public string EmitName (object domVisitable, string text) + { + if (EmitNameCallback != null) { + EmitNameCallback (domVisitable, ref text); + return text; + } + return text; + } + + public string EmitModifiers (string text) + { + if (!IncludeModifiers) + return string.Empty; + if (EmitModifiersCallback != null) + return EmitModifiersCallback (text) + " "; + if (IncludeMarkup) + return "<b>" + PangoFormat (text) + "</b> "; + return text + " "; + } + + public string EmitKeyword (string text) + { + if (EmitKeywordCallback != null) + return EmitKeywordCallback (text) + " "; + if (!IncludeKeywords) + return ""; + if (IncludeMarkup) + return "<b>" + PangoFormat (text) + "</b> "; + return text + " "; + } + + public string Highlight (string text) + { + if (HighlightCallback != null) + return HighlightCallback (text); + if (IncludeMarkup) + return "<b>" + PangoFormat (text) + "</b>"; + return text; + } + + public void PostProcess (INamedElement domVisitable, ref string outString) + { + if (PostProcessCallback != null) + PostProcessCallback (domVisitable, ref outString); + } + + static string PangoFormat (string input) + { + StringBuilder result = new StringBuilder (); + foreach (char ch in input) { + switch (ch) { + case '<': + result.Append ("<"); + break; + case '>': + result.Append (">"); + break; + case '&': + result.Append ("&"); + break; + default: + result.Append (ch); + break; + } + } + return result.ToString (); + } + + public bool IncludeMarkup { + get { + return (OutputFlags & OutputFlags.IncludeMarkup) == OutputFlags.IncludeMarkup; + } + } + + public bool IncludeKeywords { + get { + return (OutputFlags & OutputFlags.IncludeKeywords) == OutputFlags.IncludeKeywords; + } + } + + public bool IncludeModifiers { + get { + return (OutputFlags & OutputFlags.IncludeModifiers) == OutputFlags.IncludeModifiers; + } + } + + public bool UseFullName { + get { + return (OutputFlags & OutputFlags.UseFullName) == OutputFlags.UseFullName; + } + } + + public bool UseFullInnerTypeName { + get { + return (OutputFlags & OutputFlags.UseFullInnerTypeName) == OutputFlags.UseFullInnerTypeName; + } + } + + public bool IncludeParameters { + get { + return (OutputFlags & OutputFlags.IncludeParameters) == OutputFlags.IncludeParameters; + } + } + + public bool IncludeReturnType { + get { + return (OutputFlags & OutputFlags.IncludeReturnType) == OutputFlags.IncludeReturnType; + } + } + + public bool IncludeParameterName { + get { + return (OutputFlags & OutputFlags.IncludeParameterName) == OutputFlags.IncludeParameterName; + } + } + + public bool IncludeBaseTypes { + get { + return (OutputFlags & OutputFlags.IncludeBaseTypes) == OutputFlags.IncludeBaseTypes; + } + } + + public bool IncludeGenerics { + get { + return (OutputFlags & OutputFlags.IncludeGenerics) == OutputFlags.IncludeGenerics; + } + } + + public bool HideArrayBrackets { + get { + return (OutputFlags & OutputFlags.HideArrayBrackets) == OutputFlags.HideArrayBrackets; + } + } + + public bool HighlightName { + get { + return (OutputFlags & OutputFlags.HighlightName) == OutputFlags.HighlightName; + } + } + + public bool HideExtensionsParameter { + get { + return (OutputFlags & OutputFlags.HideExtensionsParameter) == OutputFlags.HideExtensionsParameter; + } + } + + public bool HideGenericParameterNames { + get { + return (OutputFlags & OutputFlags.HideGenericParameterNames) != 0; + } + } + + public bool GeneralizeGenerics { + get { + return (OutputFlags & OutputFlags.GeneralizeGenerics) != 0; + } + } + + public bool UseNETTypeNames { + get { + return (OutputFlags & OutputFlags.UseNETTypeNames) != 0; + } + } + + public bool ReformatDelegates { + get { + return (OutputFlags & OutputFlags.ReformatDelegates) != 0; + } + } + + public bool StaticUsage { + get { + return (OutputFlags & OutputFlags.StaticUsage) != 0; + } + } + + public bool IncludeConstraints { + get { + return (OutputFlags & OutputFlags.IncludeConstraints) != 0; + } + } + + public MarkupText EmitModifiersCallback; + public MarkupText EmitKeywordCallback; + public MarkupText MarkupCallback; + public MarkupText HighlightCallback; + public ProcessString EmitNameCallback; + + public delegate string MarkupText (string text); + + public ProcessString PostProcessCallback; + public delegate void ProcessString (object domVisitable, ref string outString); + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ParsedDocument.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ParsedDocument.cs new file mode 100644 index 0000000000..0fa70d8871 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/ParsedDocument.cs @@ -0,0 +1,672 @@ +// +// ParsedDocument.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using ICSharpCode.NRefactory.TypeSystem; +using System.Collections.Generic; +using System.Text; +using ICSharpCode.NRefactory.CSharp; +using System.Linq; +using System.Threading; + +namespace MonoDevelop.TypeSystem +{ + public class ParsedDocument : IParsedFile + { + DateTime parseTime = DateTime.Now; + public DateTime ParseTime { + get { return parseTime; } + } + + List<Comment> comments = new List<Comment> (); + List<Tag> tagComments = new List<Tag> (); + + List<FoldingRegion> folds = new List<FoldingRegion> (); + public IList<FoldingRegion> AdditionalFolds { + get { + return folds; + } + } + + public IEnumerable<FoldingRegion> UserRegions { + get { + return AdditionalFolds.Where (f => f.Type == FoldType.UserRegion); + } + } + + List<PreProcessorDefine> defines = new List<PreProcessorDefine> (); + public IList<PreProcessorDefine> Defines { + get { + return defines; + } + } + + List<ConditionalRegion> conditionalRegions = new List<ConditionalRegion> (); + public IList<ConditionalRegion> ConditionalRegions { + get { + return conditionalRegions; + } + } + + public ParsedDocument () + { + } + + public ParsedDocument (string fileName) + { + this.fileName = fileName; + } + + #region IParsedFile implementation + public virtual ITypeDefinition GetTopLevelTypeDefinition (AstLocation location) + { + return null; + } + + public virtual ITypeDefinition GetTypeDefinition (AstLocation location) + { + return null; + } + + public virtual IMember GetMember (AstLocation location) + { + return null; + } + + public virtual IProjectContent ProjectContent { + get { + return null; + } + } + + string fileName; + public virtual string FileName { + get { + return fileName; + } + } + + public virtual IList<ITypeDefinition> TopLevelTypeDefinitions { + get { + return new List<ITypeDefinition> (); + } + } + + public virtual IList<IAttribute> AssemblyAttributes { + get { + return new List<IAttribute> (); + } + } + + List<Error> errors = new List<Error> (); + public virtual IList<Error> Errors { + get { + return errors; + } + } + + public bool HasErrors { + get { + return Errors.Any (e => e.ErrorType == ErrorType.Error); + } + } + + #endregion + + #region IFreezable implementation + public virtual void Freeze () + { + } + + public virtual bool IsFrozen { + get { + return false; + } + } + #endregion + + public virtual IEnumerable<FoldingRegion> GenerateFolds () + { + foreach (FoldingRegion fold in AdditionalFolds) + yield return fold; + + foreach (FoldingRegion fold in ConditionalRegions.ToFolds ()) + yield return fold; + + IEnumerable<FoldingRegion> commentFolds = comments.ToFolds (); +// if (parsedFile != null) { +// commentFolds = commentFolds.FlagIfInsideMembers (CompilationUnit.Types, delegate (FoldingRegion f) { +// f.Type = FoldType.CommentInsideMember; +// }); +// } + +// foreach (FoldingRegion fold in commentFolds) +// yield return fold; + + +// FoldingRegion usingFold = CompilationUnit.Usings.ToFold (); +// if (usingFold != null) +// yield return usingFold; + +// foreach (var fold in this.parsedFile.TopLevelTypeDefinitions.ToFolds ()) +// yield return fold; + } + + public void Add (Error error) + { + errors.Add (error); + } + + public void Add (Comment comment) + { + comments.Add (comment); + } + + public void Add (Tag tagComment) + { + tagComments.Add (tagComment); + } + + public void Add (PreProcessorDefine define) + { + defines.Add (define); + } + + public void Add (ConditionalRegion region) + { + conditionalRegions.Add (region); + } + + public void Add (FoldingRegion region) + { + folds.Add (region); + } + + public void Add (IEnumerable<Error> errors) + { + foreach (Error error in errors) { + this.errors.Add (error); + } + } + + public void Add (IEnumerable<Comment> comments) + { + this.comments.AddRange (comments); + } + + public void Add (IEnumerable<Tag> tagComments) + { + this.tagComments.AddRange (tagComments); + } + + public void Add (IEnumerable<PreProcessorDefine> defines) + { + this.defines.AddRange (defines); + } + + public void Add (IEnumerable<FoldingRegion> folds) + { + this.folds.AddRange (folds); + } + + public void Add (IEnumerable<ConditionalRegion> conditionalRegions) + { + this.conditionalRegions.AddRange (conditionalRegions); + } + + #region Annotation support + // Annotations: points either null (no annotations), to the single annotation, + // or to an AnnotationList. + // Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list) + object annotations; + + sealed class AnnotationList : List<object>, ICloneable + { + // There are two uses for this custom list type: + // 1) it's private, and thus (unlike List<object>) cannot be confused with real annotations + // 2) It allows us to simplify the cloning logic by making the list behave the same as a clonable annotation. + public AnnotationList (int initialCapacity) : base(initialCapacity) + { + } + + public object Clone () + { + lock (this) { + AnnotationList copy = new AnnotationList (this.Count); + for (int i = 0; i < this.Count; i++) { + object obj = this [i]; + ICloneable c = obj as ICloneable; + copy.Add (c != null ? c.Clone () : obj); + } + return copy; + } + } + } + + public void AddAnnotation (object annotation) + { + if (annotation == null) + throw new ArgumentNullException ("annotation"); + retry: // Retry until successful + object oldAnnotation = Interlocked.CompareExchange (ref this.annotations, annotation, null); + if (oldAnnotation == null) { + return; // we successfully added a single annotation + } + AnnotationList list = oldAnnotation as AnnotationList; + if (list == null) { + // we need to transform the old annotation into a list + list = new AnnotationList (4); + list.Add (oldAnnotation); + list.Add (annotation); + if (Interlocked.CompareExchange (ref this.annotations, list, oldAnnotation) != oldAnnotation) { + // the transformation failed (some other thread wrote to this.annotations first) + goto retry; + } + } else { + // once there's a list, use simple locking + lock (list) { + list.Add (annotation); + } + } + } + + public void RemoveAnnotations<T> () where T : class + { + retry: // Retry until successful + object oldAnnotations = this.annotations; + AnnotationList list = oldAnnotations as AnnotationList; + if (list != null) { + lock (list) + list.RemoveAll (obj => obj is T); + } else if (oldAnnotations is T) { + if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) { + // Operation failed (some other thread wrote to this.annotations first) + goto retry; + } + } + } + + public void RemoveAnnotations (Type type) + { + if (type == null) + throw new ArgumentNullException ("type"); + retry: // Retry until successful + object oldAnnotations = this.annotations; + AnnotationList list = oldAnnotations as AnnotationList; + if (list != null) { + lock (list) + list.RemoveAll (obj => type.IsInstanceOfType (obj)); + } else if (type.IsInstanceOfType (oldAnnotations)) { + if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) { + // Operation failed (some other thread wrote to this.annotations first) + goto retry; + } + } + } + + public T Annotation<T> () where T: class + { + object annotations = this.annotations; + AnnotationList list = annotations as AnnotationList; + if (list != null) { + lock (list) { + foreach (object obj in list) { + T t = obj as T; + if (t != null) + return t; + } + return null; + } + } else { + return annotations as T; + } + } + + public object Annotation (Type type) + { + if (type == null) + throw new ArgumentNullException ("type"); + object annotations = this.annotations; + AnnotationList list = annotations as AnnotationList; + if (list != null) { + lock (list) { + foreach (object obj in list) { + if (type.IsInstanceOfType (obj)) + return obj; + } + } + } else { + if (type.IsInstanceOfType (annotations)) + return annotations; + } + return null; + } + + /// <summary> + /// Gets all annotations stored on this AstNode. + /// </summary> + public IEnumerable<object> Annotations { + get { + object annotations = this.annotations; + AnnotationList list = annotations as AnnotationList; + if (list != null) { + lock (list) { + return list.ToArray (); + } + } else { + if (annotations != null) + return new object[] { annotations }; + else + return Enumerable.Empty<object> (); + } + } + } + #endregion + } + + + public class ParsedDocumentDecorator : ParsedDocument + { + IParsedFile parsedFile; + + public ParsedDocumentDecorator (IParsedFile parsedFile) : base (parsedFile.FileName) + { + this.parsedFile = parsedFile; + } + + #region IParsedFile implementation + public override ITypeDefinition GetTopLevelTypeDefinition (ICSharpCode.NRefactory.CSharp.AstLocation location) + { + return parsedFile.GetTopLevelTypeDefinition (location); + } + + public override ITypeDefinition GetTypeDefinition (ICSharpCode.NRefactory.CSharp.AstLocation location) + { + return parsedFile.GetTypeDefinition (location); + } + + public override IMember GetMember (ICSharpCode.NRefactory.CSharp.AstLocation location) + { + return parsedFile.GetMember (location); + } + + public override IProjectContent ProjectContent { + get { + return parsedFile.ProjectContent; + } + } + + public override System.Collections.Generic.IList<ITypeDefinition> TopLevelTypeDefinitions { + get { + return parsedFile.TopLevelTypeDefinitions; + } + } + + public override System.Collections.Generic.IList<IAttribute> AssemblyAttributes { + get { + return parsedFile.AssemblyAttributes; + } + } + + public override System.Collections.Generic.IList<Error> Errors { + get { + return parsedFile.Errors; + } + } + #endregion + + #region IFreezable implementation + public override void Freeze () + { + parsedFile.Freeze (); + } + + public override bool IsFrozen { + get { + return parsedFile.IsFrozen; + } + } + #endregion + } + + static class FoldingUtilities + { + public static IEnumerable<FoldingRegion> ToFolds (this IEnumerable<ConditionalRegion> conditionalRegions) + { + foreach (ConditionalRegion region in conditionalRegions) { + yield return new FoldingRegion ("#if " + region.Flag, region.Region, FoldType.ConditionalDefine); + foreach (ConditionBlock block in region.ConditionBlocks) { + yield return new FoldingRegion ("#elif " + block.Flag, block.Region, + FoldType.ConditionalDefine); + } + if (!region.ElseBlock.IsEmpty) + yield return new FoldingRegion ("#else", region.ElseBlock, FoldType.ConditionalDefine); + } + } + + public static IEnumerable<FoldingRegion> ToFolds (this IEnumerable<ITypeDefinition> types) + { + foreach (var type in types) + foreach (FoldingRegion fold in type.ToFolds ()) + yield return fold; + } + + public static IEnumerable<FoldingRegion> ToFolds (this ITypeDefinition type) + { + if (!IncompleteOrSingleLine (type.BodyRegion)) + yield return new FoldingRegion (type.BodyRegion, FoldType.Type); + + foreach (var inner in type.InnerClasses) + foreach (FoldingRegion f in inner.ToFolds ()) + yield return f; + + if (type.ClassType == ClassType.Interface) + yield break; + + foreach (IMethod method in type.Methods) + if (!IncompleteOrSingleLine (method.BodyRegion)) + yield return new FoldingRegion (method.BodyRegion, FoldType.Member); + + foreach (IProperty property in type.Properties) + if (!IncompleteOrSingleLine (property.BodyRegion)) + yield return new FoldingRegion (property.BodyRegion, FoldType.Member); + } + + static bool IncompleteOrSingleLine (DomRegion region) + { + return region.BeginLine <= 0 || region.EndLine <= region.BeginLine; + } + +// public static FoldingRegion ToFold (this IEnumerable<IUsing> usings) +// { +// if (usings == null) +// return null; +// var en = usings.GetEnumerator (); +// if (!en.MoveNext ()) +// return null; +// IUsing first = en.Current; +// IUsing last = first; +// while (en.MoveNext ()) { +// if (en.Current.IsFromNamespace) +// break; +// last = en.Current; +// } +// +// if (first.Region.IsEmpty || last.Region.IsEmpty || first.Region.Start.Line == last.Region.End.Line) +// return null; +// return new FoldingRegion (new DomRegion (first.Region.Start, last.Region.End)); +// } + + public static IEnumerable<FoldingRegion> ToFolds (this IList<Comment> comments) + { + + + for (int i = 0; i < comments.Count; i++) { + Comment comment = comments [i]; + + if (comment.CommentType == CommentType.MultiLine) { + int startOffset = 0; + while (startOffset < comment.Text.Length) { + char ch = comment.Text [startOffset]; + if (!char.IsWhiteSpace (ch) && ch != '*') + break; + startOffset++; + } + int endOffset = startOffset; + while (endOffset < comment.Text.Length) { + char ch = comment.Text [endOffset]; + if (ch == '\r' || ch == '\n' || ch == '*') + break; + endOffset++; + } + + string txt; + if (endOffset > startOffset) { + txt = "/* " + SubstrEllipsize (comment.Text, startOffset, endOffset - startOffset) + " */"; + } else { + txt = "/* */"; + } + yield return new FoldingRegion (txt, comment.Region, FoldType.Comment); + continue; + } + + if (!comment.CommentStartsLine) + continue; + int j = i; + int curLine = comment.Region.BeginLine - 1; + var end = comment.Region.End; + var commentText = new StringBuilder (); + for (; j < comments.Count; j++) { + Comment curComment = comments [j]; + if (curComment == null || !curComment.CommentStartsLine + || curComment.CommentType != comment.CommentType + || curLine + 1 != curComment.Region.BeginLine) + break; + commentText.Append (curComment.Text); + end = curComment.Region.End; + curLine = curComment.Region.BeginLine; + } + + if (j - i > 1) { + string txt; + if (comment.IsDocumentation) { + txt = "/// ..."; + string cmtText = commentText.ToString (); + int idx = cmtText.IndexOf ("<summary>"); + if (idx >= 0) { + int maxOffset = cmtText.IndexOf ("</summary>"); + while (maxOffset > 0 && cmtText[maxOffset-1] == ' ') + maxOffset--; + if (maxOffset < 0) + maxOffset = cmtText.Length; + int startOffset = idx + "<summary>".Length; + while (startOffset < maxOffset) { + char ch = cmtText [startOffset]; + if (!char.IsWhiteSpace (ch) && ch != '/') + break; + startOffset++; + } + int endOffset = startOffset; + while (endOffset < maxOffset) { + char ch = cmtText [endOffset]; + if (ch == '\r' || ch == '\n') + break; + endOffset++; + } + if (endOffset > startOffset) + txt = "/// " + SubstrEllipsize (cmtText, startOffset, endOffset - startOffset); + } + } else { + txt = "// " + SubstrEllipsize (comment.Text, 0, comment.Text.Length); + } + + yield return new FoldingRegion (txt, + new DomRegion (comment.Region.Begin, end), + FoldType.Comment); + i = j - 1; + } + } + } + + static string SubstrEllipsize (string str, int start, int length) + { + //TODO: would be nice to ellipsize fold labels to a specific column, ideally the the formatting + // policy's desired width. However, we would have to know the "real" start column, i.e. respecting + // tab widths. Maybe that would work best by performing the ellipsis in the editor, instead of the parser. + const int TRUNC_LEN = 60; + + if (str.Length == 0 || length == 0) + return " ..."; + + if (!(start == 0 && length <= TRUNC_LEN)) { + if (length > TRUNC_LEN) { + length = TRUNC_LEN; + int wordBoundaryLen = str.LastIndexOf (' ', length) - start; + if (wordBoundaryLen > TRUNC_LEN - 20) + length = wordBoundaryLen; + } + str = str.Substring (start, length); + } + + if (str [str.Length - 1] == '.') + return str + ".."; + else if (char.IsPunctuation (str [str.Length - 1])) + return str + " ..."; + return str + "..."; + } + + public static IEnumerable<FoldingRegion> FlagIfInsideMembers (this IEnumerable<FoldingRegion> folds, + IEnumerable<ITypeDefinition> types, Action<FoldingRegion> flagAction) + { + foreach (FoldingRegion fold in folds) { + foreach (var type in types) { + if (fold.Region.IsInsideMember (type)) { + flagAction (fold); + break; + } + } + yield return fold; + } + } + + static bool IsInsideMember (this DomRegion region, ITypeDefinition cl) + { + if (region.IsEmpty || cl == null || !cl.BodyRegion.IsInside (region.Begin)) + return false; + foreach (var member in cl.Members) { + if (member.BodyRegion.IsEmpty) + continue; + if (member.BodyRegion.IsInside (region.Begin) && member.BodyRegion.IsInside (region.End)) + return true; + } + foreach (var inner in cl.InnerClasses) { + if (region.IsInsideMember (inner)) + return true; + } + return false; + } + } +} + diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/PreProcessorDefine.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/PreProcessorDefine.cs new file mode 100644 index 0000000000..7ae4c78c03 --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/PreProcessorDefine.cs @@ -0,0 +1,58 @@ +// PreProcessorDefine.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +using System; +using ICSharpCode.NRefactory.CSharp; + +namespace MonoDevelop.TypeSystem +{ + public class PreProcessorDefine + { + public string Define { + get; + set; + } + + public AstLocation Location { + get; + set; + } + + public PreProcessorDefine () + { + } + + public PreProcessorDefine (string define, AstLocation location) + { + this.Define = define; + this.Location = location; + } + + public override string ToString () + { + return string.Format ("[PreProcessorDefine: Define={0}, Location={1}]", Define, Location); + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/StockIcons.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/StockIcons.cs new file mode 100644 index 0000000000..763eda348f --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/StockIcons.cs @@ -0,0 +1,213 @@ +// +// StockIcons.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using MonoDevelop.Core; +using ICSharpCode.NRefactory.TypeSystem; +using Mono.Cecil; + +namespace MonoDevelop.TypeSystem +{ + public static class Stock + { + static readonly IconId Error = "gtk-dialog-error"; + static readonly IconId Class = "md-class"; + static readonly IconId Enum = "md-enum"; + static readonly IconId Event = "md-event"; + static readonly IconId Field = "md-field"; + static readonly IconId Interface = "md-interface"; + static readonly IconId Method = "md-method"; + static readonly IconId ExtensionMethod = "md-extensionmethod"; + static readonly IconId Property = "md-property"; + static readonly IconId Struct = "md-struct"; + static readonly IconId Delegate = "md-delegate"; + static readonly IconId Namespace = "md-name-space"; + static readonly IconId InternalClass = "md-internal-class"; + static readonly IconId InternalDelegate = "md-internal-delegate"; + static readonly IconId InternalEnum = "md-internal-enum"; + static readonly IconId InternalEvent = "md-internal-event"; + static readonly IconId InternalField = "md-internal-field"; + static readonly IconId InternalInterface = "md-internal-interface"; + static readonly IconId InternalMethod = "md-internal-method"; + static readonly IconId InternalExtensionMethod = "md-internal-extensionmethod"; + static readonly IconId InternalProperty = "md-internal-property"; + static readonly IconId InternalStruct = "md-internal-struct"; + static readonly IconId PrivateClass = "md-private-class"; + static readonly IconId PrivateDelegate = "md-private-delegate"; + static readonly IconId PrivateEnum = "md-private-enum"; + static readonly IconId PrivateEvent = "md-private-event"; + static readonly IconId PrivateField = "md-private-field"; + static readonly IconId PrivateInterface = "md-private-interface"; + static readonly IconId PrivateMethod = "md-private-method"; + static readonly IconId PrivateExtensionMethod = "md-private-extensionmethod"; + static readonly IconId PrivateProperty = "md-private-property"; + static readonly IconId PrivateStruct = "md-private-struct"; + static readonly IconId ProtectedClass = "md-protected-class"; + static readonly IconId ProtectedDelegate = "md-protected-delegate"; + static readonly IconId ProtectedEnum = "md-protected-enum"; + static readonly IconId ProtectedEvent = "md-protected-event"; + static readonly IconId ProtectedField = "md-protected-field"; + static readonly IconId ProtectedInterface = "md-protected-interface"; + static readonly IconId ProtectedMethod = "md-protected-method"; + static readonly IconId ProtectedExtensionMethod = "md-protected-extensionmethod"; + static readonly IconId ProtectedProperty = "md-protected-property"; + static readonly IconId ProtectedStruct = "md-protected-struct"; + + static IconId[,] typeIconTable = new IconId[,] { + {Class, PrivateClass, ProtectedClass, InternalClass}, // class + {Enum, PrivateEnum, ProtectedEnum, InternalEnum}, // enum + {Interface, PrivateInterface, ProtectedInterface, InternalInterface}, // interface + {Struct, PrivateStruct, ProtectedStruct, InternalStruct}, // struct + {Delegate, PrivateDelegate, ProtectedDelegate, InternalDelegate} // delegate + }; + static readonly IconId[] fieldIconTable = {Stock.Field, Stock.PrivateField, Stock.ProtectedField, Stock.InternalField}; + static readonly IconId[] methodIconTable = {Stock.Method, Stock.PrivateMethod, Stock.ProtectedMethod, Stock.InternalMethod}; + static readonly IconId[] extensionMethodIconTable = {Stock.ExtensionMethod, Stock.PrivateExtensionMethod, Stock.ProtectedExtensionMethod, Stock.InternalExtensionMethod}; + static readonly IconId[] propertyIconTable = {Stock.Property, Stock.PrivateProperty, Stock.ProtectedProperty, Stock.InternalProperty}; + static readonly IconId[] eventIconTable = {Stock.Event, Stock.PrivateEvent, Stock.ProtectedEvent, Stock.InternalEvent}; + + static int ModifierToOffset (Accessibility acc) + { + if ((acc & Accessibility.Private) == Accessibility.Private) + return 1; + if ((acc & Accessibility.Protected) == Accessibility.Protected) + return 2; + if ((acc & Accessibility.Internal) == Accessibility.Internal) + return 3; + return 0; + } + + public static string GetStockIcon (this INamedElement element) + { + if (element is IType) + return ((IType)element).GetStockIcon (); + return ((IEntity)element).GetStockIcon (); + } + + public static string GetStockIcon (this ITypeDefinition entity) + { + return GetStockIcon ((IType)entity); + } + + public static string GetStockIcon (this IType entity) + { + return typeIconTable [(int)entity.GetDefinition ().ClassType, ModifierToOffset (entity.GetDefinition ().Accessibility)]; + } + + public static string GetStockIcon (this IEntity entity) + { + switch (entity.EntityType) { + case EntityType.TypeDefinition: + return GetStockIcon ((IType)entity); + case EntityType.Field: + return fieldIconTable [ModifierToOffset (entity.Accessibility)]; + case EntityType.Method: + case EntityType.Constructor: + case EntityType.Destructor: + case EntityType.Operator: + if (((IMethod)entity).IsExtensionMethod) + return extensionMethodIconTable [ModifierToOffset (entity.Accessibility)]; + return methodIconTable [ModifierToOffset (entity.Accessibility)]; + case EntityType.Property: + case EntityType.Indexer: + return propertyIconTable [ModifierToOffset (entity.Accessibility)]; + case EntityType.Event: + return eventIconTable [ModifierToOffset (entity.Accessibility)]; + } + return ""; + } + + + static int ModifierToOffset (TypeAttributes acc) + { + if ((acc & TypeAttributes.Public) == TypeAttributes.Public) + return 0; + if ((acc & TypeAttributes.NestedFamily) == TypeAttributes.NestedFamily) + return 2; + if ((acc & TypeAttributes.NestedAssembly) == TypeAttributes.NestedAssembly) + return 3; + return 1; + } + + public static string GetStockIcon (this TypeDefinition type) + { + int ct; + if (type.IsEnum) { + ct = 1; + } else if (type.IsInterface) { + ct = 2; + } else if (type.IsValueType) { + ct = 3; + } else if (type.BaseType != null && (type.BaseType.FullName == "System.Delegate" || type.BaseType.FullName == "System.MulticastDelegate")) { + ct = 4; + } else { + ct = 0; + } + return typeIconTable [ct, ModifierToOffset (type.Attributes)]; + } + + static int ModifierToOffset (MethodAttributes acc) + { + if ((acc & MethodAttributes.Public) == MethodAttributes.Public) + return 0; + if ((acc & MethodAttributes.Family) == MethodAttributes.Family) + return 2; + if ((acc & MethodAttributes.Assembly) == MethodAttributes.Assembly) + return 3; + return 1; + } + + public static string GetStockIcon (this MethodDefinition method) + { + return methodIconTable [ModifierToOffset (method.Attributes)]; + } + + static int ModifierToOffset (FieldAttributes acc) + { + if ((acc & FieldAttributes.Public) == FieldAttributes.Public) + return 0; + if ((acc & FieldAttributes.Family) == FieldAttributes.Family) + return 2; + if ((acc & FieldAttributes.Assembly) == FieldAttributes.Assembly) + return 3; + return 1; + } + + public static string GetStockIcon (this FieldDefinition field) + { + return fieldIconTable [ModifierToOffset (field.Attributes)]; + } + + public static string GetStockIcon (this PropertyDefinition property) + { + return propertyIconTable [property.GetMethod != null ? ModifierToOffset (property.GetMethod.Attributes) : ModifierToOffset (property.SetMethod.Attributes)]; + } + + public static string GetStockIcon (this EventDefinition evt) + { + return eventIconTable [evt.AddMethod != null ? ModifierToOffset (evt.AddMethod.Attributes) : ModifierToOffset (evt.RemoveMethod.Attributes)]; + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Tag.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Tag.cs new file mode 100644 index 0000000000..1e15e5c50a --- /dev/null +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/Tag.cs @@ -0,0 +1,81 @@ +// +// Tag.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// TypeParameter.cs +// +// Author: +// Mike Krüger <mkrueger@novell.com> +// +// Copyright (C) 2008 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +using System; +using ICSharpCode.NRefactory.TypeSystem; + +namespace MonoDevelop.TypeSystem +{ + [Serializable] + public class Tag : Comment + { + string key; + + public string Key { + get { + return key; + } + } + + public Tag (string key, DomRegion region) + { + this.key = key; + base.Region = region; + } + + public Tag (string key, string comment, DomRegion region) : base (comment) + { + this.key = key; + base.Region = region; + } + } +} diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemProviderNode.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemProviderNode.cs index ab690fa7ef..6c8c1aad8e 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemProviderNode.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemProviderNode.cs @@ -24,7 +24,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; -using MonoDevelop.Projects.Dom.Parser; using Mono.Addins; using System.Collections; using System.Linq; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemService.cs index bb8c032742..47fe605069 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemService.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.TypeSystem/TypeSystemService.cs @@ -28,7 +28,6 @@ using System.Collections.Generic; using System.Linq; using System.IO; using MonoDevelop.Projects; -using ICSharpCode.Decompiler.Ast; using Mono.Cecil; using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.NRefactory.CSharp; @@ -36,9 +35,58 @@ using ICSharpCode.NRefactory.TypeSystem; using Mono.Addins; using MonoDevelop.Core; using MonoDevelop.Ide; +using Mono.TextEditor; namespace MonoDevelop.TypeSystem { + public static class TypeSystemServiceExt + { + public static Project GetProject (this IProjectContent content) + { + foreach (var pair in TypeSystemService.projectContents) { + if (pair.Value == content) + return pair.Key; + } + return null; + } + + public static Project GetSourceProject (this ITypeDefinition type) + { + return type.ProjectContent.GetProject (); + } + + public static Project GetSourceProject (this IType type) + { + return type.GetDefinition ().GetSourceProject (); + } + + public static IProjectContent GetProjectContent (this IType type) + { + return type.GetDefinition ().ProjectContent; + } + + public static AstLocation GetLocation (this IType type) + { + return new AstLocation (type.GetDefinition ().Region.BeginLine, type.GetDefinition ().Region.BeginColumn); + } + + public static string GetDocumentation (this IType type) + { + return "TODO"; + } + + public static bool IsBaseType (this IType type, ITypeResolveContext ctx, IType potentialBase) + { + return type.GetAllBaseTypes (ctx).Any (t => t.Equals (potentialBase)); + } + + public static bool IsObsolete (this IEntity member) + { + // TODO: Implement me! + return false; + } + } + public static class TypeSystemService { static List<TypeSystemProviderNode> parsers; @@ -70,20 +118,47 @@ namespace MonoDevelop.TypeSystem return provider != null ? provider.Provider : null; } - public static IParsedFile ParseFile (IProjectContent projectContent, string fileName, string mimeType, TextReader content) + public static ParsedDocument ParseFile (Project project, string fileName) + { + return ParseFile (GetProjectContext (project), fileName, DesktopService.GetMimeTypeForUri (fileName), File.ReadAllText (fileName)); + } + + public static ParsedDocument ParseFile (IProjectContent projectContent, string fileName, string mimeType, TextReader content) { + if (projectContent == null) + throw new ArgumentNullException ("projectContent"); var provider = GetProvider (mimeType); if (provider == null) return null; - return provider.Parse (projectContent, fileName, content); + if (ParseOperationStarted != null) + ParseOperationStarted (null, EventArgs.Empty); + ParsedDocument result = null; + try { + IsParsing = true; + result = provider.Parse (projectContent, true, fileName, content); + ((SimpleProjectContent)projectContent).UpdateProjectContent (projectContent.GetFile (fileName), result); + if (ParseOperationFinished != null) + ParseOperationFinished (null, EventArgs.Empty); + } finally { + IsParsing = false; + } + return result; } - - public static IParsedFile ParseFile (IProjectContent projectContent, string fileName, string mimeType, string content) + public static bool IsParsing = false; + public static event EventHandler ParseOperationStarted; + public static event EventHandler ParseOperationFinished; + + public static ParsedDocument ParseFile (IProjectContent projectContent, string fileName, string mimeType, string content) { using (var reader = new StringReader (content)) return ParseFile (projectContent, fileName, mimeType, reader); } + public static ParsedDocument ParseFile (IProjectContent projectContent, TextEditorData data) + { + return ParseFile (projectContent, data.FileName, data.MimeType, data.Text); + } + #region Project loading public static void Load (WorkspaceItem item) { @@ -94,21 +169,24 @@ namespace MonoDevelop.TypeSystem ws.ItemAdded += OnWorkspaceItemAdded; ws.ItemRemoved += OnWorkspaceItemRemoved; } else if (item is Solution) { + DateTime start = DateTime.Now; var solution = (Solution)item; foreach (Project project in solution.GetAllProjects ()) Load (project); solution.SolutionItemAdded += OnSolutionItemAdded; solution.SolutionItemRemoved += OnSolutionItemRemoved; + Console.WriteLine ("solution parse: " + (DateTime.Now - start).TotalMilliseconds); } } - static Dictionary<Project, IProjectContent> projectContents = new Dictionary<Project, IProjectContent> (); + internal static Dictionary<Project, IProjectContent> projectContents = new Dictionary<Project, IProjectContent> (); static Dictionary<Project, int> referenceCounter = new Dictionary<Project, int> (); public static IProjectContent LoadContent (Project project) { + DateTime start = DateTime.Now; var content = new SimpleProjectContent (); - + int files = 0; foreach (var file in project.Files) { if (!string.Equals (file.BuildAction, "compile", StringComparison.OrdinalIgnoreCase)) continue; @@ -116,12 +194,13 @@ namespace MonoDevelop.TypeSystem var provider = GetProvider (DesktopService.GetMimeTypeForUri (file.FilePath)); if (provider == null) continue; - + files++; using (var stream = new System.IO.StreamReader (file.FilePath)) { - var parsedFile = provider.Parse (content, file.FilePath, stream); + var parsedFile = provider.Parse (content, false, file.FilePath, stream); content.UpdateProjectContent (null, parsedFile); } } + Console.WriteLine (files + " project parse: " + (DateTime.Now - start).TotalMilliseconds); return content; } @@ -212,14 +291,14 @@ namespace MonoDevelop.TypeSystem static void OnProjectReferenceAdded (object sender, ProjectReferenceEventArgs args) { -// ProjectDom db = GetProjectDom (args.Project); +// ITypeResolveContext db = GetProjectDom (args.Project); // if (db != null) // db.OnProjectReferenceAdded (args.ProjectReference); } static void OnProjectReferenceRemoved (object sender, ProjectReferenceEventArgs args) { -// ProjectDom db = GetProjectDom (args.Project); +// ITypeResolveContext db = GetProjectDom (args.Project); // if (db != null) // db.OnProjectReferenceRemoved (args.ProjectReference); } @@ -273,24 +352,39 @@ namespace MonoDevelop.TypeSystem } } - static ITypeResolveContext LoadAssemblyContext (string fileName) + public static ITypeResolveContext GetAssemblyContext (string fileName) { - List<ITypeResolveContext> contexts = new List<ITypeResolveContext> (); var asm = ReadAssembly (fileName); if (asm == null) return null; - foreach (var module in asm.Modules) - contexts.Add (new CecilTypeResolveContext (module)); - return new CompositeTypeResolveContext (contexts); + return new CecilLoader ().LoadAssembly (asm); + } + + public static ITypeResolveContext GetAssemblyContext (MonoDevelop.Core.Assemblies.TargetRuntime runtime, string fileName) + { // TODO: Runtimes + var asm = ReadAssembly (fileName); + if (asm == null) + return null; + return new CecilLoader ().LoadAssembly (asm); } public static IProjectContent GetProjectContext (Project project) { + if (project == null) + return null; IProjectContent content; projectContents.TryGetValue (project, out content); return content; } + public static ITypeResolveContext GetContext (FilePath file, string mimeType, string text) + { + SimpleProjectContent content = new SimpleProjectContent (); + var parsedFile = ParseFile (content, file, mimeType, text); + content.UpdateProjectContent (null, parsedFile); + return content; + } + public static ITypeResolveContext GetContext (Project project) { List<ITypeResolveContext> contexts = new List<ITypeResolveContext> (); @@ -321,7 +415,7 @@ namespace MonoDevelop.TypeSystem ITypeResolveContext ctx; if (!assemblyContents.TryGetValue (refId, out ctx)) { try { - assemblyContents [refId] = ctx = LoadAssemblyContext (fileName); + assemblyContents [refId] = ctx = GetAssemblyContext (fileName); } catch (Exception) { } } |