private void AnalyzeIdentifier(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGeneratedOrNonUserCode())
            {
                return;
            }

            // Look at the method
            // If it has parameters, check if see if the last parameter has the IsParams set.
            IdentifierNameSyntax indentifierName = context.Node as IdentifierNameSyntax;
            IMethodSymbol        methodSymbol    = context.SemanticModel.GetSymbolInfo(indentifierName).Symbol as IMethodSymbol;

            if (methodSymbol != null)
            {
                Int32 count = methodSymbol.OriginalDefinition.Parameters.Length;
                if (count != 0)
                {
                    if (methodSymbol.OriginalDefinition.Parameters[count - 1].IsParams)
                    {
                        // Only report the error if this call is inside a loop.
                        if (context.Node.IsNodeInALoop())
                        {
                            // We got us a problem here, boss.
                            var diagnostic = Diagnostic.Create(Rule,
                                                               indentifierName.GetLocation(),
                                                               indentifierName.Parent.ToString());
                            context.ReportDiagnostic(diagnostic);
                        }
                    }
                }
            }
        }
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGenerated())
            {
                return;
            }
            var node = (InvocationExpressionSyntax)context.Node;
            IdentifierNameSyntax name = null;
            var p0 = P.InvocationExpression(expression: P.MemberAccessExpression(name: P.IdentifierName("Where", action: x => name = x)));

            if (!p0.IsMatch(context.Node))
            {
                return;
            }

            bool match1 = P.InvocationExpression(
                argumentList: P.ArgumentList(
                    P.Argument(
                        expression: P.SimpleLambdaExpression())))
                          .IsMatch(node);

            bool match2 = P.InvocationExpression(argumentList: P.ArgumentList(
                                                     P.Argument(
                                                         expression: P.ParenthesizedLambdaExpression(
                                                             parameterList: P.ParameterList(
                                                                 P.Parameter())))))
                          .MatchAncestorsAndSelf(node).Count == 1;

            if (!(match1 || match2))
            {
                return;
            }

            var nextMethodInvoke = node.Parent.
                                   FirstAncestorOrSelf <InvocationExpressionSyntax>();

            if (nextMethodInvoke == null)
            {
                return;
            }

            var candidate = GetNameOfTheInvokedMethod(nextMethodInvoke)?.ToString();

            if (!supportedMethods.Contains(candidate))
            {
                return;
            }

            if (nextMethodInvoke.ArgumentList.Arguments.Any())
            {
                return;
            }
            var properties = new Dictionary <string, string> {
                { "methodName", candidate }
            }.ToImmutableDictionary();
            var diagnostic = Diagnostic.Create(Rule, name.GetLocation(), properties, candidate);

            context.ReportDiagnostic(diagnostic);
        }
