public override object VisitComment(Comment comment, object data)
            {
                if (comment.CommentType == CommentType.SingleLine)
                {
                    UnlockWith(comment);
                }

                return base.VisitComment(comment, data);
            }
Exemple #2
0
 string GetDocumentationFromLine(int line)
 {
     foreach (RefParser.ISpecial special in GetSpecialsFromLine(line))
     {
         RefParser.Comment comment = special as RefParser.Comment;
         if (comment != null && comment.CommentType == RefParser.CommentType.Documentation)
         {
             return(comment.CommentText);
         }
     }
     return(null);
 }
        internal void AcceptNodeStart(INode node)
        {
            var doc = node.GetDocumentation();
            if (doc == null)
            {
                return;
            }

            foreach (var line in doc.Lines())
            {
                var comment = new Comment(CommentType.Documentation, line, true, Location.Empty, Location.Empty);
                _formatter.PrintComment(comment, false);
            }
        }
Exemple #4
0
        string GetDocumentation(int line, IList <AST.AttributeSection> attributes)
        {
            foreach (AST.AttributeSection att in attributes)
            {
                if (att.StartLocation.Y > 0 && att.StartLocation.Y < line)
                {
                    line = att.StartLocation.Y;
                }
            }
            List <string> lines  = new List <string>();
            int           length = 0;

            while (line > 0)
            {
                line--;
                string doku = null;
                bool   foundPreprocessing = false;
                var    specialsOnLine     = GetSpecialsFromLine(line);
                foreach (RefParser.ISpecial special in specialsOnLine)
                {
                    RefParser.Comment comment = special as RefParser.Comment;
                    if (comment != null && comment.CommentType == RefParser.CommentType.Documentation)
                    {
                        doku = comment.CommentText;
                        break;
                    }
                    else if (special is RefParser.PreprocessingDirective)
                    {
                        foundPreprocessing = true;
                    }
                }
                if (doku == null && !foundPreprocessing)
                {
                    break;
                }
                if (doku != null)
                {
                    length += 2 + doku.Length;
                    lines.Add(doku);
                }
            }
            StringBuilder b = new StringBuilder(length);

            for (int i = lines.Count - 1; i >= 0; --i)
            {
                b.AppendLine(lines[i]);
            }
            return(b.ToString());
        }
			string RetrieveDocumentation (int upToLine)
			{
				StringBuilder result = null;
				while (lastSpecial < specials.Count) {
					ISpecial cur = specials[lastSpecial];
					if (cur.StartPosition.Line >= upToLine)
						break;
					ICSharpCode.NRefactory.Comment comment = cur as ICSharpCode.NRefactory.Comment;
					if (comment != null && comment.CommentType == ICSharpCode.NRefactory.CommentType.Documentation) {
						if (result == null)
							result = new StringBuilder ();
						result.Append (comment.CommentText);
					}
					lastSpecial++;
				}
				return result == null ? null : result.ToString ();
			}
			public object Visit (ICSharpCode.NRefactory.Comment comment, object data)
			{
				MonoDevelop.Projects.Dom.Comment newComment = new MonoDevelop.Projects.Dom.Comment ();
				newComment.CommentStartsLine = comment.CommentStartsLine;
				newComment.Text = comment.CommentText;
				int commentTagLength = comment.CommentType == ICSharpCode.NRefactory.CommentType.Documentation ? 3 : 2;
				int commentEndOffset = comment.CommentType == ICSharpCode.NRefactory.CommentType.Block ? 0 : 1;
				newComment.Region = new DomRegion (comment.StartPosition.Line, comment.StartPosition.Column - commentTagLength, comment.EndPosition.Line, comment.EndPosition.Column - commentEndOffset);
				switch (comment.CommentType) {
				case ICSharpCode.NRefactory.CommentType.Block:
					newComment.CommentType = MonoDevelop.Projects.Dom.CommentType.MultiLine;
					break;
				case ICSharpCode.NRefactory.CommentType.Documentation:
					newComment.CommentType = MonoDevelop.Projects.Dom.CommentType.SingleLine;
					newComment.IsDocumentation = true;
					break;
				default:
					newComment.CommentType = MonoDevelop.Projects.Dom.CommentType.SingleLine;
					break;
				}

				result.Add (newComment);
				return null;
			}
		void AppendMultilineComment(Comment comment)
		{
			string[] lines = comment.CommentText.Split(new char[] {'\n'});
			for (int i = 0; i < lines.Length; ++i) {
				string line = "# " + lines[i].Trim();
				if ((i == 0) && !comment.CommentStartsLine) {
					codeBuilder.AppendToPreviousLine(" " + line);
				} else {
					AppendIndentedLine(line);
				}
			}
		}
		void IOutputFormatter.PrintComment(Comment comment, bool forceWriteInPreviousBlock)
		{
			if (comment.CommentType == CommentType.SingleLine) {
				AppendSingleLineComment(comment);
			} else if (comment.CommentType == CommentType.Block) {
				AppendMultilineComment(comment);
			} else if (comment.CommentType == CommentType.Documentation) {
				if (SupportsDocstring(currentNode)) {
					xmlDocComments.Add(comment);
				} else {
					AppendSingleLineComment(comment);
				}
			}
		}
		public override void InsertEventHandler(ITypeDefinition target, string name, IEvent eventDefinition, bool jumpTo, InsertEventHandlerBodyKind bodyKind = InsertEventHandlerBodyKind.ThrowNotImplementedException)
		{
			IUnresolvedTypeDefinition match = null;
			
			foreach (var part in target.Parts) {
				if (match == null || EntityModelContextUtils.IsBetterPart(part, match, ".cs"))
					match = part;
			}
			
			if (match == null) return;
			
			var view = SD.FileService.OpenFile(new FileName(match.Region.FileName), jumpTo);
			var editor = view.GetRequiredService<ITextEditor>();
			var last = match.Members.LastOrDefault() ?? (IUnresolvedEntity)match;
			editor.Caret.Location = last.BodyRegion.End;
			var context = SDRefactoringContext.Create(editor, CancellationToken.None);
			
			var node = context.RootNode.GetNodeAt<EntityDeclaration>(last.Region.Begin);
			var resolver = context.GetResolverStateAfter(node);
			var builder = new TypeSystemAstBuilder(resolver);
			var invokeMethod = eventDefinition.ReturnType.GetDelegateInvokeMethod();
			if (invokeMethod == null) return;
			var importedMethod = resolver.Compilation.Import(invokeMethod);
			var delegateDecl = builder.ConvertEntity(importedMethod) as MethodDeclaration;
			if (delegateDecl == null) return;
			var throwStmt = new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")));
			var decl = new MethodDeclaration() {
				ReturnType = delegateDecl.ReturnType.Clone(),
				Name = name,
				Body = new BlockStatement() {
					throwStmt
				}
			};
			var param = delegateDecl.Parameters.Select(p => p.Clone()).ToArray();
			decl.Parameters.AddRange(param);
			
			using (Script script = context.StartScript()) {
				int eolLen = 0;
				if (last == match) {
					eolLen = 2;
					script.AddTo((TypeDeclaration)node, decl);
				} else {
					script.InsertAfter(node, decl);
				}
				switch (bodyKind) {
					case InsertEventHandlerBodyKind.TodoComment:
						Comment comment = new Comment(" TODO: Implement " + name);
						script.Replace(throwStmt, comment);
						script.Select(comment);
						break;
					case InsertEventHandlerBodyKind.Nothing:
						var segment = script.GetSegment(throwStmt);
						if (script is DocumentScript && eolLen > 0) {
							eolLen = ((DocumentScript)script).CurrentDocument.GetLineByOffset(segment.Offset).DelimiterLength;
						}
						script.RemoveText(segment.Offset, segment.Length - eolLen);
						script.Select(segment.Offset, segment.Offset);
						break;
					case InsertEventHandlerBodyKind.ThrowNotImplementedException:
						script.Select(throwStmt);
						break;
				}
			}
		}
 private Func<QuickFixInfo, bool> Predicate(Comment begin_comment, Comment end_comment)
 {
     return x =>
            x.ReplacementSectionStartLine > begin_comment.StartPosition.Line &&
            x.ReplacementSectionEndLine < end_comment.EndPosition.Line;
 }
 private void AppendSingleLineComment(Comment comment)
 {
     if (!comment.CommentStartsLine)
     {
         this.codeBuilder.AppendToPreviousLine(string.Concat(" #", comment.CommentText));
     }
     else
     {
         this.codeBuilder.AppendIndentedLine(string.Concat("#", comment.CommentText));
     }
 }
		object ISpecialVisitor.Visit(Comment special, object data)
		{
			switch (special.CommentType) {
				case CommentType.Documentation:
					if (currentDocuNode == null)
						goto default;
					currentDocuNode.Documentation += special.CommentText;
					break;
				case CommentType.Block:
					WriteSpecialText(true, "/*{0}*/", special.CommentText);
					break;
				default:
					WriteSpecialText(false, "//{0}", special.CommentText);
					break;
			}
			return null;
		}
		void IOutputFormatter.PrintComment(Comment comment, bool forceWriteInPreviousBlock)
		{
			if (comment.CommentType == CommentType.SingleLine) {
				AppendSingleLineComment(comment);
			} else if ((comment.CommentType == CommentType.Block) || (comment.CommentType == CommentType.Documentation)) {
				AppendMultilineComment(comment);
			}
		}
        public void RunVisitor(NRefactoryResolver resolver)
        {
            this.resolver = resolver;
            if (searchedMembers.Count == 0)
            {
                return;
            }
            if (parsers.Count == 0)
            {
                ParseFile(resolver);
            }

            foreach (var p in parsers)
            {
                VisitCompilationUnit(p.CompilationUnit, null);
            }
            var parser = parsers.First();

            if (IncludeXmlDocumentation && searchedMembers.Count > 0)
            {
                var searchedMember = searchedMembers.First().Item1;
                if (searchedMember is IParameter)
                {
                    IParameter parameter   = (IParameter)searchedMember;
                    var        docComments = from ICSharpCode.NRefactory.Comment cmt in
                                             (from ISpecial s in parser.Lexer.SpecialTracker.CurrentSpecials
                                              where s is ICSharpCode.NRefactory.Comment && s.StartPosition.Line <= parameter.DeclaringMember.Location.Line
                                              select s)
                                             select cmt;

                    ICSharpCode.NRefactory.Comment lastComment = null;
                    foreach (ICSharpCode.NRefactory.Comment curComment in docComments.Reverse())
                    {
                        if (lastComment != null && Math.Abs(lastComment.StartPosition.Line - curComment.StartPosition.Line) > 1)
                        {
                            break;
                        }
                        // Concat doesn't work on MatchCollections
                        foreach (var matchCol in new [] { paramRegex.Matches(curComment.CommentText), paramRefRegex.Matches(curComment.CommentText) })
                        {
                            foreach (Match match in matchCol)
                            {
                                if (match.Groups [1].Value == SearchedMemberName)
                                {
                                    AddUniqueReference(curComment.StartPosition.Line, curComment.StartPosition.Column + match.Groups [1].Index, SearchedMemberName);
                                }
                            }
                        }
                        lastComment = curComment;
                    }
                }
                else if (searchedMember is IMember)
                {
                    IMember member      = (IMember)searchedMember;
                    var     docComments = from ICSharpCode.NRefactory.Comment cmt in
                                          (from ISpecial s in parser.Lexer.SpecialTracker.CurrentSpecials
                                           where s is ICSharpCode.NRefactory.Comment
                                           select s)
                                          select cmt;

                    string fullName = member.FullName;

                    foreach (ICSharpCode.NRefactory.Comment curComment in docComments)
                    {
                        // Concat doesn't work on MatchCollections
                        foreach (var matchCol in new [] { seeRegex.Matches(curComment.CommentText), seeAlsoRegRegex.Matches(curComment.CommentText) })
                        {
                            foreach (Match match in matchCol)
                            {
                                if (match.Groups [1].Value.StartsWith(fullName))
                                {
                                    AddUniqueReference(curComment.StartPosition.Line, curComment.StartPosition.Column + match.Groups [1].Index + fullName.Length - SearchedMemberName.Length, SearchedMemberName);
                                }
                            }
                        }
                    }
                }
            }
        }
 public void NodeDocumentation_ISpecial_Artificial()
 {
     INode node = AbstractMethodTemplate.CreateClassUnderTest();
     var comment = new Comment(CommentType.Documentation, 
         SimpleCodeDocumentationComment, true, Location.Empty, Location.Empty);
     Parent.RefactoryExtensions.SetDocumentation(node, comment);
     var actual = Parent.RefactoryExtensions.GetDocumentation(node);
     Assert.AreEqual(SimpleCodeDocumentationComment, actual);
 }
