Beispiel #1
0
        public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
        {
            Guard.AgainstNullArgument("methodDeclaration", methodDeclaration);

            IEnumerable<ParameterDeclaration> parameters = methodDeclaration
                .GetChildrenByRole(Roles.Parameter)
                .Select(x => (ParameterDeclaration)x.Clone());

            var isVoid = false;
            var isAsync = methodDeclaration.Modifiers.HasFlag(Modifiers.Async);
            AstType returnType = methodDeclaration.GetChildByRole(Roles.Type).Clone();
            var type = returnType as PrimitiveType;
            if (type != null)
            {
                isVoid = string.Compare(
                    type.Keyword, "void", StringComparison.OrdinalIgnoreCase) == 0;
            }

            var methodType = new SimpleType(Identifier.Create(isVoid ? "Action" : "Func"));

            IEnumerable<AstType> types = parameters.Select(
                x => x.GetChildByRole(Roles.Type).Clone());

            methodType
                .TypeArguments
                .AddRange(types);

            if (!isVoid)
            {
                methodType.TypeArguments.Add(returnType);
            }
            var methodName = GetIdentifierName(methodDeclaration);

            var methodBody = methodDeclaration
                .GetChildrenByRole(Roles.Body)
                .FirstOrDefault();
            if (methodBody == null)
            {
                throw new NullReferenceException(string.Format("Method '{0}' has no method body", methodName));
            }
            methodBody = (BlockStatement)methodBody.Clone();

            var prototype = new VariableDeclarationStatement { Type = methodType };
            prototype.Variables.Add(new VariableInitializer(methodName));

            var anonymousMethod = new AnonymousMethodExpression(methodBody, parameters) { IsAsync = isAsync };
            var expression = new ExpressionStatement
            {
                Expression = new AssignmentExpression(
                    new IdentifierExpression(methodName), 
                    anonymousMethod)
            };

            _methods.Add(new MethodVisitorResult
            {
                MethodDefinition = methodDeclaration,
                MethodPrototype = prototype,
                MethodExpression = expression
            });
        }
		public override void Complete(CompletionContext context)
		{
			var invokeSignature = delegateType.GetMethods(m => m.Name == "Invoke").Single();
			var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
			var builder = refactoringContext.CreateTypeSystemAstBuilder();
			var handlerName = eventDefinition.Name;
			
			var throwStatement = new ThrowStatement();
			var decl = new MethodDeclaration {
				ReturnType = refactoringContext.CreateShortType(invokeSignature.ReturnType),
				Name = handlerName,
				Body = new BlockStatement {
					throwStatement
				}
			};
			
			decl.Parameters.AddRange(invokeSignature.Parameters.Select(builder.ConvertParameter));
			
			if (eventDefinition.IsStatic)
				decl.Modifiers |= Modifiers.Static;
			
			throwStatement.Expression = new ObjectCreateExpression(refactoringContext.CreateShortType("System", "NotImplementedException"));
			
			// begin insertion
			using (context.Editor.Document.OpenUndoGroup()) {
				context.Editor.Document.Replace(context.StartOffset, context.Length, handlerName);
				context.EndOffset = context.StartOffset + handlerName.Length;
				
				using (var script = refactoringContext.StartScript()) {
					script.InsertWithCursor(this.DisplayText, Script.InsertPosition.Before, decl)
						// TODO : replace with Link, once that is implemented
						.ContinueScript(() => script.Select(throwStatement));
				}
			}
		}
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.Name.ToLower().Equals("main"))
                {
                    if (methodDeclaration.IsExtensionMethod == false &&
                        methodDeclaration.Modifiers.HasFlag(Modifiers.Static) &&
                        methodDeclaration.ReturnType.ToString() == "void")
                    {
                        var firstParam = methodDeclaration.Parameters.FirstOrDefault();

                        if (firstParam != null && firstParam.Type.ToString().ToLower() == "string[]")
                        {
                            // The following is a lesson in awesomeness:
                            //     Get all decendants of the method declaration that are IndexerExpressions,
                            //     which points to an identifier with the name [of our args variable]
                            var indexerIdentifierExpressions = methodDeclaration.Descendants
                                .OfType<IndexerExpression>()
                                .Select(a => a.Target)
                                .OfType<IdentifierExpression>();

                            if (indexerIdentifierExpressions.Any(a => a.Identifier == firstParam.Name))
                            {
                                UnlockWith(firstParam);
                            }
                        }
                    }
                }

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.IsExtensionMethod)
                    UnlockWith(methodDeclaration);

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
            public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
            {
                // Only some methods are candidates for the warning

                if (methodDeclaration.Body.IsNull)
                    return;
                var methodResolveResult = ctx.Resolve(methodDeclaration) as MemberResolveResult;
                if (methodResolveResult == null)
                    return;
                var member = methodResolveResult.Member;
                if (member.IsOverride)
                    return;
                if (member.ImplementedInterfaceMembers.Any ())
                    return;
                if (usedDelegates.UsedMethods.Any (m => m.MemberDefinition == member))
                    return;
                if (currentTypeIsPartial && methodDeclaration.Parameters.Count == 2) {
                    if (methodDeclaration.Parameters.First().Name == "sender") {
                        // Looks like an event handler; the registration might be in the designer part
                        return;
                    }
                }
                foreach (var parameter in methodDeclaration.Parameters)
                    parameter.AcceptVisitor (this);
            }
		static string GeneratePartialClassContextStub(ICodeContext context)
		{
			var member = context.CurrentMember;
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			MethodDeclaration decl;
			if (member is IMethod) {
				// If it's a method, convert it directly (including parameters + type parameters)
				decl = (MethodDeclaration)builder.ConvertEntity(member);
			} else {
				// Otherwise, create a method anyways, and copy the parameters
				decl = new MethodDeclaration();
				if (member is IParameterizedMember) {
					foreach (var p in ((IParameterizedMember)member).Parameters) {
						decl.Parameters.Add(builder.ConvertParameter(p));
					}
				}
			}
			decl.Name = "__DebuggerStub__";
			decl.ReturnType = builder.ConvertType(member.ReturnType);
			decl.Modifiers = member.IsStatic ? Modifiers.Static : Modifiers.None;
			// Make the method look like an explicit interface implementation so that it doesn't appear in CC
			decl.PrivateImplementationType = new SimpleType("__DummyType__");
			decl.Body = GenerateBodyFromContext(builder, context.LocalVariables.ToArray());
			return WrapInType(context.CurrentTypeDefinition, decl).ToString();
		}
		CodeAction CreateFromExpression(RefactoringContext context, Expression expression)
		{
			var resolveResult = context.Resolve(expression);
			if (resolveResult.IsError)
				return null;
			
			return new CodeAction(context.TranslateString("Extract method"), script => {
				string methodName = "NewMethod";
				var method = new MethodDeclaration() {
					ReturnType = context.CreateShortType(resolveResult.Type),
					Name = methodName,
					Body = new BlockStatement() {
						new ReturnStatement(expression.Clone())
					}
				};
				if (!StaticVisitor.UsesNotStaticMember(context, expression))
					method.Modifiers |= Modifiers.Static;
				var task = script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);

				Action<Task> replaceStatements = delegate {
					var target = new IdentifierExpression(methodName);
					script.Replace(expression, new InvocationExpression(target));
					script.Link(target, method.NameToken);
				};

				if (task.IsCompleted) {
					replaceStatements (null);
				} else {
					task.ContinueWith (replaceStatements, TaskScheduler.FromCurrentSynchronizationContext ());
				}
			});
		}
            public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
            {
                base.VisitMethodDeclaration (methodDeclaration);

                var resolveResult = ctx.Resolve (methodDeclaration) as MemberResolveResult;
                if (resolveResult == null)
                    return;
                var method = resolveResult.Member as IMethod;
                if (method == null)
                    return;

                if (method.Parameters.Count == 0 || !method.Parameters.Last ().IsOptional)
                    return;

                var overloads = method.DeclaringType.GetMethods(m => m.Name == method.Name && m.TypeParameters.Count == method.TypeParameters.Count)
                    .ToArray ();

                var parameterNodes = methodDeclaration.Parameters.ToArray();
                var parameters = new List<IParameter> ();
                for (int i = 0; i < method.Parameters.Count; i++) {
                    if (method.Parameters [i].IsOptional &&
                        overloads.Any (m => ParameterListComparer.Instance.Equals (parameters, m.Parameters))) {
                        AddIssue (parameterNodes [i].StartLocation, parameterNodes.Last ().EndLocation,
                            ctx.TranslateString ("Method with optional parameter is hidden by overload"));
                        break;
                    }
                    parameters.Add (method.Parameters [i]);
                }
            }
		static string GeneratePartialClassContextStub(DebuggerCompletionContext context)
		{
			var compilation = SD.ParserService.GetCompilationForFile(context.FileName);
			var file = SD.ParserService.GetExistingUnresolvedFile(context.FileName);
			if (compilation == null || file == null)
				return "";
			var unresolvedMember = file.GetMember(context.Location);
			if (unresolvedMember == null)
				return "";
			var member = unresolvedMember.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			MethodDeclaration decl;
			if (unresolvedMember is IMethod) {
				// If it's a method, convert it directly (including parameters + type parameters)
				decl = (MethodDeclaration)builder.ConvertEntity(member);
			} else {
				// Otherwise, create a method anyways, and copy the parameters
				decl = new MethodDeclaration();
				if (member is IParameterizedMember) {
					foreach (var p in ((IParameterizedMember)member).Parameters) {
						decl.Parameters.Add(builder.ConvertParameter(p));
					}
				}
			}
			decl.Name = "__DebuggerStub__";
			decl.ReturnType = builder.ConvertType(member.ReturnType);
			decl.Modifiers = unresolvedMember.IsStatic ? Modifiers.Static : Modifiers.None;
			// Make the method look like an explicit interface implementation so that it doesn't appear in CC
			decl.PrivateImplementationType = new SimpleType("__DummyType__");
			decl.Body = GenerateBodyFromContext(builder, context);
			return WrapInType(unresolvedMember.DeclaringTypeDefinition, decl).ToString();
		}
			public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration)
			{
				base.VisitMethodDeclaration (methodDeclaration);

				// partial method
				if (methodDeclaration.Body.IsNull)
					return;

				var cfg = cfgBuilder.BuildControlFlowGraph (methodDeclaration.Body, ctx.Resolver,
					ctx.CancellationToken);
				var stack = new Stack<ControlFlowNode> ();
				var visitedNodes = new HashSet<ControlFlowNode> ();
				stack.Push (cfg [0]);
				while (stack.Count > 0) {
					var node = stack.Pop ();

					// reach method's end
					if (node.PreviousStatement == methodDeclaration.Body)
						return;
					// reach a return statement
					if (node.NextStatement is ReturnStatement ||
						node.NextStatement is ThrowStatement)
						return;

					foreach (var edge in node.Outgoing) {
						if (visitedNodes.Add(edge.To))
							stack.Push(edge.To);
					}
				}

				AddIssue (methodDeclaration.NameToken, 
					ctx.TranslateString ("Method never reaches its end or a 'return' statement."));
			}