コード例 #3
0
 internal static Location GetNameLocation(this InvocationExpressionSyntax invocation)
 {
     return(invocation.Expression switch
     {
         IdentifierNameSyntax identifierName => identifierName.GetLocation(),
         MemberAccessExpressionSyntax {
             Name : { } name
         } => name.GetLocation(),
コード例 #4
0
 public static void AnalyzeMethodName(SyntaxNodeAnalysisContext context, MethodDeclarationSyntax syntax)
 {
     if (syntax != null)
     {
         IdentifierNameSyntax syntaxName = syntax.Name;
         SyntaxKind           syntaxKind = syntax.Kind;
         string name = syntax.GetNameStringValue();
         if (!IsMethodNamePascalCase(name))
         {
             ReportMethodNameMustBeDeclaratedInPascalCase(context, syntaxName.GetLocation(), name, syntaxKind, syntaxName);
         }
         if (IsMethodContainWhiteSpace(name))
         {
             ReportMethodNameMayNotContainWhiteSpace(context, syntaxName.GetLocation(), name, syntaxKind, syntaxName);
         }
     }
 }
コード例 #5
0
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            // See if we're part of a qualified name
            var qname      = node.FirstAncestorOrSelf <QualifiedNameSyntax>();
            var syntaxNode = qname == null ? (SyntaxNode)node : qname;

            // Get the symbol
            var symbolInfo = _semanticModel.GetSymbolInfo(syntaxNode, _cancellationToken);

            if (symbolInfo.Symbol == null)
            {
                _logger.LogWarning(node.GetLocation(), "Failed to resolve symbol for: {Syntax}", syntaxNode.ToString());
            }
            else if (symbolInfo.Symbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.TypeKind == TypeKind.Class)
            {
                _logger.LogTrace(node.GetLocation(), "Referenced symbol: {Kind}::{Name}", symbolInfo.Symbol.Kind, symbolInfo.Symbol.Name);
                _builder.Snapshot.ReferenceSymbol(symbolInfo.Symbol, node.GetLocation());
            }
コード例 #6
0
        private void HandleIdentifierNameImpl(SyntaxNodeAnalysisContext context, IdentifierNameSyntax nameExpression)
        {
            if (nameExpression == null)
            {
                return;
            }

            if (!this.HasThis(nameExpression))
            {
                return;
            }

            SymbolInfo symbolInfo = context.SemanticModel.GetSymbolInfo(nameExpression, context.CancellationToken);
            ImmutableArray <ISymbol> symbolsToAnalyze;

            if (symbolInfo.Symbol != null)
            {
                symbolsToAnalyze = ImmutableArray.Create(symbolInfo.Symbol);
            }
            else if (symbolInfo.CandidateReason == CandidateReason.MemberGroup)
            {
                // analyze the complete set of candidates, and use 'this.' if it applies to all
                symbolsToAnalyze = symbolInfo.CandidateSymbols;
            }
            else
            {
                return;
            }

            foreach (ISymbol symbol in symbolsToAnalyze)
            {
                if (symbol is ITypeSymbol)
                {
                    return;
                }

                if (symbol.IsStatic)
                {
                    return;
                }

                if (!(symbol.ContainingSymbol is ITypeSymbol))
                {
                    // covers local variables, parameters, etc.
                    return;
                }

                IMethodSymbol methodSymbol = symbol as IMethodSymbol;
                if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.Constructor)
                {
                    return;
                }
            }

            // Prefix local calls with this
            context.ReportDiagnostic(Diagnostic.Create(Descriptor, nameExpression.GetLocation()));
        }
コード例 #7
0
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     if (IsImplicitReturnValue(node))
     {
         context.ReportDiagnosticWhenActive(Diagnostic.Create(Rule, node.GetLocation(),
                                                              IsAssignmentStatement(node)
             ? UseReturnStatementMessage
             : DontUseImplicitMessage));
     }
 }
コード例 #8
0
        private void Analyze(SyntaxNodeAnalysisContext context)
        {
            IdentifierNameSyntax identifierNameSyntax = (IdentifierNameSyntax)context.Node;

            if (!IsIdentifierDynamicType(context, identifierNameSyntax))
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Rule, identifierNameSyntax.GetLocation()));
        }
コード例 #9
0
        private static void HandleExceptionType(SyntaxNodeAnalysisContext context, IdentifierNameSyntax simpleTypeName)
        {
            string currentType   = simpleTypeName.Identifier.Text;
            string preferredType = GetPreferredTypeName(currentType);

            if (!string.IsNullOrEmpty(preferredType))
            {
                // The code fix provider depends on this returning the location of the IdentifierNameSyntax.
                Location location = simpleTypeName.GetLocation();
                context.ReportDiagnostic(Diagnostic.Create(Rule, location, preferredType, currentType));
            }
        }
コード例 #10
0
        public static void AnalyzeVariable(SyntaxNodeAnalysisContext context, VariableDeclarationSyntax syntax)
        {
            if (syntax == null)
            {
                return;
            }
            IdentifierNameSyntax syntaxName = syntax.Name;
            SyntaxKind           syntaxKind = syntax.Kind;
            string name = syntax.GetNameStringValue();

            if (!IsVariableNamePascalCase(name))
            {
                ReportVariableNameMustBeDeclaratedInPascalCase(context, syntaxName.GetLocation(), name, syntaxKind, syntaxName);
            }
            if (IsVaraibleContainWhiteSpace(name))
            {
                ReportVariableNameMayNotContainWhiteSpace(context, syntaxName.GetLocation(), name, syntaxKind, syntaxName);
            }
            if (IsVaraibleContainWildcardSymbols(name))
            {
                ReportVariableNameMayNotContainWildcardSymbols(context, syntaxName.GetLocation(), name, syntaxKind, syntaxName);
            }
        }
