public override void GenerateCode(List<AbstractNode> nodes, IList items)
		{
			TypeReference stringReference = new TypeReference("System.String");
			MethodDeclaration method = new MethodDeclaration("ToString",
			                                                 Modifiers.Public | Modifiers.Override,
			                                                 stringReference,
			                                                 null, null);
			method.Body = new BlockStatement();
			Expression target = new FieldReferenceExpression(new TypeReferenceExpression(stringReference),
			                                                 "Format");
			InvocationExpression methodCall = new InvocationExpression(target);
			StringBuilder formatString = new StringBuilder();
			formatString.Append('[');
			formatString.Append(currentClass.Name);
			for (int i = 0; i < items.Count; i++) {
				formatString.Append(' ');
				formatString.Append(codeGen.GetPropertyName(((FieldWrapper)items[i]).Field.Name));
				formatString.Append("={");
				formatString.Append(i);
				formatString.Append('}');
			}
			formatString.Append(']');
			methodCall.Arguments.Add(new PrimitiveExpression(formatString.ToString(), formatString.ToString()));
			foreach (FieldWrapper w in items) {
				methodCall.Arguments.Add(new FieldReferenceExpression(new ThisReferenceExpression(), w.Field.Name));
			}
			method.Body.AddChild(new ReturnStatement(methodCall));
			nodes.Add(method);
		}
Пример #2
0
 public override object TrackedVisitTypeReference(TypeReference typeReference, object data)
 {
     string name = typeReference.Type;
     if (name.IndexOf('.') != -1)
         Add(name);
     return base.TrackedVisitTypeReference(typeReference, data);
 }
Пример #3
0
        void CreateDelegate(DefaultClass c, string name, AST.TypeReference returnType, IList <AST.TemplateDefinition> templates, IList <AST.ParameterDeclarationExpression> parameters)
        {
            c.BaseTypes.Add(c.ProjectContent.SystemTypes.Delegate);
            if (currentClass.Count > 0)
            {
                DefaultClass cur = GetCurrentClass();
                cur.InnerClasses.Add(c);
                c.FullyQualifiedName = cur.FullyQualifiedName + '.' + name;
            }
            else
            {
                c.FullyQualifiedName = PrependCurrentNamespace(name);
                cu.Classes.Add(c);
            }
            c.UsingScope = currentNamespace;
            currentClass.Push(c);             // necessary for CreateReturnType
            ConvertTemplates(templates, c);

            List <IParameter> p = new List <IParameter>();

            if (parameters != null)
            {
                foreach (AST.ParameterDeclarationExpression param in parameters)
                {
                    p.Add(CreateParameter(param));
                }
            }
            AnonymousMethodReturnType.AddDefaultDelegateMethod(c, CreateReturnType(returnType), p);

            currentClass.Pop();
        }
Пример #4
0
		public LocalLookupVariable(TypeReference typeRef, Location startPos, Location endPos, bool isConst)
		{
			this.typeRef = typeRef;
			this.startPos = startPos;
			this.endPos = endPos;
			this.isConst = isConst;
		}
 public static VariableDeclaration add_Variable(this BlockStatement blockDeclaration, string name, Expression expression, TypeReference typeReference)
 {
     var variableDeclaration = new VariableDeclaration(name, expression) {TypeReference = typeReference};
     var localVariableDeclaration = new LocalVariableDeclaration(variableDeclaration);
     blockDeclaration.append(localVariableDeclaration);
     return variableDeclaration;
 }