Beispiel #11
0
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.Modifiers.HasFlag(Modifiers.Abstract))
                    UnlockWith(methodDeclaration);

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
        private void ValidateMethod(MethodDeclaration method, List<string> list, CompilationResult result)
        {
            var name = method.Name;

            if (String.IsNullOrWhiteSpace(name))
            {
                result.AddError(new CompilationMessage
                {
                    FilePath = method.OriginatingTree != null ? method.OriginatingTree.FilePath : null,
                    Location = DocumentLocation.FromTreeNode(method.OriginatingTree, method.OriginatingNode),
                    Message = "All generated method calls must have a valid name."
                });

                return;
            }

            if (list.Contains(name))
            {
                result.AddError(new CompilationMessage
                {
                    FilePath = method.OriginatingTree != null ? method.OriginatingTree.FilePath : null,
                    Location = DocumentLocation.FromTreeNode(method.OriginatingTree, method.OriginatingNode),
                    Message = "Method overloading is not supported. Consider using optional parameters, " +
                        "or providing an alternate name using the ScriptName attribute."
                });

                return;
            }

            list.Add(name);
        }
Beispiel #13
0
 public static void AddPrivateImplementation(Ast.AstType type, MethodDeclaration method)
 {
     if (privateImplementations.ContainsKey(type))
         privateImplementations[type].Add(method);
     else
         privateImplementations.Add(type, new List<MethodDeclaration>() { method });
 }
		public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var entity = context.GetNode<ConstructorDeclaration>();
			if (entity == null)
				yield break;
			var type = entity.Parent as TypeDeclaration;

			if (type == null || entity.Name == type.Name)
				yield break;

			var typeDeclaration = entity.GetParent<TypeDeclaration>();

			yield return new CodeAction(context.TranslateString("This is a constructor"), script => script.Replace(entity.NameToken, Identifier.Create(typeDeclaration.Name, TextLocation.Empty)), entity) {
				Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
			};

			yield return new CodeAction(context.TranslateString("This is a void method"), script => {
				var generatedMethod = new MethodDeclaration();
				generatedMethod.Modifiers = entity.Modifiers;
				generatedMethod.ReturnType = new PrimitiveType("void");
				generatedMethod.Name = entity.Name;
				generatedMethod.Parameters.AddRange(entity.Parameters.Select(parameter => (ParameterDeclaration)parameter.Clone()));
				generatedMethod.Body = (BlockStatement)entity.Body.Clone();
				generatedMethod.Attributes.AddRange(entity.Attributes.Select(attribute => (AttributeSection)attribute.Clone()));

				script.Replace(entity, generatedMethod);
			}, entity) {
				Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
			};
		}
		void ConvertInterfaceImplementation(MethodDeclaration member)
		{
			// members without modifiers are already C# explicit interface implementations, do not convert them
			if (member.Modifier == Modifiers.None)
				return;
			while (member.InterfaceImplementations.Count > 0) {
				InterfaceImplementation impl = member.InterfaceImplementations[0];
				member.InterfaceImplementations.RemoveAt(0);
				if (member.Name != impl.MemberName) {
					MethodDeclaration newMember = new MethodDeclaration {
						Name = impl.MemberName,
						TypeReference = member.TypeReference,
						Parameters = member.Parameters,
						Body = new BlockStatement()
					};
					InvocationExpression callExpression = new InvocationExpression(new IdentifierExpression(member.Name));
					foreach (ParameterDeclarationExpression decl in member.Parameters) {
						callExpression.Arguments.Add(new IdentifierExpression(decl.ParameterName));
					}
					if (member.TypeReference.Type == "System.Void") {
						newMember.Body.AddChild(new ExpressionStatement(callExpression));
					} else {
						newMember.Body.AddChild(new ReturnStatement(callExpression));
					}
					newMember.InterfaceImplementations.Add(impl);
					InsertAfterSibling(member, newMember);
				}
			}
		}
		public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
		{
			Push();
			object result = base.VisitMethodDeclaration(methodDeclaration, data);
			Pop();
			return result;
		}
		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			VariableInitializer initializer;
			var eventDeclaration = GetEventDeclaration(context, out initializer);
			if (eventDeclaration == null) {
				yield break;
			}
			var type = (TypeDeclaration)eventDeclaration.Parent;
			if (type.Members.Any(m => m is MethodDeclaration && ((MethodDeclaration)m).Name == "On" + initializer.Name)) {
				yield break;
			}
			var resolvedType = context.Resolve(eventDeclaration.ReturnType).Type;
			if (resolvedType.Kind == TypeKind.Unknown) {
				yield break;
			}
			var invokeMethod = resolvedType.GetDelegateInvokeMethod();
			if (invokeMethod == null) {
				yield break;
			}
			yield return new CodeAction (context.TranslateString("Create event invocator"), script => {
				bool hasSenderParam = false;
				IEnumerable<IParameter> pars = invokeMethod.Parameters;
				if (invokeMethod.Parameters.Any ()) {
					var first = invokeMethod.Parameters [0];
					if (first.Name == "sender" /*&& first.Type == "System.Object"*/) {
						hasSenderParam = true;
						pars = invokeMethod.Parameters.Skip (1);
					}
				}
				const string handlerName = "handler";
						
				var arguments = new List<Expression> ();
				if (hasSenderParam)
					arguments.Add (new ThisReferenceExpression ());
				foreach (var par in pars)
					arguments.Add (new IdentifierExpression (par.Name));
				
				var methodDeclaration = new MethodDeclaration () {
					Name = "On" + initializer.Name,
					ReturnType = new PrimitiveType ("void"),
					Modifiers = ICSharpCode.NRefactory.CSharp.Modifiers.Protected | ICSharpCode.NRefactory.CSharp.Modifiers.Virtual,
					Body = new BlockStatement () {
						new VariableDeclarationStatement (eventDeclaration.ReturnType.Clone (), handlerName, new MemberReferenceExpression (new ThisReferenceExpression (), initializer.Name)),
						new IfElseStatement () {
							Condition = new BinaryOperatorExpression (new IdentifierExpression (handlerName), BinaryOperatorType.InEquality, new PrimitiveExpression (null)),
							TrueStatement = new ExpressionStatement (new InvocationExpression (new IdentifierExpression (handlerName), arguments))
						}
					}
				};
				
				foreach (var par in pars) {
					var typeName = context.CreateShortType (par.Type);
					var decl = new ParameterDeclaration (typeName, par.Name);
					methodDeclaration.Parameters.Add (decl);
				}
				
				script.InsertWithCursor (context.TranslateString("Create event invocator"), methodDeclaration, Script.InsertPosition.After);
			});
		}
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                var lines = methodDeclaration.Body.Sum(x => (x.EndLocation.Line - x.StartLocation.Line) + 1);
                if (lines >= 300)
                    UnlockWith(methodDeclaration);

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
			public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
			{
				var primitiveType = methodDeclaration.ReturnType as PrimitiveType;
				if (primitiveType == null || primitiveType.Keyword != "void")
					return;
				currentMethodName = methodDeclaration.Name;
				base.VisitMethodDeclaration(methodDeclaration);
			}
 public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
 {
     if (methodDeclaration.HasModifier(Modifiers.Static))
     {
         this.CheckDependency(methodDeclaration.ReturnType);
         base.VisitMethodDeclaration(methodDeclaration);
     }
 }
