protected override bool TryInitializeState(
			Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
			out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
		{
			var baseClassNode = node as TypeSyntax;
			if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
				baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
				((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
			{
				if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
				{
					abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
					cancellationToken.ThrowIfCancellationRequested();

					if (abstractClassType.IsAbstractClass())
					{
						var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
						classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;

						return classType != null && abstractClassType != null;
					}
				}
			}

			classType = null;
			abstractClassType = null;
			return false;
		}
		internal static IEnumerable<ISymbol> GetDeclaredSymbols(SemanticModel semanticModel, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken)
		{
			if (memberDeclaration is FieldDeclarationSyntax)
			{
				return ((FieldDeclarationSyntax)memberDeclaration).Declaration.Variables.Select(
					v => semanticModel.GetDeclaredSymbol(v, cancellationToken));
			}

			return SpecializedCollections.SingletonEnumerable(
				semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
		}
        /// <summary>
        /// Détermine si le inheritDoc du symbole méthode est présent et correct.
        /// </summary>
        /// <param name="racine">Le nœud racine de l'arbre syntaxtique courant.</param>
        /// <param name="modèleSémantique">Le modèle sémantique lié.</param>
        /// <param name="méthode">La méthode concernée.</param>
        /// <returns>La ligne inheritDoc correcte dans le cas où l'actuelle est manquante/incorrecte, sinon null.</returns>
        public static string InheritDocEstCorrect(SyntaxNode racine, SemanticModel modèleSémantique, MethodDeclarationSyntax méthode)
        {
            var classe = méthode?.Parent as ClassDeclarationSyntax;

            // Si on est bien dans une méthode de classe.
            if (méthode != null && classe != null)
            {
                // On récupère la version sémantique de la méthode pour identifier ses paramètres.
                var méthodeSémantique = modèleSémantique.GetDeclaredSymbol(méthode);

                // On liste toutes les méthodes des interfaces de la classe puis on cherche l'unique méthode avec la même signature.
                var méthodeCorrespondantes = modèleSémantique.GetDeclaredSymbol(classe).Interfaces
                    .SelectMany(contrat => contrat.GetMembers())
                    .Where(méthodeInterface => méthodeInterface.Name == méthode.Identifier.Text
                        && ((méthodeInterface as IMethodSymbol)?.Parameters.SequenceEqual(méthodeSémantique.Parameters, (p1, p2) => p1.Name == p2.Name) ?? false));

                var méthodeCorrespondante = (méthodeCorrespondantes.Count() == 1 ? méthodeCorrespondantes.Single() : null) as IMethodSymbol;

                // S'il y a bien une méthode correspondante, on continue.
                if (méthodeCorrespondante != null)
                {
                    // On récupère le nombre de méthode du même nom dans l'interface pour savoir s'il faut spécifier les paramètres ou non.
                    var nombreMéthodesSurchargées = (méthodeCorrespondante.ContainingSymbol as INamedTypeSymbol).GetMembers()
                        .Count(méthodeInterface => méthodeInterface.Name == méthode.Identifier.Text);

#pragma warning disable SA1013, SA1513

                    // On génère la ligne de documentation.
                    var inheritDoc = $@"/// <inheritdoc cref=""{
                        RécupérerNomType(méthode, méthodeCorrespondante, modèleSémantique)
                    }.{
                        RécupérerNomMéthode(méthode, méthodeCorrespondante)
                      + RécupérerParamètres(méthode, méthodeCorrespondante, modèleSémantique, nombreMéthodesSurchargées)
                    }"" />";

#pragma warning restore SA1013, SA1513

                    // On récupère la documentation actuelle de la classe.
                    var documentationActuelle = méthode.GetLeadingTrivia().ToString().Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(" ", string.Empty);

                    // On la compare avec la ligne existante de façon bien crade, parce qu'en vrai elle n'est pas générée correctement.
                    // Désolé. J'ai vraiment essayé de faire proprement mais la génération propre de commentaires XML est odieuse.
                    // Si la ligne est différente et ne contient pas le mot "summary", on retourne la ligne de commentaire attendue.
                    if (!inheritDoc.Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(" ", string.Empty)
                            .Equals(documentationActuelle) && !documentationActuelle.Contains("summary"))
                        return inheritDoc;
                }
            }

            // Sinon on renvoie null, pour affirmer au diagnostic que tout va bien.
            return null;
        }
        protected sealed override IEnumerable<Diagnostic> GetDiagnosticsForNode(SyntaxNode node, SemanticModel model)
        {
            var typeSymbol = model.GetDeclaredSymbol(node);
            var namedType = typeSymbol as INamedTypeSymbol;

            // static holder types are not already static/sealed and must be public or protected
            if (namedType != null && !namedType.IsStatic && !namedType.IsSealed
                && (namedType.DeclaredAccessibility == Accessibility.Public || namedType.DeclaredAccessibility == Accessibility.Protected))
            {
                // only get the explicitly declared members
                var allMembers = namedType.GetMembers().Where(member => !member.IsImplicitlyDeclared);
                if (!allMembers.Any())
                {
                    return null;
                }

                // to be a static holder type, all members must be static and not operator overloads
                if (allMembers.All(member => member.IsStatic && !IsUserdefinedOperator(member)))
                {
                    var diagnostic = typeSymbol.CreateDiagnostic(Rule, string.Format(FxCopRulesResources.TypeIsStaticHolderButNotSealed, namedType.Name));
                    return SpecializedCollections.SingletonEnumerable(diagnostic);
                }
            }

            return null;
        }
		internal static ImmutableArray<TypeToRemove> GetTypesToRemove(
			this SyntaxNode @this, SemanticModel model, 
			string documentFileNameWithoutExtension)
		{
			var typesToRemove = new List<TypeToRemove>();
			TypeDeclarationSyntax typeToPreserve = null;

			var typeNodes = @this.DescendantNodes(_ => true)
				.OfType<TypeDeclarationSyntax>();

			foreach(var typeNode in typeNodes)
			{
				var type = model.GetDeclaredSymbol(typeNode) as ITypeSymbol;

				if(type.ContainingType == null)
				{
					if(type.Name != documentFileNameWithoutExtension)
					{
						typesToRemove.Add(new TypeToRemove(
							typeNode, type));
					}
					else
					{
						typeToPreserve = typeNode;
					}
				}
			}

			return typesToRemove.ToImmutableArray();
		}
        protected IEnumerable<CodeAction> GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, ParameterSyntax node)
        {
            if (!node.Identifier.Span.Contains(span))
                yield break;

            var parameter = node;
            var bodyStatement = parameter.Parent.Parent.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
            if (bodyStatement == null)
                yield break;

            var parameterSymbol = semanticModel.GetDeclaredSymbol(node);
            var type = parameterSymbol.Type;
            if (type == null || type.IsValueType || HasNotNullContract(semanticModel, parameterSymbol, bodyStatement))
                yield break;

            yield return CreateAction(
                node.Identifier.Span
                , t2 => {
                    var newBody = bodyStatement.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { CreateContractRequiresCall(node.Identifier.ToString()) }.Concat(bodyStatement.Statements)));

                    var newRoot = (CompilationUnitSyntax)root.ReplaceNode((SyntaxNode)bodyStatement, newBody);

                    if (UsingStatementNotPresent(newRoot)) newRoot = AddUsingStatement(node, newRoot);

                    return Task.FromResult(document.WithSyntaxRoot(newRoot));
                }
                , "Add contract requiring parameter must not be null"
            );
        }
		protected override async Task<EvaluationResult> EvaluateImpl(SyntaxNode node, SemanticModel semanticModel, Solution solution)
		{
			var symbol = (ITypeSymbol)semanticModel.GetDeclaredSymbol(node);
			var efferent = GetReferencedTypes(node, symbol, semanticModel).AsArray();
			var awaitable = SymbolFinder.FindCallersAsync(symbol, solution, CancellationToken.None).ConfigureAwait(false);
			var callers = (await awaitable).AsArray();
			var testCallers = callers
				.Where(c => c.CallingSymbol.GetAttributes()
				.Any(x => x.AttributeClass.Name.IsKnownTestAttribute()))
				.AsArray();
			var afferent = callers.Except(testCallers)
				.Select(x => x.CallingSymbol.ContainingType)
				.DistinctBy(s => s.ToDisplayString())
				.AsArray();

			var efferentLength = (double)efferent.Length;
			var stability = efferentLength / (efferentLength + afferent.Length);
			if (stability >= 0.8)
			{
				return new EvaluationResult
				{
					ImpactLevel = ImpactLevel.Project,
					Quality = CodeQuality.NeedsReview,
					QualityAttribute = QualityAttribute.CodeQuality | QualityAttribute.Conformance,
					Snippet = node.ToFullString()
				};
			}

			return null;
		}
        internal static bool HasFlagsAttribute(SyntaxNode node, SemanticModel semanticModel)
        {
            var symbol = semanticModel.GetDeclaredSymbol(node);

            return symbol != null && 
                symbol.GetAttributes().Any(attribute => attribute.AttributeClass.Is(KnownType.System_FlagsAttribute));
        }
