protected static bool HidesMember(BaseRefactoringContext ctx, AstNode node, string variableName)
        {
            var typeDecl = node.GetParent <TypeDeclaration>();

            if (typeDecl == null)
            {
                return(false);
            }
            var entityDecl          = node.GetParent <EntityDeclaration>();
            var memberResolveResult = ctx.Resolve(entityDecl) as MemberResolveResult;

            if (memberResolveResult == null)
            {
                return(false);
            }
            var typeResolveResult = ctx.Resolve(typeDecl) as TypeResolveResult;

            if (typeResolveResult == null)
            {
                return(false);
            }

            var sourceMember = memberResolveResult.Member;

            return(typeResolveResult.Type.GetMembers(m => m.Name == variableName).Any(m2 => IsAccessible(sourceMember, m2)));
        }
        protected override NodeKind GetNodeKind(AstNode node)
        {
            var assignment = node.GetParent <AssignmentExpression> ();

            if (assignment != null && assignment.Left == node)
            {
                if (assignment.Operator == AssignmentOperatorType.Assign)
                {
                    return(NodeKind.Modification);
                }
                return(NodeKind.ReferenceAndModification);
            }
            var unaryExpr = node.GetParent <UnaryOperatorExpression> ();

            if (unaryExpr != null && unaryExpr.Expression == node &&
                (unaryExpr.Operator == UnaryOperatorType.Increment ||
                 unaryExpr.Operator == UnaryOperatorType.PostIncrement ||
                 unaryExpr.Operator == UnaryOperatorType.Decrement ||
                 unaryExpr.Operator == UnaryOperatorType.PostDecrement))
            {
                return(NodeKind.ReferenceAndModification);
            }
            if (node.Parent is ForeachStatement)
            {
                return(NodeKind.Modification);
            }

            return(NodeKind.Reference);
        }
		protected static bool HidesMember(BaseRefactoringContext ctx, AstNode node, string variableName)
		{
			var typeDecl = node.GetParent<TypeDeclaration> ();
			if (typeDecl == null)
				return false;
			var typeResolveResult = ctx.Resolve (typeDecl) as TypeResolveResult;
			if (typeResolveResult == null)
				return false;

			var entityDecl = node.GetParent<EntityDeclaration> ();
			var isStatic = (entityDecl.Modifiers & Modifiers.Static) == Modifiers.Static;

			return typeResolveResult.Type.GetMembers (m => m.Name == variableName && m.IsStatic	== isStatic).Any ();
		}
Example #4
0
        public void Analyze(AstNode node, IEnumerable <string> parameters = null)
        {
            _usesThis = false;
            _usedVariables.Clear();
            _variables.Clear();

            var methodDeclaration = node.GetParent <MethodDeclaration>();

            if (methodDeclaration != null)
            {
                foreach (var attrSection in methodDeclaration.Attributes)
                {
                    foreach (var attr in attrSection.Attributes)
                    {
                        var rr = this.resolver.Resolve(attr.Type);
                        if (rr.Type.FullName == "Bridge.InitAttribute")
                        {
                            this._usedVariables.Add(null);
                            return;
                        }
                    }
                }
            }

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    _variables.Add(parameter);
                }
            }

            node.AcceptVisitor(this);
        }
Example #5
0
        public CatchClause GetParentCatchBlock(AstNode node, bool stopOnLoops)
        {
            var insideCatch = false;
            var target      = node.GetParent(n =>
            {
                if (n is LambdaExpression || n is AnonymousMethodExpression || n is MethodDeclaration)
                {
                    return(true);
                }

                if (stopOnLoops && (n is WhileStatement || n is ForeachStatement || n is ForStatement || n is DoWhileStatement))
                {
                    return(true);
                }

                if (n is CatchClause)
                {
                    insideCatch = true;
                    return(true);
                }

                return(false);
            });

            return(insideCatch ? (CatchClause)target : null);
        }
Example #6
0
        private IType TryGetReturnType(AstNode node)
        {
            IType resolvedType = null;

            resolvedType = TryGetEntityDeclarationReturnType(node);
            if (resolvedType == null)
            {
                var anonymousMethodExpression = node.GetParent <AnonymousMethodExpression>();
                if (anonymousMethodExpression == null)
                {
                    return(null);
                }
                var parent = anonymousMethodExpression.Parent;
                if (parent is AssignmentExpression)
                {
                    resolvedType = Resolver.Resolve(((AssignmentExpression)parent).Left).Type;
                }
                else if (parent is VariableInitializer)
                {
                    resolvedType = Resolver.Resolve(((VariableDeclarationStatement)parent.Parent).Type).Type;
                }
                else
                {
                    // TODO: handle invocations
                    throw new Exception();
                }
            }
            return(resolvedType);
        }
Example #7
0
            private static QueryClause GetRelevantClause(AstNode node)
            {
                var relevantClause = node.GetParent <QueryClause>();

                do
                {
                    if (relevantClause == null)
                    {
                        throw new IOException("Can't figure out how to find the relevant clause for this query");
                    }

                    if (relevantClause is QueryGroupClause)
                    {
                        return(relevantClause);
                    }
                    var queryFromClause = relevantClause as QueryFromClause;
                    if (queryFromClause != null)
                    {
                        var parentClause = GetPreviousQueryFromClause(queryFromClause);

                        if (parentClause != null)
                        {
                            relevantClause = parentClause;
                            continue;
                        }
                        return(relevantClause);
                    }
                    if (relevantClause is QueryContinuationClause)
                    {
                        return(relevantClause);
                    }
                    relevantClause = relevantClause.GetPrevNode() as QueryClause;
                } while (true);
            }