コード例 #11
0
            public override void VisitIdentifierName(IdentifierNameSyntax node)
            {
                var symbol = _context.SemanticModel.GetSymbolInfo(node, _context.CancellationToken).Symbol;

                if (symbol == null)
                {
                    return;
                }

                if (symbol.Name == "SqlServerCommand")
                {
                    var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), symbol.Name, _classSymbol.Name);
                    _context.ReportDiagnostic(diagnostic);
                }
            }
コード例 #12
0
            public override void VisitIdentifierName(IdentifierNameSyntax node)
            {
                if (_inLambda)
                {
                    var symbol = _model.GetSymbolInfo(node);
                    if (symbol.Symbol != null && _symbols.Contains(symbol.Symbol))
                    {
                        var diagnostic = Diagnostic.Create(_rule, node.GetLocation(), node.Identifier.Text);

                        _context.ReportDiagnostic(diagnostic);
                    }
                }

                base.VisitIdentifierName(node);
            }
コード例 #13
0
            public override void VisitIdentifierName(IdentifierNameSyntax node)
            {
                ThrowIfCancellationRequested();

                TypeInfo typeInfo = _semanticModel.GetTypeInfo(node, _context.CancellationToken);

                if (typeInfo.Type == null || !typeInfo.Type.IsPXGraphOrExtension(_pxContext))
                {
                    return;
                }

                _context.ReportDiagnosticWithSuppressionCheck(
                    Diagnostic.Create(Descriptors.PX1029_PXGraphUsageInDac, node.GetLocation()),
                    _pxContext.CodeAnalysisSettings);

                base.VisitIdentifierName(node);
            }
コード例 #14
0
ファイル: LLOC.cs プロジェクト: smartshark/OpenStaticAnalyzer
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     if (entryNode is AnonymousFunctionExpressionSyntax && embeddedNode is AnonymousFunctionExpressionSyntax)
     {
         return;
     }
     if (_weComeFromMethod && _weInAnonymousMethod)
     {
         return;
     }
     if (node.IsParent <AnonymousObjectCreationExpressionSyntax>())
     {
         return;
     }
     InsertLLOCMap(node.GetLocation());
     base.VisitIdentifierName(node);
 }
コード例 #15
0
ファイル: ScopeExtractor.cs プロジェクト: askdash/refinym
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            var refSymbol = RoslynUtils.GetReferenceSymbol(node, _semanticModel);

            if (refSymbol != null && RoslynUtils.IsVariableSymbol(refSymbol) && refSymbol.Locations[0].IsInSource)
            {
                var typeSymbol = RoslynUtils.GetVariableTypeSymbol(refSymbol);
                if (typeSymbol.ToString() == _targetType)
                {
                    _inScopeSymbols.Add(_tokenToLocation(node.GetLocation(), node.ToString()),
                                        new ScopeData(SymbolToString(refSymbol),
                                                      new HashSet <String>(_semanticModel.LookupSymbols(node.GetLocation().SourceSpan.End).Where(s => RoslynUtils.IsVariableSymbol(s)).
                                                                           Where(s => s.Locations[0].IsInSource).
                                                                           Where(s => RoslynUtils.GetVariableTypeSymbol(s).ToString() == _targetType).Select(s => SymbolToString(s)))));
                }
            }
            base.VisitIdentifierName(node);
        }