Beispiel #9
0
        private static ISymbol GetDeclaredSymbol(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken)
        {
            if (!getSymbol)
            {
                return null;
            }

            var declaredSymbol = model.GetDeclaredSymbol(node, cancellationToken);

            // For namespace declarations, GetDeclaredSymbol returns a compilation scoped namespace symbol,
            // which includes declarations across the compilation, including those in referenced assemblies.
            // However, we are only interested in the namespace symbol scoped to the compilation's source assembly.
            var namespaceSymbol = declaredSymbol as INamespaceSymbol;
            if (namespaceSymbol != null && namespaceSymbol.ConstituentNamespaces.Length > 1)
            {
                var assemblyToScope = model.Compilation.Assembly;
                var assemblyScopedNamespaceSymbol = namespaceSymbol.ConstituentNamespaces.FirstOrDefault(ns => ns.ContainingAssembly == assemblyToScope);
                if (assemblyScopedNamespaceSymbol != null)
                {
                    Debug.Assert(assemblyScopedNamespaceSymbol.ConstituentNamespaces.Length == 1);
                    declaredSymbol = assemblyScopedNamespaceSymbol;
                }
            }

            return declaredSymbol;
        }
        /// <summary>
        /// This is jus a test to check the ability to preprocess the AST
        /// </summary>
        /// <param name="methodNode"></param>
        /// <param name="semanticModel"></param>
        /// <returns></returns>
        public static IMethodSymbol SimplifyASTForMethod(ref SyntaxNode methodNode, ref SemanticModel semanticModel)
        {
            var oldMethod = semanticModel.GetDeclaredSymbol(methodNode) as IMethodSymbol;

            var newMethodNode = MethodSimpifier.Test(methodNode);

            var annotation = new SyntaxAnnotation("Hi");

            newMethodNode = newMethodNode.WithAdditionalAnnotations(annotation);

            var root = methodNode.SyntaxTree.GetRoot();
            var newRoot = root.ReplaceNode(methodNode, newMethodNode);

            var oldCompilation = semanticModel.Compilation;

            var newCompilation = oldCompilation.ReplaceSyntaxTree(root.SyntaxTree, newRoot.SyntaxTree);
            var newSemanticModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);

            var recoveredMethodNode = newRoot.GetAnnotatedNodes(annotation).Single();

            var method = newSemanticModel.GetDeclaredSymbol(recoveredMethodNode) as IMethodSymbol;

            methodNode = recoveredMethodNode;
            semanticModel = newSemanticModel;

            return method;
        }
 internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, IEnumerable<SyntaxNode> executableCodeBlocks, CancellationToken cancellationToken)
 {
     var declaredSymbol = getSymbol ? model.GetDeclaredSymbol(node, cancellationToken) : null;
     var codeBlocks = executableCodeBlocks == null ?
         ImmutableArray<SyntaxNode>.Empty :
         executableCodeBlocks.Where(c => c != null).AsImmutableOrEmpty();
     return new DeclarationInfo(node, codeBlocks, declaredSymbol);
 }
 internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix, cancellationToken);
     var instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => GetDeclaration(t)).Where(d => d != null).ToList();
     var generator = SyntaxGenerator.GetGenerator(document);
     var newRoot = root.ReplaceNodes(instanceConstructors, (original, rewritten) => generator.WithAccessibility(original, Accessibility.Protected));
     return Task.FromResult(document.WithSyntaxRoot(newRoot));
 }
		protected override IEnumerable<ISymbol> GetSymbols(SyntaxNode node, SemanticModel semanticModel)
		{
			var declaration = (VariableDeclarationSyntax)node;

			var symbols = declaration.Variables.Select(x => semanticModel.GetDeclaredSymbol(x)).AsArray();

			return symbols;
		}
 static bool AreVariablesOnlyWrittenInsideDeclaration(LocalDeclarationStatementSyntax declaration, SemanticModel semanticModel)
 {
     var dfa = semanticModel.AnalyzeDataFlow(declaration);
     var symbols = from variable in declaration.Declaration.Variables
                   select semanticModel.GetDeclaredSymbol(variable);
     var result = !symbols.Any(s => dfa.WrittenOutside.Contains(s));
     return result;
 }
