public void Initialize(IClass currentClass) { this.currentClass = currentClass.GetCompoundClass(); this.codeGen = currentClass.ProjectContent.Language.CodeGenerator; this.classFinderContext = new ClassFinder(currentClass, currentClass.Region.BeginLine + 1, 0); this.InitContent(); }
/// <summary> /// Called when this switch body element is inserted to the editor. /// </summary> public override void Insert(InsertionContext context) { this.context = context; this.context.Deactivated += new EventHandler<SnippetEventArgs>(InteractiveModeCompleted); this.anchor = SetUpAnchorAtInsertion(context); this.classFinderContext = new ClassFinder(ParserService.ParseCurrentViewContent(), Editor.Document.Text, Editor.Caret.Offset); }
Variable ResolveVariable(Variable variable) { Dom.ParseInformation info = ParserService.GetParseInformation(this.textEditor.FileName); Dom.ExpressionResult res = new Dom.ExpressionResult(variable.Name, Dom.DomRegion.FromLocation(variable.StartPos, variable.EndPos), Dom.ExpressionContext.Default, null); Dom.ResolveResult result = this.GetResolver().Resolve(res, info, this.textEditor.Document.Text); Dom.IReturnType type = currentProjectContent.SystemTypes.Object; Dom.ClassFinder finder = new Dom.ClassFinder(currentClass, textEditor.Caret.Line, textEditor.Caret.Column); if (result != null && result.ResolvedType != null) { type = result.ResolvedType; } if (variable.Type.Type == "var") { variable.Type = Dom.Refactoring.CodeGenerator.ConvertType(type, finder); } variable.IsReferenceType = type.IsReferenceType == true; return(variable); }
public void Insert(CompletionContext context, ICompletionItem item) { if (item == null) throw new ArgumentNullException("item"); if (!(item is OverrideCompletionItem)) throw new ArgumentException("item is not an OverrideCompletionItem"); OverrideCompletionItem completionItem = item as OverrideCompletionItem; ITextEditor textEditor = context.Editor; IEditorUIService uiService = textEditor.GetService(typeof(IEditorUIService)) as IEditorUIService; if (uiService == null) return; ParseInformation parseInfo = ParserService.GetParseInformation(textEditor.FileName); if (parseInfo == null) return; CodeGenerator generator = parseInfo.CompilationUnit.Language.CodeGenerator; IClass current = parseInfo.CompilationUnit.GetInnermostClass(textEditor.Caret.Line, textEditor.Caret.Column); ClassFinder finder = new ClassFinder(current, textEditor.Caret.Line, textEditor.Caret.Column); if (current == null) return; using (textEditor.Document.OpenUndoGroup()) { ITextAnchor startAnchor = textEditor.Document.CreateAnchor(textEditor.Caret.Offset); startAnchor.MovementType = AnchorMovementType.BeforeInsertion; ITextAnchor endAnchor = textEditor.Document.CreateAnchor(textEditor.Caret.Offset); endAnchor.MovementType = AnchorMovementType.AfterInsertion; MethodDeclaration member = (MethodDeclaration)generator.GetOverridingMethod(completionItem.Member, finder); string indent = DocumentUtilitites.GetWhitespaceBefore(textEditor.Document, textEditor.Caret.Offset); string codeForBaseCall = generator.GenerateCode(member.Body.Children.OfType<AbstractNode>().First(), ""); string code = generator.GenerateCode(member, indent); int marker = code.IndexOf(codeForBaseCall); textEditor.Document.Insert(startAnchor.Offset, code.Substring(0, marker).TrimStart()); ITextAnchor insertionPos = textEditor.Document.CreateAnchor(endAnchor.Offset); insertionPos.MovementType = AnchorMovementType.BeforeInsertion; InsertionContext insertionContext = new InsertionContext(textEditor.GetService(typeof(TextArea)) as TextArea, startAnchor.Offset); AbstractInlineRefactorDialog dialog = new OverrideEqualsGetHashCodeMethodsDialog(insertionContext, textEditor, startAnchor, endAnchor, insertionPos, current, completionItem.Member as IMethod, codeForBaseCall.Trim()); dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog); textEditor.Document.InsertNormalized(endAnchor.Offset, Environment.NewLine + code.Substring(marker + codeForBaseCall.Length)); insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog); insertionContext.RaiseInsertionCompleted(EventArgs.Empty); } }
public AttributeReturnType(ClassFinder context, string name) { if (context == null) throw new ArgumentNullException("context"); if (name == null) throw new ArgumentNullException("name"); this.name = name; scrt1 = new SearchClassReturnType(context.ProjectContent, context.CallingClass, context.CaretLine, context.CaretColumn, name, 0); scrt2 = new SearchClassReturnType(context.ProjectContent, context.CallingClass, context.CaretLine, context.CaretColumn, name + "Attribute", 0); }
protected AbstractInlineRefactorDialog(InsertionContext context, ITextEditor editor, ITextAnchor anchor) { if (context == null) throw new ArgumentNullException("context"); this.anchor = insertionEndAnchor = anchor; this.editor = editor; this.context = context; this.classFinderContext = new ClassFinder(ParserService.ParseCurrentViewContent(), editor.Document.Text, anchor.Offset); this.Background = SystemColors.ControlBrush; }
public static PropertyDeclaration add_Property(this TypeDeclaration typeDeclaration, IProperty iProperty) { foreach (var child in typeDeclaration.Children) if (child is PropertyDeclaration) if ((child as PropertyDeclaration).Name == iProperty.Name) return (child as PropertyDeclaration); //if (field != null) // return field; AttributedNode property = null; var classFinder = new ClassFinder(iProperty.DeclaringType, 0, 0); property = ICSharpCode.SharpDevelop.Dom.Refactoring.CodeGenerator.ConvertMember(iProperty, classFinder); if (property != null && property is PropertyDeclaration) return typeDeclaration.add_Property(property as PropertyDeclaration); //typeDeclaration.Children.Insert(0, property); if (property is PropertyDeclaration) return (PropertyDeclaration)property; "in add_Property could not convert property into PropertyDeclaration, because it is: {0}".error(property.typeName()); return null; }
public void Complete(CompletionContext context) { ITextEditor editor = context.Editor; ClassFinder classFinder = new ClassFinder(ParserService.GetParseInformation(editor.FileName), editor.Caret.Line, editor.Caret.Column); int caretPosition = editor.Caret.Offset; IDocumentLine line = editor.Document.GetLine(editor.Caret.Line); string lineText = editor.Document.GetText(line.Offset, caretPosition - line.Offset); foreach (char c in lineText) { if (!char.IsWhiteSpace(c) && !char.IsLetterOrDigit(c)) { editor.Document.Replace(context.StartOffset, context.Length, this.Text); context.EndOffset = context.StartOffset + this.Text.Length; return; } } string indentation = lineText.Substring(0, lineText.Length - lineText.TrimStart().Length); editor.Document.Remove(line.Offset, caretPosition - line.Offset); foreach (ICompletionItemHandler handler in handlers) { if (handler.Handles(this)) { editor.Document.Insert(line.Offset, indentation); handler.Insert(context, this); return; } } CodeGenerator codeGen = ParserService.CurrentProjectContent.Language.CodeGenerator; string text = codeGen.GenerateCode(codeGen.GetOverridingMethod(member, classFinder), indentation); text = text.TrimEnd(); // remove newline from end editor.Document.Insert(line.Offset, text); int endPos = line.Offset + text.Length; line = editor.Document.GetLineForOffset(endPos); editor.JumpTo(line.LineNumber, endPos - line.Offset + 1); }
public static FieldDeclaration add_Field(this TypeDeclaration typeDeclaration, IField iField) { // move to fields(..) extensionmethods FieldDeclaration field = null; foreach(var child in typeDeclaration.Children) if (child is FieldDeclaration) foreach (var variable in (child as FieldDeclaration).Fields) { if (variable.Name == iField.Name) field = (child as FieldDeclaration); } if (field != null) return field; var classFinder = new ClassFinder(iField.DeclaringType, 0,0); field = ICSharpCode.SharpDevelop.Dom.Refactoring.CodeGenerator.ConvertMember(iField, classFinder); typeDeclaration.add_Field(field); //var varia = new //var field = new FieldDeclaration( /*var fields = (from child in typeDeclaration.Children where child is FieldDeclaration select (FieldDeclaration)child).ToList(); */ //var fields = typeDeclaration.fields /*var newType = namespaceDeclaration.types(typeName); // check if already exists and if it does return it if (newType != null) return newType; const Modifiers modifiers = Modifiers.None | Modifiers.Public; newType = new TypeDeclaration(modifiers, new List<AttributeSection>()) { Name = typeName }; namespaceDeclaration.AddChild(newType);*/ return field; }
IEnumerable<Ast.ParameterDeclarationExpression> CreateParameters(UnknownMethodResolveResult rr, ClassFinder context, Ast.InvocationExpression invocation) { List<string> usedNames = new List<string>(); for (int i = 0; i < rr.Arguments.Count; i++) { IReturnType type = rr.Arguments[i]; if (type is LambdaReturnType) type = (type as LambdaReturnType).ToDefaultDelegate(); Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, context); typeRef = typeRef.IsNull ? new Ast.TypeReference("object", true) : typeRef; Ast.Expression ex = invocation.Arguments[i]; string paramName = IsNumericType(type) ? "num" + i : type.Name + i.ToString(); if (ex is Ast.IdentifierExpression) { paramName = (ex as Ast.IdentifierExpression).Identifier; } if (ex is Ast.MemberReferenceExpression) { paramName = (ex as Ast.MemberReferenceExpression).MemberName; } Ast.ParameterModifiers mod = Ast.ParameterModifiers.None; if (ex is Ast.DirectionExpression) { var dex = ex as Ast.DirectionExpression; if (dex.Expression is Ast.IdentifierExpression) { paramName = (dex.Expression as Ast.IdentifierExpression).Identifier; } if (dex.Expression is Ast.MemberReferenceExpression) { paramName = (dex.Expression as Ast.MemberReferenceExpression).MemberName; } mod = dex.FieldDirection == Ast.FieldDirection.Out ? Ast.ParameterModifiers.Out : (dex.FieldDirection == Ast.FieldDirection.Ref ? Ast.ParameterModifiers.Ref : Ast.ParameterModifiers.None); } paramName = rr.CallingClass.ProjectContent.Language.CodeGenerator.GetParameterName(paramName); if (usedNames.Contains(paramName)) paramName += i.ToString(); usedNames.Add(paramName); yield return new Ast.ParameterDeclarationExpression(typeRef, paramName) { ParamModifier = mod }; } }
internal void ExecuteIntroduceMethod(UnknownMethodResolveResult rr, Ast.Expression invocationExpr, ITextEditor editor, bool isNew, object result) { IClass targetClass = IsEqualClass(rr.CallingClass, rr.Target.GetUnderlyingClass()) ? rr.CallingClass : rr.Target.GetUnderlyingClass(); CodeGenerator gen = targetClass.ProjectContent.Language.CodeGenerator; IAmbience ambience = targetClass.ProjectContent.Language.GetAmbience(); ClassFinder finder = new ClassFinder(rr.CallingMember); ModifierEnum modifiers = ModifierEnum.None; bool isExtension = !targetClass.IsUserCode(); if (IsEqualClass(rr.CallingClass, targetClass)) { if (rr.CallingMember != null) modifiers |= (rr.CallingMember.Modifiers & ModifierEnum.Static); } else { if (isExtension) { if (isNew) targetClass = rr.CallingClass; else targetClass = result as IClass; } // exclude in Unit Test mode if (WorkbenchSingleton.Workbench != null) editor = (FileService.OpenFile(targetClass.CompilationUnit.FileName) as ITextEditorProvider).TextEditor; if (targetClass.ClassType != ClassType.Interface) modifiers |= ModifierEnum.Public; if (rr.IsStaticContext) modifiers |= ModifierEnum.Static; } NRefactoryResolver resolver = Extensions.CreateResolverForContext(targetClass.ProjectContent.Language, editor); IReturnType type = resolver.GetExpectedTypeFromContext(invocationExpr); Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, finder); if (typeRef.IsNull) { if (invocationExpr.Parent is Ast.ExpressionStatement) typeRef = new Ast.TypeReference("void", true); else typeRef = new Ast.TypeReference("object", true); } Ast.MethodDeclaration method = new Ast.MethodDeclaration { Name = rr.CallName, Modifier = CodeGenerator.ConvertModifier(modifiers, finder), TypeReference = typeRef, Parameters = CreateParameters(rr, finder, invocationExpr as Ast.InvocationExpression).ToList(), }; if (targetClass.ClassType != ClassType.Interface) method.Body = CodeGenerator.CreateNotImplementedBlock(); RefactoringDocumentAdapter documentWrapper = new RefactoringDocumentAdapter(editor.Document); if (isExtension) { method.Parameters.Insert(0, new Ast.ParameterDeclarationExpression(CodeGenerator.ConvertType(rr.Target, finder), "thisInstance")); method.IsExtensionMethod = true; method.Modifier |= Ast.Modifiers.Static; } if (isNew) { Ast.TypeDeclaration newType = new Ast.TypeDeclaration(isExtension ? Ast.Modifiers.Static : Ast.Modifiers.None, null); newType.Name = result as string; newType.AddChild(method); gen.InsertCodeAfter(targetClass, documentWrapper, newType); } else { if (IsEqualClass(rr.CallingClass, targetClass)) gen.InsertCodeAfter(rr.CallingMember, documentWrapper, method); else gen.InsertCodeAtEnd(targetClass.BodyRegion, documentWrapper, method); } if (targetClass.ClassType == ClassType.Interface) return; ParseInformation info = ParserService.ParseFile(targetClass.CompilationUnit.FileName); if (info != null) { IMember newMember; if (isNew) targetClass = info.CompilationUnit.Classes.FirstOrDefault(c => c.DotNetName == c.Namespace + "." + (result as string)); else targetClass = info.CompilationUnit.Classes.Flatten(c => c.InnerClasses).FirstOrDefault(c => c.DotNetName == targetClass.DotNetName); if (targetClass == null) return; if (IsEqualClass(rr.CallingClass, targetClass)) { newMember = targetClass.GetInnermostMember(editor.Caret.Line, editor.Caret.Column); newMember = targetClass.AllMembers .OrderBy(m => m.BodyRegion.BeginLine) .ThenBy(m2 => m2.BodyRegion.BeginColumn) .First(m3 => m3.BodyRegion.BeginLine > newMember.BodyRegion.BeginLine); } else { newMember = targetClass.Methods.Last(); } IDocumentLine line = editor.Document.GetLine(newMember.BodyRegion.BeginLine + 2); int indentLength = DocumentUtilitites.GetWhitespaceAfter(editor.Document, line.Offset).Length; editor.Select(line.Offset + indentLength, "throw new NotImplementedException();".Length); } }
public override object VisitAttributeSection(NRefactoryAST.AttributeSection attributeSection, object data) { if (GetCurrentClass() == null) { ClassFinder cf = new ClassFinder(new DefaultClass(cu, "DummyClass"), attributeSection.StartLocation.Line, attributeSection.StartLocation.Column); cu.Attributes.AddRange(VisitAttributes(new[] { attributeSection }, cf)); } return null; }
List<IAttribute> VisitAttributes(IList<NRefactoryAST.AttributeSection> attributes, ClassFinder context) { // TODO Expressions??? List<IAttribute> result = new List<IAttribute>(); foreach (NRefactoryAST.AttributeSection section in attributes) { AttributeTarget target = AttributeTarget.None; if (section.AttributeTarget != null && section.AttributeTarget != "") { switch (section.AttributeTarget.ToUpperInvariant()) { case "ASSEMBLY": target = AttributeTarget.Assembly; break; case "FIELD": target = AttributeTarget.Field; break; case "EVENT": target = AttributeTarget.Event; break; case "METHOD": target = AttributeTarget.Method; break; case "MODULE": target = AttributeTarget.Module; break; case "PARAM": target = AttributeTarget.Param; break; case "PROPERTY": target = AttributeTarget.Property; break; case "RETURN": target = AttributeTarget.Return; break; case "TYPE": target = AttributeTarget.Type; break; default: target = AttributeTarget.None; break; } } foreach (NRefactoryAST.Attribute attribute in section.Attributes) { List<object> positionalArguments = new List<object>(); foreach (NRefactoryAST.Expression positionalArgument in attribute.PositionalArguments) { positionalArguments.Add(ConvertAttributeArgument(positionalArgument)); } Dictionary<string, object> namedArguments = new Dictionary<string, object>(); foreach (NRefactoryAST.NamedArgumentExpression namedArgumentExpression in attribute.NamedArguments) { namedArguments.Add(namedArgumentExpression.Name, ConvertAttributeArgument(namedArgumentExpression.Expression)); } result.Add(new DefaultAttribute(new AttributeReturnType(context, attribute.Name), target, positionalArguments, namedArguments) { CompilationUnit = cu, Region = GetRegion(attribute.StartLocation, attribute.EndLocation) }); } } return result; }
void ConvertAttributes(NRefactoryAST.AttributedNode from, AbstractEntity to) { if (from.Attributes.Count == 0) { to.Attributes = DefaultAttribute.EmptyAttributeList; } else { ICSharpCode.NRefactory.Location location = from.Attributes[0].StartLocation; ClassFinder context; if (to is IClass) { context = new ClassFinder((IClass)to, location.Line, location.Column); } else { context = new ClassFinder(to.DeclaringType, location.Line, location.Column); } to.Attributes = VisitAttributes(from.Attributes, context); } }
static bool TryDeclarationTypeInference(ITextEditor editor, IDocumentLine curLine) { string lineText = editor.Document.GetText(curLine.Offset, curLine.Length); ILexer lexer = ParserFactory.CreateLexer(SupportedLanguage.VBNet, new System.IO.StringReader(lineText)); if (lexer.NextToken().Kind != Tokens.Dim) return false; if (lexer.NextToken().Kind != Tokens.Identifier) return false; if (lexer.NextToken().Kind != Tokens.As) return false; Token t1 = lexer.NextToken(); if (t1.Kind != Tokens.QuestionMark) return false; Token t2 = lexer.NextToken(); if (t2.Kind != Tokens.Assign) return false; string expr = lineText.Substring(t2.Location.Column); LoggingService.Debug("DeclarationTypeInference: >" + expr + "<"); ResolveResult rr = ParserService.Resolve(new ExpressionResult(expr), editor.Caret.Line, t2.Location.Column, editor.FileName, editor.Document.Text); if (rr != null && rr.ResolvedType != null) { ClassFinder context = new ClassFinder(ParserService.GetParseInformation(editor.FileName), editor.Caret.Line, t1.Location.Column); VBNetAmbience ambience = new VBNetAmbience(); if (CodeGenerator.CanUseShortTypeName(rr.ResolvedType, context)) ambience.ConversionFlags = ConversionFlags.None; else ambience.ConversionFlags = ConversionFlags.UseFullyQualifiedTypeNames; string typeName = ambience.Convert(rr.ResolvedType); using (editor.Document.OpenUndoGroup()) { int offset = curLine.Offset + t1.Location.Column - 1; editor.Document.Remove(offset, 1); editor.Document.Insert(offset, typeName); } editor.Caret.Column += typeName.Length - 1; return true; } return false; }
bool TryDeclarationTypeInference(SharpDevelopTextAreaControl editor, LineSegment curLine) { string lineText = editor.Document.GetText(curLine.Offset, curLine.Length); ILexer lexer = ParserFactory.CreateLexer(SupportedLanguage.CSharp, new System.IO.StringReader(lineText)); Token typeToken = lexer.NextToken(); if (typeToken.kind == CSTokens.Question) { if (lexer.NextToken().kind == CSTokens.Identifier) { Token t = lexer.NextToken(); if (t.kind == CSTokens.Assign) { string expr = lineText.Substring(t.col); LoggingService.Debug("DeclarationTypeInference: >" + expr + "<"); ResolveResult rr = ParserService.Resolve(new ExpressionResult(expr), editor.ActiveTextAreaControl.Caret.Line + 1, t.col, editor.FileName, editor.Document.TextContent); if (rr != null && rr.ResolvedType != null) { ClassFinder context = new ClassFinder(editor.FileName, editor.ActiveTextAreaControl.Caret.Line, t.col); if (CodeGenerator.CanUseShortTypeName(rr.ResolvedType, context)) CSharpAmbience.Instance.ConversionFlags = ConversionFlags.None; else CSharpAmbience.Instance.ConversionFlags = ConversionFlags.UseFullyQualifiedNames; string typeName = CSharpAmbience.Instance.Convert(rr.ResolvedType); editor.Document.Replace(curLine.Offset + typeToken.col - 1, 1, typeName); editor.ActiveTextAreaControl.Caret.Column += typeName.Length - 1; return true; } } } } return false; }
void ConvertAttributes(AST.TypeMember node, AbstractEntity to) { if (node.Attributes.Count == 0) { to.Attributes = DefaultAttribute.EmptyAttributeList; } else { ClassFinder context; if (to is IClass) { context = new ClassFinder((IClass)to, node.LexicalInfo.Line, node.LexicalInfo.Column); } else { context = new ClassFinder(to.DeclaringType, node.LexicalInfo.Line, node.LexicalInfo.Column); } foreach (AST.Attribute a in node.Attributes) { to.Attributes.Add(new DefaultAttribute(new AttributeReturnType(context, a.Name)) { CompilationUnit = _cu, Region = GetRegion(a) }); } } to.Documentation = node.Documentation; }
public override bool InsertAction(TextArea textArea, char ch) { ClassFinder context = new ClassFinder(ParserService.GetParseInformation(textArea.MotherTextEditorControl.FileName), textArea.Caret.Line + 1, textArea.Caret.Column + 1); int caretPosition = textArea.Caret.Offset; LineSegment line = textArea.Document.GetLineSegment(textArea.Caret.Line); string lineText = textArea.Document.GetText(line.Offset, caretPosition - line.Offset); foreach (char c in lineText) { if (!char.IsWhiteSpace(c) && !char.IsLetterOrDigit(c)) { return base.InsertAction(textArea, ch); } } string indentation = lineText.Substring(0, lineText.Length - lineText.TrimStart().Length); CodeGenerator codeGen = ParserService.CurrentProjectContent.Language.CodeGenerator; string text = codeGen.GenerateCode(codeGen.GetOverridingMethod(member, context), indentation); text = text.TrimEnd(); // remove newline from end textArea.Document.Replace(line.Offset, caretPosition - line.Offset, text); int endPos = line.Offset + text.Length; int endLine = textArea.Document.GetLineNumberForOffset(endPos); line = textArea.Document.GetLineSegment(endLine); textArea.MotherTextAreaControl.JumpTo(endLine, endPos - line.Offset); textArea.Refresh(); return true; }
Variable ResolveVariable(Variable variable) { Dom.ParseInformation info = ParserService.GetParseInformation(this.textEditor.FileName); Dom.ExpressionResult res = new Dom.ExpressionResult(variable.Name, Dom.DomRegion.FromLocation(variable.StartPos, variable.EndPos), Dom.ExpressionContext.Default, null); Dom.ResolveResult result = this.GetResolver().Resolve(res, info, this.textEditor.Document.Text); Dom.IReturnType type = currentProjectContent.SystemTypes.Object; Dom.ClassFinder finder = new Dom.ClassFinder(currentClass, textEditor.Caret.Line, textEditor.Caret.Column); if (result != null && result.ResolvedType != null) type = result.ResolvedType; if (variable.Type.Type == "var") variable.Type = Dom.Refactoring.CodeGenerator.ConvertType(type, finder); variable.IsReferenceType = type.IsReferenceType == true; return variable; }