コード例 #1
0
		static bool TryDetermineOverridableMembers(SemanticModel semanticModel, SyntaxToken startToken, Accessibility seenAccessibility, out ISet<ISymbol> overridableMembers, CancellationToken cancellationToken)
		{
			var result = new HashSet<ISymbol>();
			var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, cancellationToken);
			if (containingType != null && !containingType.IsScriptClass && !containingType.IsImplicitClass)
			{
				if (containingType.TypeKind == TypeKind.Class || containingType.TypeKind == TypeKind.Struct)
				{
					var baseTypes = containingType.GetBaseTypes().Reverse();
					foreach (var type in baseTypes)
					{
						cancellationToken.ThrowIfCancellationRequested();

						// Prefer overrides in derived classes
						RemoveOverriddenMembers(result, type, cancellationToken);

						// Retain overridable methods
						AddProtocolMembers(semanticModel, result, containingType, type, cancellationToken);
					}
					// Don't suggest already overridden members
					RemoveOverriddenMembers(result, containingType, cancellationToken);
				}
			}

			// Filter based on accessibility
			if (seenAccessibility != Accessibility.NotApplicable)
			{
				result.RemoveWhere(m => m.DeclaredAccessibility != seenAccessibility);
			}

			overridableMembers = result;
			return overridableMembers.Count > 0;
		}
 private static bool IsAssignmentOutsideConstructor(AssignmentExpressionSyntax assignment, ISymbol fieldSymbol, SemanticModel model)
 {
     var assignedSymbol = model.GetSymbolInfo(assignment.Left);
     if (assignedSymbol.Symbol != fieldSymbol)
     {
         return false;
     }
     // Method (or whatever) enclosing the assignment
     var enclosingSymbol = model.GetEnclosingSymbol(assignment.SpanStart) as IMethodSymbol;
     var isCtor = enclosingSymbol?.MethodKind == MethodKind.Constructor;
     return !isCtor;
 }
コード例 #3
0
		protected override IEnumerable<CompletionData> CreateCompletionData (CompletionEngine engine, SemanticModel semanticModel, int position, ITypeSymbol returnType, Accessibility seenAccessibility, SyntaxToken startToken, SyntaxToken tokenBeforeReturnType, bool afterKeyword, CancellationToken cancellationToken)
		{
			var result = new List<CompletionData> ();
			ISet<ISymbol> overridableMembers;
			if (!TryDetermineOverridableMembers (semanticModel, tokenBeforeReturnType, seenAccessibility, out overridableMembers, cancellationToken)) {
				return result;
			}
			if (returnType != null) {
				overridableMembers = FilterOverrides (overridableMembers, returnType);
			}
			var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (startToken.SpanStart, cancellationToken);
			var declarationBegin = afterKeyword ? startToken.SpanStart : position - 1;
			foreach (var m in overridableMembers) {
				var data = new ProtocolCompletionData (this, factory, declarationBegin, curType, m, afterKeyword);
				result.Add (data);
			}
			return result;
		}
コード例 #4
0
        private static ImmutableHashSet<ISymbol> GetReturnedSymbols(StatementSyntax usingStatement,
            SemanticModel semanticModel)
        {
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(usingStatement.SpanStart);

            return usingStatement.DescendantNodesAndSelf()
                .OfType<ReturnStatementSyntax>()
                .Where(ret => semanticModel.GetEnclosingSymbol(ret.SpanStart).Equals(enclosingSymbol))
                .Select(ret => ret.Expression)
                .OfType<IdentifierNameSyntax>()
                .Select(identifier => semanticModel.GetSymbolInfo(identifier).Symbol)
                .Where(symbol => symbol != null)
                .ToImmutableHashSet();
        }
