public static IEnumerable<NamedSymbol> GetTypeSymbols(this SemanticModel semanticModel, SyntaxNode node)
 {
     var typesymbols = semanticModel.LookupSymbols(node.SpanStart)
         .OfType<ILocalSymbol>()
         .Where(x => x.Locations.Any() && x.Locations.First().GetLineSpan().StartLinePosition < node.GetLocation().GetLineSpan().StartLinePosition)
         .Select(x => new NamedSymbol( x.Name,  x.Type))
         .Concat(
             semanticModel.LookupSymbols(node.SpanStart)
                 .OfType<IParameterSymbol>()
                 .Select(x => new NamedSymbol( x.Name,  x.Type))
         ).Concat(
             semanticModel.LookupSymbols(node.SpanStart)
                 .OfType<IPropertySymbol>()
                 .Select(x => new NamedSymbol( x.Name,  x.Type))
         ).Concat(
             semanticModel.LookupSymbols(node.SpanStart)
                 .OfType<IFieldSymbol>()
                 .Select(x => new NamedSymbol( x.Name,  x.Type))
         );
     if (!semanticModel.GetEnclosingSymbol(node.SpanStart).IsStatic)
     {
         var classDeclaration = node.Ancestors().OfType<ClassDeclarationSyntax>().FirstOrDefault();
         if(classDeclaration!=null)
         {
             typesymbols = typesymbols.Concat(new NamedSymbol[]
             {
                 new NamedSymbol( "this",(ITypeSymbol)semanticModel.GetDeclaredSymbol(classDeclaration))
             });
         }
     }
     return typesymbols;
 }
 void Check(SyntaxNode n)
 {
     var info = nodeContext.SemanticModel.GetSymbolInfo(n);
     var symbol = info.Symbol;
     if ((symbol == null) || (symbol.ContainingType == null) || symbol.ContainingType.Locations.Where(loc => loc.IsInSource && loc.SourceTree.FilePath == type.SyntaxTree.FilePath).All(loc => !type.Span.Contains(loc.SourceSpan)))
         return;
     if (!symbol.IsSealed && (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride))
     {
         if (symbol.Kind == SymbolKind.Property)
         {
             var propertySymbol = symbol as IPropertySymbol;
             if (propertySymbol != null)
             {
                 if (n.Ancestors().Any(a => a is AssignmentExpressionSyntax))
                 {
                     var setterMethodSymbol = propertySymbol.SetMethod;
                     if ((setterMethodSymbol != null) && (setterMethodSymbol.DeclaredAccessibility == Accessibility.Private))
                         return;
                 }
                 else
                 {
                     var getterMethodSymbol = propertySymbol.GetMethod;
                     if ((getterMethodSymbol != null) && (getterMethodSymbol.DeclaredAccessibility == Accessibility.Private))
                         return;
                 }
             }
             else
             {
                 return;
             }
         }
         Diagnostics.Add(Diagnostic.Create(descriptor, n.GetLocation()));
     }
 }
 private static SyntaxNode GetRootNodeOfLine(SyntaxNode node) {
     int nodeLocationLine = node.GetLocation().GetLineSpan().StartLinePosition.Line;
     var ancestors = node.Ancestors();
     var nodeLocationCharacter = ancestors.Where(ancestor => GetSpanLocation(ancestor).Start.Line == nodeLocationLine)
         .Min(ancestor => GetSpanLocation(ancestor).Start.Character);
     return ancestors.Last(ancestor => GetSpanLocation(ancestor).Start == new LinePosition(nodeLocationLine, nodeLocationCharacter));
 }
Esempio n. 4
0
        /// <summary>
        /// Finds first ancestor node such that predicate is met, unless terminateAt is met first. Returns null if terminateAt is true or if no ancestor meets predicate.
        /// </summary>
        /// <param name="node">The child node to start from.</param>
        /// <param name="predicate">The condition to return an ancestor.</param>
        /// <param name="terminateAt">If this is true for any ancestor, the search will be terminated.</param>
        /// <returns>The ancestor node that meets the predicate condition, or null if terminateAt is satisfied first or if no ancestor is found.</returns>
        public static SyntaxNode GetFirstAncestorWhere(this SyntaxNode node, Func <SyntaxNode, bool> predicate,
                                                       Func <SyntaxNode, bool> terminateAt = null)
        {
            terminateAt = terminateAt ?? (_ => false);

            return(node.Ancestors()
                   .TakeWhile(n => !terminateAt(n))
                   .Where(predicate)
                   .FirstOrDefault());
        }