Example #8
0
 internal static IType GetRequestedReturnType(BaseRefactoringContext ctx, AstNode returnStatement, out AstNode entityNode)
 {
     entityNode = returnStatement.GetParent(p => p is LambdaExpression || p is AnonymousMethodExpression || !(p is Accessor) && p is EntityDeclaration);
     if (entityNode == null)
     {
         return(null);
     }
     if (entityNode is EntityDeclaration)
     {
         var rr = ctx.Resolve(entityNode) as MemberResolveResult;
         if (rr == null)
         {
             return(null);
         }
         return(rr.Member.ReturnType);
     }
     foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, entityNode))
     {
         if (type.Kind != TypeKind.Delegate)
         {
             continue;
         }
         var invoke = type.GetDelegateInvokeMethod();
         if (invoke != null && !invoke.ReturnType.IsKnownType(KnownTypeCode.Void))
         {
             return(invoke.ReturnType);
         }
     }
     return(null);
 }
Example #9
0
        internal static Statement GetOuterLoop(AstNode context)
        {
            Statement loop = null;

            context.GetParent(node =>
            {
                bool stopSearch = false;

                if (node is ForStatement ||
                    node is ForeachStatement ||
                    node is DoWhileStatement ||
                    node is WhileStatement)
                {
                    loop = (Statement)node;
                }
                else if (node is EntityDeclaration ||
                         node is LambdaExpression ||
                         node is AnonymousMethodExpression)
                {
                    stopSearch = true;
                }

                return(stopSearch);
            });

            return(loop);
        }
Example #10
0
        public AstNode GetParentFinallyBlock(AstNode node, bool stopOnLoops)
        {
            var insideTryFinally = false;
            var target           = node.GetParent(n =>
            {
                if (n is LambdaExpression || n is AnonymousMethodExpression || n is MethodDeclaration)
                {
                    return(true);
                }

                if (stopOnLoops && (n is WhileStatement || n is ForeachStatement || n is ForStatement || n is DoWhileStatement))
                {
                    return(true);
                }

                if (n is TryCatchStatement && !((TryCatchStatement)n).FinallyBlock.IsNull)
                {
                    insideTryFinally = true;
                    return(true);
                }

                return(false);
            });

            return(insideTryFinally ? ((TryCatchStatement)target).FinallyBlock : null);
        }
Example #11
0
        private void CreateSubtypeRelation(AstNode node,
                                           IType right, IType left, SubtypeKind kind, bool isRightTypeThis)
        {
            var leftType  = GetTypeOrCreateExternal(left);
            var rightType = GetTypeOrCreateExternal(right);

            var currentMethod = node.GetParent <MethodDeclaration>() ??
                                node.GetParent <ConstructorDeclaration>() as EntityDeclaration ??
                                node.GetParent <PropertyDeclaration>();
            string fromReference = currentMethod == null ? "(field initializer)" : currentMethod.Name;
            var    currentDeclaringTypeResolve = Resolver.Resolve(node.GetParent <TypeDeclaration>());

            fromReference += " in " + currentDeclaringTypeResolve.Type.FullName;

            //left is the parent, right is the child
            for (int i = 0; i < left.TypeArguments.Count && i < right.TypeArguments.Count; i++)
            {
                var leftArg       = left.TypeArguments[i];
                var rightArg      = right.TypeArguments[i];
                var leftArgument  = GetTypeOrCreateExternal(leftArg);
                var rightArgument = GetTypeOrCreateExternal(rightArg);
                CreateSubtypeRelation(node, leftArg, rightArg, SubtypeKind.CovariantTypeArgument, false);
                CreateSubtypeRelation(node, rightArg, leftArg, SubtypeKind.ContravariantTypeArgument, false);
            }


            if (rightType.IsChildOf(leftType))
            {
                rightType.HasSubtypeToObject |= leftType.IsObject;
                var relations = rightType.GetPathTo(leftType);
                foreach (var item in relations)
                {
                    item.Subtypes.Add(new Subtype(item.BaseType == leftType && item.DerivedType == rightType, kind,
                                                  fromReference));
                }
            }
            if (isRightTypeThis && kind == SubtypeKind.Parameter)
            {
                foreach (var derivedType in rightType.AllDerivedTypes())
                {
                    var relation = derivedType.GetImmediateParent(rightType);
                    relation.Subtypes.Add(new Subtype(derivedType.IsDirectChildOf(rightType),
                                                      SubtypeKind.ThisChangingType, fromReference));
                }
            }
        }
        protected static bool HidesMember(BaseRefactoringContext ctx, AstNode node, string variableName)
        {
            var typeDecl = node.GetParent<TypeDeclaration>();
            if (typeDecl == null)
                return false;
            var entityDecl = node.GetParent<EntityDeclaration>();
            var memberResolveResult = ctx.Resolve(entityDecl) as MemberResolveResult;
            if (memberResolveResult == null)
                return false;
            var typeResolveResult = ctx.Resolve(typeDecl) as TypeResolveResult;
            if (typeResolveResult == null)
                return false;

            var sourceMember = memberResolveResult.Member;

            return typeResolveResult.Type.GetMembers(m => m.Name == variableName).Any(m2 => IsAccessible(sourceMember, m2));
        }
Example #13
0
 public static T ParentOrSelf <T>(this AstNode node) where T : AstNode
 {
     if (node is T)
     {
         return((T)node);
     }
     return(node.GetParent <T>());
 }
 public void FindCheckAccess(AstNode invocation, CSharpFile file, string checkAccessMethodName)
 {
     if (allPatterns.AccessControlExpression(checkAccessMethodName).Match(invocation).Success &&
         FindWebMethod(invocation.GetParent <MethodDeclaration>()))
     {
         file.IndexofExprStmtCheckAccess.Add((ExpressionStatement)invocation);
     }
 }
            static bool IsInsideTryBlock(AstNode node)
            {
                var tryCatchStatement = node.GetParent <TryCatchStatement>();

                if (tryCatchStatement == null)
                {
                    return(false);
                }
                return(tryCatchStatement.TryBlock.Contains(node.StartLocation.Line, node.StartLocation.Column));
            }