コード例 #16
0
        //---------------------------------------------------------------------
        private static void AnalyzeTypeUsage(SyntaxNodeAnalysisContext syntaxContext)
        {
            IdentifierNameSyntax identifier = syntaxContext.Node as IdentifierNameSyntax;
            ITypeSymbol          type       = GetTypeInfo(syntaxContext, identifier);

            if (type == null)
            {
                return;
            }

            if (!IsNamespaceInternal(type.ContainingNamespace))
            {
                // don't care about non-pubternal type references
                return;
            }

            SyntaxNode parent = identifier.Parent;

            if (parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
            {
                var memberAccess = parent as MemberAccessExpressionSyntax;

                if (memberAccess.OperatorToken.IsKind(SyntaxKind.DotToken))
                {
                    ExpressionSyntax exp   = memberAccess.Expression;
                    ITypeSymbol      type1 = GetTypeInfo(syntaxContext, exp);

                    if (type1 != null && !IsNamespaceInternal(type1.ContainingNamespace))
                    {
                        return;
                    }
                }
            }

            if (syntaxContext.ContainingSymbol.ContainingAssembly != type.ContainingAssembly)
            {
                syntaxContext.ReportDiagnostic(Diagnostic.Create(
                                                   PubturnalityDescriptors.GF0001,
                                                   identifier.GetLocation(),
                                                   type.ToDisplayString()));
            }
        }
コード例 #17
0
        void AnalyzeIdentifier(IdentifierNameSyntax identifier)
        {
            var symbol = SemanticModel.GetSymbolInfo(identifier).Symbol;

            if (symbol == null)
            {
                return;
            }

            if (enablesFieldDiagnostic &&
                IsMemberVariable(symbol) &&
                !IsInitialized(symbol)
                )
            {
                Reporter.ReportFieldDiagnostic(identifier.GetLocation(), symbol);
            }

            if (MemberMap.Properties.TryGetValue(symbol, out var property))
            {
                AnalyzeProperty(property, identifier.IsAssigned());
            }
        }
コード例 #18
0
        public IEnumerable <DiagnosticInfo> GetDiagnosticInfo(SyntaxNodeAnalysisContext context)
        {
            var result = new List <DiagnosticInfo>();

            var method = context.Node as MethodDeclarationSyntax;

            //Grab the method's return type. 2 cases:
            // - GenericNameSyntax (Task<ActionResult>)
            // - IdentifierNameSyntax (ActionResult)
            IdentifierNameSyntax returnType = null;

            if (method?.ReturnType is GenericNameSyntax)
            {
                GenericNameSyntax generic = method?.ReturnType as GenericNameSyntax;
                if (generic.TypeArgumentList.Arguments.Count > 0)
                {
                    returnType = generic.TypeArgumentList.Arguments[0] as IdentifierNameSyntax;
                }
            }
            else
            {
                returnType = method?.ReturnType as IdentifierNameSyntax;
            }

            //If returnType is null, bail out
            if (returnType == null)
            {
                return(result);
            }

            //Grab the return type symbol and return if it is not a named type
            var symbol = context.SemanticModel.GetSymbolInfo(returnType).Symbol as INamedTypeSymbol;

            if (symbol == null)
            {
                return(result);
            }

            //This could be expensive, but we need search to the base type and determine if this return type
            //inherits from the System.Web.Mvc.ActionResult and verify if the return type is of type ActionResult
            if (!Utils.SymbolInheritsFrom(symbol, _ACTION_RESULT_NAMESPACE))
            {
                return(result);
            }

            //Assuming a good design pattern where GET requests (no method decoration) actually
            //only retrieve data and do not make a data modifications. We all know this isn't always the case,
            //but this is to reduce false positives on methods that are not vulnerable
            if (method.AttributeLists.Count == 0)
            {
                return(result);
            }

            //Search for HttpPost, HttpPut, HttpPatch, and HttpDelete decorators on the action
            bool dataModification         = false;
            bool validateAntiForgeryToken = false;

            foreach (AttributeListSyntax attribute in method.AttributeLists)
            {
                foreach (AttributeSyntax syntax in attribute.Attributes)
                {
                    if (!dataModification && _MODIFICATION_VERB_ATTRIBUTES.Split('|').Contains(syntax.Name?.ToString()))
                    {
                        dataModification = true;
                    }

                    if (!validateAntiForgeryToken && string.Compare(syntax.Name?.ToString(), _ANTI_FORGERY_TOKEN_ATTRIBUTE) == 0)
                    {
                        validateAntiForgeryToken = true;
                    }
                }
            }

            if (dataModification && !validateAntiForgeryToken)
            {
                result.Add(new DiagnosticInfo(returnType.GetLocation()));
            }

            return(result);
        }
コード例 #19
0
            public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
            {
                ISymbol symbol = this.model.GetSymbolInfo(node, this.cancellationToken).Symbol;

                if (symbol.Kind == CommonSymbolKind.Parameter)
                {
                    ParameterSymbol parameterSymbol = (ParameterSymbol)symbol;

                    ExpressionSyntax mappedExpression  = this.map[parameterSymbol];
                    ExpressionSyntax inlinedExpression = mappedExpression;

                    // If argument type is different than method's parameter type, additional cast is needed
                    ITypeSymbol parameterType = parameterSymbol.Type;
                    ITypeSymbol argumentType  = this.model.GetTypeInfo(mappedExpression, this.cancellationToken).Type;

                    // TODO: If this is generic type, i.e. IList<T>, visit its identifiers
                    if (parameterType.Kind == CommonSymbolKind.NamedType && ((NamedTypeSymbol)parameterType).IsGenericType)
                    {
                    }

                    // If parameter type is TypeParameter (template parameter), then it is same as argument type
                    if (parameterType.Kind == CommonSymbolKind.TypeParameter)
                    {
                        parameterType = argumentType;
                    }

                    bool castInlinedExpression = false;

                    if (!parameterType.Equals(argumentType))
                    {
                        castInlinedExpression = true;
                    }

                    SyntaxNode parentNode = node.Parent;

                    if (mappedExpression.Kind != SyntaxKind.ParenthesizedExpression)
                    {
                        // Surround with parenthesis if required
                        if ((mappedExpression is BinaryExpressionSyntax || mappedExpression is ConditionalExpressionSyntax) &&
                            (parentNode is BinaryExpressionSyntax || castInlinedExpression || parentNode.Kind == SyntaxKind.MemberAccessExpression)
                            )
                        {
                            inlinedExpression = Syntax.ParenthesizedExpression(inlinedExpression);
                        }
                    }

                    // Cast expression to preserve type semantics if necessary
                    if (castInlinedExpression)
                    {
                        TypeSyntax typeSyntax = Syntax.ParseTypeName(parameterType.ToMinimalDisplayString(node.GetLocation(), this.model));
                        inlinedExpression = Syntax.CastExpression(typeSyntax, inlinedExpression);

                        // If inlined expression is used in a context with operator of higher precedence than cast operator, then again parenthesis is needed
                        // Considers:
                        // a[0]  ->  >(< (IList<int>)a >)< [0]  , not (IList<int>)a[0]
                        // a.b   ->  >(< (A)a >)< .b            , not (A)a.b
                        // a++   ->  >(< (A)a >)< ++            , not (A)a++
                        if (parentNode.Kind == SyntaxKind.ElementAccessExpression ||
                            parentNode.Kind == SyntaxKind.MemberAccessExpression ||
                            parentNode.Kind == SyntaxKind.PostDecrementExpression ||
                            parentNode.Kind == SyntaxKind.PostIncrementExpression)
                        {
                            inlinedExpression = Syntax.ParenthesizedExpression(inlinedExpression);
                        }
                    }

                    inlinedExpression = inlinedExpression.WithLeadingTrivia(node.GetLeadingTrivia())
                                        .WithTrailingTrivia(node.GetTrailingTrivia());

                    return(inlinedExpression);
                }
                else if (symbol.Kind == CommonSymbolKind.TypeParameter)
                {
                    // TypeParameter identifier is replaced with actual type in target scope
                    // Considers:
                    // T foo<T>() { return (T)1; }
                    // foo<int>() -> (int)1;

                    TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)symbol;

                    TypeSymbol actualTypeSymbol = mapTypeParameters[typeParameterSymbol];

                    IdentifierNameSyntax newIdentifier = Syntax.IdentifierName(actualTypeSymbol.ToMinimalDisplayString(node.GetLocation(), this.model));

                    return(newIdentifier);
                }

                return(base.VisitIdentifierName(node));
            }