Exemple #16
0
 public void VisitComment(Comment comment)
 {
     writer.StartNode(comment);
     writer.WriteComment(comment.CommentType, comment.Content);
     writer.EndNode(comment);
 }
		void AppendSingleLineComment(Comment comment)
		{
			if (comment.CommentStartsLine) {
				codeBuilder.AppendIndentedLine("#" + comment.CommentText);
			} else {
				codeBuilder.AppendToPreviousLine(" #" + comment.CommentText);
			}
		}
		public override void VisitComment(Comment comment) {
			switch (comment.CommentType) {
				case CommentType.SingleLine: {
					_result.Add(JsStatement.Comment(comment.Content));
					break;
				}

				case CommentType.MultiLine: {
					string prefix = new Regex(@"^\s*").Match(comment.Content).Captures[0].Value;
					List<string> commentLines = comment.Content.Replace("\r", "").Split('\n').Select(item => item.Trim()).SkipWhile(l => l == "").ToList();
					while (commentLines.Count > 0 && commentLines[commentLines.Count - 1] == "")
						commentLines.RemoveAt(commentLines.Count - 1);

					if (commentLines.Count > 0)
						_result.Add(JsStatement.Comment(string.Join(Environment.NewLine, commentLines.Select(item => prefix + item))));	// Replace the space at the start of each line with the same as the space in the first line.
					break;
				}
					
				case CommentType.Documentation:
				case CommentType.MultiLineDocumentation:
					// Better to use the NRefactory XML support if we want these.
					break;
				case CommentType.InactiveCode:
					// Should not appear in script.
					break;
				default:
					throw new ArgumentException("Invalid comment type " + comment.CommentType);
			}
		}