Beispiel #21
0
 public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
 {
     if (methodDeclaration.Name.Equals("Main"))
     {
         if (!methodDeclaration.Body.Statements.Any())
             UnlockWith(methodDeclaration);
     }
     return base.VisitMethodDeclaration(methodDeclaration, data);
 }
        public static Method Method(NRefactory.MethodDeclaration methodDeclaration, object context, INRefcatoryExpressionVisitor visitor, IScope scope = null) {
            Method methodBlock = null;

            if (!methodDeclaration.IsCompilerGeneratorEnumerator(ref methodBlock)) {
                methodBlock = new MethodDeclaration(methodDeclaration, context, scope, visitor);
            }

            return methodBlock;
        }
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                string modifiers = methodDeclaration.Modifiers.ToString();

                if (modifiers.Split(",".ToCharArray()).Length >= 2)
                    UnlockWith(methodDeclaration);

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
        public static OverloadsCollection Create(IEmitter emitter, MethodDeclaration methodDeclaration)
        {
            string key = methodDeclaration.GetHashCode().ToString();
            if (emitter.OverloadsCache.ContainsKey(key))
            {
                return emitter.OverloadsCache[key];
            }

            return new OverloadsCollection(emitter, methodDeclaration);
        }
Beispiel #25
0
            public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
            {
                if (methodDeclaration.Body != null)
                {
                    if (methodDeclaration.Body.Children.Count() == 0)
                        UnlockWith(methodDeclaration);
                }

                return base.VisitMethodDeclaration(methodDeclaration, data);
            }
 private void AddMainMethod(Compilation compilation, List<Statement> bodyOfMainRoutine, FieldDeclaration labelField) {
   MethodDeclaration mainMethod = new MethodDeclaration(null, 0, TypeMemberVisibility.Public,
     TypeExpression.For(compilation.PlatformType.SystemVoid.ResolvedType), null, new NameDeclaration(compilation.NameTable.GetNameFor("Main"), SourceDummy.SourceLocation), null, 
     null, null, new BlockStatement(bodyOfMainRoutine, this.SourceLocation), this.SourceLocation);
   bodyOfMainRoutine.Add(new SwitchStatement(new SimpleName(labelField.Name, SourceDummy.SourceLocation, false), this.cases, SourceDummy.SourceLocation));
   bodyOfMainRoutine.Add(new LabeledStatement(new NameDeclaration(labelField.Name, SourceDummy.SourceLocation), new EmptyStatement(false, SourceDummy.SourceLocation), SourceDummy.SourceLocation));
   this.AddLabel(new SimpleName(labelField.Name, SourceDummy.SourceLocation, false));
   this.members.Add(mainMethod);
   this.mainMethod = mainMethod;
 }
        public MethodReferenceExpression(Expression target,MethodDeclaration method)
        {
            if (target==null)
                throw new ArgumentNullException("target");
            if (method==null)
                throw new ArgumentNullException("method");

            this.target = target;
            this.declaringMethod = method;
        }
		CodeAction GetAction (RefactoringContext context, AstNode node, MethodDeclaration method)
		{
			return new CodeAction (context.TranslateString ("Extract anonymous method"),
				script =>
				{
					var identifier = new IdentifierExpression ("Method");
					script.Replace (node, identifier);
					script.InsertBefore (node.GetParent<EntityDeclaration> (), method);
					script.Link (method.NameToken, identifier);
				});
		}
		CodeAction CreateFromExpression(RefactoringContext context, Expression expression)
		{
			var resolveResult = context.Resolve(expression);
			if (resolveResult.IsError)
				return null;
			
			return new CodeAction(context.TranslateString("Extract method"), script => {
				string methodName = "NewMethod";
				var method = new MethodDeclaration {
					ReturnType = context.CreateShortType(resolveResult.Type),
					Name = methodName,
					Body = new BlockStatement {
						new ReturnStatement(expression.Clone())
					}
				};
				if (!StaticVisitor.UsesNotStaticMember(context, expression))
					method.Modifiers |= Modifiers.Static;

				var usedVariables = VariableLookupVisitor.Analyze(context, expression);
				
				var inExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);

				usedVariables.Sort ((l, r) => l.Region.Begin.CompareTo (r.Region.Begin));
				var target = new IdentifierExpression(methodName);
				var invocation = new InvocationExpression(target);
				foreach (var variable in usedVariables) {
					Expression argumentExpression = new IdentifierExpression(variable.Name); 
					
					var mod = ParameterModifier.None;
					if (inExtractedRegion.GetStatus (variable) == VariableState.Changed) {
						mod = ParameterModifier.Ref;
						argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
					}
					
					method.Parameters.Add(new ParameterDeclaration(context.CreateShortType(variable.Type), variable.Name, mod));
					invocation.Arguments.Add(argumentExpression);
				}

				var task = script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);

				Action<Task> replaceStatements = delegate {
					script.Replace(expression, invocation);
					script.Link(target, method.NameToken);
				};

				if (task.IsCompleted) {
					replaceStatements (null);
				} else {
					task.ContinueWith (replaceStatements, TaskScheduler.FromCurrentSynchronizationContext ());
				}
			});
		}
			public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
			{
				// Check that this declaration is a GetHashCode override, _then_ continue traversing

				if (methodDeclaration.Name != "GetHashCode") {
					return;
				}
				if (!methodDeclaration.Modifiers.HasFlag(Modifiers.Override)) {
					return;
				}

				base.VisitMethodDeclaration(methodDeclaration);
			}
 public override AstNode VisitMethodDeclaration(MethodDeclaration methodDeclaration)
 {
     return(TransformDestructor(methodDeclaration) ?? base.VisitMethodDeclaration(methodDeclaration));
 }
 public static MethodDeclaration name(this MethodDeclaration methodDeclaration, string methodName)
 {
     methodDeclaration.Name = methodName;
     return(methodDeclaration);
 }
 public static MethodDeclaration body(this MethodDeclaration methodDeclaration, BlockStatement newBody)
 {
     methodDeclaration.Body = newBody;
     return(methodDeclaration);
 }