コード例 #20
0
            public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
            {
                IdentifierNameSyntax processedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node);

                ISymbol symbol = this.model.GetSymbolInfo(node, this.cancellationToken).Symbol;

                // If this is reference to renamed symbol, replace identifier
                if (this.renamedSymbol.Equals(symbol))
                {
                    SyntaxToken identifier = node.Identifier;

                    SyntaxToken newIdentifier = Syntax.Identifier(identifier.LeadingTrivia, this.newName, identifier.TrailingTrivia);

                    IdentifierNameSyntax newIdentifierName = processedNode.WithIdentifier(newIdentifier);

                    return newIdentifierName;
                }
                else if (node.Identifier.ValueText == this.newName)
                {
                    // If the Identifier refers to type name within variable declaration, no action is undertaken
                    // Consider:
                    // newVariableName myVariable; -> type name can remain as is
                    if (node.Ancestors().OfType<VariableDeclarationSyntax>().Any(n => n.Type.DescendantNodesAndSelf().Contains(node)))
                    {
                        return processedNode;
                    }

                    // If it is not a top-most expression of MemberAccessExpression, don't qualify
                    if (node.Ancestors().OfType<MemberAccessExpressionSyntax>().Any(n => n.Name.DescendantNodesAndSelf().Contains(node)))
                    {
                        return processedNode;
                    }

                    ExpressionSyntax qualifier = null;

                    if (symbol.IsStatic)
                    {
                        // If symbol is static, qualify the reference with containing type's name
                        qualifier = Syntax.ParseTypeName(symbol.ContainingType.ToMinimalDisplayString(node.GetLocation(), this.model));
                    }
                    else
                    {
                        // If symbol is instance, qualify the reference with `this' keyword
                        qualifier = Syntax.ThisExpression();
                    }

                    MemberAccessExpressionSyntax memberAccess = Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, qualifier, processedNode);

                    return memberAccess;
                }

                return processedNode;
            }