Exemple #19
0
			public void Run (AstNode compilationUnit)
			{
				var c = new Comment ("/<reference path='mscorlib.ts'/>");
				compilationUnit.InsertChildBefore (compilationUnit.FirstChild, c, Roles.Comment);
			}
		bool AreTwoSinglelineCommentsInConsecutiveLines(Comment comment1, Comment comment2)
		{
			if (comment1 == null || comment2 == null)
				return false;
			return comment1.CommentType == comment2.CommentType
				&& comment1.StartLocation.Line == comment1.EndLocation.Line
				&& comment1.EndLocation.Line + 1 == comment2.StartLocation.Line
				&& comment1.StartLocation.Column == comment2.StartLocation.Column
				&& comment2.StartLocation.Line == comment2.EndLocation.Line;
		}
Exemple #21
0
		public void VisitComment(Comment comment)
		{
			if (lastWritten == LastWritten.Division) {
				// When there's a comment starting after a division operator
				// "1.0 / /*comment*/a", then we need to insert a space in front of the comment.
				formatter.Space();
			}
			formatter.StartNode(comment);
			formatter.WriteComment(comment.CommentType, comment.Content);
			formatter.EndNode(comment);
			lastWritten = LastWritten.Whitespace;
		}
Exemple #22
0
        public void VisitComment(Comment comment)
        {
            JsonObject visit = new JsonObject();
            visit.Comment = "VisitComment";
            switch (comment.CommentType)
            {
                case CommentType.Documentation:
                    visit.AddJsonValue("comment-type", new JsonElement("documentation"));
                    break;
                case CommentType.InactiveCode:
                    visit.AddJsonValue("comment-type", new JsonElement("inactive-code"));
                    break;
                case CommentType.MultiLine:
                    visit.AddJsonValue("comment-type", new JsonElement("multiline"));
                    break;
                case CommentType.MultiLineDocumentation:
                    visit.AddJsonValue("comment-type", new JsonElement("multiline-documentation"));
                    break;
                case CommentType.SingleLine:
                    visit.AddJsonValue("comment-type", new JsonElement("single-line"));
                    break;
                default:
                    throw new NotSupportedException("Invalid value for CommentType");
            }
            visit.AddJsonValue("comment-content", new JsonElement(comment.Content));

            Push(visit);
            throw new FirstTimeUseException();
        }
		public override void VisitComment(Comment comment)
		{
			if (comment.CommentType == CommentType.InactiveCode)
				return; // don't fold the inactive code comment; instead fold the preprocessor directives
			if (AreTwoSinglelineCommentsInConsecutiveLines(comment.PrevSibling as Comment, comment))
				return; // already handled by previous comment
			Comment lastComment = comment;
			Comment nextComment;
			while (true) {
				nextComment = lastComment.NextSibling as Comment;
				if (!AreTwoSinglelineCommentsInConsecutiveLines(lastComment, nextComment))
					break;
				lastComment = nextComment;
			}
			if (lastComment.EndLocation.Line - comment.StartLocation.Line > 2) {
				var folding = AddFolding(comment.StartLocation, lastComment.EndLocation);
				if (folding != null) {
					switch (comment.CommentType) {
						case CommentType.SingleLine:
							folding.Name = "// ...";
							break;
						case CommentType.MultiLine:
							folding.Name = "/* ... */";
							break;
						case CommentType.Documentation:
							folding.Name = "/// ...";
							break;
						case CommentType.MultiLineDocumentation:
							folding.Name = "/** ... */";
							break;
					}
				}
			}
		}
        string GetDocumentationFromLine(int line)
        {
            if (specials == null)
            {
                return(null);
            }
            if (line < 0)
            {
                return(null);
            }
            // specials is a sorted list: use interpolation search
            int left  = 0;
            int right = specials.Count - 1;
            int m;

            while (left <= right)
            {
                int leftLine = specials[left].StartPosition.Y;
                if (line < leftLine)
                {
                    break;
                }
                int rightLine = specials[right].StartPosition.Y;
                if (line > rightLine)
                {
                    break;
                }
                if (leftLine == rightLine)
                {
                    if (leftLine == line)
                    {
                        m = left;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    m = left + (line - leftLine) * (right - left) / (rightLine - leftLine);
                }

                int mLine = specials[m].StartPosition.Y;
                if (mLine < line)                   // found line smaller than line we are looking for
                {
                    left = m + 1;
                }
                else if (mLine > line)
                {
                    right = m - 1;
                }
                else
                {
                    // correct line found,
                    // look for first special in that line
                    while (--m >= 0 && specials[m].StartPosition.Y == line)
                    {
                        ;
                    }
                    // look at all specials in that line: find doku-comment
                    while (++m < specials.Count && specials[m].StartPosition.Y == line)
                    {
                        RefParser.Comment comment = specials[m] as RefParser.Comment;
                        if (comment != null && comment.CommentType == RefParser.CommentType.Documentation)
                        {
                            return(comment.CommentText);
                        }
                    }
                    break;
                }
            }
            return(null);
        }
 private void AppendMultilineComment(Comment comment)
 {
     string[] strArrays = comment.CommentText.Split(new char[] { '\n' });
     for (int i = 0; i < (int)strArrays.Length; i++)
     {
         string str = string.Concat("# ", strArrays[i].Trim());
         if ((i != 0 ? true : comment.CommentStartsLine))
         {
             this.AppendIndentedLine(str);
         }
         else
         {
             this.codeBuilder.AppendToPreviousLine(string.Concat(" ", str));
         }
     }
 }
Exemple #26
0
        public void RunVisitor()
        {
            if (searchedMember == null)
            {
                return;
            }

            // search if the member name exists in the file (otherwise it doesn't make sense to search it)
            FindReplace   findReplace   = new FindReplace();
            FilterOptions filterOptions = new FilterOptions {
                CaseSensitive  = true,
                WholeWordsOnly = true
            };

            findReplace.CompilePattern(searchedMemberName, filterOptions);
            IEnumerable <SearchResult> result = findReplace.Search(new FileProvider(null), text.Text, searchedMemberName, null, filterOptions);

            if (result == null || !result.Any())
            {
                return;
            }

            string parseText = text.Text;

            ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StringReader(parseText));
            parser.Lexer.EvaluateConditionalCompilation = true;
            parser.Parse();
            resolver.SetupParsedCompilationUnit(parser.CompilationUnit);
            VisitCompilationUnit(parser.CompilationUnit, null);

            List <HashSet <string> > usedIdentifiers = GetUsedDefineCombinations(parser);

            for (int i = 0; i < usedIdentifiers.Count; i++)
            {
                parser.Lexer.ConditionalCompilationSymbols.Clear();
                foreach (string define in usedIdentifiers[i])
                {
                    parser.Lexer.ConditionalCompilationSymbols.Add(define, true);
                }
                parser.Dispose();
                parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, new StringReader(parseText));
                parser.Parse();

                VisitCompilationUnit(parser.CompilationUnit, null);
            }

            if (IncludeXmlDocumentation)
            {
                if (searchedMember is IParameter)
                {
                    IParameter parameter   = (IParameter)searchedMember;
                    var        docComments = from ICSharpCode.NRefactory.Comment cmt in
                                             (from ISpecial s in parser.Lexer.SpecialTracker.CurrentSpecials
                                              where s is ICSharpCode.NRefactory.Comment && s.StartPosition.Line <= parameter.DeclaringMember.Location.Line
                                              select s)
                                             select cmt;

                    ICSharpCode.NRefactory.Comment lastComment = null;
                    foreach (ICSharpCode.NRefactory.Comment curComment in docComments.Reverse())
                    {
                        if (lastComment != null && Math.Abs(lastComment.StartPosition.Line - curComment.StartPosition.Line) > 1)
                        {
                            break;
                        }
                        // Concat doesn't work on MatchCollections
                        foreach (var matchCol in new [] { paramRegex.Matches(curComment.CommentText), paramRefRegex.Matches(curComment.CommentText) })
                        {
                            foreach (Match match in matchCol)
                            {
                                if (match.Groups[1].Value == searchedMemberName)
                                {
                                    AddUniqueReference(curComment.StartPosition.Line, curComment.StartPosition.Column + match.Groups[1].Index, searchedMemberName);
                                }
                            }
                        }
                        lastComment = curComment;
                    }
                }
                else if (searchedMember is IMember)
                {
                    IMember member      = (IMember)searchedMember;
                    var     docComments = from ICSharpCode.NRefactory.Comment cmt in
                                          (from ISpecial s in parser.Lexer.SpecialTracker.CurrentSpecials
                                           where s is ICSharpCode.NRefactory.Comment
                                           select s)
                                          select cmt;

                    string fullName = member.FullName;

                    foreach (ICSharpCode.NRefactory.Comment curComment in docComments)
                    {
                        // Concat doesn't work on MatchCollections
                        foreach (var matchCol in new [] { seeRegex.Matches(curComment.CommentText), seeAlsoRegRegex.Matches(curComment.CommentText) })
                        {
                            foreach (Match match in matchCol)
                            {
                                if (match.Groups[1].Value.StartsWith(fullName))
                                {
                                    AddUniqueReference(curComment.StartPosition.Line, curComment.StartPosition.Column + match.Groups[1].Index + fullName.Length - searchedMemberName.Length, searchedMemberName);
                                }
                            }
                        }
                    }
                }
            }
            parser.Dispose();
        }
 void ICSharpCode.NRefactory.PrettyPrinter.IOutputFormatter.PrintComment(Comment comment, bool forceWriteInPreviousBlock)
 {
     if (comment.CommentType == CommentType.SingleLine)
     {
         this.AppendSingleLineComment(comment);
     }
     else if (comment.CommentType == CommentType.Block)
     {
         this.AppendMultilineComment(comment);
     }
     else if (comment.CommentType == CommentType.Documentation)
     {
         if (!this.SupportsDocstring(this.currentNode))
         {
             this.AppendSingleLineComment(comment);
         }
         else
         {
             this.xmlDocComments.Add(comment);
         }
     }
 }
 private static Comment CreateComment (StringBuilder sb, int startLine, int endLine)
 {
     var startLocation = new Location (0, startLine);
     var endLocation = new Location (0, endLine);
     var comment = new Comment (CommentType.Documentation, sb.ToString(), true, startLocation, endLocation);
     return comment;
 }