Beispiel #34
0
 protected virtual bool HasDelegateAttribute(MethodDeclaration method)
 {
     return(this.GetAttribute(method.Attributes, "Delegate") != null);
 }
Beispiel #35
0
        static private ProcessTemplate CreateModuleAccessPermissionCheck(ProcessTemplate ATemplate,
                                                                         string AConnectorClassWithNamespace,
                                                                         MethodDeclaration m)
        {
            if (m.Attributes != null)
            {
                foreach (AttributeSection attrSection in m.Attributes)
                {
                    foreach (ICSharpCode.NRefactory.Ast.Attribute attr in attrSection.Attributes)
                    {
                        if (attr.Name == "RequireModulePermission")
                        {
                            ProcessTemplate snippet = ATemplate.GetSnippet("CHECKUSERMODULEPERMISSIONS");
                            snippet.SetCodelet("METHODNAME", m.Name);
                            snippet.SetCodelet("CONNECTORWITHNAMESPACE", AConnectorClassWithNamespace);
                            snippet.SetCodelet("LEDGERNUMBER", "");

                            string ParameterTypes = ";";

                            foreach (ParameterDeclarationExpression p in m.Parameters)
                            {
                                if (p.ParameterName == "ALedgerNumber")
                                {
                                    snippet.SetCodelet("LEDGERNUMBER", ", ALedgerNumber");
                                }

                                string ParameterType = p.TypeReference.Type.Replace("&", "").Replace("System.", String.Empty);

                                if (ParameterType == "List")
                                {
                                    ParameterType = ParameterType.Replace("List", "List[" + p.TypeReference.GenericTypes[0].ToString() + "]");
                                    ParameterType = ParameterType.Replace("System.", String.Empty);
                                }

                                if (ParameterType == "Dictionary")
                                {
                                    // this does not seem to work with Mono 5.12 api browser
                                    // ParameterType = ParameterType.Replace("Dictionary", "Dictionary[" +
                                    //    p.TypeReference.GenericTypes[0].ToString() + "," +
                                    //    p.TypeReference.GenericTypes[1].ToString() + "]");
                                    // ParameterType = ParameterType.Replace("System.", String.Empty);
                                    ParameterType = "String";
                                }

                                if (ParameterType.Contains("."))
                                {
                                    ParameterType = ParameterType.Substring(ParameterType.LastIndexOf(".") + 1);
                                }

                                if (p.TypeReference.Type == "System.Nullable")
                                {
                                    ParameterType = ParameterType.Replace("Nullable", "Nullable[" + p.TypeReference.GenericTypes[0].ToString() + "]");
                                }

                                if (p.TypeReference.IsArrayType)
                                {
                                    ParameterType += ".ARRAY";
                                }

//                            if (ParameterType == "SortedList")
//                            {
//Console.WriteLine(p.ParameterName + "'s ParameterType = SortedList");
//                                ParameterType = ParameterType.Replace("List", "List[" +
//                                    p.TypeReference.GenericTypes[0].ToString() + "," +
//                                    p.TypeReference.GenericTypes[1].ToString() + "]");
//                                ParameterType = ParameterType.Replace("System.", String.Empty);
//                            }

                                ParameterType = ParameterType.Replace("Boolean", "bool");
                                ParameterType = ParameterType.Replace("Int32", "int");
                                ParameterType = ParameterType.Replace("Int64", "long");

                                ParameterTypes += ParameterType + ";";
                            }

                            ParameterTypes = ParameterTypes.ToUpper();
                            snippet.SetCodelet("PARAMETERTYPES", ParameterTypes);
                            return(snippet);
                        }
                        else if (attr.Name == "CheckServerAdminToken")
                        {
                            ProcessTemplate snippet         = ATemplate.GetSnippet("CHECKSERVERADMINPERMISSION");
                            string          paramdefinition = "string AServerAdminSecurityToken";

                            if (ATemplate.FCodelets["PARAMETERDEFINITION"].Length != 0)
                            {
                                paramdefinition += ", ";
                            }

                            ATemplate.AddToCodeletPrepend("PARAMETERDEFINITION", paramdefinition);
                            return(snippet);
                        }
                    }
                }
            }

            TLogging.Log("Warning !!! Missing module access permissions for " + AConnectorClassWithNamespace + "::" + m.Name);

            return(new ProcessTemplate());
        }