コード例 #21
0
        private void Report(SyntaxNodeAnalysisContext context, IdentifierNameSyntax identifier)
        {
            var diagnostic = Diagnostic.Create(Rule, identifier.GetLocation(), identifier.Identifier.ValueText);

            context.ReportDiagnostic(diagnostic);
        }
コード例 #22
0
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            string name = node.Identifier.Text;

            if (m_ClassInfoStack.Count > 0)
            {
                ClassInfo  classInfo  = m_ClassInfoStack.Peek();
                SymbolInfo symbolInfo = m_Model.GetSymbolInfo(node);
                var        sym        = symbolInfo.Symbol;
                if (null != sym)
                {
                    if (sym.Kind == SymbolKind.NamedType || sym.Kind == SymbolKind.Namespace)
                    {
                        string fullName = ClassInfo.GetFullName(sym);
                        CodeBuilder.Append(fullName);

                        if (sym.Kind == SymbolKind.NamedType)
                        {
                            var namedType = sym as INamedTypeSymbol;
                            AddReferenceAndTryDeriveGenericTypeInstance(classInfo, namedType);
                        }
                        return;
                    }
                    else if (sym.Kind == SymbolKind.Field || sym.Kind == SymbolKind.Property || sym.Kind == SymbolKind.Event)
                    {
                        if (m_ObjectCreateStack.Count > 0)
                        {
                            ITypeSymbol symInfo = m_ObjectCreateStack.Peek();
                            if (null != symInfo)
                            {
                                var names = symInfo.GetMembers(name);
                                if (names.Length > 0)
                                {
                                    CodeBuilder.AppendFormat("newobj.{0}", name);
                                    return;
                                }
                            }
                        }
                        if (sym.ContainingType == classInfo.SemanticInfo || sym.ContainingType == classInfo.SemanticInfo.OriginalDefinition || classInfo.IsInherit(sym.ContainingType))
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("{0}.{1}", classInfo.Key, sym.Name);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("this.{0}", sym.Name);
                            }
                            return;
                        }
                    }
                    else if (sym.Kind == SymbolKind.Method && sym.ContainingType == classInfo.SemanticInfo)
                    {
                        var    msym         = sym as IMethodSymbol;
                        string manglingName = NameMangling(msym);
                        var    mi           = new MethodInfo();
                        mi.Init(msym, node);
                        if (node.Parent is InvocationExpressionSyntax)
                        {
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat("{0}.{1}", classInfo.Key, manglingName);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat("this:{0}", manglingName);
                            }
                        }
                        else
                        {
                            string className     = ClassInfo.GetFullName(msym.ContainingType);
                            string delegationKey = string.Format("{0}:{1}", className, manglingName);
                            string varName       = string.Format("__compiler_delegation_{0}", node.GetLocation().GetLineSpan().StartLinePosition.Line);
                            CodeBuilder.AppendFormat("(function() local {0} = ", varName);

                            CodeBuilder.Append("(function(");
                            string paramsString = string.Join(", ", mi.ParamNames.ToArray());
                            CodeBuilder.Append(paramsString);
                            if (sym.IsStatic)
                            {
                                CodeBuilder.AppendFormat(") {0}{1}.{2}({3}); end)", msym.ReturnsVoid ? string.Empty : "return ", classInfo.Key, manglingName, paramsString);
                            }
                            else
                            {
                                CodeBuilder.AppendFormat(") {0}this:{1}({2}); end)", msym.ReturnsVoid ? string.Empty : "return ", manglingName, paramsString);
                            }

                            CodeBuilder.AppendFormat("; setdelegationkey({0}, \"{1}\", ", varName, delegationKey);
                            if (sym.IsStatic)
                            {
                                CodeBuilder.Append(classInfo.Key);
                                CodeBuilder.Append(", ");
                                CodeBuilder.Append(classInfo.Key);
                            }
                            else
                            {
                                CodeBuilder.Append("this, this");
                            }
                            CodeBuilder.Append(".");
                            CodeBuilder.Append(manglingName);
                            CodeBuilder.AppendFormat("); return {0}; end)()", varName);
                        }
                        return;
                    }
                }
                else
                {
                    if (m_ObjectCreateStack.Count > 0)
                    {
                        ITypeSymbol symInfo = m_ObjectCreateStack.Peek();
                        if (null != symInfo)
                        {
                            var names = symInfo.GetMembers(name);
                            if (names.Length > 0)
                            {
                                CodeBuilder.AppendFormat("newobj.{0}", name);
                                return;
                            }
                        }
                    }
                    else
                    {
                        ReportIllegalSymbol(node, symbolInfo);
                    }
                }
            }
            CodeBuilder.Append(name);
        }
