public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { if (nameComparer.Equals(from, parameterDeclarationExpression.ParameterName)) { parameterDeclarationExpression.ParameterName = to; } return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); }
public static MethodDeclaration add_Method(this TypeDeclaration typeDeclaration, string methodName, Dictionary<string, object> invocationParameters, BlockStatement body) { var newMethod = new MethodDeclaration { Name = methodName, //Modifier = Modifiers.None | Modifiers.Public | Modifiers.Static, Modifier = Modifiers.None | Modifiers.Public, Body = body }; newMethod.setReturnType(); if (invocationParameters != null) foreach (var invocationParameter in invocationParameters) { var parameterType = new TypeReference( (invocationParameter.Value != null && invocationParameter.Key != "returnData") ? invocationParameter.Value.typeFullName() : "System.Object", true); var parameter = new ParameterDeclarationExpression(parameterType, invocationParameter.Key); newMethod.Parameters.Add(parameter); } typeDeclaration.AddChild(newMethod); return newMethod; }
public void Equals() { string program = TestUtil.TypeMemberParse("public string Sentence(string title , string text);"); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration) cu.Children[0]; TypeDeclaration ty = (TypeDeclaration) ns.Children[0]; MethodDeclaration pgMethod = (MethodDeclaration) ty.Children[0]; ParameterDeclarationExpression p1 = new ParameterDeclarationExpression(new TypeReference("string"), "title"); p1.TypeReference.RankSpecifier = new int[] {}; ParameterDeclarationExpression p2 = new ParameterDeclarationExpression(new TypeReference("string"), "text"); p2.TypeReference.RankSpecifier = new int[] {}; List<ParameterDeclarationExpression> argList = new List<ParameterDeclarationExpression>(); argList.Add(p1); argList.Add(p2); MethodDeclaration exMethod = new MethodDeclaration("Sentence", Modifiers.Public, new TypeReference("string"), argList, null); Assert.IsTrue(Equals(exMethod, pgMethod)); string program2 = TestUtil.TypeMemberParse("public string Sentence(string title , string[] text);"); cu = TestUtil.ParseProgram(program2); ns = (NamespaceDeclaration) cu.Children[0]; ty = (TypeDeclaration) ns.Children[0]; pgMethod = (MethodDeclaration) ty.Children[0]; Assert.IsFalse(Equals(exMethod, pgMethod)); }
/// <summary> /// Adds a <see cref="ParameterDeclarationExpression"/> to <see cref="ParametrizedNode.Parameters"/> in a single /// call, for convenience. /// </summary> /// /// <param name="node"> /// The method or constructor to add the parameter to. /// </param> /// /// <param name="parameterType"> /// The <see cref="TypeReference"/> of the parameter to add. /// </param> /// /// <param name="parameterName"> /// The name of the parameter to add. /// </param> /// /// <returns> /// The <see cref="ParameterDeclarationExpression"/> instance that was created and added to /// <paramref name="node"/>. /// </returns> public static ParameterDeclarationExpression AddParameter(this ParametrizedNode node, TypeReference parameterType, string parameterName) { var parameter = new ParameterDeclarationExpression(parameterType, parameterName); node.Parameters.Add(parameter); return parameter; }
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { if (RenameTable.ContainsKey(parameterDeclarationExpression.ParameterName)) { parameterDeclarationExpression.ParameterName = RenameTable[parameterDeclarationExpression.ParameterName]; } return null; }
internal static IParameter CreateParameter(AST.ParameterDeclarationExpression par, IMethod method, IClass currentClass, ICompilationUnit cu) { IReturnType parType = CreateReturnType(par.TypeReference, method, currentClass, cu, TypeVisitor.ReturnTypeOptions.None); DefaultParameter p = new DefaultParameter(par.ParameterName, parType, GetRegion(par.StartLocation, par.EndLocation)); p.Modifiers = (ParameterModifiers)par.ParamModifier; return(p); }
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { if (parameterDeclarationExpression.ParamModifier == ParameterModifiers.Out) { UnlockWith(parameterDeclarationExpression); } return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); }
public override object TrackedVisitInvocationExpression(InvocationExpression invocationExpression, object data) { if (invocationExpression.TargetObject is IdentifierExpression) { TypeDeclaration typeDeclaration = (TypeDeclaration) AstUtil.GetParentOfType(invocationExpression, typeof(TypeDeclaration)); IdentifierExpression methodIdentifier = (IdentifierExpression) invocationExpression.TargetObject; if (typeDeclaration.Parent is TypeDeclaration) { List<ParameterDeclarationExpression> argList = new List<ParameterDeclarationExpression>(); int i = 0; foreach (Expression argument in invocationExpression.Arguments) { TypeReference argumentType = GetExpressionType(argument); if (argumentType != null) { string argType = argumentType.Type; TypeReference typeReference = new TypeReference(argType); ParameterDeclarationExpression parameterExpression = new ParameterDeclarationExpression(typeReference, "arg" + i); parameterExpression.TypeReference.RankSpecifier = new int[0]; i++; argList.Add(parameterExpression); } } MethodDeclaration argMethod = new MethodDeclaration(methodIdentifier.Identifier, Modifiers.None, null, argList, null); IList parentMethods = GetAccessibleMethods((TypeDeclaration) typeDeclaration.Parent); if (Contains(parentMethods, argMethod)) { int methodIndex = IndexOf(parentMethods, argMethod); argMethod = (MethodDeclaration) parentMethods[methodIndex]; if (!AstUtil.ContainsModifier(argMethod, Modifiers.Static)) { string parentTypeName = ((TypeDeclaration) typeDeclaration.Parent).Name; AddInstanceField(typeDeclaration, parentTypeName); AddProperConstructor(typeDeclaration, parentTypeName); FieldReferenceExpression newReference = new FieldReferenceExpression( new IdentifierExpression(parentTypeName), ((IdentifierExpression) invocationExpression.TargetObject).Identifier); InvocationExpression newInvication = new InvocationExpression(newReference, invocationExpression.Arguments); newInvication.Parent = invocationExpression.Parent; ReplaceCurrentNode(newInvication); } } } } return base.TrackedVisitInvocationExpression(invocationExpression, data); }
public void Contains() { string program = TestUtil.GetInput(); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration) cu.Children[0]; TypeDeclaration ty = (TypeDeclaration) ns.Children[0]; IList methods = AstUtil.GetChildrenWithType(ty, typeof(MethodDeclaration)); ParameterDeclarationExpression pm = new ParameterDeclarationExpression( new TypeReference("int"), "from"); pm.TypeReference.RankSpecifier = new int[] {}; List<ParameterDeclarationExpression> al = new List<ParameterDeclarationExpression>(); al.Add(pm); MethodDeclaration myMethod = new MethodDeclaration("Distance", Modifiers.Protected, new TypeReference("int"), al, null); Assert.IsTrue(Contains(methods, myMethod)); }
public void IndexOf() { string program = TestUtil.GetInput(); CompilationUnit cu = TestUtil.ParseProgram(program); NamespaceDeclaration ns = (NamespaceDeclaration) cu.Children[0]; TypeDeclaration ty = (TypeDeclaration) ns.Children[0]; IList methodDecList = AstUtil.GetChildrenWithType(ty, typeof(MethodDeclaration)); ParameterDeclarationExpression p1 = new ParameterDeclarationExpression(new TypeReference("Circle"), "circle"); p1.TypeReference.RankSpecifier = new int[] {}; List<ParameterDeclarationExpression> md1Param = new List<ParameterDeclarationExpression>(); md1Param.Add(p1); MethodDeclaration md1 = new MethodDeclaration("GetRadius", Modifiers.Private, new TypeReference("int"), md1Param, null); int md1Index = IndexOf(methodDecList, md1); Assert.AreEqual(1, md1Index); MethodDeclaration md2 = new MethodDeclaration("ToString", Modifiers.Protected, new TypeReference("string"), null, null); int md2Index = IndexOf(methodDecList, md2); Assert.AreEqual(-1, md2Index); }
private void VisitParametrizedNode(NR.ParametrizedNode node, bool isConstructor) { if (((isConstructor && this.Method.IsConstructor) || (node.Name == this.Method.Name)) && node.Parameters.Count == this.Method.Parameters.Count) { var doParametersMatch = true; NR.ParameterDeclarationExpression matchingParameter = null; for (var i = 0; i < node.Parameters.Count; i++) { var parsedParameter = node.Parameters[i]; if (parsedParameter.ParameterName != this.Method.Parameters[i].Name) { doParametersMatch = false; break; } else if (parsedParameter.ParameterName == this.Parameter.Name) { matchingParameter = parsedParameter; } } if (doParametersMatch && matchingParameter != null) { this.SequencePoint = (from attributeSection in matchingParameter.Attributes from attribute in attributeSection.Attributes where (attribute.Name == "NotNullAttribute" || attribute.Name == "NotNull") select new SequencePoint(this.Document) { EndColumn = attribute.EndLocation.Column, EndLine = attribute.EndLocation.Line, StartColumn = attribute.StartLocation.Column, StartLine = attribute.StartLocation.Line }).Single(); } } }
IParameter CreateParameter(AST.ParameterDeclarationExpression par, IMethod method) { return(CreateParameter(par, method, GetCurrentClass(), cu)); }
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(ConvType(parameterDeclarationExpression.TypeReference), parameterDeclarationExpression.ParameterName); parameters.Add(parameter); return parameter; }
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { parameterDeclarationExpression.Attributes.Clear(); return null; }
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { if (this.CheckNode(parameterDeclarationExpression)) { return null; } return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); }
void ParameterArray( #line 678 "Frames/cs.ATG" out ParameterDeclarationExpression p) { #line 679 "Frames/cs.ATG" TypeReference type; Expect(95); Type( #line 681 "Frames/cs.ATG" out type); Identifier(); #line 681 "Frames/cs.ATG" p = new ParameterDeclarationExpression(type, t.val, ParameterModifiers.Params); }
public virtual object TrackedVisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); }
public virtual object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { throw new global::System.NotImplementedException("ParameterDeclarationExpression"); }
public void ParameterNameSafe_NegativeCase() { const string not_a_reserverd_word = "not_a_reserverd_word"; ParameterDeclarationExpression p = new ParameterDeclarationExpression(new TypeReference("foo"), not_a_reserverd_word); Assert.AreEqual("not_a_reserverd_word", p.ParameterNameSafe()); }
IParameter CreateParameter(AST.ParameterDeclarationExpression par) { return(CreateParameter(par, null)); }
void FormalParameter( #line 2189 "VBNET.ATG" out ParameterDeclarationExpression p) { #line 2191 "VBNET.ATG" TypeReference type = null; ParamModifierList mod = new ParamModifierList(this); Expression expr = null; p = null;ArrayList arrayModifiers = null; while (StartOf(33)) { ParameterModifier( #line 2196 "VBNET.ATG" mod); } Identifier(); #line 2197 "VBNET.ATG" string parameterName = t.val; if ( #line 2198 "VBNET.ATG" IsDims()) { ArrayTypeModifiers( #line 2198 "VBNET.ATG" out arrayModifiers); } if (la.kind == 48) { lexer.NextToken(); TypeName( #line 2199 "VBNET.ATG" out type); } #line 2201 "VBNET.ATG" if(type != null) { if (arrayModifiers != null) { if (type.RankSpecifier != null) { Error("array rank only allowed one time"); } else { type.RankSpecifier = (int[])arrayModifiers.ToArray(typeof(int)); } } } else { type = new TypeReference("System.Object", arrayModifiers == null ? null : (int[])arrayModifiers.ToArray(typeof(int))); } if (la.kind == 11) { lexer.NextToken(); Expr( #line 2213 "VBNET.ATG" out expr); } #line 2215 "VBNET.ATG" mod.Check(); p = new ParameterDeclarationExpression(type, parameterName, mod.Modifier, expr); }
public override List<Change> PerformChanges (RefactoringOptions options, object prop) { List<Change> result = new List<Change> (); IResolver resolver = options.GetResolver (); INRefactoryASTProvider provider = options.GetASTProvider (); if (resolver == null || provider == null) return result; TextEditorData data = options.GetTextEditorData (); TextReplaceChange insertNewMethod = new TextReplaceChange (); insertNewMethod.FileName = fileName; insertNewMethod.RemovedChars = insertionPoint.LineBefore == NewLineInsertion.Eol ? 0 : insertionPoint.Location.Column; insertNewMethod.Offset = insertionOffset - insertNewMethod.RemovedChars; MethodDeclaration methodDecl = new MethodDeclaration (); bool isInInterface = false; methodDecl.Modifier = modifiers; methodDecl.TypeReference = HelperMethods.ConvertToTypeReference (returnType); methodDecl.Name = newMethodName; if (!isInInterface) { methodDecl.Body = new BlockStatement (); methodDecl.Body.AddChild (new ThrowStatement (new ObjectCreateExpression (new TypeReference ("System.NotImplementedException"), null))); } insertNewMethod.Description = string.Format (GettextCatalog.GetString ("Create new method {0}"), methodDecl.Name); int i = 0; foreach (Expression expression in invoke.Arguments) { i++; string output = provider.OutputNode (options.Dom, expression); string parameterName = "par" + i; int idx = output.LastIndexOf ('.'); string lastName = output.Substring (idx + 1); // start from 0, if '.' wasn't found ResolveResult resolveResult2 = resolver.Resolve (new ExpressionResult (output), resolvePosition); TypeReference typeReference = new TypeReference ((resolveResult2 != null && resolveResult2.ResolvedType != null) ? options.Document.CompilationUnit.ShortenTypeName (resolveResult2.ResolvedType, data.Caret.Line, data.Caret.Column).ToInvariantString () : "System.Object"); if (lastName == "this" || lastName == "base") { idx = typeReference.Type.LastIndexOf ('.'); lastName = typeReference.Type.Substring (idx + 1); } if (!string.IsNullOrEmpty (lastName)) lastName = char.ToLower (lastName[0]) + lastName.Substring (1); if (IsValidIdentifier (lastName)) parameterName = lastName; typeReference.IsKeyword = true; ParameterDeclarationExpression pde = new ParameterDeclarationExpression (typeReference, parameterName); methodDecl.Parameters.Add (pde); } StringBuilder sb = new StringBuilder (); switch (insertionPoint.LineBefore) { case NewLineInsertion.Eol: sb.AppendLine (); break; case NewLineInsertion.BlankLine: sb.Append (indent); sb.AppendLine (); break; } sb.Append (provider.OutputNode (options.Dom, methodDecl, indent).TrimEnd ('\n', '\r')); switch (insertionPoint.LineAfter) { case NewLineInsertion.Eol: sb.AppendLine (); break; case NewLineInsertion.BlankLine: sb.AppendLine (); sb.AppendLine (); sb.Append (indent); break; } insertNewMethod.InsertedText = sb.ToString (); result.Add (insertNewMethod); if (!isInInterface) { int idx = insertNewMethod.InsertedText.IndexOf ("throw"); selectionStart = insertNewMethod.Offset + idx; selectionEnd = insertNewMethod.Offset + insertNewMethod.InsertedText.IndexOf (';', idx) + 1; } else { selectionStart = selectionEnd = insertNewMethod.Offset; } return result; }
public override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { curBlock.Add(parameterDeclarationExpression.ParameterName); //print("add parameter ${parameterDeclarationExpression.ParameterName} to block") return base.VisitParameterDeclarationExpression(parameterDeclarationExpression, data); }
public override bool Extract() { using (var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader("class Tmp { void Test() {\n " + this.textEditor.SelectedText + "\n}}"))) { parser.Parse(); if (parser.Errors.Count > 0) { MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ParseErrors}"); return false; } this.specialsList = parser.Lexer.SpecialTracker.RetrieveSpecials(); } this.currentProjectContent = ParserService.GetProjectContent(ProjectService.CurrentProject); MethodDeclaration newMethod = new MethodDeclaration(); List<VariableDeclaration> possibleReturnValues = new List<VariableDeclaration>(); List<VariableDeclaration> otherReturnValues = new List<VariableDeclaration>(); // Initialise new method newMethod.Body = GetBlock(this.textEditor.SelectedText); newMethod.Body.StartLocation = new Location(0,0); this.parentNode = GetParentMember(start, end); Dom.IMember member = GetParentMember(textEditor, textEditor.Caret.Line, textEditor.Caret.Column); if (parentNode == null || member == null) { MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.InvalidSelection}"); return false; } this.currentClass = member.DeclaringType; ErrorKind kind = CheckForJumpInstructions(newMethod); if (kind != ErrorKind.None) { switch (kind) { case ErrorKind.ContainsBreak: MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsBreakError}"); break; case ErrorKind.ContainsContinue: MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsContinueError}"); break; case ErrorKind.ContainsGoto: MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsGotoError}"); break; } return false; } newMethod.Modifier = parentNode.Modifier; newMethod.Modifier &= ~(Modifiers.Internal | Modifiers.Protected | Modifiers.Private | Modifiers.Public | Modifiers.Override); LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp); parentNode.AcceptVisitor(ltv, null); var variablesList = (from list in ltv.Variables.Values from item in list select new Variable(item)) .Where(v => !(v.StartPos > end || v.EndPos < start) && (HasReferencesInSelection(newMethod, v) || HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, v.Name, v.StartPos, v.EndPos))) .Union(FromParameters(newMethod)) .Select(va => ResolveVariable(va)); foreach (var variable in variablesList) { LoggingService.Debug(variable); bool hasOccurrencesAfter = HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, variable.Name, variable.StartPos, variable.EndPos); bool isInitialized = (variable.Initializer != null) ? !variable.Initializer.IsNull : false; bool hasAssignment = HasAssignment(newMethod, variable); if (IsInCurrentSelection(variable.StartPos) && hasOccurrencesAfter) { possibleReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type)); otherReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type)); } if (!(IsInCurrentSelection(variable.StartPos) || IsInCurrentSelection(variable.EndPos))) { ParameterDeclarationExpression newParam = null; if ((hasOccurrencesAfter && isInitialized) || variable.WasRefParam) newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Ref); else { if ((hasOccurrencesAfter && hasAssignment) || variable.WasOutParam) newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Out); else { if (!hasOccurrencesAfter) newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.None); else { if (!hasOccurrencesAfter && !isInitialized) newMethod.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type))); else newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.In); } } } if (newParam != null) newMethod.Parameters.Add(newParam); } } List<VariableDeclaration> paramsAsVarDecls = new List<VariableDeclaration>(); this.beforeCallDeclarations = new List<LocalVariableDeclaration>(); for (int i = 0; i < otherReturnValues.Count - 1; i++) { VariableDeclaration varDecl = otherReturnValues[i]; paramsAsVarDecls.Add(varDecl); ParameterDeclarationExpression p = new ParameterDeclarationExpression(varDecl.TypeReference, varDecl.Name); p.ParamModifier = ParameterModifiers.Out; if (!newMethod.Parameters.Contains(p)) { newMethod.Parameters.Add(p); } else { this.beforeCallDeclarations.Add(new LocalVariableDeclaration(varDecl)); } } CreateReturnStatement(newMethod, possibleReturnValues); newMethod.Name = "NewMethod"; this.extractedMethod = newMethod; return true; }
public void ParameterNameSafe_PositiveCase() { const string reserved_word = "this"; ParameterDeclarationExpression p = new ParameterDeclarationExpression(new TypeReference("foo"), reserved_word); Assert.AreEqual("@this", p.ParameterNameSafe()); }
public override object TrackedVisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { Console.WriteLine("VisitParameterDeclarationExpression"); return null; }
void FormalParameter( #line 2642 "VBNET.ATG" out ParameterDeclarationExpression p) { #line 2644 "VBNET.ATG" AttributeSection section; List<AttributeSection> attributes = new List<AttributeSection>(); TypeReference type = null; ParamModifierList mod = new ParamModifierList(this); Expression expr = null; p = null; ArrayList arrayModifiers = null; while (la.kind == 28) { AttributeSection( #line 2653 "VBNET.ATG" out section); #line 2653 "VBNET.ATG" attributes.Add(section); } while (StartOf(35)) { ParameterModifier( #line 2654 "VBNET.ATG" mod); } Identifier(); #line 2655 "VBNET.ATG" string parameterName = t.val; if ( #line 2656 "VBNET.ATG" IsDims()) { ArrayTypeModifiers( #line 2656 "VBNET.ATG" out arrayModifiers); } if (la.kind == 50) { lexer.NextToken(); TypeName( #line 2657 "VBNET.ATG" out type); } #line 2659 "VBNET.ATG" if(type != null) { if (arrayModifiers != null) { if (type.RankSpecifier != null) { Error("array rank only allowed one time"); } else { type.RankSpecifier = (int[])arrayModifiers.ToArray(typeof(int)); } } } else { type = new TypeReference("System.Object", arrayModifiers == null ? null : (int[])arrayModifiers.ToArray(typeof(int))); } if (la.kind == 10) { lexer.NextToken(); Expr( #line 2671 "VBNET.ATG" out expr); } #line 2673 "VBNET.ATG" mod.Check(); p = new ParameterDeclarationExpression(type, parameterName, mod.Modifier, expr); p.Attributes = attributes; }
void LambdaExpressionParameter( #line 2152 "cs.ATG" out ParameterDeclarationExpression p) { #line 2153 "cs.ATG" Location start = la.Location; p = null; TypeReference type; ParameterModifiers mod = ParameterModifiers.In; if ( #line 2158 "cs.ATG" Peek(1).kind == Tokens.Comma || Peek(1).kind == Tokens.CloseParenthesis) { Identifier(); #line 2160 "cs.ATG" p = new ParameterDeclarationExpression(null, t.val); p.StartLocation = start; p.EndLocation = t.EndLocation; } else if (StartOf(36)) { if (la.kind == 93 || la.kind == 100) { if (la.kind == 100) { lexer.NextToken(); #line 2163 "cs.ATG" mod = ParameterModifiers.Ref; } else { lexer.NextToken(); #line 2164 "cs.ATG" mod = ParameterModifiers.Out; } } Type( #line 2166 "cs.ATG" out type); Identifier(); #line 2168 "cs.ATG" p = new ParameterDeclarationExpression(type, t.val, mod); p.StartLocation = start; p.EndLocation = t.EndLocation; } else SynErr(213); }
public override List<Change> PerformChanges (RefactoringOptions options, object prop) { IResolver resolver = options.GetResolver (); List<Change> result = new List<Change> (); INRefactoryASTProvider provider = options.GetASTProvider (); if (resolver == null || provider == null) return result; TypeDeclaration newType = new TypeDeclaration (ICSharpCode.NRefactory.Ast.Modifiers.None, null); newType.Name = createExpression.CreateType.Type; newType.Type = GetNewTypeType (); ConstructorDeclaration constructor = new ConstructorDeclaration (newType.Name, ICSharpCode.NRefactory.Ast.Modifiers.Public, null, null); constructor.Body = new BlockStatement (); int i = 0; foreach (Expression expression in createExpression.Parameters) { i++; string output = provider.OutputNode (options.Dom, expression); string parameterName; if (Char.IsLetter (output[0]) || output[0] == '_') { parameterName = output; } else { parameterName = "par" + i; } ResolveResult resolveResult2 = resolver.Resolve (new ExpressionResult (output), options.ResolveResult.ResolvedExpression.Region.Start); TypeReference typeReference = new TypeReference (resolveResult2.ResolvedType.ToInvariantString ()); typeReference.IsKeyword = true; ParameterDeclarationExpression pde = new ParameterDeclarationExpression (typeReference, parameterName); constructor.Parameters.Add (pde); } ICSharpCode.NRefactory.Ast.INode node = newType; IType curType = options.Document.CompilationUnit.GetTypeAt (options.Document.TextEditor.CursorLine, options.Document.TextEditor.CursorColumn); if (curType != null && !string.IsNullOrEmpty (curType.Namespace)) { NamespaceDeclaration namespaceDeclaration = new NamespaceDeclaration (curType.Namespace); namespaceDeclaration.Children.Add (newType); node = namespaceDeclaration; } newType.Children.Add (constructor); string fileName = GetName (Path.Combine (Path.GetDirectoryName (options.Document.FileName), newType.Name + Path.GetExtension (options.Document.FileName))); string header = options.Dom.Project is DotNetProject ? StandardHeaderService.GetHeader (options.Dom.Project, fileName, true) + Environment.NewLine : ""; CreateFileChange createFile = new CreateFileChange (fileName, header + provider.OutputNode (options.Dom, node)); result.Add (createFile); result.Add (new OpenFileChange (fileName)); return result; }
public override List<Change> PerformChanges (RefactoringOptions options, object prop) { List<Change> result = new List<Change> (); ExtractMethodParameters param = (ExtractMethodParameters)prop; TextEditorData data = options.GetTextEditorData (); INRefactoryASTProvider provider = options.GetASTProvider (); IResolver resolver = options.GetResolver (); ICSharpCode.NRefactory.Ast.INode node = Analyze (options, param, false); if (param.VariablesToGenerate.Count > 0) { TextReplaceChange varGen = new TextReplaceChange (); varGen.Description = GettextCatalog.GetString ("Generate some temporary variables"); varGen.FileName = options.Document.FileName; LineSegment line = data.Document.GetLine (Math.Max (0, data.Document.OffsetToLineNumber (data.SelectionRange.Offset) - 1)); varGen.Offset = line.Offset + line.EditableLength; varGen.InsertedText = Environment.NewLine + options.GetWhitespaces (line.Offset); foreach (VariableDescriptor var in param.VariablesToGenerate) { TypeReference tr = options.ShortenTypeName (var.ReturnType).ConvertToTypeReference (); varGen.InsertedText += provider.OutputNode (options.Dom, new LocalVariableDeclaration (new VariableDeclaration (var.Name, null, tr))).Trim (); } result.Add (varGen); } InvocationExpression invocation = new InvocationExpression (new IdentifierExpression (param.Name)); foreach (VariableDescriptor var in param.Parameters) { if (!param.OneChangedVariable && param.ChangedVariables.Contains (var.Name)) { FieldDirection fieldDirection = FieldDirection.Ref; VariableDescriptor outsideVar = null; if (param.VariablesOutside.TryGetValue (var.Name, out outsideVar) && (var.GetsAssigned || param.VariablesToGenerate.Where (v => v.Name == var.Name).Any ())) { if (!outsideVar.GetsAssigned) fieldDirection = FieldDirection.Out; } invocation.Arguments.Add (new DirectionExpression (fieldDirection, new IdentifierExpression (var.Name))); } else { invocation.Arguments.Add (new IdentifierExpression (var.Name)); } } // string mimeType = DesktopService.GetMimeTypeForUri (options.Document.FileName); TypeReference returnType = new TypeReference ("System.Void", true); ICSharpCode.NRefactory.Ast.INode outputNode; if (param.OneChangedVariable) { string name = param.ChangedVariables.First (); returnType = options.ShortenTypeName (param.Variables.Find (v => v.Name == name).ReturnType).ConvertToTypeReference (); if (param.OutsideVariableList.Any (v => v.Name == name && !v.IsDefined)) { LocalVariableDeclaration varDecl = new LocalVariableDeclaration (returnType); varDecl.Variables.Add (new VariableDeclaration (name, invocation)); outputNode = varDecl; } else { outputNode = new ExpressionStatement (new AssignmentExpression (new IdentifierExpression (name), ICSharpCode.NRefactory.Ast.AssignmentOperatorType.Assign, invocation)); } } else { outputNode = node is BlockStatement ? (ICSharpCode.NRefactory.Ast.INode)new ExpressionStatement (invocation) : invocation; } TextReplaceChange replacement = new TextReplaceChange (); replacement.Description = string.Format (GettextCatalog.GetString ("Substitute selected statement(s) with call to {0}"), param.Name); replacement.FileName = options.Document.FileName; replacement.Offset = options.Document.Editor.SelectionRange.Offset; replacement.RemovedChars = options.Document.Editor.SelectionRange.Length; replacement.MoveCaretToReplace = true; LineSegment line1 = data.Document.GetLineByOffset (options.Document.Editor.SelectionRange.EndOffset); if (options.Document.Editor.SelectionRange.EndOffset == line1.Offset) { if (line1.Offset > 0) { LineSegment line2 = data.Document.GetLineByOffset (line1.Offset - 1); replacement.RemovedChars -= line2.DelimiterLength; } } replacement.InsertedText = options.GetWhitespaces (options.Document.Editor.SelectionRange.Offset) + provider.OutputNode (options.Dom, outputNode).Trim (); result.Add (replacement); TextReplaceChange insertNewMethod = new TextReplaceChange (); insertNewMethod.FileName = options.Document.FileName; insertNewMethod.Description = string.Format (GettextCatalog.GetString ("Create new method {0} from selected statement(s)"), param.Name); insertNewMethod.RemovedChars = param.InsertionPoint.LineBefore == NewLineInsertion.Eol ? 0 : param.InsertionPoint.Location.Column; insertNewMethod.Offset = data.Document.LocationToOffset (param.InsertionPoint.Location) - insertNewMethod.RemovedChars; ExtractMethodAstTransformer transformer = new ExtractMethodAstTransformer (param.VariablesToGenerate); node.AcceptVisitor (transformer, null); if (!param.OneChangedVariable && node is Expression) { ResolveResult resolveResult = resolver.Resolve (new ExpressionResult ("(" + provider.OutputNode (options.Dom, node) + ")"), new DomLocation (options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column)); if (resolveResult.ResolvedType != null) returnType = options.ShortenTypeName (resolveResult.ResolvedType).ConvertToTypeReference (); } MethodDeclaration methodDecl = new MethodDeclaration (); methodDecl.Name = param.Name; methodDecl.Modifier = param.Modifiers; methodDecl.TypeReference = returnType; if (!param.ReferencesMember) methodDecl.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Static; if (node is BlockStatement) { methodDecl.Body = new BlockStatement (); methodDecl.Body.AddChild (new EmptyStatement ()); if (param.OneChangedVariable) methodDecl.Body.AddChild (new ReturnStatement (new IdentifierExpression (param.ChangedVariables.First ()))); } else if (node is Expression) { methodDecl.Body = new BlockStatement (); methodDecl.Body.AddChild (new ReturnStatement (node as Expression)); } foreach (VariableDescriptor var in param.VariablesToDefine) { BlockStatement block = methodDecl.Body; LocalVariableDeclaration varDecl = new LocalVariableDeclaration (options.ShortenTypeName (var.ReturnType).ConvertToTypeReference ()); varDecl.Variables.Add (new VariableDeclaration (var.Name)); block.Children.Insert (0, varDecl); } foreach (VariableDescriptor var in param.Parameters) { TypeReference typeReference = options.ShortenTypeName (var.ReturnType).ConvertToTypeReference (); ParameterDeclarationExpression pde = new ParameterDeclarationExpression (typeReference, var.Name); if (!param.OneChangedVariable) { if (param.ChangedVariables.Contains (var.Name)) pde.ParamModifier = ICSharpCode.NRefactory.Ast.ParameterModifiers.Ref; if (param.VariablesToGenerate.Where (v => v.Name == var.Name).Any ()) { pde.ParamModifier = ICSharpCode.NRefactory.Ast.ParameterModifiers.Out; } VariableDescriptor outsideVar = null; if (var.GetsAssigned && param.VariablesOutside.TryGetValue (var.Name, out outsideVar)) { if (!outsideVar.GetsAssigned) pde.ParamModifier = ICSharpCode.NRefactory.Ast.ParameterModifiers.Out; } } methodDecl.Parameters.Add (pde); } string indent = options.GetIndent (param.DeclaringMember); StringBuilder methodText = new StringBuilder (); switch (param.InsertionPoint.LineBefore) { case NewLineInsertion.Eol: methodText.AppendLine (); break; case NewLineInsertion.BlankLine: methodText.Append (indent); methodText.AppendLine (); break; } if (param.GenerateComment) { methodText.Append (indent); methodText.AppendLine ("/// <summary>"); methodText.Append (indent); methodText.AppendLine ("/// TODO: write a comment."); methodText.Append (indent); methodText.AppendLine ("/// </summary>"); Ambience ambience = AmbienceService.GetAmbienceForFile (options.Document.FileName); foreach (ParameterDeclarationExpression pde in methodDecl.Parameters) { methodText.Append (indent); methodText.Append ("/// <param name=\""); methodText.Append (pde.ParameterName); methodText.Append ("\"> A "); methodText.Append (ambience.GetString (pde.TypeReference.ConvertToReturnType (), OutputFlags.IncludeGenerics | OutputFlags.UseFullName)); methodText.Append (" </param>"); methodText.AppendLine (); } if (methodDecl.TypeReference.Type != "System.Void") { methodText.Append (indent); methodText.AppendLine ("/// <returns>"); methodText.Append (indent); methodText.Append ("/// A "); methodText.AppendLine (ambience.GetString (methodDecl.TypeReference.ConvertToReturnType (), OutputFlags.IncludeGenerics | OutputFlags.UseFullName)); methodText.Append (indent); methodText.AppendLine ("/// </returns>"); } } methodText.Append (indent); if (node is BlockStatement) { string text = provider.OutputNode (options.Dom, methodDecl, indent).Trim (); int emptyStatementMarker = text.LastIndexOf (';'); if (param.OneChangedVariable) emptyStatementMarker = text.LastIndexOf (';', emptyStatementMarker - 1); StringBuilder sb = new StringBuilder (); sb.Append (text.Substring (0, emptyStatementMarker)); sb.Append (AddIndent (param.Text, indent + "\t")); sb.Append (text.Substring (emptyStatementMarker + 1)); methodText.Append (sb.ToString ()); } else { methodText.Append (provider.OutputNode (options.Dom, methodDecl, options.GetIndent (param.DeclaringMember)).Trim ()); } switch (param.InsertionPoint.LineAfter) { case NewLineInsertion.Eol: methodText.AppendLine (); break; case NewLineInsertion.BlankLine: methodText.AppendLine (); methodText.AppendLine (); methodText.Append (indent); break; } insertNewMethod.InsertedText = methodText.ToString (); result.Add (insertNewMethod); return result; }
public sealed override object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data) { this.BeginVisit(parameterDeclarationExpression); object result = this.TrackedVisitParameterDeclarationExpression(parameterDeclarationExpression, data); this.EndVisit(parameterDeclarationExpression); return result; }
void FixedParameter( #line 664 "Frames/cs.ATG" out ParameterDeclarationExpression p) { #line 666 "Frames/cs.ATG" TypeReference type; ParameterModifiers mod = ParameterModifiers.In; Location start = la.Location; if (la.kind == 93 || la.kind == 100) { if (la.kind == 100) { lexer.NextToken(); #line 672 "Frames/cs.ATG" mod = ParameterModifiers.Ref; } else { lexer.NextToken(); #line 673 "Frames/cs.ATG" mod = ParameterModifiers.Out; } } Type( #line 675 "Frames/cs.ATG" out type); Identifier(); #line 675 "Frames/cs.ATG" p = new ParameterDeclarationExpression(type, t.val, mod); p.StartLocation = start; p.EndLocation = t.Location; }
void FormalParameter( //#line 2948 "VBNET.ATG" out ParameterDeclarationExpression p) { //#line 2950 "VBNET.ATG" AttributeSection section; List<AttributeSection> attributes = new List<AttributeSection>(); TypeReference type = null; ParamModifierList mod = new ParamModifierList(this); Expression expr = null; p = null; ArrayList arrayModifiers = null; Location startLocation = la.Location; while (la.kind == 40) { AttributeSection( //#line 2960 "VBNET.ATG" out section); //#line 2960 "VBNET.ATG" attributes.Add(section); } while (StartOf(29)) { ParameterModifier( //#line 2961 "VBNET.ATG" mod); } Identifier(); //#line 2962 "VBNET.ATG" string parameterName = t.val; if ( //#line 2963 "VBNET.ATG" IsDims()) { ArrayTypeModifiers( //#line 2963 "VBNET.ATG" out arrayModifiers); } if (la.kind == 63) { lexer.NextToken(); TypeName( //#line 2964 "VBNET.ATG" out type); } //#line 2966 "VBNET.ATG" if(type != null) { if (arrayModifiers != null) { if (type.RankSpecifier != null) { Error("array rank only allowed one time"); } else { type.RankSpecifier = (int[])arrayModifiers.ToArray(typeof(int)); } } } if (la.kind == 20) { lexer.NextToken(); Expr( //#line 2976 "VBNET.ATG" out expr); } //#line 2978 "VBNET.ATG" mod.Check(); p = new ParameterDeclarationExpression(type, parameterName, mod.Modifier, expr); p.Attributes = attributes; p.StartLocation = startLocation; p.EndLocation = t.EndLocation; }
void FixedParameter( #line 666 "cs.ATG" out ParameterDeclarationExpression p) { #line 668 "cs.ATG" TypeReference type; ParameterModifiers mod = ParameterModifiers.In; Location start = la.Location; Expression expr; if (la.kind == 93 || la.kind == 95 || la.kind == 100) { if (la.kind == 100) { lexer.NextToken(); #line 675 "cs.ATG" mod = ParameterModifiers.Ref; } else if (la.kind == 93) { lexer.NextToken(); #line 676 "cs.ATG" mod = ParameterModifiers.Out; } else { lexer.NextToken(); #line 677 "cs.ATG" mod = ParameterModifiers.Params; } } Type( #line 679 "cs.ATG" out type); Identifier(); #line 680 "cs.ATG" p = new ParameterDeclarationExpression(type, t.val, mod); if (la.kind == 3) { lexer.NextToken(); Expr( #line 681 "cs.ATG" out expr); #line 681 "cs.ATG" p.DefaultValue = expr; p.ParamModifier |= ParameterModifiers.Optional; } #line 682 "cs.ATG" p.StartLocation = start; p.EndLocation = t.EndLocation; }