Beispiel #36
0
        /// <summary>
        /// 完善本地绑定的方法
        /// </summary>
        /// <param name="item"></param>
        protected void CompleteMethod(BindingEvent item)
        {
            var funcNode = classNode.Descendants.OfType <MethodDeclaration>().Where(x => x.Name == item.bindingSource).FirstOrDefault();

            if (funcNode == null)
            {
                UnityEngine.Debug.Assert(item.bindingTargetType.type != null, item.bindingSource + ":" + item.bindingTarget);
                var parameter = item.bindingTargetType.type.GetMethod("AddListener").GetParameters()[0];
                List <ParameterDeclaration> arguments = new List <ParameterDeclaration>();
                var parameters = parameter.ParameterType.GetGenericArguments();
                int count      = 0;

                var oldType = typeof(PanelBase).Assembly.GetType(classNode.Name);
                System.Reflection.MethodInfo oldMethod = null;
                if (oldType != null)
                {
                    oldMethod = oldType.GetMethod(item.bindingSource, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                }

                System.Reflection.ParameterInfo[] oldParamters = null;

                if (oldMethod != null)
                {
                    if (parameters.Count() == 0)
                    {
                        return;
                    }
                    else
                    {
                        oldParamters = oldMethod.GetParameters();
                    }
                }

                bool sameFunc = parameters.Length > 0;

                for (int i = 0; i < parameters.Length; i++)
                {
                    var para = parameters[i];
                    if (oldParamters != null)
                    {
                        var oldParam = oldParamters[i];
                        if (oldParam.ParameterType.FullName != para.FullName)
                        {
                            sameFunc = false;
                        }
                    }
                    else
                    {
                        sameFunc = false;
                    }

                    ParameterDeclaration argument = new ParameterDeclaration(new BridgeUI.NRefactory.CSharp.PrimitiveType(para.FullName), "arg" + count++);
                    arguments.Add(argument);
                }

                if (!sameFunc)
                {
                    funcNode            = new MethodDeclaration();
                    funcNode.Name       = item.bindingSource;
                    funcNode.Modifiers |= Modifiers.Protected;
                    funcNode.ReturnType = new BridgeUI.NRefactory.CSharp.PrimitiveType("void");
                    funcNode.Parameters.AddRange(arguments);
                    funcNode.Body = new BlockStatement();
                    classNode.AddChild(funcNode, Roles.TypeMemberRole);
                }
            }
        }
            protected override IEnumerable <string> GenerateCode(List <object> includedMembers)
            {
                // Genereate Equals
                var methodDeclaration = new MethodDeclaration();

                methodDeclaration.Name = "Equals";

                methodDeclaration.ReturnType = new PrimitiveType("bool");
                methodDeclaration.Modifiers  = ICSharpCode.NRefactory.CSharp.Modifiers.Public | ICSharpCode.NRefactory.CSharp.Modifiers.Override;
                methodDeclaration.Body       = new BlockStatement();
                methodDeclaration.Parameters.Add(new ParameterDeclaration(new PrimitiveType("object"), "obj"));
                var             paramId     = new IdentifierExpression("obj");
                IfElseStatement ifStatement = new IfElseStatement();

                ifStatement.Condition     = new BinaryOperatorExpression(paramId, BinaryOperatorType.Equality, new PrimitiveExpression(null));
                ifStatement.TrueStatement = new ReturnStatement(new PrimitiveExpression(false));
                methodDeclaration.Body.Statements.Add(ifStatement);

                ifStatement = new IfElseStatement();
                var arguments = new List <Expression> ();

                arguments.Add(new ThisReferenceExpression());
                arguments.Add(paramId.Clone());
                ifStatement.Condition     = new InvocationExpression(new IdentifierExpression("ReferenceEquals"), arguments);
                ifStatement.TrueStatement = new ReturnStatement(new PrimitiveExpression(true));
                methodDeclaration.Body.Statements.Add(ifStatement);

                ifStatement               = new IfElseStatement();
                ifStatement.Condition     = new BinaryOperatorExpression(new InvocationExpression(new MemberReferenceExpression(paramId.Clone(), "GetType")), BinaryOperatorType.InEquality, new TypeOfExpression(new SimpleType(Options.EnclosingType.Name)));
                ifStatement.TrueStatement = new ReturnStatement(new PrimitiveExpression(false));
                methodDeclaration.Body.Statements.Add(ifStatement);

                var varType = new SimpleType(Options.EnclosingType.Name);
                var varDecl = new VariableDeclarationStatement(varType, "other", new CastExpression(varType.Clone(), paramId.Clone()));

                methodDeclaration.Body.Statements.Add(varDecl);

                var        otherId = new IdentifierExpression("other");
                Expression binOp   = null;

                foreach (IMember member in includedMembers)
                {
                    Expression right = new BinaryOperatorExpression(new IdentifierExpression(member.Name), BinaryOperatorType.Equality, new MemberReferenceExpression(otherId.Clone(), member.Name));
                    if (binOp == null)
                    {
                        binOp = right;
                    }
                    else
                    {
                        binOp = new BinaryOperatorExpression(binOp, BinaryOperatorType.ConditionalAnd, right);
                    }
                }

                methodDeclaration.Body.Statements.Add(new ReturnStatement(binOp));
                yield return(methodDeclaration.GetText(Options.FormattingOptions));

                methodDeclaration      = new MethodDeclaration();
                methodDeclaration.Name = "GetHashCode";

                methodDeclaration.ReturnType = new PrimitiveType("int");
                methodDeclaration.Modifiers  = ICSharpCode.NRefactory.CSharp.Modifiers.Public | ICSharpCode.NRefactory.CSharp.Modifiers.Override;
                methodDeclaration.Body       = new BlockStatement();

                binOp = null;
                foreach (IMember member in includedMembers)
                {
                    Expression right;
                    right = new InvocationExpression(new MemberReferenceExpression(new IdentifierExpression(member.Name), "GetHashCode"));

                    IType type = member.ReturnType;
                    if (type != null && type.Kind != TypeKind.Struct && type.Kind != TypeKind.Enum)
                    {
                        right = new ParenthesizedExpression(new ConditionalExpression(new BinaryOperatorExpression(new IdentifierExpression(member.Name), BinaryOperatorType.InEquality, new PrimitiveExpression(null)), right, new PrimitiveExpression(0)));
                    }

                    if (binOp == null)
                    {
                        binOp = right;
                    }
                    else
                    {
                        binOp = new BinaryOperatorExpression(binOp, BinaryOperatorType.ExclusiveOr, right);
                    }
                }
                var uncheckedBlock = new BlockStatement();

                uncheckedBlock.Statements.Add(new ReturnStatement(binOp));

                methodDeclaration.Body.Statements.Add(new UncheckedStatement(uncheckedBlock));
                yield return(methodDeclaration.GetText(Options.FormattingOptions));
            }
        public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
        {
            if (!IsClassType(ClassType.Interface) && (methodDeclaration.Modifier & Modifiers.Visibility) == 0)
            {
                methodDeclaration.Modifier |= Modifiers.Public;
            }

            if ("Finalize".Equals(methodDeclaration.Name, StringComparison.InvariantCultureIgnoreCase) &&
                methodDeclaration.Parameters.Count == 0 &&
                methodDeclaration.Modifier == (Modifiers.Protected | Modifiers.Override) &&
                methodDeclaration.Body.Children.Count == 1)
            {
                TryCatchStatement tcs = methodDeclaration.Body.Children[0] as TryCatchStatement;
                if (tcs != null &&
                    tcs.StatementBlock is BlockStatement &&
                    tcs.CatchClauses.Count == 0 &&
                    tcs.FinallyBlock is BlockStatement &&
                    tcs.FinallyBlock.Children.Count == 1)
                {
                    ExpressionStatement se = tcs.FinallyBlock.Children[0] as ExpressionStatement;
                    if (se != null)
                    {
                        InvocationExpression ie = se.Expression as InvocationExpression;
                        if (ie != null &&
                            ie.Arguments.Count == 0 &&
                            ie.TargetObject is FieldReferenceExpression &&
                            (ie.TargetObject as FieldReferenceExpression).TargetObject is BaseReferenceExpression &&
                            "Finalize".Equals((ie.TargetObject as FieldReferenceExpression).FieldName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            DestructorDeclaration des = new DestructorDeclaration("Destructor", Modifiers.None, methodDeclaration.Attributes);
                            ReplaceCurrentNode(des);
                            des.Body = (BlockStatement)tcs.StatementBlock;
                            return(base.VisitDestructorDeclaration(des, data));
                        }
                    }
                }
            }

            if ((methodDeclaration.Modifier & (Modifiers.Static | Modifiers.Extern)) == Modifiers.Static &&
                methodDeclaration.Body.Children.Count == 0)
            {
                foreach (AttributeSection sec in methodDeclaration.Attributes)
                {
                    foreach (Attribute att in sec.Attributes)
                    {
                        if ("DllImport".Equals(att.Name, StringComparison.InvariantCultureIgnoreCase))
                        {
                            methodDeclaration.Modifier |= Modifiers.Extern;
                            methodDeclaration.Body      = null;
                        }
                    }
                }
            }

            if (methodDeclaration.TypeReference.SystemType != "System.Void" && methodDeclaration.Body.Children.Count > 0)
            {
                if (IsAssignmentTo(methodDeclaration.Body.Children[methodDeclaration.Body.Children.Count - 1], methodDeclaration.Name))
                {
                    ReturnStatement rs = new ReturnStatement(GetAssignmentFromStatement(methodDeclaration.Body.Children[methodDeclaration.Body.Children.Count - 1]).Right);
                    methodDeclaration.Body.Children.RemoveAt(methodDeclaration.Body.Children.Count - 1);
                    methodDeclaration.Body.AddChild(rs);
                }
                else
                {
                    ReturnStatementForFunctionAssignment visitor = new ReturnStatementForFunctionAssignment(methodDeclaration.Name);
                    methodDeclaration.Body.AcceptVisitor(visitor, null);
                    if (visitor.replacementCount > 0)
                    {
                        Expression init;
                        switch (methodDeclaration.TypeReference.SystemType)
                        {
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                        case "System.UInt16":
                        case "System.UInt32":
                        case "System.UInt64":
                            init = new PrimitiveExpression(0, "0");
                            break;

                        case "System.Boolean":
                            init = new PrimitiveExpression(false, "false");
                            break;

                        default:
                            init = new PrimitiveExpression(null, "null");
                            break;
                        }
                        methodDeclaration.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(FunctionReturnValueName, init, methodDeclaration.TypeReference)));
                        methodDeclaration.Body.Children[0].Parent = methodDeclaration.Body;
                        methodDeclaration.Body.AddChild(new ReturnStatement(new IdentifierExpression(FunctionReturnValueName)));
                    }
                }
            }

            return(base.VisitMethodDeclaration(methodDeclaration, data));
        }
            void Fix(Script script, MethodDeclaration methodDeclaration, TypeDeclaration typeDeclaration)
            {
                var newTypeDeclaration = (TypeDeclaration)typeDeclaration.Clone();

                var resolver = ctx.GetResolverStateAfter(typeDeclaration.LBraceToken);

                var  typeResolve           = resolver.ResolveSimpleName("IDisposable", new List <IType>()) as TypeResolveResult;
                bool canShortenIDisposable = typeResolve != null && typeResolve.Type.FullName == "System.IDisposable";

                string interfaceName = (canShortenIDisposable ? string.Empty : "System.") + "IDisposable";

                newTypeDeclaration.BaseTypes.Add(new SimpleType(interfaceName));

                foreach (var method in DisposeMethods(newTypeDeclaration).ToList())
                {
                    if (typeDeclaration.ClassType == ClassType.Interface)
                    {
                        method.Remove();
                    }
                    else
                    {
                        method.Modifiers &= ~Modifiers.Private;
                        method.Modifiers &= ~Modifiers.Protected;
                        method.Modifiers &= ~Modifiers.Internal;
                        method.Modifiers |= Modifiers.Public;
                    }
                }

                if (typeDeclaration.ClassType == ClassType.Interface)
                {
                    var disposeMember = ((MemberResolveResult)ctx.Resolve(methodDeclaration)).Member;
                    script.DoGlobalOperationOn(new List <IEntity>()
                    {
                        disposeMember
                    }, (nCtx, nScript, nodes) =>
                    {
                        List <Tuple <AstType, AstType> > pendingChanges = new List <Tuple <AstType, AstType> >();
                        foreach (var node in nodes)
                        {
                            var method = node as MethodDeclaration;
                            if (method != null && !method.PrivateImplementationType.IsNull)
                            {
                                var nResolver = ctx.GetResolverStateAfter(typeDeclaration.LBraceToken);

                                var nTypeResolve            = nResolver.ResolveSimpleName("IDisposable", new List <IType>()) as TypeResolveResult;
                                bool nCanShortenIDisposable = nTypeResolve != null && nTypeResolve.Type.FullName == "System.IDisposable";

                                string nInterfaceName = (nCanShortenIDisposable ? string.Empty : "System.") + "IDisposable";

                                pendingChanges.Add(Tuple.Create(method.PrivateImplementationType, AstType.Create(nInterfaceName)));
                            }
                        }

                        foreach (var change in pendingChanges)
                        {
                            nScript.Replace(change.Item1, change.Item2);
                        }
                    }, "Fix explicitly implemented members");
                }

                script.Replace(typeDeclaration, newTypeDeclaration);
            }
 public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
 {
     base.VisitMethodDeclaration(methodDeclaration);
     CheckNode(methodDeclaration);
 }
 public static List <IdentifierExpression> parameters_Names_as_Indentifiers(this MethodDeclaration methodDeclaration)
 {
     return(methodDeclaration.parameters().names().ast_Identifiers());
 }
 public static MethodDeclaration private_Static(this MethodDeclaration methodDeclaration)
 {
     methodDeclaration.Modifier = Modifiers.Static | Modifiers.Private;
     return(methodDeclaration);
 }
        protected void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
        {
            foreach (var attrSection in methodDeclaration.Attributes)
            {
                foreach (var attr in attrSection.Attributes)
                {
                    var rr = this.Emitter.Resolver.ResolveNode(attr.Type, this.Emitter);
                    if (rr.Type.FullName == "Bridge.ExternalAttribute" || rr.Type.FullName == "Bridge.IgnoreAttribute")
                    {
                        return;
                    }
                    else if (rr.Type.FullName == "Bridge.InitAttribute")
                    {
                        int initPosition = 0;

                        if (attr.HasArgumentList)
                        {
                            if (attr.Arguments.Any())
                            {
                                var argExpr = attr.Arguments.First();
                                var argrr   = this.Emitter.Resolver.ResolveNode(argExpr, this.Emitter);
                                if (argrr.ConstantValue is int)
                                {
                                    initPosition = (int)argrr.ConstantValue;
                                }
                            }
                        }

                        if (initPosition > 0)
                        {
                            return;
                        }
                    }
                }
            }

            this.EnsureComma();
            this.ResetLocals();

            var prevMap      = this.BuildLocalsMap();
            var prevNamesMap = this.BuildLocalsNamesMap();

            this.AddLocals(methodDeclaration.Parameters, methodDeclaration.Body);

            var typeDef   = this.Emitter.GetTypeDefinition();
            var overloads = OverloadsCollection.Create(this.Emitter, methodDeclaration);

            XmlToJsDoc.EmitComment(this, this.MethodDeclaration);

            string name = overloads.GetOverloadName();

            this.Write(name);

            this.WriteColon();

            if (methodDeclaration.TypeParameters.Count > 0)
            {
                this.WriteFunction();
                this.EmitTypeParameters(methodDeclaration.TypeParameters, methodDeclaration);
                this.WriteSpace();
                this.BeginBlock();
                this.WriteReturn(true);
                this.Write("Bridge.fn.bind(this, ");
            }

            this.WriteFunction();

            this.EmitMethodParameters(methodDeclaration.Parameters, methodDeclaration);

            this.WriteSpace();

            var script = this.Emitter.GetScript(methodDeclaration);

            if (script == null)
            {
                if (methodDeclaration.HasModifier(Modifiers.Async))
                {
                    new AsyncBlock(this.Emitter, methodDeclaration).Emit();
                }
                else
                {
                    methodDeclaration.Body.AcceptVisitor(this.Emitter);
                }
            }
            else
            {
                this.BeginBlock();

                foreach (var line in script)
                {
                    this.Write(line);
                    this.WriteNewLine();
                }

                this.EndBlock();
            }

            if (methodDeclaration.TypeParameters.Count > 0)
            {
                this.Write(");");
                this.WriteNewLine();
                this.EndBlock();
            }

            this.ClearLocalsMap(prevMap);
            this.ClearLocalsNamesMap(prevNamesMap);
            this.Emitter.Comma = true;
        }