Пример #6
0
        public override object TrackedVisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            if (invocationExpression.TargetObject is FieldReferenceExpression)
            {
                FieldReferenceExpression targetObject = (FieldReferenceExpression) invocationExpression.TargetObject;

                if (targetObject.FieldName == "toArray" || targetObject.FieldName == "ToArray")
                {
                    Expression invoker = targetObject.TargetObject;
                    TypeReference invokerType = GetExpressionType(invoker);
                    if (invokerType != null && collectionTypes.Contains(invokerType.Type))
                    {
                        if (invocationExpression.Arguments.Count == 1)
                        {
                            Expression argExpression = (Expression) invocationExpression.Arguments[0];
                            if (argExpression is ArrayCreateExpression)
                            {
                                InvocationExpression newInvocation = invocationExpression;
                                TypeReference old = ((ArrayCreateExpression) argExpression).CreateType;
                                TypeReference tr = new TypeReference(old.Type);
                                TypeOfExpression tof = new TypeOfExpression(tr);
                                tr.Parent = tof;
                                tof.Parent = newInvocation;
                                newInvocation.Arguments.Clear();
                                newInvocation.Arguments.Add(tof);

                                ReplaceCurrentNode(newInvocation);
                            }
                        }
                    }
                }
            }
            return base.TrackedVisitInvocationExpression(invocationExpression, 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;
        }
 /// <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;
 }
Пример #9
0
 public static IReturnType CreateReturnType(TypeReference reference, NRefactoryResolver resolver)
 {
     return CreateReturnType(reference,
                             resolver.CallingClass, resolver.CallingMember,
                             resolver.CaretLine, resolver.CaretColumn,
                             resolver.ProjectContent, ReturnTypeOptions.None);
 }
		public static Expression CreateDefaultValueForType(TypeReference type)
		{
			if (type != null && !type.IsArrayType) {
				switch (type.Type) {
					case "System.SByte":
					case "System.Byte":
					case "System.Int16":
					case "System.UInt16":
					case "System.Int32":
					case "System.UInt32":
					case "System.Int64":
					case "System.UInt64":
					case "System.Single":
					case "System.Double":
						return new PrimitiveExpression(0, "0");
					case "System.Char":
						return new PrimitiveExpression('\0', "'\\0'");
					case "System.Object":
					case "System.String":
						return new PrimitiveExpression(null, "null");
					case "System.Boolean":
						return new PrimitiveExpression(false, "false");
					default:
						return new DefaultValueExpression(type);
				}
			} else {
				return new PrimitiveExpression(null, "null");
			}
		}
		public HasAssignmentsVisitor(string name, TypeReference type, Location startRange, Location endRange)
		{
			this.name = name;
			this.type = type;
			this.startRange = startRange;
			this.endRange = endRange;
		}
Пример #12
0
 public override object TrackedVisitBlockStatement(BlockStatement blockStatement, object data)
 {
     blockStatement.Children.Clear();
     TypeReference notImplmentedException = new TypeReference("System.NotImplementedException");
     ObjectCreateExpression objectCreate = new ObjectCreateExpression(notImplmentedException, new List<Expression>());
     blockStatement.Children.Add(new ThrowStatement(objectCreate));
     return null;
 }
		bool IsIn(TypeReference type, List<TypeReference> list)
		{
			foreach (TypeReference tr in list) {
				if (tr.Type == type.Type)
					return true;
			}
			
			return false;
		}
        public void HasReturnValue_HasOne()
        {
            var methodToTest = new MethodDeclaration();
            var retval = new TypeReference("string", new[] { 0 });
            methodToTest.TypeReference = retval;
            var victim = new TestableMethodTemplate(methodToTest, null);

            Assert.IsTrue(victim.HasReturnValue);
        }
Пример #15
0
 public TypeReference[] GetArgumentTypes(string sig)
 {
     Match m = methodRegex.Match(sig);
     int count = m.Groups["param"].Captures.Count;
     TypeReference[] arguments = new TypeReference[count];
     for (int i = 0; i < count; i++)
         arguments[i] = GetTypeReference(m.Groups["param"].Captures[i].Value);
     return arguments;
 }
Пример #16
0
        public static IReturnType CreateReturnType(TypeReference reference, IClass callingClass,
		                                           IMember callingMember, int caretLine, int caretColumn,
		                                           IProjectContent projectContent,
		                                           bool useLazyReturnType)
        {
            return CreateReturnType(reference, callingClass, callingMember, caretLine, caretColumn,
                                    projectContent,
                                    useLazyReturnType ? ReturnTypeOptions.Lazy : ReturnTypeOptions.None);
        }
        public void HasReturnValue_HasVoid()
        {
            var methodToTest = new MethodDeclaration();
            var retval = new TypeReference("void");
            methodToTest.TypeReference = retval;
            var victim = new TestableMethodTemplate(methodToTest, null);

            Assert.IsFalse(victim.HasReturnValue);
        }