Esempio n. 5
0
        /// <summary>
        /// Get the first ancestor which is a member declaration syntax of the provided kind (class, method, namespace, etc)
        /// </summary>
        /// <param name="node">The current node</param>
        /// <param name="includeSelf">If true, the current node will be considered when checking for MemberDeclarationSyntax ancestors</param>
        /// <param name="takeLast">If true, will grab the last surrounding declaration syntax of the given type. Useful to ignore of nested classes or namespaces</param>
        /// <returns>The surrounding member declaration syntax</returns>
        public static MemberDeclarationSyntax GetSurroundingMemberDeclarationSyntax <TMemberDeclarationType>(
            this SyntaxNode node,
            bool includeSelf = false,
            bool takeLast    = false)
            where TMemberDeclarationType : MemberDeclarationSyntax
        {
            var ancestors = includeSelf ? node.AncestorsAndSelf() : node.Ancestors();
            var target    = takeLast
                                ? ancestors.LastOrDefault(ancestor => ancestor.IsSyntaxOfType <TMemberDeclarationType>())
                                : ancestors.FirstOrDefault(ancestor => ancestor.IsSyntaxOfType <TMemberDeclarationType>());

            return(target as TMemberDeclarationType);
        }
Esempio n. 6
0
        /// <summary>
        /// Indicates if this node is directly or conditionally returned in the context of its declaration
        /// </summary>
        /// <param name="node">The node to check</param>
        /// <returns>Is the node is an active member of a return statement</returns>
        public static bool IsReturned(this SyntaxNode node)
        {
            if (node.Parent.IsSyntaxOfType <ReturnStatementSyntax>())
            {
                return(true);
            }

            var ancestorsUntilReturn = node.Ancestors()
                                       .TakeWhile(ancestor => !ancestor.IsSyntaxOfType <ReturnStatementSyntax>() && IsConditionalOrCoalesce(node));

            var returnStatement = ancestorsUntilReturn.LastOrDefault()?.Parent?.GetAsSyntaxOfType <ReturnStatementSyntax>();

            return(returnStatement != null && returnStatement.Expression.GetAsSyntaxOfType <ConditionalExpressionSyntax>()?.Condition != node);
        }
Esempio n. 7
0
        /// <summary>
        /// True if the given syntax node is in the scope of a state.
        /// </summary>
        /// <param name="node">SyntaxNode</param>
        /// <returns>Boolean</returns>
        protected bool IsInStateScope(SyntaxNode node)
        {
            var result = false;

            var ancestors = node.Ancestors().OfType<ClassDeclarationSyntax>().ToList();
            foreach (var ancestor in ancestors)
            {
                result = this.Project.PSharpPrograms.
                    SelectMany(p => p.NamespaceDeclarations).
                    SelectMany(n => n.MachineDeclarations).
                    SelectMany(m => m.StateDeclarations).
                    Any(s => s.Identifier.TextUnit.Text.Equals(ancestor.Identifier.ValueText));

                if (result)
                {
                    break;
                }
            }

            return result;
        }
            public string GenerateName(SyntaxNode node)
            {
                Debug.Assert(IsNameableNode(node));

                var builder = new StringBuilder();

                var ancestors = node.Ancestors().ToArray();
                for (int i = ancestors.Length - 1; i >= 0; i--)
                {
                    var ancestor = ancestors[i];

                    // We skip "unnameable" nodes to ensure that we don't add empty names
                    // for nodes like the compilation unit or field declarations.
                    if (IsNameableNode(ancestor))
                    {
                        AppendNodeName(builder, ancestor);
                    }
                }

                AppendNodeName(builder, node);

                return builder.ToString();
            }