Beispiel #44
0
        protected virtual void EmitMethods(Dictionary <string, List <MethodDeclaration> > methods, Dictionary <string, List <EntityDeclaration> > properties, Dictionary <OperatorType, List <OperatorDeclaration> > operators)
        {
            var names = new List <string>(properties.Keys);

            foreach (var name in names)
            {
                var props = properties[name];

                foreach (var prop in props)
                {
                    if (prop is PropertyDeclaration)
                    {
                        this.Emitter.VisitPropertyDeclaration((PropertyDeclaration)prop);
                    }
                    else if (prop is CustomEventDeclaration)
                    {
                        this.Emitter.VisitCustomEventDeclaration((CustomEventDeclaration)prop);
                    }
                    else if (prop is IndexerDeclaration)
                    {
                        this.Emitter.VisitIndexerDeclaration((IndexerDeclaration)prop);
                    }
                }
            }

            if (!this.StaticBlock)
            {
                MethodDeclaration entryPoint = null;
                if (this.TypeInfo.StaticMethods.Any(group =>
                {
                    return(group.Value.Any(method =>
                    {
                        var result = Helpers.IsEntryPointMethod(this.Emitter, method);
                        if (result)
                        {
                            entryPoint = method;
                        }
                        return result;
                    }));
                }))
                {
                    if (!entryPoint.Body.IsNull)
                    {
                        this.Emitter.VisitMethodDeclaration(entryPoint);
                    }
                }
            }

            names = new List <string>(methods.Keys);

            foreach (var name in names)
            {
                this.EmitMethodsGroup(methods[name]);
            }

            if (operators != null)
            {
                var ops = new List <OperatorType>(operators.Keys);

                foreach (var op in ops)
                {
                    this.EmitOperatorGroup(operators[op]);
                }
            }

            if (this.TypeInfo.ClassType == ClassType.Struct)
            {
                if (!this.StaticBlock)
                {
                    this.EmitStructMethods();
                }
                else
                {
                    string structName = BridgeTypes.ToJsName(this.TypeInfo.Type, this.Emitter);
                    if (this.TypeInfo.Type.TypeArguments.Count > 0 &&
                        !Helpers.IsIgnoreGeneric(this.TypeInfo.Type, this.Emitter))
                    {
                        structName = "(" + structName + ")";
                    }

                    this.EnsureComma();
                    this.Write(JS.Funcs.GETDEFAULTVALUE + ": function () { return new " + structName + "(); }");
                    this.Emitter.Comma = true;
                }
            }
            else if (this.StaticBlock)
            {
                var ctor = this.TypeInfo.Type.GetConstructors().FirstOrDefault(c => c.Parameters.Count == 0 && this.Emitter.GetInline(c) != null);

                if (ctor != null)
                {
                    var code = this.Emitter.GetInline(ctor);
                    this.EnsureComma();
                    this.Write(JS.Funcs.GETDEFAULTVALUE + ": function () ");
                    this.BeginBlock();
                    this.Write("return ");
                    var argsInfo = new ArgumentsInfo(this.Emitter, ctor);
                    new InlineArgumentsBlock(this.Emitter, argsInfo, code).Emit();
                    this.Write(";");
                    this.WriteNewLine();
                    this.EndBlock();
                    this.Emitter.Comma = true;
                }
            }
        }
 public VisitorMethodBlock(IEmitter emitter, MethodDeclaration methodDeclaration)
     : base(emitter, methodDeclaration)
 {
     this.Emitter           = emitter;
     this.MethodDeclaration = methodDeclaration;
 }