Пример #18
0
 public TypeReference GetTypeReference(string val)
 {
     string type = val.TrimStart('[', 'L').Replace("$", ".").TrimEnd(';');
     if (types.Contains(type))
         type = (string) types[type];
     TypeReference typeRef = new TypeReference(type);
     if (val.StartsWith("["))
         typeRef.RankSpecifier = new int[1] {0};
     return typeRef;
 }
Пример #19
0
 public LocalLookupVariable(string name, TypeReference typeRef, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer)
 {
     this.Name = name;
     this.TypeRef = typeRef;
     this.StartPos = startPos;
     this.EndPos = endPos;
     this.IsConst = isConst;
     this.IsLoopVariable = isLoopVariable;
     this.Initializer = initializer;
 }
Пример #20
0
 static IReturnType CreateReturnType(AST.TypeReference reference, IMethod method, IClass currentClass, ICompilationUnit cu, TypeVisitor.ReturnTypeOptions options)
 {
     if (currentClass == null)
     {
         return(TypeVisitor.CreateReturnType(reference, new DefaultClass(cu, "___DummyClass"), method, 1, 1, cu.ProjectContent, options | TypeVisitor.ReturnTypeOptions.Lazy));
     }
     else
     {
         return(TypeVisitor.CreateReturnType(reference, currentClass, method, currentClass.Region.BeginLine + 1, 1, cu.ProjectContent, options | TypeVisitor.ReturnTypeOptions.Lazy));
     }
 }
        public override object VisitTypeReference(TypeReference typeReference, object data)
        {
            var withinRange = _column >= typeReference.StartLocation.Column && _column < typeReference.StartLocation.Column + typeReference.Type.Length;

            if (typeReference.StartLocation.Line == _line && withinRange)
            {
                Found = typeReference.Type;
                return(true);
            }
            return(base.VisitTypeReference(typeReference, data));
        }
		public LocalLookupVariable(string name, TypeReference typeRef, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer, LambdaExpression parentLambdaExpression, bool isQueryContinuation)
		{
			this.Name = name;
			this.TypeRef = typeRef;
			this.StartPos = startPos;
			this.EndPos = endPos;
			this.IsConst = isConst;
			this.IsLoopVariable = isLoopVariable;
			this.Initializer = initializer;
			this.ParentLambdaExpression = parentLambdaExpression;
			this.IsQueryContinuation = isQueryContinuation;
		}
Пример #23
0
		string GetDotNetNameFromTypeReference(TypeReference type)
		{
			string name;
			InnerClassTypeReference ictr = type as InnerClassTypeReference;
			if (ictr != null) {
				name = GetDotNetNameFromTypeReference(ictr.BaseType) + "+" + ictr.Type;
			} else {
				name = type.Type;
			}
			if (type.GenericTypes.Count != 0)
				name = name + "`" + type.GenericTypes.Count.ToString();
			return name;
		}
Пример #24
0
		public void AddVariable(TypeReference typeRef, string name, Location startPos, Location endPos, bool isConst)
		{
			if (name == null || name.Length == 0) {
				return;
			}
			List<LocalLookupVariable> list;
			if (!variables.ContainsKey(name)) {
				variables[name] = list = new List<LocalLookupVariable>();
			} else {
				list = (List<LocalLookupVariable>)variables[name];
			}
			list.Add(new LocalLookupVariable(typeRef, startPos, endPos, isConst));
		}
        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);
        }