Beispiel #15
0
 /// <summary>
 /// Returns true if the given expression flows in the target.
 /// </summary>
 /// <param name="variable">Variable</param>
 /// <param name="target">Target</param>
 /// <param name="syntaxNode">SyntaxNode</param>
 /// <param name="cfgNode">ControlFlowGraphNode</param>
 /// <param name="targetSyntaxNode">Target syntaxNode</param>
 /// <param name="targetCfgNode">Target controlFlowGraphNode</param>
 /// <param name="model">SemanticModel</param>
 /// <returns>Boolean</returns>
 internal static bool FlowsIntoTarget(VariableDeclaratorSyntax variable, ISymbol target,
     SyntaxNode syntaxNode, ControlFlowGraphNode cfgNode, SyntaxNode targetSyntaxNode,
     ControlFlowGraphNode targetCfgNode, SemanticModel model)
 {
     ISymbol reference = model.GetDeclaredSymbol(variable);
     return DataFlowAnalysis.FlowsIntoTarget(reference, target, syntaxNode,
         cfgNode, targetSyntaxNode, targetCfgNode);
 }
        public static ISymbol GetDeclaredOrReferencedSymbol(this SyntaxNode node, SemanticModel model)
        {
            if (node == null)
            {
                return null;
            }

            return model.GetDeclaredSymbol(node) ?? model.GetSymbolInfo(node).Symbol;
        }
        private static async Task<Document> Fix(CodeFixContext context, SyntaxNode root, SyntaxGenerator generator, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            SyntaxNode node = root.FindNode(context.Span);
            Diagnostic diagnostic = context.Diagnostics.First();
            switch (diagnostic.Properties[OperatorOverloadsHaveNamedAlternatesAnalyzer.DiagnosticKindText])
            {
                case OperatorOverloadsHaveNamedAlternatesAnalyzer.AddAlternateText:
                    SyntaxNode methodDeclaration = generator.GetDeclaration(node, DeclarationKind.Operator) ?? generator.GetDeclaration(node, DeclarationKind.ConversionOperator);
                    var operatorOverloadSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);
                    INamedTypeSymbol typeSymbol = operatorOverloadSymbol.ContainingType;

                    // For C# the following `typeDeclarationSyntax` and `typeDeclaration` nodes are identical, but for VB they're different so in
                    // an effort to keep this as language-agnostic as possible, the heavy-handed approach is used.
                    SyntaxNode typeDeclarationSyntax = typeSymbol.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
                    SyntaxNode typeDeclaration = generator.GetDeclaration(typeDeclarationSyntax, DeclarationKind.Class);

                    SyntaxNode addedMember;
                    ImmutableArray<SyntaxNode> bodyStatements = ImmutableArray.Create(
                        generator.ThrowStatement(generator.ObjectCreationExpression(semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"))));
                    if (OperatorOverloadsHaveNamedAlternatesAnalyzer.IsPropertyExpected(operatorOverloadSymbol.Name))
                    {
                        // add a property
                        addedMember = generator.PropertyDeclaration(
                            name: OperatorOverloadsHaveNamedAlternatesAnalyzer.IsTrueText,
                            type: generator.TypeExpression(SpecialType.System_Boolean),
                            accessibility: Accessibility.Public,
                            modifiers: DeclarationModifiers.ReadOnly,
                            getAccessorStatements: bodyStatements);
                    }
                    else
                    {
                        // add a method
                        ExpectedMethodSignature expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);
                        addedMember = generator.MethodDeclaration(
                            name: expectedSignature.Name,
                            parameters: expectedSignature.Parameters.Select(p => generator.ParameterDeclaration(p.Item1, generator.TypeExpression(p.Item2))),
                            returnType: generator.TypeExpression(expectedSignature.ReturnType),
                            accessibility: Accessibility.Public,
                            modifiers: expectedSignature.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None,
                            statements: bodyStatements);
                    }

                    SyntaxNode newTypeDeclaration = generator.AddMembers(typeDeclaration, addedMember);
                    return context.Document.WithSyntaxRoot(root.ReplaceNode(typeDeclaration, newTypeDeclaration));
                case OperatorOverloadsHaveNamedAlternatesAnalyzer.FixVisibilityText:
                    SyntaxNode badVisibilityNode = generator.GetDeclaration(node, DeclarationKind.Method) ?? generator.GetDeclaration(node, DeclarationKind.Property);
                    ISymbol badVisibilitySymbol = semanticModel.GetDeclaredSymbol(badVisibilityNode, cancellationToken);
                    SymbolEditor symbolEditor = SymbolEditor.Create(context.Document);
                    ISymbol newSymbol = await symbolEditor.EditOneDeclarationAsync(badVisibilitySymbol,
                        (documentEditor, syntaxNode) => documentEditor.SetAccessibility(badVisibilityNode, Accessibility.Public)).ConfigureAwait(false);
                    Document newDocument = symbolEditor.GetChangedDocuments().Single();
                    SyntaxNode newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                    return context.Document.WithSyntaxRoot(newRoot);
                default:
                    return context.Document;
            }
        }
        private static SyntaxNode RemoveFlagsAttribute(SyntaxGenerator generator, SemanticModel model, SyntaxNode enumTypeSyntax, INamedTypeSymbol flagsAttributeType, CancellationToken cancellationToken)
        {
            var enumType = model.GetDeclaredSymbol(enumTypeSyntax, cancellationToken) as INamedTypeSymbol;
            Debug.Assert(enumType != null);

            AttributeData flagsAttribute = enumType.GetAttributes().First(a => a.AttributeClass == flagsAttributeType);
            SyntaxNode attributeNode = flagsAttribute.ApplicationSyntaxReference.GetSyntax(cancellationToken);

            return generator.RemoveNode(enumTypeSyntax, attributeNode);
        }
 public static IEnumerable<MemberDeclarationSyntax> GetMembersFromAllParts(this ClassDeclarationSyntax type, SemanticModel model)
 {
     var typeSymbol = model.GetDeclaredSymbol(type);
     if (typeSymbol.IsErrorType())
         return null;
     var allTypeDeclarations = typeSymbol.DeclaringSyntaxReferences.Select(sr => sr.GetSyntax()).OfType<ClassDeclarationSyntax>();
     if (allTypeDeclarations.Any())
         return allTypeDeclarations.SelectMany(t => t.Members);
     return null;
 }
        private static void CaptureCandidateFields(FieldDeclarationSyntax field, SemanticModel semanticModel, List<FieldCandidate> candidateFields)
        {

            if (!CanBecameReadOnlyField(field)) return;
            var variables = field.Declaration.Variables;
            var currentAnalysisCandidateFields = variables.Select(s => new FieldCandidate { Variable = s, FieldSymbol = semanticModel.GetDeclaredSymbol(s) as IFieldSymbol })
                .Where(p => p.FieldSymbol != null && p.FieldSymbol.ContainingType != null);

            if (!currentAnalysisCandidateFields.Any()) return;
            candidateFields.AddRange(currentAnalysisCandidateFields);
        }
 private bool IsInternal(SyntaxNode invocation, SemanticModel model, out string nameSpace)
 {
     var containingType = _documentWalker.GetContainingNodeOfType<TypeDeclarationSyntax>(invocation);
     var typeSymbol = model.GetDeclaredSymbol(containingType) as INamedTypeSymbol;
     if (typeSymbol == null) throw new NoNamedTypeException(containingType.ToString());
     nameSpace = typeSymbol.ContainingNamespace.Name;
     var invocationSymbol = model.GetSymbolInfo(invocation).Symbol;
     if (invocationSymbol == null) return true;  // No Symbol -> Anonymous Method -> is Internal
     var members = containingType.Members;
     return _documentWalker.IsSymbolInvocationOfNodes(members, invocationSymbol, model);
 }
        internal static NavTaskAnnotation ReadNavTaskAnnotation(SemanticModel semanticModel, ClassDeclarationSyntax classDeclarationSyntax) {

            if(semanticModel == null || classDeclarationSyntax == null) {
                return null;
            }

            var classSymbol = semanticModel.GetDeclaredSymbol(classDeclarationSyntax);
            var navTaskInfo = ReadNavTaskAnnotation(classDeclarationSyntax, classSymbol);
           
            return navTaskInfo;
        }
        internal static bool IsEventHandler(MethodStatementSyntax declaration, SemanticModel semanticModel)
        {
            if (declaration.HandlesClause != null)
            {
                return true;
            }

            var symbol = semanticModel.GetDeclaredSymbol(declaration);
            return symbol != null &&
                symbol.IsProbablyEventHandler();
        }
 private ReferenceRewriter(
     SemanticModel semanticModel,
     VariableDeclaratorSyntax variableDeclarator,
     ExpressionSyntax expressionToInline,
     CancellationToken cancellationToken)
 {
     _semanticModel = semanticModel;
     _localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
     _variableDeclarator = variableDeclarator;
     _expressionToInline = expressionToInline;
     _cancellationToken = cancellationToken;
 }
Beispiel #25
0
        public static SyntaxNode MockClass(SyntaxTree tree, SemanticModel semanticModel, ClassDeclarationSyntax classNode)
        {
            SyntaxNode root = tree.GetRoot();
            Console.WriteLine("Class name: " + classNode.Identifier.Text);

            SyntaxList<MemberDeclarationSyntax> members = new SyntaxList<MemberDeclarationSyntax>();

            List<string> usedNames = new List<string>();

            foreach (var member in classNode.Members)
            {
                if (member is MethodDeclarationSyntax)
                {
                    var method = (MethodDeclarationSyntax)member;
                    Console.WriteLine("\tMethod name: " + method.Identifier.Text);

                    IMethodSymbol methodSemanticData = semanticModel.GetDeclaredSymbol(method) as IMethodSymbol;
                    members = members.Add(CreateMethodDelegate(method, methodSemanticData, usedNames));
                    members = members.Add(CreateMethodBody(method, methodSemanticData, usedNames));
                }
                else if (member is PropertyDeclarationSyntax)
                {
                    var property = (PropertyDeclarationSyntax)member;
                    Console.WriteLine("\tProperty name: " + property.Identifier.Text);

                    IPropertySymbol propertySemanticData = semanticModel.GetDeclaredSymbol(property) as IPropertySymbol;
                    members = members.Add(GenerateProperty(property, propertySemanticData, usedNames));
                }
                else
                {
                    members = members.Add(member);
                }
            }

            SyntaxToken classIdentifier = SF.IdentifierName(classNode.Identifier.Text + "Mock").GetFirstToken();
            var classDeclaration = SF.ClassDeclaration(classNode.AttributeLists, classNode.Modifiers, classIdentifier, classNode.TypeParameterList, classNode.BaseList, classNode.ConstraintClauses, members);

            return SF.NamespaceDeclaration(SF.IdentifierName("TestNamespace")).AddUsings(SF.UsingDirective(SF.IdentifierName("System"))).AddMembers(classDeclaration);
        }
        private static bool IsMethodUsed(MethodDeclarationSyntax methodTarget, SemanticModel semanticModel)
        {
            var typeDeclaration = methodTarget.Parent as TypeDeclarationSyntax;
            if (typeDeclaration == null) return true;

            if (!typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword))
                return IsMethodUsed(methodTarget, typeDeclaration);

            var symbol = semanticModel.GetDeclaredSymbol(typeDeclaration);

            return
                symbol == null ||
                symbol.DeclaringSyntaxReferences.Any(reference => IsMethodUsed(methodTarget, reference.GetSyntax()));
        }