コード例 #23
0
            public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
            {
                ISymbol symbol = this.model.GetSymbolInfo(node).Symbol;

                if (symbol != null)
                {
                    // If this identifier expression is the variable we are looking for
                    if (symbol.Equals(this.declaredSymbol))
                    {
                        ExpressionSyntax newNode = this.expressionSyntax;

                        SyntaxNode parentNode = node.Parent;

                        if (newNode.Kind != SyntaxKind.ParenthesizedExpression)
                        {
                            // Surround with parenthesis if required
                            // Considers:
                            // int a = b = 1; a.ToString(); -> (b = 1).ToString();
                            // float a = 2; float b = 5 / a; -> float b = 5 / (float)2;
                            // int a = 1 + 2; int b = a * 3; -> int b = (1 + 2) * 3;
                            // int a = c == true ? 1 : 4; int b = a + 3; -> int b = (c == true ? 1 : 4) + 3;
                            // Visual Studio Roslyn Refactoring Extension does not properly handle those samples

                            if ((this.expressionSyntax is BinaryExpressionSyntax || this.expressionSyntax is ConditionalExpressionSyntax) &&
                                (parentNode is BinaryExpressionSyntax || this.castInlinedExpression || parentNode.Kind == SyntaxKind.MemberAccessExpression)
                                )
                            {
                                newNode = Syntax.ParenthesizedExpression(this.expressionSyntax);
                            }
                        }

                        // Cast expression to preserve type semantics if necessary
                        if (this.castInlinedExpression)
                        {
                            TypeSyntax typeSyntax = Syntax.ParseTypeName(this.typeSymbol.ToMinimalDisplayString(node.GetLocation(), model));
                            newNode = Syntax.CastExpression(typeSyntax, newNode);

                            // If inlined expression is used in a context with operator of higher precedence than cast operator, then again parenthesis is needed
                            // Considers:
                            // a[0]  ->  >(< (IList<int>)a >)< [0]  , not (IList<int>)a[0]
                            // a.b   ->  >(< (A)a >)< .b            , not (A)a.b
                            // a++   ->  >(< (A)a >)< ++            , not (A)a++
                            if (parentNode.Kind == SyntaxKind.ElementAccessExpression ||
                                parentNode.Kind == SyntaxKind.MemberAccessExpression ||
                                parentNode.Kind == SyntaxKind.PostDecrementExpression ||
                                parentNode.Kind == SyntaxKind.PostIncrementExpression)
                            {
                                newNode = Syntax.ParenthesizedExpression(newNode);
                            }
                        }

                        return(CodeAnnotations.Formatting.AddAnnotationTo(newNode));
                    }
                }

                return(node);
            }
コード例 #24
0
ファイル: LLOC.cs プロジェクト: smartshark/OpenStaticAnalyzer
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     InsertLLOCMap(node.GetLocation());
     base.VisitIdentifierName(node);
 }