コード例 #5
0
        private static void ProcessPropertyChange(ExpressionSyntax expression, SemanticModel semanticModel,
            SyntaxNodeAnalysisContext context)
        {
            var memberAccess = expression as MemberAccessExpressionSyntax;
            if (memberAccess == null)
            {
                return;
            }

            var propertySymbol = semanticModel.GetSymbolInfo(expression).Symbol as IPropertySymbol;
            if (propertySymbol == null)
            {
                return;
            }

            var fieldSymbol = semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol as IFieldSymbol;
            if (fieldSymbol == null ||
                !fieldSymbol.IsReadOnly ||
                !RelevantFieldType(fieldSymbol.Type))
            {
                return;
            }

            var constructorSymbol = semanticModel.GetEnclosingSymbol(expression.SpanStart) as IMethodSymbol;
            if (constructorSymbol != null &&
                constructorSymbol.MethodKind == MethodKind.Constructor &&
                constructorSymbol.ContainingType.Equals(fieldSymbol.ContainingType))
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Rule, expression.GetLocation(), fieldSymbol.Name, propertySymbol.Name));
        }
コード例 #6
0
 private static List<IdentifierFieldMapping> GetIdentifierFieldMappings(VariableDeclaratorSyntax variable,
     INamedTypeSymbol containingType, SemanticModel semanticModel)
 {
     return variable.Initializer.DescendantNodes()
         .OfType<IdentifierNameSyntax>()
         .Select(identifier =>
         {
             var field = semanticModel.GetSymbolInfo(identifier).Symbol as IFieldSymbol;
             var enclosingSymbol = semanticModel.GetEnclosingSymbol(identifier.SpanStart);
             return new IdentifierFieldMapping
             {
                 Identifier = identifier,
                 Field = field,
                 IsRelevant = field != null &&
                     field.IsStatic &&
                     containingType.Equals(field.ContainingType) &&
                     enclosingSymbol is IFieldSymbol &&
                     enclosingSymbol.ContainingType.Equals(field.ContainingType)
             };
         })
         .Where(identifier => identifier.IsRelevant)
         .ToList();
 }
コード例 #7
0
        private static bool IsCallInsideOverride(InvocationExpressionSyntax invocation, IMethodSymbol calledMethod,
            SemanticModel semanticModel)
        {
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(invocation.SpanStart) as IMethodSymbol;

            return enclosingSymbol != null &&
                enclosingSymbol.IsOverride &&
                object.Equals(enclosingSymbol.OverriddenMethod, calledMethod);
        }
コード例 #8
0
        /// <summary>
        /// The the enclosing symbol for the current syntax node
        /// </summary>
        /// <param name="syntaxNode">The syntax node</param>
        /// <param name="semanticModel">The current semantic model</param>
        /// <returns></returns>
        public static ISymbol GetEnclosingSymbol(this SyntaxNode syntaxNode, SemanticModel semanticModel)
        {
            var position = syntaxNode.SpanStart;

            return(semanticModel.GetEnclosingSymbol(position));
        }
コード例 #9
0
		protected virtual IEnumerable<CompletionData> CreateCompletionData (CompletionEngine engine, SemanticModel semanticModel, int position, ITypeSymbol returnType, Accessibility seenAccessibility, SyntaxToken startToken, SyntaxToken tokenBeforeReturnType, bool afterKeyword, CancellationToken cancellationToken)
		{
			var result = new List<CompletionData> ();
			ISet<ISymbol> overridableMembers;
			if (!TryDetermineOverridableMembers (semanticModel, tokenBeforeReturnType, seenAccessibility, out overridableMembers, cancellationToken)) {
				return result;
			}
			if (returnType != null) {
				overridableMembers = FilterOverrides (overridableMembers, returnType);
			}
			var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (position, cancellationToken);
			var declarationBegin = afterKeyword ? (startToken.Parent.AncestorsAndSelf ().OfType<IncompleteMemberSyntax> ().FirstOrDefault () ?? startToken.Parent).SpanStart : position - 1;
			foreach (var m in overridableMembers) {
				var data = engine.Factory.CreateNewOverrideCompletionData (this, declarationBegin, curType, m, afterKeyword);
				result.Add (data);
			}
			return result;
		}