Beispiel #46
0
 public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
 {
     //ignore method declarations
 }
Beispiel #47
0
 public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
 {
     CheckNode(methodDeclaration);
     return(base.VisitMethodDeclaration(methodDeclaration, data));
 }
 public static MethodDeclaration returnType_using_Keyword(this MethodDeclaration methodDeclaration, string returnType)
 {
     methodDeclaration.TypeReference = new TypeReference(returnType, true);
     return(methodDeclaration);
 }
Beispiel #49
0
 public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
 {
     new VisitorMethodBlock(this, methodDeclaration).Emit();
 }
 public static MethodDeclaration setReturnType(this MethodDeclaration methodDeclaration, string returnType)
 {
     return(methodDeclaration.returnType_using_Keyword(returnType));
 }
 public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
 {
     ConvertInterfaceImplementation(methodDeclaration);
     return(base.VisitMethodDeclaration(methodDeclaration, data));
 }
 public static MethodDeclaration empty_Body(this MethodDeclaration methodDeclaration)
 {
     return(methodDeclaration.body(new BlockStatement()));
 }
 public static MethodDeclaration returnType_Void(this MethodDeclaration methodDeclaration)
 {
     return(methodDeclaration.setReturnType("void"));
 }
Beispiel #54
0
            public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
            {
                StatementIssueCollector.Collect(this, methodDeclaration.Body);

                base.VisitMethodDeclaration(methodDeclaration);
            }