Пример #26
0
        private Expression GetReplacedExpression(TypeReference typeReference)
        {
            TypeOfExpression typeOfExpression = new TypeOfExpression(typeReference);
            Expression replacedExpression = typeOfExpression;

            if (Mode == "IKVM")
            {
                InvocationExpression methodInvocation = CreateGetClassMethodInvocation(typeOfExpression);
                replacedExpression = methodInvocation;
            }

            replacedExpression.Parent = typeReference.Parent.Parent;
            return replacedExpression;
        }
        public override object TrackedVisitTypeReference(TypeReference typeReference, object data)
        {
            string type = typeReference.Type;
            if (type.StartsWith("System.") && typeReference.Parent != null)
            {
                string name = type.Substring(type.LastIndexOf('.') + 1);

                TypeReference newTypeReference = typeReference;
                newTypeReference.Type = name;
                ReplaceCurrentNode(newTypeReference);

                AddUsing(typeReference, data, type);
            }
            return null;
        }
		public void AddVariable(TypeReference typeRef, string name,
		                        Location startPos, Location endPos, bool isConst,
		                        bool isLoopVariable, Expression initializer,
		                        LambdaExpression parentLambdaExpression)
		{
			if (name == null || name.Length == 0) {
				return;
			}
			List<LocalLookupVariable> list;
			if (!variables.ContainsKey(name)) {
				variables[name] = list = new List<LocalLookupVariable>();
			} else {
				list = (List<LocalLookupVariable>)variables[name];
			}
			list.Add(new LocalLookupVariable(name, typeRef, startPos, endPos, isConst, isLoopVariable, initializer, parentLambdaExpression));
		}
Пример #29
0
		public override void GenerateCode(List<AbstractNode> nodes, IList items)
		{
			TypeReference intReference = new TypeReference("System.Int32");
			MethodDeclaration method = new MethodDeclaration("GetHashCode", Modifiers.Public | Modifiers.Override, intReference, null, null);
			Expression expr = CallGetHashCode(new IdentifierExpression(currentClass.Fields[0].Name));
			for (int i = 1; i < currentClass.Fields.Count; i++) {
				IdentifierExpression identifier = new IdentifierExpression(currentClass.Fields[i].Name);
				expr = new BinaryOperatorExpression(expr, BinaryOperatorType.ExclusiveOr,
				                                    CallGetHashCode(identifier));
			}
			method.Body = new BlockStatement();
			method.Body.AddChild(new ReturnStatement(expr));
			nodes.Add(method);
			
			TypeReference boolReference = new TypeReference("System.Boolean");
			TypeReference objectReference = new TypeReference("System.Object");
			
			method = new MethodDeclaration("Equals", Modifiers.Public | Modifiers.Override, boolReference, null, null);
			method.Parameters.Add(new ParameterDeclarationExpression(objectReference, "obj"));
			method.Body = new BlockStatement();
			
			TypeReference currentType = ConvertType(currentClass.DefaultReturnType);
			expr = new TypeOfIsExpression(new IdentifierExpression("obj"), currentType);
			expr = new ParenthesizedExpression(expr);
			expr = new UnaryOperatorExpression(expr, UnaryOperatorType.Not);
			method.Body.AddChild(new IfElseStatement(expr, new ReturnStatement(new PrimitiveExpression(false, "false"))));
			
			expr = new BinaryOperatorExpression(new ThisReferenceExpression(),
			                                    BinaryOperatorType.Equality,
			                                    new IdentifierExpression("obj"));
			method.Body.AddChild(new IfElseStatement(expr, new ReturnStatement(new PrimitiveExpression(true, "true"))));
			
			VariableDeclaration var = new VariableDeclaration("my" + currentClass.Name,
			                                                  new CastExpression(currentType, new IdentifierExpression("obj"), CastType.Cast),
			                                                  currentType);
			method.Body.AddChild(new LocalVariableDeclaration(var));
			
			expr = TestEquality(var.Name, currentClass.Fields[0]);
			for (int i = 1; i < currentClass.Fields.Count; i++) {
				expr = new BinaryOperatorExpression(expr, BinaryOperatorType.LogicalAnd,
				                                    TestEquality(var.Name, currentClass.Fields[i]));
			}
			
			method.Body.AddChild(new ReturnStatement(expr));
			
			nodes.Add(method);
		}