コード例 #10
0
        private static bool TryGetTypeFromReturnMappedToFloatType(BinaryExpressionSyntax division, SemanticModel semanticModel,
            out ITypeSymbol type)
        {
            if (division.Parent is ReturnStatementSyntax ||
                division.Parent is LambdaExpressionSyntax)
            {
                type = (semanticModel.GetEnclosingSymbol(division.SpanStart) as IMethodSymbol)?.ReturnType;
                return type.IsAny(KnownType.NonIntegralNumbers);
            }

            type = null;
            return false;
        }
コード例 #11
0
        private static void ProcessExpressionChange(ExpressionSyntax expression, SemanticModel semanticModel,
            ref ImmutableHashSet<IFieldSymbol> nonCandidateFields, ref ImmutableHashSet<IFieldSymbol> assignedAsReadonly)
        {
            var fieldSymbol = semanticModel.GetSymbolInfo(expression).Symbol as IFieldSymbol;
            if (fieldSymbol== null || !FieldIsRelevant(fieldSymbol))
            {
                return;
            }

            var constructorSymbol = semanticModel.GetEnclosingSymbol(expression.SpanStart) as IMethodSymbol;
            if (constructorSymbol == null)
            {
                nonCandidateFields = nonCandidateFields.Add(fieldSymbol);
                return;
            }

            if (constructorSymbol.MethodKind == MethodKind.Constructor &&
                constructorSymbol.ContainingType.Equals(fieldSymbol.ContainingType))
            {
                assignedAsReadonly = assignedAsReadonly.Add(fieldSymbol);
            }
            else
            {
                nonCandidateFields = nonCandidateFields.Add(fieldSymbol);
            }
        }
コード例 #12
0
		void AddDelegateHandlers (List<CompletionData> completionList, SyntaxNode parent, SemanticModel semanticModel, CompletionEngine engine, CompletionResult result, ITypeSymbol delegateType, int position, string optDelegateName, CancellationToken cancellationToken)
		{
			var delegateMethod = delegateType.GetDelegateInvokeMethod ();
			result.PossibleDelegates.Add (delegateMethod);

			var thisLineIndent = "";
			string EolMarker = "\n";
			bool addSemicolon = true;
			bool addDefault = true;

			string delegateEndString = EolMarker + thisLineIndent + "}" + (addSemicolon ? ";" : "");
			//bool containsDelegateData = completionList.Result.Any(d => d.DisplayText.StartsWith("delegate("));
			CompletionData item;
			if (addDefault) {
				item = engine.Factory.CreateAnonymousMethod (
					this,
					"delegate",
					"Creates anonymous delegate.",
					"delegate {" + EolMarker + thisLineIndent,
					delegateEndString
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);

				//if (LanguageVersion.Major >= 5)

				item = engine.Factory.CreateAnonymousMethod (
					this,
					"async delegate",
					"Creates anonymous async delegate.",
					"async delegate {" + EolMarker + thisLineIndent,
					delegateEndString
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);
			}

			var sb = new StringBuilder ("(");
			var sbWithoutTypes = new StringBuilder ("(");
			for (int k = 0; k < delegateMethod.Parameters.Length; k++) {
				if (k > 0) {
					sb.Append (", ");
					sbWithoutTypes.Append (", ");
				}
				sb.Append (RoslynCompletionData.SafeMinimalDisplayString (delegateMethod.Parameters [k], semanticModel, position, overrideNameFormat));
				sbWithoutTypes.Append (delegateMethod.Parameters [k].Name);
			}

			sb.Append (")");
			sbWithoutTypes.Append (")");
			var signature = sb.ToString ()
				.Replace (", params ", ", ")
				.Replace ("(params ", "(");

			if (completionList.All (data => data.DisplayText != signature)) {
				item = engine.Factory.CreateAnonymousMethod (
					this,
					signature + " =>",
					"Creates typed lambda expression.",
					signature + " => ",
					(addSemicolon ? ";" : "")
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);

				// if (LanguageVersion.Major >= 5) {

				item = engine.Factory.CreateAnonymousMethod (
					this,
					"async " + signature + " =>",
					"Creates typed async lambda expression.",
					"async " + signature + " => ",
					(addSemicolon ? ";" : "")
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);

				var signatureWithoutTypes = sbWithoutTypes.ToString ();
				if (!delegateMethod.Parameters.Any (p => p.RefKind != RefKind.None) && completionList.All (data => data.DisplayText != signatureWithoutTypes)) {
					item = engine.Factory.CreateAnonymousMethod (
						this,
						signatureWithoutTypes + " =>",
						"Creates typed lambda expression.",
						signatureWithoutTypes + " => ",
						(addSemicolon ? ";" : "")
					);
					if (!completionList.Any (i => i.DisplayText == item.DisplayText))
						completionList.Add (item);

					//if (LanguageVersion.Major >= 5) {
					item = engine.Factory.CreateAnonymousMethod (
						this,
						"async " + signatureWithoutTypes + " =>",
						"Creates typed async lambda expression.",
						"async " + signatureWithoutTypes + " => ",
						(addSemicolon ? ";" : "")
					);
					if (!completionList.Any (i => i.DisplayText == item.DisplayText))
						completionList.Add (item);

					//}
				}
			}
			string varName = optDelegateName ?? "Handle" + delegateType.Name;

            
			var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (position, cancellationToken);
			var uniqueName = new UniqueNameGenerator (semanticModel).CreateUniqueMethodName (parent, varName);
			item = engine.Factory.CreateNewMethodDelegate (this, delegateType, uniqueName, curType);
			if (!completionList.Any (i => i.DisplayText == item.DisplayText))
				completionList.Add (item);
		}
 private static bool IsInsideConstructorDeclaration(ExpressionSyntax expression, INamedTypeSymbol currentType,
     SemanticModel semanticModel)
 {
     var constructorSymbol = semanticModel.GetEnclosingSymbol(expression.SpanStart) as IMethodSymbol;
     return constructorSymbol != null &&
         constructorSymbol.MethodKind == MethodKind.Constructor &&
         constructorSymbol.ContainingType.Equals(currentType);
 }