Example #16
0
        public virtual IVisitorException CreateException(AstNode node, string message)
        {
            if (String.IsNullOrEmpty(message))
            {
                message = String.Format("Language construction {0} is not supported", node.GetType().Name);
            }
            string file = node.GetParent <SyntaxTree>().FileName;

            return(Exception.Create("{0} {1} {2}: {3}", file, message, node.StartLocation, node.ToString()));
        }
Example #17
0
 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);
     }));
 }
Example #18
0
        protected static bool HidesMember(BaseRefactoringContext ctx, AstNode node, string variableName)
        {
            var typeDecl = node.GetParent <TypeDeclaration> ();

            if (typeDecl == null)
            {
                return(false);
            }
            var typeResolveResult = ctx.Resolve(typeDecl) as TypeResolveResult;

            if (typeResolveResult == null)
            {
                return(false);
            }

            var entityDecl = node.GetParent <EntityDeclaration> ();
            var isStatic   = (entityDecl.Modifiers & Modifiers.Static) == Modifiers.Static;

            return(typeResolveResult.Type.GetMembers(m => m.Name == variableName && m.IsStatic == isStatic).Any());
        }
Example #19
0
            static EntityDeclaration GetParentMethodOrProperty(AstNode node)
            {
                var containerEntity = node.GetParent <EntityDeclaration>();

                if (containerEntity is Accessor)
                {
                    containerEntity = containerEntity.GetParent <EntityDeclaration>();
                }

                return(containerEntity);
            }
Example #20
0
        protected bool IsDirectAsyncBlockChild(AstNode node)
        {
            var block = node.GetParent <BlockStatement>();

            if (block != null && (block.Parent is MethodDeclaration || block.Parent is AnonymousMethodExpression || block.Parent is LambdaExpression))
            {
                return(true);
            }

            return(false);
        }
		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);
				});
		}
        protected static bool HidesMember(BaseRefactoringContext ctx, AstNode node, string variableName, out IMember member)
        {
            MemberCollectionService mcs = (MemberCollectionService)ctx.GetService(typeof(MemberCollectionService));

            if (mcs == null)
            {
                lock (ctx) {
                    if ((mcs = (MemberCollectionService)ctx.GetService(typeof(MemberCollectionService))) == null)
                    {
                        mcs = new MemberCollectionService();
                        ctx.Services.AddService(typeof(MemberCollectionService), mcs);
                    }
                }
            }

            var typeDecl = node.GetParent <TypeDeclaration>();

            member = null;
            if (typeDecl == null)
            {
                return(false);
            }
            var entityDecl          = node.GetParent <EntityDeclaration>();
            var memberResolveResult = ctx.Resolve(entityDecl) as MemberResolveResult;

            if (memberResolveResult == null)
            {
                return(false);
            }
            var typeResolveResult = ctx.Resolve(typeDecl) as TypeResolveResult;

            if (typeResolveResult == null)
            {
                return(false);
            }

            var sourceMember = memberResolveResult.Member;

            member = mcs.GetMembers(typeResolveResult.Type, variableName).FirstOrDefault(m2 => IsAccessible(sourceMember, m2));
            return(member != null);
        }
		protected override NodeKind GetNodeKind (AstNode node)
		{
			var assignment = node.GetParent<AssignmentExpression> ();
			if (assignment != null && assignment.Left == node) {
				if (assignment.Operator == AssignmentOperatorType.Assign) 
					return NodeKind.Modification;
				return NodeKind.ReferenceAndModification;
			}
			var unaryExpr = node.GetParent<UnaryOperatorExpression> ();
			if (unaryExpr != null && unaryExpr.Expression == node &&
				(unaryExpr.Operator == UnaryOperatorType.Increment ||
				 unaryExpr.Operator == UnaryOperatorType.PostIncrement ||
				 unaryExpr.Operator == UnaryOperatorType.Decrement ||
				 unaryExpr.Operator == UnaryOperatorType.PostDecrement)) {
				return NodeKind.ReferenceAndModification;
			}
			if (node.Parent is ForeachStatement)
				return NodeKind.Modification;

			return NodeKind.Reference;
		}
        public void FindFirstTryCatchInWebMethod(AstNode invocation, CSharpFile file)
        {
            var methodName = invocation.GetParent <MethodDeclaration>();

            if (invocation.GetType().Name == "MethodDeclaration" && FindWebMethod(invocation))
            {
                try
                {
                    var tryCatchStmt = invocation.Descendants.OfType <TryCatchStatement>().First();
                    file.IndexOfTryCatchStmt.Add((TryCatchStatement)tryCatchStmt);
                }
                catch (Exception) { }
            }
        }
Example #25
0
        private IType TryGetEntityDeclarationReturnType(AstNode node)
        {
            var method = node.GetParent <EntityDeclaration>();

            if (method != null)
            {
                var resolve = Resolver.Resolve(method);
                if (!resolve.IsError)
                {
                    return(resolve.Type);
                }
            }
            return(null);
        }