Esempio n. 9
0
        private static void FixMissingType(SyntaxNode node, Scope scope)
        {
            var type = node
                .Ancestors()
                .OfType<TypeDeclarationSyntax>()
                .FirstOrDefault();

            if (type != null)
            {
                var typeScope = scope.GetScope<SyntaxToken, SyntaxNode, SemanticModel>(type);
                if (typeScope != null)
                {
                    SyntaxNode realType = typeScope.get<SyntaxNode>("__tdef" + node.ToString());
                    if (realType != null)
                    {
                        realType = RoslynCompiler.Mark(realType); //make sure not to duplicate nodes

                        var document = scope.GetDocument<SyntaxToken, SyntaxNode, SemanticModel>();
                        document.change(node, RoslynCompiler.ReplaceNode(realType));
                    }
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Tries to return the parent machine identifier, if any.
        /// </summary>
        /// <param name="node">SyntaxNode</param>
        /// <param name="machine">MachineDeclaration</param>
        /// <returns>Boolean value</returns>
        protected bool TryGetParentMachine(SyntaxNode node, out MachineDeclaration machine)
        {
            var result = false;
            machine = null;

            var ancestors = node.Ancestors().OfType<ClassDeclarationSyntax>().ToList();
            foreach (var ancestor in ancestors)
            {
                machine = this.Project.PSharpPrograms.
                    SelectMany(p => p.NamespaceDeclarations).
                    SelectMany(n => n.MachineDeclarations).
                    FirstOrDefault(s => s.Identifier.TextUnit.Text.Equals(ancestor.Identifier.ValueText));

                if (machine != null)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
 public override void Visit(SyntaxNode node)
 {
     var padding = node.Ancestors().Count();
     var prepend = node.ChildNodes().Any() ? "[-]" : "[.]";
     var line = new string(' ', padding) + prepend + " " + node.GetType().ToString();
     Console.WriteLine(line);
     base.Visit(node);
 }
        protected override bool CanAddImportForType(Diagnostic diagnostic, ref SyntaxNode node)
        {
            switch (diagnostic.Id)
            {
                case CS0103:
                case CS0246:
                case CS0305:
                case CS0308:
                case CS0122:
                case CS0307:
                case CS0616:
                case CS1003:
                case CS1580:
                case CS1581:
                    break;

                case CS1002:
                    //// only lookup errors inside ParenthesizedLambdaExpression e.g., () => { ... }
                    if (node.Ancestors().OfType<ParenthesizedLambdaExpressionSyntax>().Any())
                    {
                        if (node is SimpleNameSyntax)
                        {
                            break;
                        }
                        else if (node is BlockSyntax || node is MemberAccessExpressionSyntax || node is BinaryExpressionSyntax)
                        {
                            var last = node.DescendantNodes().OfType<SimpleNameSyntax>().LastOrDefault();
                            if (!TryFindStandaloneType(ref node))
                            {
                                node = node.DescendantNodes().OfType<SimpleNameSyntax>().FirstOrDefault();
                            }
                            else
                            {
                                node = last;
                            }
                        }
                    }
                    else
                    {
                        return false;
                    }

                    break;

                case CS1574:
                case CS1584:
                    var cref = node as QualifiedCrefSyntax;
                    if (cref != null)
                    {
                        node = cref.Container;
                    }

                    break;

                default:
                    return false;
            }

            return TryFindStandaloneType(ref node);
        }
		private static SyntaxNode GetContainingMember(SyntaxNode oldNode)
		{
			var parenthesizedLambda = oldNode
				.Ancestors()
				.FirstOrDefault(n =>
				                n.IsKind(SyntaxKind.ParenthesizedLambdaExpression));

			if (parenthesizedLambda != null)
			{
				return parenthesizedLambda;
			}

			var simpleLambda = oldNode
				.Ancestors()
				.FirstOrDefault(n =>
				                n.IsKind(SyntaxKind.SimpleLambdaExpression));

			if (simpleLambda != null)
			{
				return simpleLambda;
			}

			return oldNode
				.Ancestors()
				.FirstOrDefault(n =>
				                n.IsKind(SyntaxKind.MethodDeclaration));
		}
        public override void Visit(SyntaxNode node)
        {
            var padding = node.Ancestors().Count();
            var prepend = node.ChildNodes().Any() ? "[-]" : "[.]";
            var nodetype = node.GetType().FullName;
            if (nodetype.StartsWith(prefix)) nodetype = nodetype.Substring(prefix.Length);
            var line = new string(' ', padding) + prepend + " " + nodetype;
            Console.WriteLine(line);

            //var decl = node as ClassDeclarationSyntax;
            //if (decl != null && decl.BaseList != null)
            //{
            //    Console.Write(new string(' ', padding + 4) + decl.Identifier);
            //    foreach (var n in decl.BaseList.Types.OfType<IdentifierNameSyntax>())
            //    {
            //        Console.Write(" " + n.Identifier);
            //    }
            //    Console.WriteLine();
            //}

            var attr = node as AttributeSyntax;
            if (attr != null)
            {
                Console.WriteLine(new string(' ', padding + 4) + "> " + attr.Name);
                foreach (var arg in attr.ArgumentList.Arguments)
                {
                    var expr = arg.Expression as LiteralExpressionSyntax;
                    //Console.WriteLine(new string(' ', padding + 4) + "> " + arg.NameColon + " " + arg.NameEquals);
                    Console.WriteLine(new string(' ', padding + 4) + "> " + (expr == null ? null : expr.Token.Value));
                }
            }
            var attr2 = node as IdentifierNameSyntax;
            if (attr2 != null)
            {
                Console.WriteLine(new string(' ', padding + 4) + "T " + attr2.Identifier.GetType());
                Console.WriteLine(new string(' ', padding + 4) + "V " + attr2.Identifier);
            }

            var x = node as TypeSyntax;
            if (x != null)
            {
                var xtype = x.GetType().FullName;
                if (xtype.StartsWith(prefix)) xtype = nodetype.Substring(prefix.Length);
                Console.WriteLine(new string(' ', padding + 4) + "> " + xtype);
            }

            base.Visit(node);
        }
        private static IEnumerable<string> GetIdentifiersInScope(SyntaxNode node)
        {
            var withinFirstClass = true;
            foreach (var ancestor in node.Ancestors())
            {
                switch (ancestor.Kind())
                {
                    case SyntaxKind.IndexerDeclaration:
                        var indexerDeclarationSyntax = (IndexerDeclarationSyntax)ancestor;
                        foreach (var parameter in indexerDeclarationSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        break;
                    case SyntaxKind.ConstructorDeclaration:
                        var constructorDeclarationSyntax = (ConstructorDeclarationSyntax)ancestor;
                        foreach (var parameter in constructorDeclarationSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        break;
                    case SyntaxKind.ParenthesizedLambdaExpression:
                        var parenthesizedLambdaExpressionSyntax = (ParenthesizedLambdaExpressionSyntax)ancestor;
                        foreach (var parameter in parenthesizedLambdaExpressionSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        break;
                    case SyntaxKind.SimpleLambdaExpression:
                        yield return ((SimpleLambdaExpressionSyntax)ancestor).Parameter.Identifier.ValueText;
                        break;
                    case SyntaxKind.MethodDeclaration:
                        var methodDeclarationSyntax = (MethodDeclarationSyntax)ancestor;
                        foreach (var parameter in methodDeclarationSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        yield return methodDeclarationSyntax.Identifier.ValueText;
                        if (methodDeclarationSyntax.TypeParameterList != null)
                        {
                            foreach (var typeParameter in methodDeclarationSyntax.TypeParameterList.Parameters)
                            {
                                yield return typeParameter.Identifier.ValueText;
                            }
                        }
                        break;
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.ClassDeclaration:
                        var typeDeclarationSyntax = (TypeDeclarationSyntax)ancestor;
                        yield return typeDeclarationSyntax.Identifier.ValueText;
                        if (typeDeclarationSyntax.TypeParameterList != null)
                        {
                            foreach (var typeParameter in typeDeclarationSyntax.TypeParameterList.Parameters)
                            {
                                yield return typeParameter.Identifier.ValueText;
                            }
                        }
                        if (withinFirstClass)
                        {
                            var children = typeDeclarationSyntax.ChildNodes();
                            foreach (var property in children.OfType<PropertyDeclarationSyntax>())
                            {
                                yield return property.Identifier.ValueText;
                            }
                            foreach (var field in children.OfType<FieldDeclarationSyntax>())
                            {
                                foreach (var variable in field.Declaration.Variables)
                                {
                                    yield return variable.Identifier.ValueText;
                                }
                            }
                            withinFirstClass = false;
                        }
                        break;

                }
            }
        }
        internal void WriteDetectedThreadingNamespaceUsage(Enums.ThreadingNamespaceDetected type, string documentPath, ISymbol symbol, SyntaxNode node)
        {
            if (Enums.ThreadingNamespaceDetected.None != type)
            {


                Logger usagelog=null;
                Logger typelog=null;

                switch (type)
                {
                    case Enums.ThreadingNamespaceDetected.ThreadClass:
                        usagelog = Logs.TempLog;
                        typelog = Logs.TempLog2;
                        break;
                    case Enums.ThreadingNamespaceDetected.ThreadpoolClass:
                        usagelog = Logs.TempLog3;
                        typelog = Logs.TempLog4;
                        break;
                    case Enums.ThreadingNamespaceDetected.OtherClass:
                        usagelog = Logs.TempLog5;
                        typelog = Logs.TempLog6;
                        break;
                }

                SyntaxNode block=null;
                var temp = node.Ancestors().OfType<BlockSyntax>();
                if (temp.Any())
                    block = temp.First();
                else
                    block = node.Ancestors().ElementAt(3);

                typelog.Info("{0};{1}", symbol.ContainingType, symbol.ToString());
                usagelog.Info("{0} {1}\r\n{2}\r\n--------------------------", symbol, documentPath,  block);


                //// Let's get rid of all specific information!
                //if (!symbol.ReturnsVoid)
                //    returntype = symbol.ReturnType.OriginalDefinition.ToString();

                //typelog.Info(@"{0};{1};{2};{3};{4};{5};{6};{7}", AppName, documentPath, type.ToString(), returntype, symbol.OriginalDefinition.ContainingNamespace, symbol.OriginalDefinition.ContainingType, symbol.OriginalDefinition.Name, ((MethodSymbol)symbol.OriginalDefinition).Parameters);
            }
        }
        public override SyntaxNode Visit(SyntaxNode node)
        {
            Context.LastNode = node;
            try
            {

                if (node is NameEqualsSyntax)
                    return (node);

               

                //			SyntaxNode visit; //Needs update
                //                     if (FixPropertyUnaryExpressions(node, out visit))
                //                return visit;
                  if (node is IdentifierNameSyntax &&
                   //   (node.Parent is ExpressionSyntax || node.Parent is MethodDeclarationSyntax || node.Parent is PropertyDeclarationSyntax
                     // || node.Parent is BlockSyntax) &&
                      !(node.Parent.Parent is InitializerExpressionSyntax) &&
                      !(node.Parent is QualifiedNameSyntax) && !(node.Parent is MemberAccessExpressionSyntax) && !(node.Parent is ThisExpressionSyntax))
                  {
                      //Lets fully qualify these so that we can have property code working
                      var symbolInfo = _semanticModel.GetSymbolInfo(node);

                      if (symbolInfo.Symbol != null &&
                          (symbolInfo.Symbol.Kind == SymbolKind.Field || symbolInfo.Symbol.Kind == SymbolKind.Property))
                      {
                          if (symbolInfo.Symbol.ContainingType != null && symbolInfo.Symbol.IsStatic)
                          {
                              var newName = symbolInfo.Symbol.ContainingType.GetFullNameCSharp() + "." +
                                            symbolInfo.Symbol.Name;
                              return SyntaxFactory.ParseExpression(newName);
                          }
                          else
                          {

                              var firstParent =
                                  TypeProcessor.GetDeclaredSymbol(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                              //_semanticModel.GetSymbolInfo(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                              if (symbolInfo.Symbol.ContainingType != null && !symbolInfo.Symbol.IsStatic && symbolInfo.Symbol.ContainingType == firstParent)
                                  return SyntaxFactory.ParseExpression("this." + symbolInfo.Symbol.Name);
                          }
                          return base.Visit(node);
                      }
                  }

                if (node is MemberAccessExpressionSyntax &&
                //   (node.Parent is ExpressionSyntax || node.Parent is MethodDeclarationSyntax || node.Parent is PropertyDeclarationSyntax
                // || node.Parent is BlockSyntax) &&
                !(node.Parent.Parent is InitializerExpressionSyntax) &&
              !(node.Parent is QualifiedNameSyntax) && !(node.Parent is MemberAccessExpressionSyntax) && !(node.Parent is ThisExpressionSyntax))
            {
                var nodeasMember = node as MemberAccessExpressionSyntax;
                if (!(nodeasMember.Expression is ThisExpressionSyntax))
                { 
                //Lets fully qualify these so that we can have property code working
                var symbolInfo = _semanticModel.GetSymbolInfo(node);

                    if (symbolInfo.Symbol != null &&
                        (symbolInfo.Symbol.Kind == SymbolKind.Field || symbolInfo.Symbol.Kind == SymbolKind.Property))
                    {
                        if (symbolInfo.Symbol.ContainingType != null && symbolInfo.Symbol.IsStatic)
                        {
                            var newName = symbolInfo.Symbol.ContainingType.GetFullNameCSharp() + "." +
                                          symbolInfo.Symbol.Name;
                            return SyntaxFactory.ParseExpression(newName);
                        }
                        else
                        {
                            ISymbol symbol = TypeProcessor.GetSymbolInfo((node as MemberAccessExpressionSyntax).Expression).Symbol;
                            if (
                                symbol != null && (!(symbol
                                    is
                                    ILocalSymbol) && !(symbol is IParameterSymbol) && symbol.Name != ".ctor"))
                            {
                                var firstParent =
                                    TypeProcessor.GetDeclaredSymbol(
                                        node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                                //_semanticModel.GetSymbolInfo(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                                if (symbolInfo.Symbol.ContainingType != null && !symbolInfo.Symbol.IsStatic &&
                                    symbolInfo.Symbol.ContainingType == firstParent)
                                    return SyntaxFactory.ParseExpression("this." + node.ToFullString());
                            }

                        }
                    }
                    return base.Visit(node);
                }
            }

            return base.Visit(node);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }