public GenerateNamespaceImport GetResult (ProjectDom dom, ICompilationUnit unit, IType type, TextEditorData data)
		{
			GenerateNamespaceImport result;
			if (cache.TryGetValue (type.Namespace, out result))
				return result;
			result = new GenerateNamespaceImport ();
			cache[type.Namespace] = result;
			
			result.InsertNamespace  = false;
			
			DomLocation location = new DomLocation (data.Caret.Line, data.Caret.Column);
			foreach (IUsing u in unit.Usings.Where (u => u.ValidRegion.Contains (location))) {
				if (u.Namespaces.Any (ns => type.Namespace == ns)) {
					result.GenerateUsing = false;
					return result;
				}
			}
			result.GenerateUsing = true;
			string name = type.DecoratedFullName.Substring (type.Namespace.Length + 1);
			
			foreach (IUsing u in unit.Usings.Where (u => u.ValidRegion.Contains (location))) {
				foreach (string ns in u.Namespaces) {
					if (dom.SearchType (unit, unit.GetTypeAt (location), unit.GetMemberAt (location), ns + "." + name) != null) {
						result.GenerateUsing = false;
						result.InsertNamespace = true;
						return result;
					}
				}
			}
			return result;
		}
		public static void Format (TextEditorData data, ProjectDom dom, DomLocation location, bool correctBlankLines)
		{
			PolicyContainer policyParent = dom != null && dom.Project != null? dom.Project.Policies
				: PolicyService.DefaultPolicies;
			var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			Format (policyParent, mimeTypeChain, data, dom, location, correctBlankLines);
		}
		public override bool IsValid (RefactoringOptions options)
		{
			INRefactoryASTProvider provider = options.GetASTProvider ();
			IResolver resolver = options.GetResolver ();
			if (provider == null || resolver == null)
				return false;
			if (invoke == null)
				invoke = GetInvocationExpression (options);
			if (invoke == null)
				return false;
			returnType = DomReturnType.Void;
			modifiers = ICSharpCode.NRefactory.Ast.Modifiers.None;
			resolvePosition = new DomLocation (options.Document.Editor.Caret.Line + 1, options.Document.Editor.Caret.Column + 1);
			ResolveResult resolveResult = resolver.Resolve (new ExpressionResult (provider.OutputNode (options.Dom, invoke)), resolvePosition);
			
			if (resolveResult is MethodResolveResult) {
				MethodResolveResult mrr = (MethodResolveResult)resolveResult ;
				if (mrr.ExactMethodMatch)
					return false;
				returnType = mrr.MostLikelyMethod.ReturnType;
				modifiers = (ICSharpCode.NRefactory.Ast.Modifiers)mrr.MostLikelyMethod.Modifiers;
			}
			
			if (invoke.TargetObject is MemberReferenceExpression) {
				string callingObject = provider.OutputNode (options.Dom, ((MemberReferenceExpression)invoke.TargetObject).TargetObject);
				resolveResult = resolver.Resolve (new ExpressionResult (callingObject), resolvePosition);
				if (resolveResult == null || resolveResult.ResolvedType == null || resolveResult.CallingType == null)
					return false;
				IType type = options.Dom.GetType (resolveResult.ResolvedType);
				return type != null && type.CompilationUnit != null && File.Exists (type.CompilationUnit.FileName) && RefactoringService.GetASTProvider (DesktopService.GetMimeTypeForUri (type.CompilationUnit.FileName)) != null;
			}
			return invoke.TargetObject is IdentifierExpression;
		}
		public static void Write (BinaryWriter writer, INameEncoder nameTable, DomLocation location)
		{
			if (WriteNull (writer, location)) 
				return;
			writer.Write (location.Line);
			writer.Write (location.Column);
		}
		public static void Format (MonoDevelop.Ide.Gui.Document data, ProjectDom dom, DomLocation location, bool correctBlankLines, bool runAferCR = false)
		{
			PolicyContainer policyParent = dom != null && dom.Project != null ? dom.Project.Policies
 : PolicyService.DefaultPolicies;
			var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			Format (policyParent, mimeTypeChain, data, dom, location, correctBlankLines, runAferCR);
		}
Exemple #6
0
 public UsingScope GetUsingScope(DomLocation location)
 {
     foreach (UsingScope scope in usingScopes) {
         if (scope.Region.IsInside(location.Line, location.Column))
             return scope;
     }
     return rootUsingScope;
 }
Exemple #7
0
 public ITypeDefinition GetTopLevelTypeDefinition(DomLocation location)
 {
     foreach (ITypeDefinition typeDef in topLevelTypeDefinitions) {
         if (typeDef.Region.IsInside(location.Line, location.Column))
             return typeDef;
     }
     return null;
 }
Exemple #8
0
 public virtual IType SearchType(ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, string decoratedFullName)
 {
     if (string.IsNullOrEmpty(decoratedFullName))
     {
         return(null);
     }
     return(SearchType(unit, callingClass, lookupLocation, decoratedFullName, null));
 }
Exemple #9
0
 public virtual IType SearchType(ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, IReturnType returnType)
 {
     if (returnType == null)
     {
         return(null);
     }
     return(SearchType(unit, callingClass, lookupLocation, returnType.DecoratedFullName, returnType.GenericArguments));
 }
        public ResolveResult ResolveExpression(Expression expr, DomLocation resolvePosition)
        {
            this.expr = expr;
            this.SetupResolver(resolvePosition);
            ResolveVisitor visitor = new ResolveVisitor(this);
            ResolveResult  result  = visitor.Resolve(expr);

            return(result);
        }
        public override INode Visit(IMethod source, IType data)
        {
            currentMethod   = source;
            resolvePosition = source.Location;
            INode res = base.Visit(source, data);

            currentMethod = null;
            return(res);
        }
Exemple #12
0
        void Init(NRefactoryResolver resolver, MonoDevelop.Projects.Dom.INode searchedMember)
        {
            this.resolver = resolver;
            if (searchedMember is IMember)
            {
                searchedMember = GetUnderlyingMember((IMember)searchedMember);
            }

            this.searchedMember          = searchedMember;
            this.IncludeXmlDocumentation = false;

            if (searchedMember is IMethod)
            {
                IMethod method = (IMethod)searchedMember;
                this.searchedMemberName     = method.IsConstructor ? method.DeclaringType.Name : method.Name;
                this.searchedMemberLocation = method.Location;
                if (method.DeclaringType != null && method.DeclaringType.CompilationUnit != null)
                {
                    this.searchedMemberFile = method.DeclaringType.CompilationUnit.FileName;
                }
            }
            else if (searchedMember is IMember)
            {
                this.searchedMemberName     = ((IMember)searchedMember).Name;
                this.searchedMemberLocation = ((IMember)searchedMember).Location;

                if (searchedMember is IType)
                {
                    this.searchedMemberFile = ((IType)searchedMember).CompilationUnit.FileName;
                }
                else
                {
                    if (((IMember)searchedMember).DeclaringType != null && ((IMember)searchedMember).DeclaringType.CompilationUnit != null)
                    {
                        this.searchedMemberFile = ((IMember)searchedMember).DeclaringType.CompilationUnit.FileName;
                    }
                }
            }
            else if (searchedMember is IParameter)
            {
                this.searchedMemberName     = ((IParameter)searchedMember).Name;
                this.searchedMemberLocation = ((IParameter)searchedMember).Location;
                if (((IParameter)searchedMember).DeclaringMember.DeclaringType.CompilationUnit != null)
                {
                    this.searchedMemberFile = ((IParameter)searchedMember).DeclaringMember.DeclaringType.CompilationUnit.FileName;
                }
            }
            else if (searchedMember != null)
            {
                this.searchedMemberName     = ((LocalVariable)searchedMember).Name;
                this.searchedMemberLocation = ((LocalVariable)searchedMember).Region.Start;
                if (((LocalVariable)searchedMember).CompilationUnit != null)
                {
                    this.searchedMemberFile = ((LocalVariable)searchedMember).CompilationUnit.FileName;
                }
            }
        }
 public static void Write(BinaryWriter writer, INameEncoder nameTable, DomLocation location)
 {
     if (WriteNull(writer, location))
     {
         return;
     }
     writer.Write(location.Line);
     writer.Write(location.Column);
 }