Example #26
0
        internal static IType GetRequestedReturnType(BaseRefactoringContext ctx, AstNode returnStatement, out AstNode entityNode)
        {
            entityNode = returnStatement.GetParent(p => p is LambdaExpression || p is AnonymousMethodExpression || !(p is Accessor) && p is EntityDeclaration);
            if (entityNode == null)
            {
                return(SpecialType.UnknownType);
            }
            if (entityNode is EntityDeclaration)
            {
                var rr = ctx.Resolve(entityNode) as MemberResolveResult;
                if (rr == null)
                {
                    return(SpecialType.UnknownType);
                }
                if (((EntityDeclaration)entityNode).HasModifier(Modifiers.Async))
                {
                    return(TaskType.UnpackTask(ctx.Compilation, rr.Member.ReturnType));
                }
                return(rr.Member.ReturnType);
            }
            bool isAsync = false;

            if (entityNode is LambdaExpression)
            {
                isAsync = ((LambdaExpression)entityNode).IsAsync;
            }
            if (entityNode is AnonymousMethodExpression)
            {
                isAsync = ((AnonymousMethodExpression)entityNode).IsAsync;
            }
            foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, entityNode))
            {
                if (type.Kind != TypeKind.Delegate)
                {
                    continue;
                }
                var invoke = type.GetDelegateInvokeMethod();
                if (invoke != null)
                {
                    return(isAsync ? TaskType.UnpackTask(ctx.Compilation, invoke.ReturnType) : invoke.ReturnType);
                }
            }
            return(SpecialType.UnknownType);
        }
            static bool IsInsideTryOrCatchBlock(AstNode node)
            {
                var tryCatchStatement = node.GetParent <TryCatchStatement>();

                if (tryCatchStatement != null)
                {
                    if (tryCatchStatement.TryBlock.Contains(node.StartLocation))
                    {
                        return(true);
                    }
                    foreach (var catchBlock in tryCatchStatement.CatchClauses)
                    {
                        if (catchBlock.Body.Contains(node.StartLocation))
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            }
		IEnumerable<ICompletionData> CreateTypeAndNamespaceCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state)
		{
			if (resolveResult == null || resolveResult.IsError) {
				return null;
			}
			var exprParent = resolvedNode.GetParent<Expression>();
			var unit = exprParent != null ? exprParent.GetParent<SyntaxTree>() : null;

			var astResolver = unit != null ? CompletionContextProvider.GetResolver(state, unit) : null;
			IType hintType = exprParent != null && astResolver != null ? 
			                 TypeGuessing.GetValidTypes(astResolver, exprParent).FirstOrDefault() :
			                 null;
			var result = new CompletionDataWrapper(this);
			var lookup = new MemberLookup(
				ctx.CurrentTypeDefinition,
				Compilation.MainAssembly
			);
			if (resolveResult is NamespaceResolveResult) {
				var nr = (NamespaceResolveResult)resolveResult;
				if (!(resolvedNode.Parent is UsingDeclaration || resolvedNode.Parent != null && resolvedNode.Parent.Parent is UsingDeclaration)) {
					foreach (var cl in nr.Namespace.Types) {
						if (hintType != null && hintType.Kind != TypeKind.Array && cl.Kind == TypeKind.Interface) {
							continue;
						}
						if (!lookup.IsAccessible(cl, false))
							continue;
						result.AddType(cl, false, IsAttributeContext(resolvedNode));
					}
				}
				foreach (var ns in nr.Namespace.ChildNamespaces) {
					result.AddNamespace(lookup, ns);
				}
			} else if (resolveResult is TypeResolveResult) {
				var type = resolveResult.Type;
				foreach (var nested in type.GetNestedTypes ()) {
					if (hintType != null && hintType.Kind != TypeKind.Array && nested.Kind == TypeKind.Interface) {
						continue;
					}
					var def = nested.GetDefinition();
					if (def != null && !lookup.IsAccessible(def, false))
						continue;
					result.AddType(nested, false);
				}
			}
			return result.Result;
		}
Example #29
0
        public ResolveResult ResolveNode(AstNode node)
        {
            var syntaxTree = node.GetParent <SyntaxTree>();

            InitResolver(syntaxTree);

            var result = resolver.Resolve(node);

            if (result is MethodGroupResolveResult resolveResult && node.Parent != null)
            {
                var methodGroupResolveResult = resolveResult;
                var parentResolveResult      = ResolveNode(node.Parent);
                var parentInvocation         = parentResolveResult as InvocationResolveResult;
                IParameterizedMember method  = methodGroupResolveResult.Methods.LastOrDefault();
                bool isInvocation            = node.Parent is InvocationExpression invocationExp && (invocationExp.Target == node);

                if (node is Expression expression)
                {
                    var conversion = Resolver.GetConversion(expression);
                    if (conversion != null && conversion.IsMethodGroupConversion)
                    {
                        return(new MemberResolveResult(new TypeResolveResult(conversion.Method.DeclaringType), conversion.Method));
                    }
                }

                if (isInvocation && parentInvocation != null)
                {
                    var or = methodGroupResolveResult.PerformOverloadResolution(compilation, parentInvocation.GetArgumentsForCall().ToArray());
                    if (or.FoundApplicableCandidate)
                    {
                        method = or.BestCandidate;
                        return(new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method));
                    }
                }

                if (parentInvocation != null && method == null)
                {
                    if (methodGroupResolveResult.TargetType is DefaultResolvedTypeDefinition typeDef)
                    {
                        var methods = typeDef.Methods.Where(m => m.Name == methodGroupResolveResult.MethodName);
                        method = methods.FirstOrDefault();
                    }
                }

                if (method == null)
                {
                    var extMethods = methodGroupResolveResult.GetEligibleExtensionMethods(false);

                    if (!extMethods.Any())
                    {
                        extMethods = methodGroupResolveResult.GetExtensionMethods();
                    }

                    if (!extMethods.Any() || !extMethods.First().Any())
                    {
                        throw new EmitterException(node, "Cannot find method defintion");
                    }

                    method = extMethods.First().First();
                }

                if (parentInvocation == null || method.FullName != parentInvocation.Member.FullName)
                {
                    MemberResolveResult memberResolveResult = new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method);
                    return(memberResolveResult);
                }

                return(parentResolveResult);
            }

            if ((result == null || result.IsError))
            {
                if (result is CSharpInvocationResolveResult invocationResult && invocationResult.OverloadResolutionErrors != OverloadResolutionErrors.None)
                {
                    return(result);
                }

                if (result.IsError)
                {
                    Logger.ZLogTrace("Node resolving has failed {0}: {1}", node.StartLocation, node.ToString());
                }
            }

            return(result);
        }