コード例 #14
0
 internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken)
 {
     return (IMethodSymbol)model.GetEnclosingSymbol(lambdaExpression.SpanStart, cancellationToken);
 }
コード例 #15
0
		ParameterHintingResult HandleInvocationExpression(SemanticModel semanticModel, InvocationExpressionSyntax node, CancellationToken cancellationToken)
		{
			var info = semanticModel.GetSymbolInfo (node, cancellationToken);
			var result = new ParameterHintingResult(node.SpanStart);

			var targetTypeInfo = semanticModel.GetTypeInfo (node.Expression);
			if (targetTypeInfo.Type != null && targetTypeInfo.Type.TypeKind == TypeKind.Delegate) {
				result.AddData (factory.CreateMethodDataProvider (targetTypeInfo.Type.GetDelegateInvokeMethod ()));
				return result;
			}

			var within = semanticModel.GetEnclosingNamedTypeOrAssembly(node.SpanStart, cancellationToken);
			ITypeSymbol type;
			string name = null;
			bool staticLookup = false;
			var ma = node.Expression as MemberAccessExpressionSyntax;
			var mb = node.Expression as MemberBindingExpressionSyntax;
			if (mb != null) {
				info = semanticModel.GetSymbolInfo (mb, cancellationToken);
				type = (info.Symbol ?? info.CandidateSymbols.FirstOrDefault ())?.ContainingType;
				name = mb.Name.Identifier.ValueText;
			} else if (ma != null) {
				staticLookup = semanticModel.GetSymbolInfo (ma.Expression).Symbol is ITypeSymbol;
				type = semanticModel.GetTypeInfo (ma.Expression).Type;
				name = info.Symbol?.Name ?? ma.Name.Identifier.ValueText;
			} else {
				type = within as ITypeSymbol;
				name = info.Symbol?.Name ?? node.Expression.ToString ();
				var sym = semanticModel.GetEnclosingSymbol (node.SpanStart, cancellationToken); 
				staticLookup = sym.IsStatic;
			}
			var addedMethods = new List<IMethodSymbol> ();
			var filterMethod = new HashSet<IMethodSymbol> ();
			for (;type != null; type = type.BaseType) {
				foreach (var method in type.GetMembers ().OfType<IMethodSymbol> ().Concat (GetExtensionMethods(semanticModel, type, node, cancellationToken)).Where (m => m.Name == name)) {
					if (staticLookup && !method.IsStatic)
						continue;
					if (method.OverriddenMethod != null)
						filterMethod.Add (method.OverriddenMethod);
					if (filterMethod.Contains (method))
						continue;
					if (addedMethods.Any (added => SignatureComparer.HaveSameSignature (method, added, true)))
						continue;
					if (method.IsAccessibleWithin (within)) {
						if (info.Symbol != null) {
							var smethod = (IMethodSymbol)info.Symbol;
							if (smethod != null && smethod.OriginalDefinition == method) {
								continue;
							}
						}
						addedMethods.Add (method); 
						result.AddData (factory.CreateMethodDataProvider (method));
					}
				}
			}
			if (info.Symbol != null && !addedMethods.Contains (info.Symbol)) {
				if (!staticLookup || info.Symbol.IsStatic)
					result.AddData (factory.CreateMethodDataProvider ((IMethodSymbol)info.Symbol));
			}
			return result;
		}
        private static bool IsBinaryCandidateForReporting(BinaryExpressionSyntax binary, SemanticModel semanticModel)
        {
            var equalitySymbol = semanticModel.GetSymbolInfo(binary).Symbol as IMethodSymbol;

            return equalitySymbol.IsInType(KnownType.System_Object) &&
                !IsInEqualsOverride(semanticModel.GetEnclosingSymbol(binary.SpanStart) as IMethodSymbol);
        }