Пример #30
0
 public override object VisitTypeReference(TypeReference typeReference, object data)
 {
     string fullName = typeReference.Type;
     string shortName = GetShortName(fullName);
     if (shortName != null) {
         typeReference.Type = shortName;
         return null;
     }
     if (fullName.EndsWith("[]")) {
         shortName = GetShortName(fullName.Replace("[]",""));
         if (shortName != null) {
             typeReference.Type = shortName + "[]";
             return null;
         }
     }
     return null;
 }
 /// <summary>
 /// Provides a mechanism for making a <see cref="ConstructorDeclaration"/> a bit more like a
 /// <see cref="MethodDeclaration"/> by simulating a common method for the result of their respective executions.
 /// </summary>
 /// 
 /// <param name="node">
 /// A constructor or method.
 /// </param>
 /// 
 /// <param name="parentType">
 /// The <see cref="TypeDeclaration"/> in which the constructor or method denoted by <paramref name="node"/> can
 /// be found.
 /// </param>
 /// 
 /// <returns>
 /// A <see cref="TypeReference"/>, if one could be determined; otherwise <see cref="NullTypeReference"/>.
 /// </returns>
 public static TypeReference GetTypeReference(this ParametrizedNode node, TypeDeclaration parentType)
 {
     var result = TypeReference.Null;
     var method = node as MethodDeclaration;
     if(method != null)
     {
         result = method.TypeReference;
     }
     else
     {
         var constructor = node as ConstructorDeclaration;
         if (constructor != null)
         {
             result = new TypeReference(parentType.Name);
         }
     }
     return result;
 }
        public void MethodInDefaultType()
        {
            string program = TestUtil.StatementParse("getClass();");
            string expected = TestUtil.CSharpStatementParse("java.lang.Object.instancehelper_getClass(this);");

            CompilationUnit cu = TestUtil.ParseProgram(program);
            NamespaceDeclaration ns = (NamespaceDeclaration) cu.Children[0];
            TypeDeclaration type = (TypeDeclaration) ns.Children[0];
            TypeReference objectType = new TypeReference("java.lang.Object");
            type.BaseTypes.Add(objectType);

            CodeBase.Types.Clear();
            CodeBase.Types.Add("Test.Test", type);

            VisitCompilationUnit(cu, null);
            RemoveBaseTypeFrom(type, objectType);
            TestUtil.CodeEqual(expected, TestUtil.GenerateCode(cu));
        }
Пример #33
0
		public static TypeReference ConvertToTypeReference (this MonoDevelop.Projects.Dom.IReturnType returnType)
		{
			List<TypeReference> genericTypes = new List<TypeReference> ();
			foreach (MonoDevelop.Projects.Dom.IReturnType genericType in returnType.GenericArguments) {
				genericTypes.Add (ConvertToTypeReference (genericType));
			}
			TypeReference result = new TypeReference (returnType.FullName, genericTypes);
			result.IsKeyword = true;
			result.PointerNestingLevel = returnType.PointerNestingLevel;
			if (returnType.ArrayDimensions > 0) {
				int[] rankSpecfier = new int[returnType.ArrayDimensions];
				for (int i = 0; i < returnType.ArrayDimensions; i++) {
					rankSpecfier[i] = returnType.GetDimension (i);
				}
				result.RankSpecifier = rankSpecfier;
			}
			return result;
		}
Пример #34
0
 IReturnType CreateReturnType(AST.TypeReference reference)
 {
     return(CreateReturnType(reference, null, TypeVisitor.ReturnTypeOptions.None));
 }
Пример #35
0
 IReturnType CreateReturnType(AST.TypeReference reference, IMethod method, TypeVisitor.ReturnTypeOptions options)
 {
     return(CreateReturnType(reference, method, GetCurrentClass(), cu, options));
 }
Пример #36
0
        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);
            }
        }
Пример #37
0
        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
                });
            }
        }
 IReturnType CreateReturnType(AST.TypeReference reference, IMethod method)
 {
     return(CreateReturnType(reference, method, GetCurrentClass(), cu));
 }
 IReturnType CreateReturnType(AST.TypeReference reference)
 {
     return(CreateReturnType(reference, null));
 }