Beispiel #27
0
		protected override async Task<EvaluationResult> EvaluateImpl(SyntaxNode node, SemanticModel semanticModel, Solution solution)
		{
			var symbol = semanticModel.GetDeclaredSymbol(node);
			var callers = await solution.FindReferences(symbol).ConfigureAwait(false);

			if (!callers.Locations.Any(x => IsNotAssignment(x.Location)))
			{
				return new EvaluationResult
					   {
						   Snippet = node.ToFullString()
					   };
			}

			return null;
		}
        private static ClassNode CreateClassNode(SemanticModel model, ClassDeclarationSyntax c)
        {
            var declaredSymbol = model.GetDeclaredSymbol(c);

            var subnodes = c.DescendantNodes();
            var symbols = subnodes.Select(node => model.GetSymbolInfo(node).Symbol).ToList();

            var dependencies = symbols.OfType<INamedTypeSymbol>();
            var nrOfMethods = subnodes.OfType<MethodDeclarationSyntax>().Count();

            IEnumerable<TypeSyntax> basetypes = new List<TypeSyntax>();
            if (c.BaseList != null && c.BaseList.Types.Any())
                basetypes = c.BaseList.Types.Select(x => x.Type);
            return new ClassNode(declaredSymbol, basetypes, nrOfMethods) {SymbolDependencies = dependencies};
        }
        public override ITypeSymbol GetClassDeclarationTypeSymbol(SyntaxNode node, SemanticModel semanticModel)
        {
            if (node == null)
            {
                return null;
            }

            SyntaxKind kind = node.Kind();
            if (kind == SyntaxKind.ClassDeclaration)
            {
                return semanticModel.GetDeclaredSymbol((ClassDeclarationSyntax)node);
            }

            return null;
        }
		private static ITypeSymbol ResolveContainingType(SyntaxNode node, SemanticModel model)
		{
			if (node == null)
			{
				return null;
			}

			var parent = node.Parent;
			if (parent is BaseTypeDeclarationSyntax)
			{
				var symbolInfo = model.GetDeclaredSymbol(parent);
				return symbolInfo as ITypeSymbol;
			}

			return ResolveContainingType(parent, model);
		}
 /// <summary>
 /// Returns the semantic declared symbol of the provided syntax node as the provided symbol type
 /// </summary>
 /// <param name="syntaxNode">The syntax node</param>
 /// <param name="model">The syntax semantic model</param>
 /// <returns>The symbol of the provided syntax node</returns>
 public static ISymbol GetDeclaredSymbol(this SyntaxNode syntaxNode, SemanticModel model)
 {
     return(model.GetDeclaredSymbol(syntaxNode));
 }
 /// <summary>
 /// Returns the semantic symbol of the provided syntax node, or the declared symbol if the previous cast was invalid
 /// </summary>
 /// <param name="syntaxNode"></param>
 /// <param name="semanticModel"></param>
 /// <returns>The symbol or declared symbol of the provided syntax node</returns>
 public static ISymbol GetSymbolOrDeclared(this SyntaxNode syntaxNode, SemanticModel semanticModel)
 {
     return(semanticModel.GetSymbolInfo(syntaxNode).Symbol ?? semanticModel.GetDeclaredSymbol(syntaxNode));
 }
 /// <summary>
 /// Returns the semantic declared symbol of the provided syntax node as the provided symbol type
 /// </summary>
 /// <param name="syntaxNode">The syntax node</param>
 /// <param name="model">The syntax analysis context</param>
 /// <returns>The symbol of the provided syntax node</returns>
 public static TSymbolType GetDeclaredSymbolAs <TSymbolType>(this SyntaxNode syntaxNode, SemanticModel model) where TSymbolType : class, ISymbol
 {
     return(model.GetDeclaredSymbol(syntaxNode) as TSymbolType);
 }