Exemple #14
0
        public static DomLocation Location2DomLocation(Location inLocation)
        {
            DomLocation outLocation = new DomLocation()
            {
                Id      = inLocation.Id,
                Address = inLocation.Address
            };

            return(outLocation);
        }
 public static IType GetTypeAtCursor(IType outerType, string fileName, DomLocation position)
 {
     foreach (IType type in outerType.InnerTypes)
     {
         if (type.BodyRegion.Contains(position))
         {
             return(GetTypeAtCursor(type, fileName, position));
         }
     }
     return(outerType);
 }
Exemple #16
0
/*		void TextCut (object sender, ReplaceEventArgs e)
 *              {
 *                      if (!string.IsNullOrEmpty (e.Value) || e.Count == 0)
 *                              return;
 *                      RunFormatterAt (e.Offset);
 *              }*/

        void RunFormatterAt(int offset)
        {
            if (PropertyService.Get("OnTheFlyFormatting", false) && textEditorData != null && Document != null)
            {
                //	textEditorData.Document.TextReplaced -= TextCut;
                ProjectDom       dom      = Document.Dom;
                DocumentLocation loc      = textEditorData.Document.OffsetToLocation(offset);
                DomLocation      location = new DomLocation(loc.Line, loc.Column);
                CSharpFormatter.Format(textEditorData, dom, Document.CompilationUnit, location);
                //	textEditorData.Document.TextReplaced += TextCut;
            }
        }
		public void ReadWriteLocationTest ()
		{
			DomLocation input = new DomLocation (3, 9);
			MemoryStream ms = new MemoryStream ();
			BinaryWriter writer = new BinaryWriter (ms);
			DomPersistence.Write (writer, null, input);
			byte[] bytes = ms.ToArray ();
			
			DomLocation result = DomPersistence.ReadLocation (CreateReader (bytes), null);
			Assert.AreEqual (3, result.Line);
			Assert.AreEqual (9, result.Column);
		}
Exemple #18
0
        void ForceSpacesAfter(INode node, int tokenLength, bool forceSpaces)
        {
            DomLocation location = ((ICSharpNode)node).StartLocation;
            int         offset   = data.Document.LocationToOffset(location.Line, location.Column) + 1;
            int         i        = offset;

            while (i < data.Document.Length && Char.IsWhiteSpace(data.Document.GetCharAt(i)))
            {
                i++;
            }
            ForceSpace(offset - 1, i, forceSpaces);
        }
		public ContextActionWidget (ContextActionEditorExtension ext, MonoDevelop.Ide.Gui.Document document, DomLocation loc, List<ContextAction> fixes)
		{
			this.ext = ext;
			this.document = document;
			this.loc = loc;
			this.fixes = fixes;
			Events = Gdk.EventMask.AllEventsMask;
			icon = ImageService.GetPixbuf ("md-text-quickfix", Gtk.IconSize.Menu);
			this.SetSizeRequest (Math.Max ((int)document.Editor.LineHeight , icon.Width) + 4, (int)document.Editor.LineHeight + 4);
			ShowAll ();
			document.Editor.Parent.EditorOptionsChanged += HandleDocumentEditorParentEditorOptionsChanged;
			;
		}
 public ContextActionWidget(ContextActionEditorExtension ext, MonoDevelop.Ide.Gui.Document document, DomLocation loc, List <ContextAction> fixes)
 {
     this.ext      = ext;
     this.document = document;
     this.loc      = loc;
     this.fixes    = fixes;
     Events        = Gdk.EventMask.AllEventsMask;
     icon          = ImageService.GetPixbuf("md-text-quickfix", Gtk.IconSize.Menu);
     this.SetSizeRequest(Math.Max((int)document.Editor.LineHeight, icon.Width) + 4, (int)document.Editor.LineHeight + 4);
     ShowAll();
     document.Editor.Parent.EditorOptionsChanged += HandleDocumentEditorParentEditorOptionsChanged;
     ;
 }
		public void CreateWidget (List<ContextAction> fixes, DomLocation loc)
		{
			if (!fixes.Any ())
				return;
			
			widget = new ContextActionWidget (this, Document, loc, fixes);
			var container = Document.Editor.Parent.Parent as TextEditorContainer;
			if (container == null) 
				return;
			container.AddTopLevelWidget (widget,
				2 + (int)Document.Editor.Parent.TextViewMargin.XOffset,
				-2 + (int)document.Editor.Parent.LineToY (document.Editor.Caret.Line));
			widget.Show ();
		}
        /// <summary>
        /// Formats a text document directly with insert/remove operations.
        /// </summary>
        /// <param name="textEditorData">
        /// A <see cref="System.Object"/> that must be from type Mono.TextEditorData.
        /// </param>
        /// <param name="dom">
        /// A <see cref="ProjectDom"/>
        /// </param>
        /// <param name="unit">
        /// A <see cref="ICompilationUnit"/>
        /// </param>
        /// <param name="caretLocation">
        /// A <see cref="DomLocation"/> 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)
        {
            var adv = formatter as IAdvancedCodeFormatter;

            if (adv == null || !adv.SupportsOnTheFlyFormatting)
            {
                throw new InvalidOperationException("On the fly formatting not supported");
            }

            adv.OnTheFlyFormat(policyParent ?? PolicyService.DefaultPolicies, mimeTypeChain,
                               data, callingType, callingMember, dom, unit, endLocation);
        }
Exemple #23
0
        int ForceSpacesBefore(INode node, bool forceSpaces)
        {
            DomLocation location = ((ICSharpNode)node).StartLocation;

            int offset = data.Document.LocationToOffset(location.Line, location.Column);
            int i      = offset - 1;

            while (i >= 0 && Char.IsWhiteSpace(data.Document.GetCharAt(i)))
            {
                i--;
            }
            ForceSpace(i, offset, forceSpaces);
            return(i);
        }
Exemple #24
0
        public void ReadWriteLocationTest()
        {
            DomLocation  input  = new DomLocation(3, 9);
            MemoryStream ms     = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(ms);

            DomPersistence.Write(writer, null, input);
            byte[] bytes = ms.ToArray();

            DomLocation result = DomPersistence.ReadLocation(CreateReader(bytes), null);

            Assert.AreEqual(3, result.Line);
            Assert.AreEqual(9, result.Column);
        }
 public static IType GetTypeAtCursor(ICompilationUnit unit, string fileName, DomLocation position)
 {
     if (unit == null)
     {
         return(null);
     }
     foreach (IType type in unit.Types)
     {
         if (type.BodyRegion.Contains(position))
         {
             return(GetTypeAtCursor(type, fileName, position));
         }
     }
     return(null);
 }
		public override void CursorPositionChanged ()
		{
			RemoveWidget ();
			
			if (Document.ParsedDocument != null) {
				DomLocation loc = new DomLocation (Document.Editor.Caret.Line, Document.Editor.Caret.Column);
				RefactoringService.QueueQuickFixAnalysis (Document, loc, delegate(List<ContextAction> fixes) {
					Application.Invoke (delegate {
						RemoveWidget ();
						CreateWidget (fixes, loc);
					});
				});
			}
			base.CursorPositionChanged ();
		}
Exemple #27
0
        public static List <InsertionPoint> GetInsertionPoints(Document doc, IType type)
        {
            if (doc == null)
            {
                throw new ArgumentNullException("doc");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            List <InsertionPoint> result = new List <InsertionPoint> ();

            int offset = doc.LocationToOffset(type.BodyRegion.Start.Line - 1, type.BodyRegion.Start.Column);

            if (offset < 0)
            {
                return(result);
            }
            while (offset < doc.Length && doc.GetCharAt(offset) != '{' && char.IsWhiteSpace(doc.GetCharAt(offset)))
            {
                offset++;
            }
            var realStartLocation = doc.OffsetToLocation(offset);

            result.Add(GetInsertionPosition(doc, 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 = doc.GetLine(member.Location.Line - 1);
                    if (lineSegment == null)
                    {
                        continue;
                    }
                    domLocation = new DomLocation(member.Location.Line, lineSegment.EditableLength + 1);
                }
                result.Add(GetInsertionPosition(doc, domLocation.Line - 1, domLocation.Column - 1));
            }
            result[result.Count - 1].LineAfter = NewLineInsertion.None;
            CheckStartPoint(doc, result[0], result.Count == 1);
            if (result.Count > 1)
            {
                CheckEndPoint(doc, result[result.Count - 1], result.Count == 1);
            }
            return(result);
        }
Exemple #28
0
        public override void CursorPositionChanged()
        {
            RemoveWidget();

            if (Document.ParsedDocument != null && Document.Editor != null && Document.Editor.Caret != null)
            {
                DomLocation loc = new DomLocation(Document.Editor.Caret.Line, Document.Editor.Caret.Column);
                RefactoringService.QueueQuickFixAnalysis(Document, loc, delegate(List <ContextAction> fixes) {
                    Application.Invoke(delegate {
                        RemoveWidget();
                        CreateWidget(fixes, loc);
                    });
                });
            }
            base.CursorPositionChanged();
        }
Exemple #29
0
        private InsertionPoint GetInsertionPoint(MonoDevelop.Ide.Gui.Document document, IType type)
        {
            data = document.Editor;
            if (data == null)
            {
                throw new System.ArgumentNullException("data");
            }
            var parsedDocument = document.ParsedDocument;

            if (parsedDocument == null)
            {
                throw new System.ArgumentNullException("parsedDocument");
            }
            if (type == null)
            {
                throw new System.ArgumentNullException("type");
            }
            type = (parsedDocument.CompilationUnit.GetTypeAt(type.Location) ?? type);
            DomRegion domRegion = type.BodyRegion;
            var       start     = type.BodyRegion.Start.Line;

            indent = data.GetLine(start).GetIndentation(data.Document);
            DomLocation domLocation = domRegion.End;
            int         num         = data.LocationToOffset(domLocation.Line, 1);

            while (num < data.Length && data.GetCharAt(num) != '}')
            {
                num++;
            }
            num++;
            DocumentLocation documentLocation = data.OffsetToLocation(num);

            LineSegment      lineAfterClassEnd = data.GetLine(domLocation.Line + 1);
            NewLineInsertion lineAfter;

            if (lineAfterClassEnd != null && lineAfterClassEnd.EditableLength == lineAfterClassEnd.GetIndentation(data.Document).Length)
            {
                lineAfter = NewLineInsertion.BlankLine;
            }
            else
            {
                lineAfter = NewLineInsertion.None;
            }

            return(new InsertionPoint(documentLocation, NewLineInsertion.None, lineAfter));
        }
        public static IEnumerable <FoldingRegion> ToPythonFolds(this IList <Comment> comments)
        {
            for (int i = 0; i < comments.Count; i++)
            {
                Comment comment = comments[i];

                if (comment.CommentType == CommentType.MultiLine)
                {
                    yield return(new FoldingRegion("...", comment.Region, FoldType.Comment));

                    continue;
                }

                if (!comment.CommentStartsLine)
                {
                    continue;
                }
                int         j       = i;
                int         curLine = comment.Region.Start.Line - 1;
                DomLocation end     = comment.Region.End;

                for (; j < comments.Count; j++)
                {
                    Comment curComment = comments[j];
                    if (curComment == null || !curComment.CommentStartsLine ||
                        curComment.CommentType != comment.CommentType ||
                        curLine + 1 != curComment.Region.Start.Line)
                    {
                        break;
                    }
                    end     = curComment.Region.End;
                    curLine = curComment.Region.Start.Line;
                }

                if (j - i > 1)
                {
                    yield return(new FoldingRegion(
                                     comment.IsDocumentation  ? "/// " : "// " + comment.Text + "...",
                                     new DomRegion(comment.Region.Start.Line,
                                                   comment.Region.Start.Column, end.Line, end.Column),
                                     FoldType.Comment));

                    i = j - 1;
                }
            }
        }
Exemple #31
0
        public override bool IsValid(RefactoringOptions options)
        {
            INRefactoryASTProvider provider = options.GetASTProvider();
            IResolver resolver = options.GetResolver();

            if (provider == null || resolver == null)
            {
                return(false);
            }
            if (invoke == null)
            {
                invoke = GetInvocationExpression(options);
            }
            if (invoke == null)
            {
                return(false);
            }
            returnType      = DomReturnType.Void;
            modifiers       = ICSharpCode.NRefactory.Ast.Modifiers.None;
            resolvePosition = new DomLocation(options.Document.TextEditor.CursorLine, options.Document.TextEditor.CursorColumn);
            ResolveResult resolveResult = resolver.Resolve(new ExpressionResult(provider.OutputNode(options.Dom, invoke)), resolvePosition);

            if (resolveResult is MethodResolveResult)
            {
                MethodResolveResult mrr = (MethodResolveResult)resolveResult;
                if (mrr.ExactMethodMatch)
                {
                    return(false);
                }
                returnType = mrr.MostLikelyMethod.ReturnType;
                modifiers  = (ICSharpCode.NRefactory.Ast.Modifiers)mrr.MostLikelyMethod.Modifiers;
            }

            if (invoke.TargetObject is MemberReferenceExpression)
            {
                string callingObject = provider.OutputNode(options.Dom, ((MemberReferenceExpression)invoke.TargetObject).TargetObject);
                resolveResult = resolver.Resolve(new ExpressionResult(callingObject), resolvePosition);
                if (resolveResult == null || resolveResult.ResolvedType == null || resolveResult.CallingType == null)
                {
                    return(false);
                }
                IType type = options.Dom.GetType(resolveResult.ResolvedType);
                return(type != null && type.CompilationUnit != null && File.Exists(type.CompilationUnit.FileName) && RefactoringService.GetASTProvider(DesktopService.GetMimeTypeForUri(type.CompilationUnit.FileName)) != null);
            }
            return(invoke.TargetObject is IdentifierExpression);
        }
        internal void SetupResolver(DomLocation resolvePosition)
        {
            this.resolvePosition = resolvePosition;
            this.resultTable.Clear();
            callingType = GetTypeAtCursor(unit, fileName, resolvePosition);

            if (callingType != null)
            {
                callingMember = GetMemberAt(callingType, fileName, resolvePosition);
                callingType   = dom.ResolveType(callingType);
                if (callingMember == null)
                {
                    DomLocation posAbove = resolvePosition;
                    posAbove.Line--;
                    callingMember = GetMemberAt(callingType, fileName, posAbove);
                }
            }

            if (memberCompilationUnit != null)
            {
                return;
            }
            if (callingMember != null && !setupLookupTableVisitor)
            {
                string wrapper = CreateWrapperClassForMember(callingMember, fileName, editor);
                using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(lang, new StringReader(wrapper))) {
                    parser.Parse();
                    memberCompilationUnit = parser.CompilationUnit;
                    lookupTableVisitor.VisitCompilationUnit(parser.CompilationUnit, null);
                    lookupVariableLine      = CallingMember.Location.Line - 2;
                    setupLookupTableVisitor = true;
                }
            }
            else if (editor != null)
            {
                string wrapper = editor.Text;
                using (ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(lang, new StringReader(wrapper))) {
                    parser.Parse();
                    memberCompilationUnit = parser.CompilationUnit;
                    lookupTableVisitor.VisitCompilationUnit(parser.CompilationUnit, null);
                    lookupVariableLine      = 0;
                    setupLookupTableVisitor = true;
                }
            }
        }
        void RunFormatter()
        {
            if (PropertyService.Get("OnTheFlyFormatting", false) && textEditorData != null && !(textEditorData.CurrentMode is TextLinkEditMode))
            {
                //		textEditorData.Document.TextReplaced -= TextCut;
                ProjectDom dom = ProjectDomService.GetProjectDom(Document.Project);
                if (dom == null)
                {
                    dom = ProjectDomService.GetFileDom(Document.FileName);
                }

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

                //		textEditorData.Document.TextReplaced += TextCut;
            }
        }
Exemple #34
0
		public static void Format (TextEditorData data, ProjectDom dom, DomLocation location)
		{
			CSharp.Dom.CompilationUnit compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			IEnumerable<string> types = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType);
			CSharpFormattingPolicy policy = dom.Project.Policies != null ? dom.Project.Policies.Get<CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<CSharpFormattingPolicy> (types);
			DomSpacingVisitor domSpacingVisitor = new DomSpacingVisitor (policy, data);
			domSpacingVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			DomIndentationVisitor domIndentationVisitor = new DomIndentationVisitor (policy, data);
			domIndentationVisitor.AutoAcceptChanges = false;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);
			
			List<Change> changes = new List<Change> ();
			changes.AddRange (domSpacingVisitor.Changes);
			changes.AddRange (domIndentationVisitor.Changes);
			RefactoringService.AcceptChanges (null, null, changes);
		}
Exemple #35
0
        MemberReferenceCollection GetReferences(RefactoringOptions options)
        {
            CodeRefactorer   refactorer = IdeApp.Workspace.GetCodeRefactorer(IdeApp.ProjectOperations.CurrentSelectedSolution);
            IProgressMonitor monitor    = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(this.Name, null);

            if (options.SelectedItem is IType)
            {
                IType cls = (IType)options.SelectedItem;
                return(refactorer.FindClassReferences(monitor, cls, RefactoryScope.Solution, true));
            }
            else if (options.SelectedItem is LocalVariable)
            {
                return(refactorer.FindVariableReferences(monitor, (LocalVariable)options.SelectedItem));
            }
            else if (options.SelectedItem is IParameter)
            {
                return(refactorer.FindParameterReferences(monitor, (IParameter)options.SelectedItem, true));
            }
            else if (options.SelectedItem is IMember)
            {
                IMember member = (IMember)options.SelectedItem;
                Dictionary <string, HashSet <DomLocation> > foundLocations = new Dictionary <string, HashSet <DomLocation> > ();
                MemberReferenceCollection result = new MemberReferenceCollection();
                foreach (IMember m in CollectMembers(member.DeclaringType.SourceProjectDom, member))
                {
                    foreach (MemberReference r in refactorer.FindMemberReferences(monitor, m.DeclaringType, m, true))
                    {
                        DomLocation location = new DomLocation(r.Line, r.Column);
                        if (!foundLocations.ContainsKey(r.FileName))
                        {
                            foundLocations[r.FileName] = new HashSet <DomLocation> ();
                        }
                        if (foundLocations[r.FileName].Contains(location))
                        {
                            continue;
                        }
                        foundLocations[r.FileName].Add(location);
                        result.Add(r);
                    }
                }
                return(result);
            }
            return(null);
        }
Exemple #36
0
        public void CreateWidget(List <ContextAction> fixes, DomLocation loc)
        {
            if (!fixes.Any())
            {
                return;
            }

            widget = new ContextActionWidget(this, Document, loc, fixes);
            var container = Document.Editor.Parent.Parent as TextEditorContainer;

            if (container == null)
            {
                return;
            }
            container.AddTopLevelWidget(widget,
                                        2 + (int)Document.Editor.Parent.TextViewMargin.XOffset,
                                        -2 + (int)document.Editor.Parent.LineToY(document.Editor.Caret.Line));
            widget.Show();
        }
 internal static IMember GetMemberAt(IType type, string fileName, DomLocation location)
 {
     foreach (IMember member in type.Members)
     {
         if (member.DeclaringType.CompilationUnit.FileName != fileName)
         {
             continue;
         }
         if (!(member is IMethod || member is IProperty || member is IEvent || member is IField))
         {
             continue;
         }
         if (member.Location.Line == location.Line || (!member.BodyRegion.IsEmpty && member.BodyRegion.Start <= location && (location < member.BodyRegion.End || member.BodyRegion.End.IsEmpty)))
         {
             return(member);
         }
     }
     return(null);
 }
Exemple #38
0
        Parser(Parser copyFrom)
        {
            buildTree = false;

            rootState     = copyFrom.rootState;
            currentState  = copyFrom.currentState;
            previousState = copyFrom.previousState;

            position           = copyFrom.position;
            location           = copyFrom.location;
            stateTag           = copyFrom.stateTag;
            keywordBuilder     = new StringBuilder(copyFrom.keywordBuilder.ToString());
            currentStateLength = copyFrom.currentStateLength;

            //clone the node stack
            List <XObject> l = new List <XObject> (CopyXObjects(copyFrom.nodes));

            l.Reverse();
            nodes = new NodeStack(l);
        }
Exemple #39
0
        void RunFormatter()
        {
            if (PropertyService.Get("OnTheFlyFormatting", false) && textEditorData != null)
            {
                textEditorData.Paste -= TextEditorDataPaste;
                //		textEditorData.Document.TextReplaced -= TextCut;
                ProjectDom dom = ProjectDomService.GetProjectDom(Document.Project);
                if (dom == null)
                {
                    dom = ProjectDomService.GetFileDom(Document.FileName);
                }

                DomLocation location = new DomLocation(textEditorData.Caret.Location.Line, textEditorData.Caret.Location.Column);
                CSharpFormatter.Format(textEditorData, dom, Document.CompilationUnit, location);
//				OnTheFlyFormatter.Format (textEditorData, dom, location);

                //		textEditorData.Document.TextReplaced += TextCut;
                textEditorData.Paste += TextEditorDataPaste;
            }
        }
Exemple #40
0
        void ForceSpacesAfter(AstNode n, bool forceSpaces)
        {
            if (n == null)
            {
                return;
            }
            DomLocation location = n.EndLocation;
            int         offset   = data.Document.LocationToOffset(location.Line, location.Column);

            if (offset < 0)
            {
                return;
            }
            int i = offset;

            while (i < data.Document.Length && IsSpacing(data.Document.GetCharAt(i)))
            {
                i++;
            }
            ForceSpace(offset - 1, i, forceSpaces);
        }
		public static void Format (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain,
			TextEditorData data, ProjectDom dom, DomLocation location, bool correctBlankLines)
		{
			var compilationUnit = new MonoDevelop.CSharp.Parser.CSharpParser ().Parse (data);
			var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
			var domSpacingVisitor = new DomSpacingVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			compilationUnit.AcceptVisitor (domSpacingVisitor, null);
			
			var domIndentationVisitor = new DomIndentationVisitor (policy, data) {
				AutoAcceptChanges = false,
			};
			domIndentationVisitor.CorrectBlankLines = correctBlankLines;
			compilationUnit.AcceptVisitor (domIndentationVisitor, null);
			
			var changes = new List<Change> ();
			changes.AddRange (domSpacingVisitor.Changes);
			changes.AddRange (domIndentationVisitor.Changes);
			RefactoringService.AcceptChanges (null, null, changes);
		}
Exemple #42
0
        public GenerateNamespaceImport GetResult(ProjectDom dom, ICompilationUnit unit, IType type, TextEditorData data)
        {
            GenerateNamespaceImport result;

            if (cache.TryGetValue(type.Namespace, out result))
            {
                return(result);
            }
            result = new GenerateNamespaceImport();
            cache[type.Namespace] = result;

            result.InsertNamespace = false;

            DomLocation location = new DomLocation(data.Caret.Line, data.Caret.Column);

            foreach (IUsing u in unit.Usings.Where(u => u.ValidRegion.Contains(location)))
            {
                if (u.Namespaces.Any(ns => type.Namespace == ns))
                {
                    result.GenerateUsing = false;
                    return(result);
                }
            }
            result.GenerateUsing = true;
            string name = type.DecoratedFullName.Substring(type.Namespace.Length + 1);

            foreach (IUsing u in unit.Usings.Where(u => u.ValidRegion.Contains(location)))
            {
                foreach (string ns in u.Namespaces)
                {
                    if (dom.SearchType(unit, unit.GetTypeAt(location), location, ns + "." + name) != null)
                    {
                        result.GenerateUsing   = false;
                        result.InsertNamespace = true;
                        return(result);
                    }
                }
            }
            return(result);
        }