Beispiel #55
0
 public override bool Visit(MethodDeclaration node)
 {
     Visit((CallableDeclaration)node);
     return(true);
 }
 public static MethodDeclaration public_Static(this MethodDeclaration methodDeclaration)
 {
     methodDeclaration.Modifier = Modifiers.Static | Modifiers.Public;
     return(methodDeclaration);
 }
Beispiel #57
0
            public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
            {
                base.VisitMethodDeclaration(methodDeclaration);

                CheckName(methodDeclaration, methodDeclaration.Modifiers.HasFlag(Modifiers.Async) ? AffectedEntity.AsyncMethod : AffectedEntity.Method, methodDeclaration.NameToken, GetAccessibiltiy(methodDeclaration, Modifiers.Private));
            }
Beispiel #58
0
 private bool IsGenericMethod(MethodDeclaration methodDeclaration)
 {
     return(methodDeclaration.TypeParameters.Any());
 }
 public static MethodDeclaration public_Instance(this MethodDeclaration methodDeclaration)
 {
     methodDeclaration.Modifier = Modifiers.Public;
     return(methodDeclaration);
 }
 public static MethodDeclaration name_Add(this MethodDeclaration methodDeclaration, string textToAdd)
 {
     methodDeclaration.Name += textToAdd;
     return(methodDeclaration);
 }