コード例 #17
0
        private static IDictionary<ISymbol, IDictionary<SyntaxNode, ISymbol>> GetReferencesByEnclosingSymbol(
            SyntaxNode node,
            IImmutableDictionary<ISymbol, PrivateField> privateFields,
            SemanticModel semanticModel)
        {
            var privateFieldNames = privateFields.Keys.Select(s => s.Name).ToImmutableHashSet();

            var potentialReferences = node.DescendantNodes()
                .Where(n => n.IsKind(SyntaxKind.IdentifierName))
                .Cast<IdentifierNameSyntax>()
                .Where(id => privateFieldNames.Contains(id.Identifier.ValueText));

            var builder = new Dictionary<ISymbol, IDictionary<SyntaxNode, ISymbol>>();
            foreach (var potentialReference in potentialReferences)
            {
                var referencedSymbol = semanticModel.GetSymbolInfo(potentialReference).Symbol;
                if (referencedSymbol == null || !privateFields.ContainsKey(referencedSymbol))
                {
                    continue;
                }

                SyntaxNode referenceSyntax = potentialReference;
                while (referenceSyntax.Parent != null && referencedSymbol.Equals(semanticModel.GetSymbolInfo(referenceSyntax.Parent).Symbol))
                {
                    referenceSyntax = referenceSyntax.Parent;
                }

                if (referenceSyntax.Parent != null && referenceSyntax.Parent.IsKind(SyntaxKind.ConditionalAccessExpression))
                {
                    referenceSyntax = referenceSyntax.Parent;
                }


                var enclosingSymbol = semanticModel.GetEnclosingSymbol(potentialReference.SpanStart);
                if (!builder.ContainsKey(enclosingSymbol))
                {
                    builder.Add(enclosingSymbol, new Dictionary<SyntaxNode, ISymbol>());
                }

                builder[enclosingSymbol].Add(referenceSyntax, referencedSymbol);
            }

            return builder;
        }