Exemple #43
0
        public static int CalculateBodyIndentLevel(IType declaringType)
        {
            int   indentLevel = 0;
            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);
        }
		public NRefactoryTemplateParameterDataProvider (TextEditorData editor, NRefactoryResolver resolver, IEnumerable<string> namespaces, ExpressionResult expressionResult, DomLocation loc)
		{
//			this.editor = editor;
			ResolveResult plainResolveResult = resolver.Resolve (expressionResult, loc);
			MethodResolveResult resolveResult = plainResolveResult as MethodResolveResult;
			if (resolveResult != null) {
				foreach (IMethod method in resolveResult.Methods) {
					if (method.TypeParameters.Count > 0)
						this.types.Add (method);
				}
			} else {
				string typeName = expressionResult.Expression.Trim ();
				foreach (string ns in namespaces) {
					string prefix = ns + (ns.Length > 0 ? "." : "") + typeName + "`";
					for (int i = 1; i < 99; i++) {
						IType possibleType = resolver.Dom.GetType (prefix + i);
						if (possibleType != null)
							this.types.Add (possibleType);
					}
				}
				IType resolvedType = plainResolveResult != null ? resolver.Dom.GetType (plainResolveResult.ResolvedType) : null;
				if (resolvedType == null) {
					int idx = expressionResult.Expression.LastIndexOf (".");
					if (idx < 0)
						return;
					typeName = expressionResult.Expression.Substring (idx + 1);
					expressionResult.Expression = expressionResult.Expression.Substring (0, idx);
					plainResolveResult = resolver.Resolve (expressionResult, loc);
					resolvedType = resolver.Dom.GetType (plainResolveResult.ResolvedType);
				}
				if (resolvedType == null)
					return;
				foreach (IType innerType in resolvedType.InnerTypes) {
					this.types.Add (innerType);
				}
			}
		}
		public unsafe ParsedDocument Parse (string fileName, string content)
		{
			var regionStack = new Stack<Tuple<string, DomLocation>> ();
			var result = new ParsedDocument (fileName);
			bool inSingleComment = false, inMultiLineComment = false;
			bool inString = false, inVerbatimString = false;
			bool inChar = false;
			bool inLineStart = true, hasStartedAtLine = false;
			int line = 1, column = 1;
			var startLoc = DomLocation.Empty;
			
			fixed (char* startPtr = content) {
				char* endPtr = startPtr + content.Length;
				char* ptr = startPtr;
				char* beginPtr = ptr;
				while (ptr < endPtr) {
					switch (*ptr) {
					case '#':
						if (!inLineStart)
							break;
						ptr++;

						if (StartsIdentifier (ptr, endPtr, "region")) {
							var regionLocation = new DomLocation (line, column);
							column++;
							ptr += "region".Length;
							column += "region".Length;
							SkipWhitespaces (ref ptr, endPtr, ref column);
							regionStack.Push (Tuple.Create (ReadToEol (content, ref ptr, endPtr, ref line, ref column), regionLocation));
							continue;
						} else if (StartsIdentifier (ptr, endPtr, "endregion")) {
							column++;
							ptr += "endregion".Length;
							column += "endregion".Length;
							if (regionStack.Count > 0) {
								var beginRegion = regionStack.Pop ();
								result.Add (new FoldingRegion (
									beginRegion.Item1, 
									new DomRegion (beginRegion.Item2.Line, beginRegion.Item2.Column, line, column),
									FoldType.UserRegion,
									true));
							}
							continue;
						} else {
							column++;
						}
						break;
					case '/':
						if (inString || inChar || inVerbatimString || inMultiLineComment || inSingleComment)
							break;
						if (ptr + 1 < endPtr) {
							char nextCh = *(ptr + 1);
							if (nextCh == '/') {
								hasStartedAtLine = inLineStart;
								beginPtr = ptr + 2;
								startLoc = new DomLocation (line, column);
								ptr++;
								column++;
								inSingleComment = true;
							} else if (nextCh == '*') {
								hasStartedAtLine = inLineStart;
								beginPtr = ptr + 2;
								startLoc = new DomLocation (line, column);
								ptr++;
								column++;
								inMultiLineComment = true;
							}
						}
						break;
					case '*':
						if (inString || inChar || inVerbatimString || inSingleComment)
							break;
						if (inMultiLineComment && ptr + 1 < endPtr) {
							if (ptr + 1 < endPtr && *(ptr + 1) == '/') {
								ptr += 2;
								column += 2;
								inMultiLineComment = false;
								result.Add (new Comment () {
									Region = new DomRegion (startLoc, new DomLocation (line, column)),
									CommentType = CommentType.MultiLine,
									Text = content.Substring ((int)(beginPtr - startPtr), (int)(ptr - beginPtr)),
									CommentStartsLine = hasStartedAtLine
								});
								continue;
							}
						}
						break;
					case '@':
						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
							break;
						if (ptr + 1 < endPtr && *(ptr + 1) == '"') {
							ptr++;
							column++;
							inVerbatimString = true;
						}
						break;
					case '\n':
						if (inSingleComment) {
							bool isDocumentation = *beginPtr == '/';
							if (isDocumentation)
								beginPtr++;
							result.Add (new Comment () { 
								Region = new DomRegion (startLoc, new DomLocation (line, column)),
								CommentType = CommentType.SingleLine, 
								Text = content.Substring ((int)(beginPtr - startPtr), (int)(ptr - beginPtr)),
								CommentStartsLine = hasStartedAtLine,
								IsDocumentation = isDocumentation
							});
							inSingleComment = false;
						}
						inString = false;
						inChar = false;
						inLineStart = true;
						line++;
						column = 1;
						ptr++;
						continue;
					case '\r':
						if (ptr + 1 < endPtr && *(ptr + 1) == '\n')
							ptr++;
						goto case '\n';
					case '\\':
						if (inString || inChar)
							ptr++;
						break;
					case '"':
						if (inSingleComment || inMultiLineComment || inChar)
							break;
						if (inVerbatimString) {
							if (ptr + 1 < endPtr && *(ptr + 1) == '"') {
								ptr++;
								column++;
								break;
							}
							inVerbatimString = false;
							break;
						}
						inString = !inString;
						break;
					case '\'':
						if (inSingleComment || inMultiLineComment || inString || inVerbatimString)
							break;
						inChar = !inChar;
						break;
					}

					column++;
					ptr++;
				}
			}
			return result;
		}
Exemple #46
0
/*		public virtual IType SearchType (SearchTypeRequest request)
		{
			return SearchType (request.Name, request.CallingType, request.CurrentCompilationUnit, request.GenericParameters);
		}*/
		
		internal IType SearchType (ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, string name, IList<IReturnType> genericParameters)
		{
			// TODO dom check generic parameter count
			if (string.IsNullOrEmpty (name))
				return null;
			
			IType result = null;
			// It may be one of the generic parameters in the calling class
			if (genericParameters == null || genericParameters.Count == 0) {
				if (callingClass != null) {
					result = FindGenericParameter (unit, ResolveType (callingClass), name);
					if (result != null)
						return result;
				}
			}
			
			// A known type?
			result = GetType (name, genericParameters, false, true);
			if (result != null)
				return result;

			// Maybe an inner type that isn't fully qualified?
			if (callingClass != null) {
				IType t = ResolveType (callingClass);
				result = SearchInnerType (t, name.Split ('.'), 0, genericParameters != null ? genericParameters.Count : 0, true);
				if (result != null) {
					if (genericParameters != null && genericParameters.Count > 0) 
						return CreateInstantiatedGenericType (result, genericParameters);
					return result;
				}
			}
			// If the name matches an alias, try using the alias first.
			if (unit != null) {
				IReturnType ualias = FindAlias (name, unit.Usings);
				if (ualias != null) {
					// Don't provide the compilation unit when trying to resolve the alias,
					// since aliases are not affected by other 'using' directives.
					result = GetType (ualias.FullName, ualias.GenericArguments, false, true);
					if (result != null)
						return result;
				}
			}
			
			// The enclosing namespace has preference over the using directives.
			// Check it now.
			if (callingClass != null) {
				List<int> indices = new List<int> ();
				string str = callingClass.FullName;
				for (int i = 0; i < str.Length; i++) {
					if (str[i] == '.')
						indices.Add (i);
				}
				for (int n = indices.Count - 1; n >= 0; n--) {
					if (n < 1)
						continue;
					string curnamespace = str.Substring (0, indices[n] + 1);
					result = GetType (curnamespace + name, genericParameters, false, true);
					if (result != null)
						return result;
				}
			}
			
			// Now try to find the class using the included namespaces
			if (unit != null) {
				// it's a difference having using A; namespace B { } or namespace B { using A;  }, when a type 
				// request equals a namespace name; for example the type B could be resolved in the 2nd case when a type
				// A.B exists but not in the 1st.
				foreach (IUsing u in unit.Usings.Reverse ()) {
					if (u.Namespaces.Contains (name)) 
						return null;
					if (callingClass != null && !u.ValidRegion.Contains (lookupLocation))
						continue;
					if (u != null) {
						result = SearchType (u, name, genericParameters, true);
						if (result != null)
							return result;
					}
				}
			}
			
			return null;
		}
Exemple #47
0
		public virtual IType SearchType (ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, IReturnType returnType)
		{
			if (returnType == null)
				return null;
			return SearchType (unit, callingClass, lookupLocation, returnType.DecoratedFullName,returnType.GenericArguments);
		}