Example #30
0
        public ResolveResult ResolveNode(AstNode node, ILog log)
        {
            var syntaxTree = node.GetParent <SyntaxTree>();

            this.InitResolver(syntaxTree);

            var result = this.resolver.Resolve(node);

            if (result is MethodGroupResolveResult && node.Parent != null)
            {
                var methodGroupResolveResult = (MethodGroupResolveResult)result;
                var parentResolveResult      = this.ResolveNode(node.Parent, log);
                var parentInvocation         = parentResolveResult as InvocationResolveResult;
                IParameterizedMember method  = methodGroupResolveResult.Methods.LastOrDefault();
                bool isInvocation            = node.Parent is InvocationExpression && (((InvocationExpression)(node.Parent)).Target == node);

                if (node is Expression)
                {
                    var conversion = this.Resolver.GetConversion((Expression)node);
                    if (conversion != null && conversion.IsMethodGroupConversion)
                    {
                        return(new MemberResolveResult(new TypeResolveResult(conversion.Method.DeclaringType), conversion.Method));
                    }
                }

                if (isInvocation && parentInvocation != null)
                {
                    var or = methodGroupResolveResult.PerformOverloadResolution(this.compilation, parentInvocation.GetArgumentsForCall().ToArray());
                    if (or.FoundApplicableCandidate)
                    {
                        method = or.BestCandidate;
                        return(new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method));
                    }
                }

                if (parentInvocation != null && method == null)
                {
                    var typeDef = methodGroupResolveResult.TargetType as DefaultResolvedTypeDefinition;

                    if (typeDef != null)
                    {
                        var methods = typeDef.Methods.Where(m => m.Name == methodGroupResolveResult.MethodName);
                        method = methods.FirstOrDefault();
                    }
                }

                if (method == null)
                {
                    var extMethods = methodGroupResolveResult.GetEligibleExtensionMethods(false);

                    if (extMethods.Count() == 0)
                    {
                        extMethods = methodGroupResolveResult.GetExtensionMethods();
                    }

                    if (extMethods.Count() == 0 || extMethods.First().Count() == 0)
                    {
                        throw new Exception("Cannot find method defintion for " + node.ToString());
                    }

                    method = extMethods.First().First();
                }

                if (parentInvocation == null || method.FullName != parentInvocation.Member.FullName)
                {
                    MemberResolveResult memberResolveResult = new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method);
                    return(memberResolveResult);
                }

                return(parentResolveResult);
            }

            if ((result == null || result.IsError) && log != null)
            {
                if (result is CSharpInvocationResolveResult && ((CSharpInvocationResolveResult)result).OverloadResolutionErrors != OverloadResolutionErrors.None)
                {
                    return(result);
                }

                log.LogWarning(string.Format("Node resolving has failed {0}: {1}", node.StartLocation, node.ToString()));
            }

            return(result);
        }
		IEnumerable<ICompletionData> CreateTypeAndNamespaceCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state)
		{
			if (resolveResult == null || resolveResult.IsError) {
				return null;
			}
			var exprParent = resolvedNode.GetParent<Expression>();
			var unit = exprParent != null ? exprParent.GetParent<CompilationUnit>() : null;

			var astResolver = unit != null ? new CSharpAstResolver(
				state,
				unit,
				CSharpParsedFile
			) : null;
			IType hintType = exprParent != null && astResolver != null ? 
				CreateFieldAction.GetValidTypes(astResolver, exprParent) .FirstOrDefault() :
				null;
			var result = new CompletionDataWrapper(this);
			if (resolveResult is NamespaceResolveResult) {
				var nr = (NamespaceResolveResult)resolveResult;
				if (!(resolvedNode.Parent is UsingDeclaration || resolvedNode.Parent != null && resolvedNode.Parent.Parent is UsingDeclaration)) {
					foreach (var cl in nr.Namespace.Types) {
						string name = cl.Name;
						if (hintType != null && hintType.Kind != TypeKind.Array && cl.Kind == TypeKind.Interface) {
							continue;
						}
						if (IsAttributeContext(resolvedNode) && name.EndsWith("Attribute") && name.Length > "Attribute".Length) {
							name = name.Substring(0, name.Length - "Attribute".Length);
						}
						result.AddType(cl, name);
					}
				}
				foreach (var ns in nr.Namespace.ChildNamespaces) {
					result.AddNamespace(ns.Name);
				}
			} else if (resolveResult is TypeResolveResult) {
				var type = resolveResult.Type;
				foreach (var nested in type.GetNestedTypes ()) {
					if (hintType != null && hintType.Kind != TypeKind.Array && nested.Kind == TypeKind.Interface) {
						continue;
					}
					result.AddType(nested, nested.Name);
				}
			}
			return result.Result;
		}
 private StringBuilder InvalidNode(AstNode invalidNode, string msg)
 {
     DebugLog.Error(msg, GetInstructionFromStmt(invalidNode.GetParent <Statement>()));
     return(new StringBuilder());
 }