Exemple #48
0
		public virtual IType SearchType (ICompilationUnit unit, IType callingClass, DomLocation lookupLocation, string decoratedFullName)
		{
			if (string.IsNullOrEmpty (decoratedFullName))
				return null;
			return SearchType (unit, callingClass, lookupLocation, decoratedFullName, null);
		}
		void VisitPreprocessorDirective (ParsedDocument result, SpecialsBag.PreProcessorDirective directive)
		{
			DomLocation loc = new DomLocation (directive.Line, directive.Col);
			switch (directive.Cmd) {
			case Tokenizer.PreprocessorDirective.If:
				conditionalRegions.Push (new ConditionalRegion (visitor.Text));
				ifBlocks.Push (directive);
				ConditionalRegion.Start = loc;
				break;
			case Tokenizer.PreprocessorDirective.Elif:
				CloseConditionBlock (new DomLocation (directive.EndLine, directive.EndCol));
				if (ConditionalRegion != null)
					ConditionalRegion.ConditionBlocks.Add (new ConditionBlock (visitor.Text, loc));
				break;
			case Tokenizer.PreprocessorDirective.Else:
				CloseConditionBlock (new DomLocation (directive.EndLine, directive.EndCol));
				if (ConditionalRegion != null)
					ConditionalRegion.ElseBlock = new DomRegion (loc, DomLocation.Empty);
				break;
			case Tokenizer.PreprocessorDirective.Endif:
				DomLocation endLoc = new DomLocation (directive.EndLine, directive.EndCol);
				CloseConditionBlock (endLoc);
				if (ConditionalRegion != null && !ConditionalRegion.ElseBlock.Start.IsEmpty)
					ConditionalRegion.ElseBlock = new DomRegion (ConditionalRegion.ElseBlock.Start, endLoc);
				AddCurRegion (result, directive.EndLine, directive.EndCol);
				if (ifBlocks.Count > 0) {
					var ifBlock = ifBlocks.Pop ();
					DomRegion dr = new DomRegion (ifBlock.Line, ifBlock.Col, directive.EndLine, directive.EndCol);
					result.Add (new FoldingRegion ("#if " + ifBlock.Arg.Trim (), dr, FoldType.UserRegion, false));
					foreach (var d in elifBlocks) {
						dr.Start = new DomLocation (d.Line, d.Col);
						result.Add (new FoldingRegion ("#elif " + ifBlock.Arg.Trim (), dr, FoldType.UserRegion, false));
					}
					if (elseBlock != null) {
						dr.Start = new DomLocation (elseBlock.Line, elseBlock.Col);
						result.Add (new FoldingRegion ("#else", dr, FoldType.UserRegion, false));
					}
				}
				elseBlock = null;
				break;
			case Tokenizer.PreprocessorDirective.Define:
				result.Add (new PreProcessorDefine (directive.Arg, loc));
				break;
			case Tokenizer.PreprocessorDirective.Region:
				regions.Push (directive);
				break;
			case Tokenizer.PreprocessorDirective.Endregion:
				if (regions.Count > 0) {
					var start = regions.Pop ();
					DomRegion dr = new DomRegion (start.Line, start.Col, directive.EndLine, directive.EndCol);
					result.Add (new FoldingRegion (start.Arg, dr, FoldType.UserRegion, true));
				}
				break;
			}
		}
		void CloseConditionBlock (DomLocation loc)
		{
			if (ConditionalRegion == null || ConditionalRegion.ConditionBlocks.Count == 0 || !ConditionalRegion.ConditionBlocks[ConditionalRegion.ConditionBlocks.Count - 1].End.IsEmpty)
				return;
			ConditionalRegion.ConditionBlocks[ConditionalRegion.ConditionBlocks.Count - 1].End = loc;
		}
		ICompletionDataList CreateCaseCompletionData (DomLocation location, ExpressionResult expressionResult)
		{
			NRefactoryResolver resolver = CreateResolver ();
			
			resolver.SetupResolver (location);
			
			SwitchFinder switchFinder = new SwitchFinder (location);
			if (resolver.MemberCompilationUnit != null)
				switchFinder.VisitCompilationUnit (resolver.MemberCompilationUnit, null);
			CompletionDataList result = new ProjectDomCompletionDataList ();
			if (switchFinder.SwitchStatement == null)
				return result;
			ResolveResult resolveResult = resolver.ResolveExpression (switchFinder.SwitchStatement.SwitchExpression, location);
			IType type = dom.GetType (resolveResult.ResolvedType);
			if (type != null && type.ClassType == ClassType.Enum) {
				OutputFlags flags = OutputFlags.None;
				var declaringType = resolver.CallingType;
				if (declaringType != null && dom != null) {
					foreach (IType t in new List<IType>(dom.GetInheritanceTree (declaringType))) {
						if (t.SearchMember (type.Name, true).Any (m => m.MemberType != MonoDevelop.Projects.Dom.MemberType.Type)) {
							flags |= OutputFlags.UseFullName;
							break;
						}
					}
				}
//				if (!foundType && (NamePrefix.Length == 0 || !type.Namespace.StartsWith (NamePrefix)) && !type.Namespace.EndsWith ("." + NamePrefix) && type.DeclaringType == null && NamePrefix != null && !NamePrefix.Contains ("::"))
//					flags |= OutputFlags.UseFullName;
				CompletionDataCollector cdc = new CompletionDataCollector (dom, result, Document.CompilationUnit, resolver.CallingType, location);
				cdc.Add (type, flags);
			}
			return result;
		}
Exemple #52
0
		public static void Format (TextEditorData data, ProjectDom dom, ICompilationUnit unit, DomLocation caretLocation)
		{
			IType type = NRefactoryResolver.GetTypeAtCursor (unit, unit.FileName, caretLocation);
			if (type == null)
				return;
			Format (data, type, NRefactoryResolver.GetMemberAt (type, unit.FileName, caretLocation), dom, unit, caretLocation);
		}
Exemple #53
0
		public override void OnTheFlyFormat (object textEditorData, IType type, IMember member, ProjectDom dom, ICompilationUnit unit, DomLocation caretLocation)
		{
			Format ((TextEditorData)textEditorData, type, member, dom, unit, caretLocation);
		}
		public override void AddLocalNamespaceImport (RefactorerContext ctx, string fileName, string nsName, DomLocation caretLocation)
		{
			IEditableTextFile file = ctx.GetFile (fileName);
			int pos = 0;
			ParsedDocument parsedDocument = parser.Parse (ctx.ParserContext, fileName, file.Text);
			StringBuilder text = new StringBuilder ();
			string indent = "";
			if (parsedDocument.CompilationUnit != null) {
				IUsing containingUsing = null;
				foreach (IUsing u in parsedDocument.CompilationUnit.Usings) {
					if (u.IsFromNamespace && u.Region.Contains (caretLocation)) {
						containingUsing = u;
					}
				}
				
				if (containingUsing != null) {
					indent = GetLineIndent (file, containingUsing.Region.Start.Line);
					
					IUsing lastUsing = null;
					foreach (IUsing u in parsedDocument.CompilationUnit.Usings) {
						if (u == containingUsing)
							continue;
						if (containingUsing.Region.Contains (u.Region)) {
							if (u.IsFromNamespace)
								break;
							lastUsing = u;
						}
					}
					
					if (lastUsing != null) {
						pos = file.GetPositionFromLineColumn (lastUsing.Region.End.Line, lastUsing.Region.End.Column);
					} else {
						pos = file.GetPositionFromLineColumn (containingUsing.ValidRegion.Start.Line, containingUsing.ValidRegion.Start.Column);
						// search line end
						while (pos < file.Length) {
							char ch = file.GetCharAt (pos);
							if (ch == '\n') {
								if (file.GetCharAt (pos + 1) == '\r')
									pos++;
								break;
							} else if (ch == '\r') {
								break;
							}
							pos++;
						}
					}
					
				} else {
					AddGlobalNamespaceImport (ctx, fileName, nsName);
					return;
				}
			}
			if (pos != 0)
				text.AppendLine ();
			text.Append (indent);
			text.Append ("\t");
			text.Append ("using ");
			text.Append (nsName);
			text.Append (";");
			if (pos == 0)
				text.AppendLine ();
			if (file is Mono.TextEditor.ITextEditorDataProvider) {
				Mono.TextEditor.TextEditorData data = ((Mono.TextEditor.ITextEditorDataProvider)file).GetTextEditorData ();
				int caretOffset = data.Caret.Offset;
				int insertedChars = data.Insert (pos, text.ToString ());
				if (pos < caretOffset) {
					data.Caret.Offset = caretOffset + insertedChars;
				}
			} else {
				file.InsertText (pos, text.ToString ());
			} 
		}
		public override DomLocation CompleteStatement (RefactorerContext ctx, string fileName, DomLocation caretLocation)
		{
			IEditableTextFile file = ctx.GetFile (fileName);
			int pos = file.GetPositionFromLineColumn (caretLocation.Line + 1, 1);
			
			StringBuilder line = new StringBuilder ();
			int lineNr = caretLocation.Line + 1, column = 1, maxColumn = 1, lastPos = pos;
			
			while (lineNr == caretLocation.Line + 1) {
				maxColumn = column;
				lastPos = pos;
				line.Append (file.GetCharAt (pos));
				pos++;
				file.GetLineColumnFromPosition (pos, out lineNr, out column);
			}
			string trimmedline = line.ToString ().Trim ();
			string indent      = line.ToString ().Substring (0, line.Length - line.ToString ().TrimStart (' ', '\t').Length);
			if (trimmedline.EndsWith (";") || trimmedline.EndsWith ("{"))
				return caretLocation;
			if (trimmedline.StartsWith ("if") || 
			    trimmedline.StartsWith ("while") ||
			    trimmedline.StartsWith ("switch") ||
			    trimmedline.StartsWith ("for") ||
			    trimmedline.StartsWith ("foreach")) {
				if (!trimmedline.EndsWith (")")) {
					file.InsertText (lastPos, " () {" + Environment.NewLine + indent + TextEditorProperties.IndentString + Environment.NewLine + indent + "}");
					caretLocation.Column = maxColumn + 1;
				} else {
					file.InsertText (lastPos, " {" + Environment.NewLine + indent + TextEditorProperties.IndentString + Environment.NewLine + indent + "}");
					caretLocation.Column = indent.Length + 1;
					caretLocation.Line++;
				}
			} else if (trimmedline.StartsWith ("do")) {
				file.InsertText (lastPos, " {" + Environment.NewLine + indent + TextEditorProperties.IndentString + Environment.NewLine + indent + "} while ();");
				caretLocation.Column = indent.Length + 1;
				caretLocation.Line++;
			} else {
				file.InsertText (lastPos, ";" + Environment.NewLine + indent);
				caretLocation.Column = indent.Length;
				caretLocation.Line++;
			}
			return caretLocation;
		}
		public ICompletionDataList HandleKeywordCompletion (CodeCompletionContext completionContext, ExpressionResult result, int wordStart, string word)
		{
			if (stateTracker.Engine.IsInsideDocLineComment || stateTracker.Engine.IsInsideOrdinaryCommentOrString)
				return null;
			DomLocation location = new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
			switch (word) {
			case "using":
				if (result.ExpressionContext != ExpressionContext.NamespaceNameExcepted)
					return null;
				return CreateCompletionData (location, new NamespaceResolveResult (""), result, null);
			case "namespace":
				result.ExpressionContext = ExpressionContext.NamespaceNameExcepted;
				return CreateCompletionData (location, new NamespaceResolveResult (""), result, null);
			case "case":
				return CreateCaseCompletionData (location, result);
			case ",":
			case ":":
				if (result.ExpressionContext == ExpressionContext.InheritableType) {
					IType cls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
					CompletionDataList completionList = new ProjectDomCompletionDataList ();
					List<string> namespaceList = GetUsedNamespaces ();
					CSharpTextEditorCompletion.CompletionDataCollector col = new CSharpTextEditorCompletion.CompletionDataCollector (dom, completionList, Document.CompilationUnit, null, location);
					bool isInterface = false;
					HashSet<string> baseTypeNames = new HashSet<string> ();
					if (cls != null) {
						baseTypeNames.Add (cls.Name);
						if (cls.ClassType == ClassType.Struct)
							isInterface = true;
					}
					int tokenIndex = completionContext.TriggerOffset;

										// Search base types " : [Type1, ... ,TypeN,] <Caret>"
					string token = null;
					do {
						token = GetPreviousToken (ref tokenIndex, false);
						if (string.IsNullOrEmpty (token))
							break;
						token = token.Trim ();
						if (Char.IsLetterOrDigit (token[0]) || token[0] == '_') {
							IType baseType = dom.SearchType (Document.CompilationUnit, Document.CompilationUnit, token);
							if (baseType != null) {
								if (baseType.ClassType != ClassType.Interface)
									isInterface = true;
								baseTypeNames.Add (baseType.Name);
							}
						}
					} while (token != ":");
					foreach (object o in dom.GetNamespaceContents (namespaceList, true, true)) {
						IType type = o as IType;
						if (type != null && (type.IsStatic || type.IsSealed || baseTypeNames.Contains (type.Name) || isInterface && type.ClassType != ClassType.Interface)) {
							continue;
						}
						if (o is Namespace && !namespaceList.Any (ns => ns.StartsWith (((Namespace)o).FullName)))
							continue;
						col.Add (o);
					}
					// Add inner classes
					Stack<IType> innerStack = new Stack<IType> ();
					innerStack.Push (cls);
					while (innerStack.Count > 0) {
						IType curType = innerStack.Pop ();
						if (curType == null)
							continue;
						foreach (IType innerType in curType.InnerTypes) {
							if (innerType != cls)
								// don't add the calling class as possible base type
								col.Add (innerType);
						}
						if (curType.DeclaringType != null)
							innerStack.Push (curType.DeclaringType);
					}
					return completionList;
				}
				break;
			case "is":
			case "as":
				
				{
					CompletionDataList completionList = new ProjectDomCompletionDataList ();
					ExpressionResult expressionResult = FindExpression (dom, completionContext, wordStart - textEditorData.Caret.Offset);
					NRefactoryResolver resolver = CreateResolver ();
					ResolveResult resolveResult = resolver.Resolve (expressionResult, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
					if (resolveResult != null && resolveResult.ResolvedType != null) {
						CompletionDataCollector col = new CompletionDataCollector (dom, completionList, Document.CompilationUnit, resolver.CallingType, location);
						IType foundType = null;
						if (word == "as") {
							ExpressionContext exactContext = new NewCSharpExpressionFinder (dom).FindExactContextForAsCompletion (textEditorData, Document.CompilationUnit, Document.FileName, resolver.CallingType);
							if (exactContext is ExpressionContext.TypeExpressionContext) {
								foundType = resolver.SearchType (((ExpressionContext.TypeExpressionContext)exactContext).Type);
								AddAsCompletionData (col, foundType);
							}
						}
					
						if (foundType == null)
							foundType = resolver.SearchType (resolveResult.ResolvedType);
					
						if (foundType != null) {
							if (foundType.ClassType == ClassType.Interface)
								foundType = resolver.SearchType (DomReturnType.Object);
						
							foreach (IType type in dom.GetSubclasses (foundType)) {
								if (type.IsSpecialName || type.Name.StartsWith ("<"))
									continue;
								AddAsCompletionData (col, type);
							}
						}
						List<string> namespaceList = GetUsedNamespaces ();
						foreach (object o in dom.GetNamespaceContents (namespaceList, true, true)) {
							if (o is IType) {
								IType type = (IType)o;
								if (type.ClassType != ClassType.Interface || type.IsSpecialName || type.Name.StartsWith ("<"))
									continue;
//								if (foundType != null && !dom.GetInheritanceTree (foundType).Any (x => x.FullName == type.FullName))
//									continue;
								AddAsCompletionData (col, type);
								continue;
							}
							if (o is Namespace)
								continue;
							col.Add (o);
						}
						return completionList;
					}
					result.ExpressionContext = ExpressionContext.TypeName;
					return CreateCtrlSpaceCompletionData (completionContext, result);
				}
			case "override":
				// Look for modifiers, in order to find the beginning of the declaration
				int firstMod = wordStart;
				int i = wordStart;
				for (int n = 0; n < 3; n++) {
					string mod = GetPreviousToken (ref i, true);
					if (mod == "public" || mod == "protected" || mod == "private" || mod == "internal" || mod == "sealed") {
						firstMod = i;
					} else if (mod == "static") {
						// static methods are not overridable
						return null;
					} else
						break;
				}
				IType overrideCls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				if (overrideCls == null)
					overrideCls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine - 1, 1));
				if (overrideCls != null && (overrideCls.ClassType == ClassType.Class || overrideCls.ClassType == ClassType.Struct)) {
					string modifiers = textEditorData.GetTextBetween (firstMod, wordStart);
					return GetOverrideCompletionData (completionContext, overrideCls, modifiers);
				}
				return null;
			case "partial":
				// Look for modifiers, in order to find the beginning of the declaration
				firstMod = wordStart;
				i = wordStart;
				for (int n = 0; n < 3; n++) {
					string mod = GetPreviousToken (ref i, true);
					if (mod == "public" || mod == "protected" || mod == "private" || mod == "internal" || mod == "sealed") {
						firstMod = i;
					} else if (mod == "static") {
						// static methods are not overridable
						return null;
					} else
						break;
				}
				overrideCls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				if (overrideCls != null && (overrideCls.ClassType == ClassType.Class || overrideCls.ClassType == ClassType.Struct)) {
					string modifiers = textEditorData.GetTextBetween (firstMod, wordStart);
					return GetPartialCompletionData (completionContext, overrideCls, modifiers);
				}
				return null;
				
			case "new":
				IType callingType = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (textEditorData.Caret.Line, textEditorData.Caret.Column));
				ExpressionContext newExactContext = new NewCSharpExpressionFinder (dom).FindExactContextForNewCompletion (textEditorData, Document.CompilationUnit, Document.FileName, callingType);
				if (newExactContext is ExpressionContext.TypeExpressionContext)
					return CreateTypeCompletionData (location, callingType, newExactContext, ((ExpressionContext.TypeExpressionContext)newExactContext).Type, ((ExpressionContext.TypeExpressionContext)newExactContext).UnresolvedType);
				if (newExactContext == null) {
					int j = completionContext.TriggerOffset - 4;
					string token = GetPreviousToken (ref j, true);
					string yieldToken = GetPreviousToken (ref j, true);
					if (token == "return") {
						NRefactoryResolver resolver = CreateResolver ();
						resolver.SetupResolver (new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
						IReturnType returnType = resolver.CallingMember.ReturnType;
						if (yieldToken == "yield" && returnType.GenericArguments.Count > 0)
							returnType = returnType.GenericArguments[0];
						if (resolver.CallingMember != null)
							return CreateTypeCompletionData (location, callingType, newExactContext, null, returnType);
					}
				}
				return CreateCtrlSpaceCompletionData (completionContext, null);
			case "if":
			case "elif":
				if (stateTracker.Engine.IsInsidePreprocessorDirective) 
					return GetDefineCompletionData ();
				return null;
			case "yield":
				CompletionDataList yieldDataList = new CompletionDataList ();
				yieldDataList.DefaultCompletionString = "return";
				yieldDataList.Add ("break", "md-keyword");
				yieldDataList.Add ("return", "md-keyword");
				return yieldDataList;
			case "where":
				CompletionDataList whereDataList = new CompletionDataList ();
				NRefactoryResolver constraintResolver = CreateResolver ();
				constraintResolver.SetupResolver (new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				if (constraintResolver.CallingMember is IMethod) {
					foreach (ITypeParameter tp in ((IMethod)constraintResolver.CallingMember).TypeParameters) {
						whereDataList.Add (tp.Name, "md-keyword");
					}
				} else {
					if (constraintResolver.CallingType != null) {
						foreach (ITypeParameter tp in constraintResolver.CallingType.TypeParameters) {
							whereDataList.Add (tp.Name, "md-keyword");
						}
					}
				}

				return whereDataList;
			}
			if (IsInLinqContext (result)) {
				if (linqKeywords.Contains (word)) {
					if (word == "from") // after from no auto code completion.
						return null;
					result.Expression = "";
					return CreateCtrlSpaceCompletionData (completionContext, result);
				}
				CompletionDataList dataList = new ProjectDomCompletionDataList ();
				CompletionDataCollector col = new CompletionDataCollector (dom, dataList, Document.CompilationUnit, null, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				foreach (string kw in linqKeywords) {
					col.Add (kw, "md-keyword");
				}
				return dataList;
			}
			return null;
		}
			public SwitchFinder (DomLocation location)
			{
				//this.location = new ICSharpCode.NRefactory.Location (location.Column, location.Line);
			}
		public override void OnTheFlyFormat (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, 
			TextEditorData data, IType type, IMember member, ProjectDom dom, ICompilationUnit unit, DomLocation caretLocation)
		{
			//		OnTheFlyFormatter.Format (policyParent, mimeTypeChain, data, dom, caretLocation, true);
		}
		public static void QueueQuickFixAnalysis (MonoDevelop.Ide.Gui.Document doc, DomLocation loc, Action<List<ContextAction>> callback)
		{
			System.Threading.ThreadPool.QueueUserWorkItem (delegate {
				try {
					string disabledNodes = PropertyService.Get ("ContextActions." + doc.Editor.Document.MimeType, "") ?? "";
					
					var availableFixes = new List<ContextAction> (contextActions.Where (fix => disabledNodes.IndexOf (fix.Type.FullName) < 0 && fix.Action.IsValid (doc, loc)).Select (fix => fix.Action));
					var ext = doc.GetContent<MonoDevelop.AnalysisCore.Gui.ResultsEditorExtension> ();
					if (ext != null) {
						foreach (var result in ext.GetResultsAtOffset (doc.Editor.LocationToOffset (loc.Line, loc.Column))) {
							var fresult = result as FixableResult;
							if (fresult == null)
								continue;
							foreach (var action in FixOperationsHandler.GetActions (doc, fresult)) {
								availableFixes.Add (new AnalysisContextAction (result, action));
							}
						}
					}
					
					callback (availableFixes);
				} catch (Exception ex) {
					LoggingService.LogError ("Error in analysis service", ex);
				}
			});
		}	
Exemple #60
0
		public static void Format (TextEditorData data, IType type, IMember member, ProjectDom dom, ICompilationUnit unit, DomLocation caretLocation)
		{
			if (type == null)
				return;
			if (member == null) {
				//				member = type;
				return;
			}
			string wrapper;
			int endPos;
			wrapper = CreateWrapperClassForMember (member, member != type, data, out endPos);
			if (string.IsNullOrEmpty (wrapper) || endPos < 0)
				return;
		//			Console.WriteLine (wrapper);
			
			int bracketIndex = wrapper.IndexOf ('{') + 1;
			int col = GetColumn (wrapper, bracketIndex, data.Options.TabSize);
			
			CSharpFormatter formatter = new CSharpFormatter ();
			formatter.startIndentLevel = System.Math.Max (0, col / data.Options.TabSize - 1);
			
			string formattedText = formatter.InternalFormat (dom != null && dom.Project != null ? dom.Project.Policies : null, MimeType, wrapper, 0, wrapper.Length);
			
			if (formatter.hasErrors)
				return;
			
			int startPos = data.Document.LocationToOffset (member.Location.Line, 1) - 1;
			InFormat = true;
			if (member != type) {
				int len1 = formattedText.IndexOf ('{') + 1;
				int last = formattedText.LastIndexOf ('}');
				formattedText = formattedText.Substring (len1, last - len1 - 1).TrimStart ('\n', '\r');
			} else {
				startPos++;
			}
			
			//Console.WriteLine ("formattedText0:" + formattedText.Replace ("\t", "->").Replace (" ", "°"));
			if (member != type) {
				string indentToRemove = GetIndent (formattedText);
		//				Console.WriteLine ("Remove:" + indentToRemove.Replace ("\t", "->").Replace (" ", "°"));
				formattedText = RemoveIndent (formattedText, indentToRemove);
			} else {
				formattedText = formattedText.TrimStart ();
			}
			//Console.WriteLine ("Indent:" + GetIndent (data, member.Location.Line - 1).Replace ("\t", "->").Replace (" ", "°"));
			//Console.WriteLine ("formattedText1:" + formattedText.Replace ("\t", "->").Replace (" ", "°"));
			formattedText = AddIndent (formattedText, GetIndent (data, member.Location.Line));
			
			Document doc = new Document ();
			doc.Text = formattedText;
			for (int i = doc.LineCount; i --> DocumentLocation.MinLine;) {
				LineSegment lineSegment = doc.GetLine (i);
				if (doc.IsEmptyLine (lineSegment))
					((IBuffer)doc).Remove (lineSegment.Offset, lineSegment.Length);
			}
			formattedText = doc.Text;
			
			//Console.WriteLine ("formattedText3:" + formattedText.Replace ("\t", "->").Replace (" ", "°").Replace ("\n", "\\n").Replace ("\r", "\\r"));
	
			int textLength = CanInsertFormattedText (data, startPos, data.Document.LocationToOffset (caretLocation.Line, caretLocation.Column), formattedText);
			if (textLength > 0) {
//				Console.WriteLine (formattedText.Substring (0, textLength));
				InsertFormattedText (data, startPos, formattedText.Substring (0, textLength).TrimEnd ());
			} else {
				Console.WriteLine ("Can't insert !!!");
			}
			InFormat = false;
		}