Example #33
0
 public Node(AstNode astNode, NodeKind kind)
 {
     AstNode             = astNode;
     Kind                = kind;
     ContainingStatement = astNode.GetParent <Statement> ();
 }
        public void FindIfElseInWebMethod(AstNode invocation, CSharpFile file)
        {
            if (invocation.GetType().Name == "IfElseStatement" &&
                FindWebMethod(invocation.GetParent <MethodDeclaration>()))
            {
                Expression childOfTypeRoleCondition = invocation.GetChildByRole(Roles.Condition);
                if (childOfTypeRoleCondition.GetType().Name == "UnaryOperatorExpression")
                {
                    string strToCheck = "Valid" + invocation.GetParent <MethodDeclaration>().Name;

                    if (allPatterns.IfElseValidMethodUnary(strToCheck).Match(childOfTypeRoleCondition).Success)
                    {
                        file.IndexOfIfElStmt.Add((IfElseStatement)invocation);
                    }
                    else if (allPatterns.IfElseValidMethodUnaryOld().Match(childOfTypeRoleCondition).Success)
                    {
                        string strToCheckforAlreadyDeclared = childOfTypeRoleCondition.Descendants.OfType <IdentifierExpression>().First().GetText();
                        if (strToCheckforAlreadyDeclared.IndexOf(("valid"), StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            file.IndexOfIfElStmtValidation.Add((IfElseStatement)invocation);
                        }
                    }
                    else if (allPatterns.IfElseValidMethodUnaryMemberRef().Match(childOfTypeRoleCondition).Success)
                    {
                        string strToCheckAlreadyDecare = childOfTypeRoleCondition.Descendants.OfType <MemberReferenceExpression>().First().LastChild.GetText();
                        if (strToCheckAlreadyDecare.IndexOf(("valid"), StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            file.IndexOfIfElStmtValidation.Add((IfElseStatement)invocation);
                        }
                    }
                }
                else if (childOfTypeRoleCondition.GetType().Name == "BinaryOperatorExpression")
                {
                    if (allPatterns.IfElseValidMethodBinary().Match(childOfTypeRoleCondition).Success)
                    {
                        string strToCheck = childOfTypeRoleCondition.Descendants.OfType <IdentifierExpression>().First().GetText();
                        if (strToCheck.IndexOf("Valid", StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            file.IndexOfIfElStmtValidation.Add((IfElseStatement)invocation);
                        }
                    }
                    else if (allPatterns.IfElseValidMethodBinaryMemberRef().Match(childOfTypeRoleCondition).Success)
                    {
                        string strToCheck = childOfTypeRoleCondition.Descendants.OfType <IdentifierExpression>().First().NextSibling.GetText();
                        if (strToCheck.IndexOf("Valid", StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            file.IndexOfIfElStmtValidation.Add((IfElseStatement)invocation);
                        }
                    }
                }
                //else if ()
                //   if(childRole == "UnaryOperatorExpression" || childRole == "BinaryOperatorExpression")
                //     file.IndexOfIfElStmt.Add((IfElseStatement)invocation);

                /*                file.IndexOfIfElStmt.Add((IfElseStatement)invocation);
                 *              string strToCheck = null;
                 *              try{
                 *                  //strToCheck = invocation.FirstChild.NextSibling.NextSibling.FirstChild.NextSibling.FirstChild.GetText();
                 *                  strToCheck = invocation.GetChildByRole(Roles.Condition).DescendantsAndSelf.OfType<InvocationExpression>().First().Children.OfType<IdentifierExpression>().First().GetText();
                 *              }
                 *              catch(Exception) {}
                 *              if (strToCheck != null)
                 *              {
                 *                  if (strToCheck.IndexOf("Valid", StringComparison.OrdinalIgnoreCase) >= 0  &&
                 *                      FoundWebMethodAttribute(invocation.GetParent<MethodDeclaration>()))
                 *                  {
                 *                      if (strToCheck == "Valid" + invocation.GetParent<MethodDeclaration>().Name)
                 *                      {
                 *                          file.IndexOfIfElStmt.Add((IfElseStatement)invocation);
                 *                      }
                 *                      else
                 *                      {
                 *                          invocation.Descendants.OfType<InvocationExpression>().First().GetNodeAt(invocation.StartLocation, null);
                 *                          //foreach(var expr)
                 *                      }
                 * //                        else if()
                 *                  }
                 *              }
                 */
            }
        }
			public Node (AstNode astNode, NodeKind kind)
			{
				AstNode = astNode;
				Kind = kind;
				ContainingStatement = astNode.GetParent<Statement> ();
			}
Example #36
0
        public static string ResolveExpression(TextEditorData editor, ResolveResult result, AstNode node, out int startOffset)
        {
            //Console.WriteLine ("result is a {0}", result.GetType ().Name);
            startOffset = -1;

            if (result is NamespaceResolveResult ||
                result is ConversionResolveResult ||
                result is ConstantResolveResult ||
                result is ForEachResolveResult ||
                result is TypeIsResolveResult ||
                result is TypeOfResolveResult ||
                result is ErrorResolveResult)
            {
                return(null);
            }

            if (result.IsCompileTimeConstant)
            {
                return(null);
            }

            startOffset = editor.LocationToOffset(node.StartLocation.Line, node.StartLocation.Column);

            if (result is InvocationResolveResult)
            {
                var ir = (InvocationResolveResult)result;
                if (ir.Member.Name == ".ctor")
                {
                    // if the user is hovering over something like "new Abc (...)", we want to show them type information for Abc
                    return(ir.Member.DeclaringType.FullName);
                }

                // do not support general method invocation for tooltips because it could cause side-effects
                return(null);
            }
            else if (result is LocalResolveResult)
            {
                if (node is ParameterDeclaration)
                {
                    // user is hovering over a method parameter, but we don't want to include the parameter type
                    var param = (ParameterDeclaration)node;

                    return(GetIdentifierName(editor, param.NameToken, out startOffset));
                }

                if (node is VariableInitializer)
                {
                    // user is hovering over something like "int fubar = 5;", but we don't want the expression to include the " = 5"
                    var variable = (VariableInitializer)node;

                    return(GetIdentifierName(editor, variable.NameToken, out startOffset));
                }
            }
            else if (result is MemberResolveResult)
            {
                var mr = (MemberResolveResult)result;

                if (node is PropertyDeclaration)
                {
                    var prop = (PropertyDeclaration)node;
                    var name = GetIdentifierName(editor, prop.NameToken, out startOffset);

                    // if the property is static, then we want to return "Full.TypeName.Property"
                    if (prop.Modifiers.HasFlag(Modifiers.Static))
                    {
                        return(mr.Member.DeclaringType.FullName + "." + name);
                    }

                    // otherwise we want to return "this.Property" so that it won't conflict with anything else in the local scope
                    return("this." + name);
                }

                if (node is FieldDeclaration)
                {
                    var field = (FieldDeclaration)node;
                    var name  = GetIdentifierName(editor, field.NameToken, out startOffset);

                    // if the field is static, then we want to return "Full.TypeName.Field"
                    if (field.Modifiers.HasFlag(Modifiers.Static))
                    {
                        return(mr.Member.DeclaringType.FullName + "." + name);
                    }

                    // otherwise we want to return "this.Field" so that it won't conflict with anything else in the local scope
                    return("this." + name);
                }

                if (node is VariableInitializer)
                {
                    // user is hovering over a field declaration that includes initialization
                    var variable = (VariableInitializer)node;
                    var name     = GetIdentifierName(editor, variable.NameToken, out startOffset);

                    // walk up the AST to find the FieldDeclaration so that we can determine if it is static or not
                    var field = variable.GetParent <FieldDeclaration> ();

                    // if the field is static, then we want to return "Full.TypeName.Field"
                    if (field.Modifiers.HasFlag(Modifiers.Static))
                    {
                        return(mr.Member.DeclaringType.FullName + "." + name);
                    }

                    // otherwise we want to return "this.Field" so that it won't conflict with anything else in the local scope
                    return("this." + name);
                }

                if (node is NamedExpression)
                {
                    // user is hovering over 'Property' in an expression like: var fubar = new Fubar () { Property = baz };
                    var variable = node.GetParent <VariableInitializer> ();
                    if (variable != null)
                    {
                        var variableName = GetIdentifierName(editor, variable.NameToken, out startOffset);
                        var name         = GetIdentifierName(editor, ((NamedExpression)node).NameToken, out startOffset);

                        return(variableName + "." + name);
                    }
                }
            }
            else if (result is TypeResolveResult)
            {
                return(((TypeResolveResult)result).Type.FullName);
            }

            return(editor.GetTextBetween(node.StartLocation, node.EndLocation));
        }
Example #37
0
        public AstNode GetParentFinallyBlock(AstNode node, bool stopOnLoops)
        {
            var insideTryFinally = false;
            var target = node.GetParent(n =>
            {
                if (n is LambdaExpression || n is AnonymousMethodExpression || n is MethodDeclaration)
                {
                    return true;
                }

                if (stopOnLoops && (n is WhileStatement || n is ForeachStatement || n is ForStatement || n is DoWhileStatement))
                {
                    return true;
                }

                if (n is TryCatchStatement && !((TryCatchStatement)n).FinallyBlock.IsNull)
                {
                    insideTryFinally = true;
                    return true;
                }

                return false;
            });

            return insideTryFinally ? ((TryCatchStatement)target).FinallyBlock : null;
        }
Example #38
0
        protected bool IsDirectAsyncBlockChild(AstNode node)
        {
            var block = node.GetParent<BlockStatement>();

            if (block != null && (block.Parent is MethodDeclaration || block.Parent is AnonymousMethodExpression || block.Parent is LambdaExpression))
            {
                return true;
            }

            return false;
        }
		public static string ResolveExpression (TextEditorData editor, ResolveResult result, AstNode node, out int startOffset)
		{
			//Console.WriteLine ("result is a {0}", result.GetType ().Name);
			startOffset = -1;

			if (result is NamespaceResolveResult ||
			    result is ConversionResolveResult ||
			    result is ConstantResolveResult ||
			    result is ForEachResolveResult ||
			    result is TypeIsResolveResult ||
			    result is TypeOfResolveResult ||
			    result is ErrorResolveResult)
				return null;

			if (result.IsCompileTimeConstant)
				return null;

			startOffset = editor.LocationToOffset (node.StartLocation.Line, node.StartLocation.Column);

			if (result is InvocationResolveResult) {
				var ir = (InvocationResolveResult) result;
				if (ir.Member.Name == ".ctor") {
					// if the user is hovering over something like "new Abc (...)", we want to show them type information for Abc
					return ir.Member.DeclaringType.FullName;
				}

				// do not support general method invocation for tooltips because it could cause side-effects
				return null;
			} else if (result is LocalResolveResult) {
				if (node is ParameterDeclaration) {
					// user is hovering over a method parameter, but we don't want to include the parameter type
					var param = (ParameterDeclaration) node;

					return GetIdentifierName (editor, param.NameToken, out startOffset);
				}

				if (node is VariableInitializer) {
					// user is hovering over something like "int fubar = 5;", but we don't want the expression to include the " = 5"
					var variable = (VariableInitializer) node;

					return GetIdentifierName (editor, variable.NameToken, out startOffset);
				}
			} else if (result is MemberResolveResult) {
				var mr = (MemberResolveResult) result;

				if (node is PropertyDeclaration) {
					var prop = (PropertyDeclaration) node;
					var name = GetIdentifierName (editor, prop.NameToken, out startOffset);

					// if the property is static, then we want to return "Full.TypeName.Property"
					if (prop.Modifiers.HasFlag (Modifiers.Static))
						return mr.Member.DeclaringType.FullName + "." + name;

					// otherwise we want to return "this.Property" so that it won't conflict with anything else in the local scope
					return "this." + name;
				}

				if (node is FieldDeclaration) {
					var field = (FieldDeclaration) node;
					var name = GetIdentifierName (editor, field.NameToken, out startOffset);

					// if the field is static, then we want to return "Full.TypeName.Field"
					if (field.Modifiers.HasFlag (Modifiers.Static))
						return mr.Member.DeclaringType.FullName + "." + name;

					// otherwise we want to return "this.Field" so that it won't conflict with anything else in the local scope
					return "this." + name;
				}

				if (node is VariableInitializer) {
					// user is hovering over a field declaration that includes initialization
					var variable = (VariableInitializer) node;
					var name = GetIdentifierName (editor, variable.NameToken, out startOffset);

					// walk up the AST to find the FieldDeclaration so that we can determine if it is static or not
					var field = variable.GetParent<FieldDeclaration> ();

					// if the field is static, then we want to return "Full.TypeName.Field"
					if (field.Modifiers.HasFlag (Modifiers.Static))
						return mr.Member.DeclaringType.FullName + "." + name;

					// otherwise we want to return "this.Field" so that it won't conflict with anything else in the local scope
					return "this." + name;
				}

				if (node is NamedExpression) {
					// user is hovering over 'Property' in an expression like: var fubar = new Fubar () { Property = baz };
					var variable = node.GetParent<VariableInitializer> ();
					if (variable != null) {
						var variableName = GetIdentifierName (editor, variable.NameToken, out startOffset);
						var name = GetIdentifierName (editor, ((NamedExpression) node).NameToken, out startOffset);

						return variableName + "." + name;
					}
				}
			} else if (result is TypeResolveResult) {
				return ((TypeResolveResult) result).Type.FullName;
			}

			return editor.GetTextBetween (node.StartLocation, node.EndLocation);
		}
Example #40
0
        public ResolveResult ResolveNode(AstNode node, ILog log)
        {
            var syntaxTree = node.GetParent<SyntaxTree>();
            this.InitResolver(syntaxTree);

            var result = this.resolver.Resolve(node);

            if (result is MethodGroupResolveResult && node.Parent != null)
            {
                var methodGroupResolveResult = (MethodGroupResolveResult)result;
                var parentResolveResult = this.ResolveNode(node.Parent, log);
                var parentInvocation = parentResolveResult as InvocationResolveResult;
                IParameterizedMember method = methodGroupResolveResult.Methods.LastOrDefault();
                bool isInvocation = node.Parent is InvocationExpression && (((InvocationExpression)(node.Parent)).Target == node);

                if (node is Expression)
                {
                    var conversion = this.Resolver.GetConversion((Expression)node);
                    if (conversion != null && conversion.IsMethodGroupConversion)
                    {
                        return new MemberResolveResult(new TypeResolveResult(conversion.Method.DeclaringType), conversion.Method);
                    }
                }

                if (isInvocation && parentInvocation != null)
                {
                    var or = methodGroupResolveResult.PerformOverloadResolution(this.compilation, parentInvocation.GetArgumentsForCall().ToArray());
                    if (or.FoundApplicableCandidate)
                    {
                        method = or.BestCandidate;
                        return new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method);
                    }
                }

                if (parentInvocation != null && method == null)
                {
                    var typeDef = methodGroupResolveResult.TargetType as DefaultResolvedTypeDefinition;

                    if (typeDef != null)
                    {
                        var methods = typeDef.Methods.Where(m => m.Name == methodGroupResolveResult.MethodName);
                        method = methods.FirstOrDefault();
                    }
                }

                if (method == null)
                {
                    var extMethods = methodGroupResolveResult.GetEligibleExtensionMethods(false);

                    if (!extMethods.Any())
                    {
                        extMethods = methodGroupResolveResult.GetExtensionMethods();
                    }

                    if (!extMethods.Any() || !extMethods.First().Any())
                    {
                        throw new EmitterException(node, "Cannot find method defintion");
                    }

                    method = extMethods.First().First();
                }

                if (parentInvocation == null || method.FullName != parentInvocation.Member.FullName)
                {
                    MemberResolveResult memberResolveResult = new MemberResolveResult(new TypeResolveResult(method.DeclaringType), method);
                    return memberResolveResult;
                }

                return parentResolveResult;
            }

            if ((result == null || result.IsError) && log != null)
            {
                if (result is CSharpInvocationResolveResult && ((CSharpInvocationResolveResult)result).OverloadResolutionErrors != OverloadResolutionErrors.None)
                {
                    return result;
                }

                log.LogWarning(string.Format("Node resolving has failed {0}: {1}", node.StartLocation, node.ToString()));
            }

            return result;
        }
Example #41
0
			public bool Visit(AstNode node)
			{
				int type = node.GetType();
				if (type == Token.SCRIPT)
				{
					return true;
				}
				if (node.GetParent() == null)
				{
					throw new InvalidOperationException("No parent for node: " + node + "\n" + node.ToSource(0));
				}
				return true;
			}
 static bool IsInsideTryBlock(AstNode node)
 {
     var tryCatchStatement = node.GetParent<TryCatchStatement> ();
     if (tryCatchStatement == null)
         return false;
     return tryCatchStatement.TryBlock.Contains (node.StartLocation.Line,node.StartLocation.Column);
 }