コード例 #1
0
ファイル: FunctionSyntax.cs プロジェクト: tgjones/HlslTools
 protected FunctionSyntax(SyntaxKind kind, List<AttributeSyntax> attributes, List<SyntaxToken> modifiers, TypeSyntax returnType, DeclarationNameSyntax name, ParameterListSyntax parameterList, SemanticSyntax semantic)
     : base(kind)
 {
     RegisterChildNodes(out Attributes, attributes);
     RegisterChildNodes(out Modifiers, modifiers);
     RegisterChildNode(out ReturnType, returnType);
     RegisterChildNode(out Name, name);
     RegisterChildNode(out ParameterList, parameterList);
     RegisterChildNode(out Semantic, semantic);
 }
コード例 #2
0
        private static string GetFunctionDescription(TypeSyntax returnType, SyntaxToken name, ParameterListSyntax parameterList, bool includeReturnType, bool includeParameterNames)
        {
            var result = new StringBuilder();

            if (includeReturnType)
                result.Append($"{returnType.ToStringIgnoringMacroReferences()} ");

            result.Append(name.GetFullyQualifiedName());
            result.Append("(");

            for (var i = 0; i < parameterList.Parameters.Count; i++)
            {
                var parameter = parameterList.Parameters[i];

                result.Append(parameter.GetDescription(includeParameterNames));

                if (i < parameterList.Parameters.Count - 1)
                    result.Append(", ");
            }

            result.Append(")");

            return result.ToString().Replace(Environment.NewLine, string.Empty);
        }
コード例 #3
0
 public override SyntaxNode VisitParameterList(ParameterListSyntax node)
 {
     node = (ParameterListSyntax)base.VisitParameterList(node);
     Classes.Add(node);
     return(node);
 }
コード例 #4
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, ParameterListSyntax parameterList)
        {
            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            if (parameters.Any())
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.DuplicateParameter))
                {
                    var refactoring = new DuplicateParameterRefactoring(parameterList);
                    refactoring.ComputeRefactoring(context, RefactoringIdentifiers.DuplicateParameter);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.CheckParameterForNull))
                {
                    await CheckParameterForNullRefactoring.ComputeRefactoringAsync(context, parameterList).ConfigureAwait(false);
                }

                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.IntroduceAndInitializeField,
                        RefactoringIdentifiers.IntroduceAndInitializeProperty))
                {
                    IntroduceAndInitializeRefactoring.ComputeRefactoring(context, parameterList);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatParameterList) &&
                    (context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(parameterList)))
                {
                    if (parameterList.IsSingleLine())
                    {
                        if (parameters.Count > 1)
                        {
                            context.RegisterRefactoring(
                                "Format parameters on separate lines",
                                cancellationToken => SyntaxFormatter.ToMultiLineAsync(context.Document, parameterList, cancellationToken),
                                RefactoringIdentifiers.FormatParameterList);
                        }
                    }
                    else if (parameterList.DescendantTrivia(parameterList.Span).All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                    {
                        context.RegisterRefactoring(
                            "Format parameters on a single line",
                            cancellationToken => SyntaxFormatter.ToSingleLineAsync(context.Document, parameterList, cancellationToken),
                            RefactoringIdentifiers.FormatParameterList);
                    }
                }
            }
        }
コード例 #5
0
 private static IEnumerable <ParameterSyntax> GetSelectedParameters(ParameterListSyntax parameterList, TextSpan span)
 {
     return(parameterList.Parameters
            .SkipWhile(f => span.Start > f.Span.Start)
            .TakeWhile(f => span.End >= f.Span.End));
 }
コード例 #6
0
        public static Task <Document> RefactorAsync(
            Document document,
            ParenthesizedLambdaExpressionSyntax parenthesizedLambda,
            MemberDeclarationSyntax memberDeclaration,
            TypeDeclarationSyntax typeDeclaration,
            string methodName,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            methodName = NameGenerator.Default.EnsureUniqueLocalName(methodName, semanticModel, parenthesizedLambda.SpanStart, cancellationToken: cancellationToken);

            MemberDeclarationSyntax newMemberDeclaration = memberDeclaration.ReplaceNode(parenthesizedLambda, IdentifierName(methodName).WithTriviaFrom(parenthesizedLambda));

            IMethodSymbol lambdaSymbol = semanticModel.GetMethodSymbol(parenthesizedLambda, cancellationToken);

            ParameterListSyntax parameterList = parenthesizedLambda.ParameterList;

            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            ImmutableArray <IParameterSymbol> parameterSymbols = lambdaSymbol.Parameters;

            parameters = parameters
                         .ReplaceAt(0, AddTypeIfMissing(parameters[0], parameterSymbols[0]))
                         .ReplaceAt(1, AddTypeIfMissing(parameters[1], parameterSymbols[1]));

            cancellationToken.ThrowIfCancellationRequested();

            MethodDeclarationSyntax newMethodDeclaration = MethodDeclaration(
                (SyntaxInfo.ModifierListInfo(memberDeclaration).IsStatic) ? Modifiers.Private_Static() : Modifiers.Private(),
                VoidType(),
                Identifier(methodName).WithRenameAnnotation(),
                parameterList.WithParameters(parameters),
                CreateMethodBody(parenthesizedLambda.Body)).WithFormatterAnnotation();

            SyntaxList <MemberDeclarationSyntax> newMembers = typeDeclaration.Members.Replace(memberDeclaration, newMemberDeclaration);

            newMembers = MemberDeclarationInserter.Default.Insert(newMembers, newMethodDeclaration);

            return(document.ReplaceNodeAsync(typeDeclaration, typeDeclaration.WithMembers(newMembers), cancellationToken));

            BlockSyntax CreateMethodBody(CSharpSyntaxNode lambdaBody)
            {
                switch (lambdaBody)
                {
                case BlockSyntax block:
                    return(block);

                case ExpressionSyntax expression:
                    return(Block(ExpressionStatement(expression)));

                default:
                    return(Block());
                }
            }

            ParameterSyntax AddTypeIfMissing(ParameterSyntax parameter, IParameterSymbol parameterSymbol)
            {
                TypeSyntax type = parameter.Type;

                if (type?.IsMissing == false)
                {
                    return(parameter);
                }

                type = parameterSymbol.Type.ToMinimalTypeSyntax(semanticModel, typeDeclaration.OpenBraceToken.Span.End);

                return(parameter.WithType(type));
            }
        }
        private static void HandleParameterListSyntax(SyntaxNodeAnalysisContext context, ParameterListSyntax parameterList)
        {
            if (parameterList == null)
            {
                return;
            }

            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            if (parameters.Count > 2)
            {
                Analyze(context, parameters);
            }
        }
コード例 #8
0
 public override UstNode VisitParameterList(ParameterListSyntax node)
 {
     throw new InvalidOperationException();
 }
コード例 #9
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static DelegateDeclarationSyntax DelegateDeclaration(TypeSyntax returnType = null, string identifier = null, ParameterListSyntax parameterList = null)
        {
            var result = new DelegateDeclarationSyntax();

            result.ReturnType = returnType;
            result.Identifier = identifier;
            result.ParameterList = parameterList;

            return result;
        }
コード例 #10
0
        public static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context)
        {
            var methodDeclaration = (MethodDeclarationSyntax)context.Node;

            BlockSyntax body = methodDeclaration.Body;

            if (body == null)
            {
                return;
            }

            ParameterListSyntax parameterList = methodDeclaration.ParameterList;

            if (parameterList == null)
            {
                return;
            }

            if (!parameterList.Parameters.Any())
            {
                return;
            }

            SyntaxList <StatementSyntax> statements = body.Statements;

            int statementCount = statements.Count;

            int index = -1;

            for (int i = 0; i < statementCount; i++)
            {
                if (IsNullCheck(statements[i]))
                {
                    index++;
                }
                else
                {
                    break;
                }
            }

            if (index == -1)
            {
                return;
            }

            if (index == statementCount - 1)
            {
                return;
            }

            TextSpan span = TextSpan.FromBounds(statements[index + 1].SpanStart, statements.Last().Span.End);

            if (body.ContainsUnbalancedIfElseDirectives(span))
            {
                return;
            }

            context.CancellationToken.ThrowIfCancellationRequested();

            ContainsYieldWalker walker = ContainsYieldWalker.GetInstance();

            walker.VisitBlock(body);

            YieldStatementSyntax yieldStatement = walker.YieldStatement;

            ContainsYieldWalker.Free(walker);

            if (yieldStatement == null)
            {
                return;
            }

            if (yieldStatement.SpanStart < statements[index].Span.End)
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context,
                                               DiagnosticDescriptors.ValidateArgumentsCorrectly,
                                               Location.Create(body.SyntaxTree, new TextSpan(statements[index + 1].SpanStart, 0)));
        }
コード例 #11
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(Modifiers modifiers = default(Modifiers), ParameterListSyntax parameterList = null, SyntaxNode body = null)
        {
            var result = new ParenthesizedLambdaExpressionSyntax();

            result.Modifiers = modifiers;
            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #12
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(IEnumerable<AttributeListSyntax> attributeLists = null, Modifiers modifiers = default(Modifiers), ImplicitOrExplicit kind = default(ImplicitOrExplicit), string type = null, ParameterListSyntax parameterList = null, BlockSyntax body = null)
        {
            var result = new ConversionOperatorDeclarationSyntax();

            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            result.Modifiers = modifiers;
            result.Kind = kind;
            if (type != null)
                result.Type = ParseName(type);
            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #13
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList = null, SyntaxNode body = null)
        {
            var result = new ParenthesizedLambdaExpressionSyntax();

            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #14
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static ParameterListSyntax ParameterList(params ParameterSyntax[] parameters)
        {
            var result = new ParameterListSyntax();

            if (parameters != null)
                result.Parameters.AddRange(parameters);

            return result;
        }
コード例 #15
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static ParameterListSyntax ParameterList(IEnumerable<ParameterSyntax> parameters = null)
        {
            var result = new ParameterListSyntax();

            if (parameters != null)
                result.Parameters.AddRange(parameters);

            return result;
        }
コード例 #16
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static OperatorDeclarationSyntax OperatorDeclaration(IEnumerable<AttributeListSyntax> attributeLists = null, Modifiers modifiers = default(Modifiers), string returnType = null, Operator @operator = default(Operator), ParameterListSyntax parameterList = null, BlockSyntax body = null)
        {
            var result = new OperatorDeclarationSyntax();

            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            result.Modifiers = modifiers;
            if (returnType != null)
                result.ReturnType = ParseName(returnType);
            result.Operator = @operator;
            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #17
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static DelegateDeclarationSyntax DelegateDeclaration(IEnumerable<AttributeListSyntax> attributeLists = null, Modifiers modifiers = default(Modifiers), string returnType = null, string identifier = null, TypeParameterListSyntax typeParameterList = null, ParameterListSyntax parameterList = null, IEnumerable<TypeParameterConstraintClauseSyntax> constraintClauses = null)
        {
            var result = new DelegateDeclarationSyntax();

            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            result.Modifiers = modifiers;
            if (returnType != null)
                result.ReturnType = ParseName(returnType);
            result.Identifier = identifier;
            result.TypeParameterList = typeParameterList;
            result.ParameterList = parameterList;
            if (constraintClauses != null)
                result.ConstraintClauses.AddRange(constraintClauses);

            return result;
        }
        public static void AnalyzeAnonyousMethodExpression(SyntaxNodeAnalysisContext context)
        {
            if (context.Node.SpanContainsDirectives())
            {
                return;
            }

            var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node;

            ParameterListSyntax parameterList = anonymousMethod.ParameterList;

            if (parameterList == null)
            {
                return;
            }

            InvocationExpressionSyntax invocationExpression = GetInvocationExpression(anonymousMethod.Body);

            if (invocationExpression == null)
            {
                return;
            }

            ExpressionSyntax expression = invocationExpression.Expression;

            if (!IsSimpleInvocation(expression))
            {
                return;
            }

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            if (!(semanticModel.GetSymbol(invocationExpression, cancellationToken) is IMethodSymbol methodSymbol))
            {
                return;
            }

            if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
            {
                return;
            }

            if (!methodSymbol.IsStatic &&
                expression.Kind() != SyntaxKind.IdentifierName)
            {
                if (!ExpressionIsParameter(expression, parameterList))
                {
                    return;
                }
                else if (methodSymbol.MethodKind == MethodKind.ReducedExtension &&
                         !context.ContainingSymbol.ContainingType.Equals(methodSymbol.ContainingType))
                {
                    return;
                }
            }

            ImmutableArray <IParameterSymbol> parameterSymbols = methodSymbol.Parameters;

            ArgumentListSyntax argumentList = invocationExpression.ArgumentList;

            SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

            if (arguments.Count != parameterSymbols.Length)
            {
                return;
            }

            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension;

            if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count))
            {
                return;
            }

            MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null;

            if (isReduced)
            {
                if (!CheckParameter(
                        parameters[0],
                        ((MemberAccessExpressionSyntax)expression).Expression,
                        methodSymbol.ReducedFrom.Parameters[0]))
                {
                    return;
                }

                parameters = parameters.RemoveAt(0);
            }

            if (!CheckParameters(parameters, arguments, parameterSymbols))
            {
                return;
            }

            methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol;

            if (!CheckInvokeMethod(anonymousMethod, methodSymbol, semanticModel, context.CancellationToken))
            {
                return;
            }

            if (!CheckSpeculativeSymbol(
                    anonymousMethod,
                    (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression,
                    methodSymbol,
                    semanticModel,
                    cancellationToken))
            {
                return;
            }

            context.ReportDiagnostic(DiagnosticDescriptors.UseMethodGroupInsteadOfAnonymousFunction, anonymousMethod);

            FadeOut(context, null, parameterList, anonymousMethod.Block, argumentList, anonymousMethod.DelegateKeyword, memberAccessExpression);
        }
コード例 #19
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static DelegateDeclarationSyntax DelegateDeclaration(string returnType = null, string identifier = null, ParameterListSyntax parameterList = null)
        {
            var result = new DelegateDeclarationSyntax();

            if (returnType != null)
                result.ReturnType = ParseName(returnType);
            result.Identifier = identifier;
            result.ParameterList = parameterList;

            return result;
        }
		// ParameterListSyntax
		public virtual bool WalkParameterList(ParameterListSyntax parameterListSyntax) { return DefaultWalk(parameterListSyntax); }
コード例 #21
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static DestructorDeclarationSyntax DestructorDeclaration(IEnumerable<AttributeListSyntax> attributeLists = null, Modifiers modifiers = default(Modifiers), string identifier = null, ParameterListSyntax parameterList = null, BlockSyntax body = null)
        {
            var result = new DestructorDeclarationSyntax();

            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            result.Modifiers = modifiers;
            result.Identifier = identifier;
            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #22
0
 // Preserved as shipped public API for binary compatibility
 public static LocalFunctionStatementSyntax LocalFunctionStatement(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody)
 {
     return(LocalFunctionStatement(attributeLists: default, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken: default));
コード例 #23
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static DestructorDeclarationSyntax DestructorDeclaration(string identifier = null, ParameterListSyntax parameterList = null, BlockSyntax body = null)
        {
            var result = new DestructorDeclarationSyntax();

            result.Identifier = identifier;
            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #24
0
 public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList, BlockSyntax?block, ExpressionSyntax?expressionBody)
 => ParenthesizedLambdaExpression(default(SyntaxTokenList), parameterList, block, expressionBody);
コード例 #25
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(ParameterListSyntax parameterList = null, BlockSyntax block = null)
        {
            var result = new AnonymousMethodExpressionSyntax();

            result.ParameterList = parameterList;
            result.Block = block;

            return result;
        }
コード例 #26
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static MethodDeclarationSyntax MethodDeclaration(IEnumerable<AttributeListSyntax> attributeLists = null, Modifiers modifiers = default(Modifiers), string returnType = null, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier = null, string identifier = null, TypeParameterListSyntax typeParameterList = null, ParameterListSyntax parameterList = null, IEnumerable<TypeParameterConstraintClauseSyntax> constraintClauses = null, BlockSyntax body = null)
        {
            var result = new MethodDeclarationSyntax();

            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            result.Modifiers = modifiers;
            if (returnType != null)
                result.ReturnType = ParseName(returnType);
            result.ExplicitInterfaceSpecifier = explicitInterfaceSpecifier;
            result.Identifier = identifier;
            result.TypeParameterList = typeParameterList;
            result.ParameterList = parameterList;
            if (constraintClauses != null)
                result.ConstraintClauses.AddRange(constraintClauses);
            result.Body = body;

            return result;
        }
コード例 #27
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(Modifiers modifiers = default(Modifiers), ParameterListSyntax parameterList = null, BlockSyntax block = null)
        {
            var result = new AnonymousMethodExpressionSyntax();

            result.Modifiers = modifiers;
            result.ParameterList = parameterList;
            result.Block = block;

            return result;
        }
コード例 #28
0
            private SyntaxNode CreateAttributeListForSal(AttributeListSyntax cppAttrList)
            {
                ParameterSyntax paramNode      = (ParameterSyntax)cppAttrList.Parent;
                bool            marshalAsAdded = this.nodesWithMarshalAs.Contains(paramNode);

                AttributeSyntax        cppAttr        = cppAttrList.Attributes[0];
                List <AttributeSyntax> attributesList = new List <AttributeSyntax>();

                string salText = cppAttr.ArgumentList.Arguments[0].ToString();

                salText = salText.Substring(1, salText.Length - 2);

                string nativeArrayInfoParams = null;
                bool   isIn        = false;
                bool   isOut       = false;
                bool   isOpt       = false;
                bool   isComOutPtr = false;
                bool   isRetVal    = false;
                bool   isNullNullTerminated;
                bool?  pre  = null;
                bool?  post = null;

                var salAttrs = GetSalAttributes(salText);

                isNullNullTerminated = salAttrs.Any(a => a.Name == "SAL_name" && a.P1 == "_NullNull_terminated_");

                foreach (var salAttr in salAttrs)
                {
                    if (salAttr.Name == "SAL_name")
                    {
                        if (salAttr.P1.StartsWith("_COM_Outptr"))
                        {
                            isComOutPtr = true;
                            continue;
                        }
                        else if (salAttr.P1.StartsWith("_Outptr_") && !isComOutPtr)
                        {
                            isOut = true;
                            continue;
                        }
                        else if (salAttr.P1.StartsWith("__RPC__"))
                        {
                            // TODO: Handle ecount, xcount and others that deal with counts

                            string[] parts = salAttr.P1.Split('_');
                            foreach (var part in parts)
                            {
                                switch (part)
                                {
                                case "in":
                                    isIn = true;
                                    break;

                                case "out":
                                    isOut = true;
                                    break;

                                case "inout":
                                    isIn = isOut = true;
                                    break;

                                case "opt":
                                    isOpt = true;
                                    break;
                                }
                            }

                            break;
                        }
                    }

                    if (salAttr.Name == "SAL_null" && salAttr.P1 == "__maybe")
                    {
                        isOpt = true;
                        continue;
                    }

                    if (salAttr.Name == "SAL_retval")
                    {
                        isRetVal = true;
                        continue;
                    }

                    if (salAttr.Name == "SAL_pre")
                    {
                        pre = true;
                        continue;
                    }

                    if (salAttr.Name == "SAL_post")
                    {
                        pre  = false;
                        post = true;
                        continue;
                    }

                    if (salAttr.Name == "SAL_end")
                    {
                        pre = post = false;
                    }

                    if (salAttr.Name == "SAL_valid")
                    {
                        if (pre.HasValue && pre.Value)
                        {
                            isIn = true;
                        }
                        else if (post.HasValue && post.Value)
                        {
                            isOut = true;
                        }
                        else
                        {
                            isIn = isOut = true;
                        }

                        continue;
                    }

                    if (salAttr.Name == "SAL_name" && salAttr.P1 == "_Post_valid_")
                    {
                        isOut = true;
                        continue;
                    }

                    if (!marshalAsAdded && (salAttr.Name == "SAL_writableTo" || salAttr.Name == "SAL_readableTo") && pre.HasValue && pre.Value)
                    {
                        nativeArrayInfoParams = GetArrayMarshalAsFromP1(paramNode, salAttr.P1);
                        if (!string.IsNullOrEmpty(nativeArrayInfoParams))
                        {
                            marshalAsAdded = true;
                        }

                        continue;
                    }
                }

                // If we didn't add marshal as yet, try again without using pre
                if (!marshalAsAdded)
                {
                    var salAttr = salAttrs.FirstOrDefault(attr => attr.Name == "SAL_readableTo" || attr.Name == "SAL_writeableTo");
                    if (salAttr != null)
                    {
                        nativeArrayInfoParams = GetArrayMarshalAsFromP1(paramNode, salAttr.P1);
                        if (!string.IsNullOrEmpty(nativeArrayInfoParams))
                        {
                            marshalAsAdded = true;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(nativeArrayInfoParams))
                {
                    var attrName  = SyntaxFactory.ParseName("NativeArrayInfo");
                    var args      = SyntaxFactory.ParseAttributeArgumentList(nativeArrayInfoParams.ToString());
                    var finalAttr = SyntaxFactory.Attribute(attrName, args);
                    attributesList.Add(finalAttr);
                }

                if (isIn)
                {
                    attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("In")));
                }

                if (isComOutPtr)
                {
                    attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("ComOutPtr")));
                }
                else if (isOut)
                {
                    attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Out")));
                }

                if (isOpt)
                {
                    attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("Optional")));
                }

                if (isNullNullTerminated)
                {
                    attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("NullNullTerminated")));
                }

                if (isRetVal)
                {
                    attributesList.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName("RetVal")));
                }

                if (attributesList.Count == 0)
                {
                    return(null);
                }

                return(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributesList)));

                string GetArrayMarshalAsFromP1(ParameterSyntax paramNode, string p1Text)
                {
                    ParameterListSyntax parameterListNode = (ParameterListSyntax)paramNode.Parent;
                    var           match = elementCountRegex.Match(p1Text);
                    StringBuilder ret   = new StringBuilder("(");

                    if (match.Success)
                    {
                        string sizeOrParamName = match.Groups[1].Value;
                        if (int.TryParse(sizeOrParamName, out int size))
                        {
                            // Don't bother marking this as an array if it only has 1
                            if (size == 1)
                            {
                                return(string.Empty);
                            }

                            if (ret.Length != 1)
                            {
                                ret.Append(", ");
                            }

                            ret.Append($"SizeConst = {size}");
                        }
                        else
                        {
                            sizeOrParamName = sizeOrParamName.Replace("*", string.Empty);
                            for (int i = 0; i < parameterListNode.Parameters.Count; i++)
                            {
                                if (parameterListNode.Parameters[i].Identifier.ValueText == sizeOrParamName)
                                {
                                    if (ret.Length != 1)
                                    {
                                        ret.Append(", ");
                                    }

                                    string propName = p1Text.StartsWith("elementCount") ? "SizeParamIndex" : "BytesParamIndex";
                                    ret.Append($"{propName} = {i}");
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        // If it didn't match the regex and we don't see inexpressibleCount, we can't do
                        // anything but return an empty string, because we don't know how to interpret it
                        if (!p1Text.StartsWith("inexpressibleCount"))
                        {
                            ret = new StringBuilder();
                        }
                    }

                    if (ret.Length > 1)
                    {
                        ret.Append(')');
                        return(ret.ToString());
                    }

                    return(string.Empty);
                }

                IEnumerable <SalAttribute> GetSalAttributes(string salArgsText)
                {
                    foreach (var attr in salArgsText.Split('^'))
                    {
                        var salAttr = SalAttribute.CreateFromCppAttribute(attr);
                        if (salAttr != null)
                        {
                            yield return(salAttr);
                        }
                    }
                }
            }
        public static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context)
        {
            if (context.Node.SpanContainsDirectives())
            {
                return;
            }

            var lambda = (ParenthesizedLambdaExpressionSyntax)context.Node;

            InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body);

            if (invocationExpression == null)
            {
                return;
            }

            ExpressionSyntax expression = invocationExpression.Expression;

            if (!IsSimpleInvocation(expression))
            {
                return;
            }

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            var methodSymbol = semanticModel.GetSymbol(invocationExpression, cancellationToken) as IMethodSymbol;

            if (methodSymbol == null)
            {
                return;
            }

            ImmutableArray <IParameterSymbol> parameterSymbols = methodSymbol.Parameters;

            ArgumentListSyntax argumentList = invocationExpression.ArgumentList;

            SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

            if (arguments.Count != parameterSymbols.Length)
            {
                return;
            }

            ParameterListSyntax parameterList = lambda.ParameterList;

            SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

            bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension;

            if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count))
            {
                return;
            }

            MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null;

            if (isReduced)
            {
                if (!CheckParameter(
                        parameters[0],
                        memberAccessExpression.Expression,
                        methodSymbol.ReducedFrom.Parameters[0]))
                {
                    return;
                }

                parameters = parameters.RemoveAt(0);
            }

            if (!CheckParameters(parameters, arguments, parameterSymbols))
            {
                return;
            }

            methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol;

            if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken))
            {
                return;
            }

            if (!CheckSpeculativeSymbol(
                    lambda,
                    (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression,
                    methodSymbol,
                    semanticModel))
            {
                return;
            }

            context.ReportDiagnostic(DiagnosticDescriptors.UseMethodGroupInsteadOfAnonymousFunction, lambda);

            FadeOut(context, null, parameterList, lambda.Body as BlockSyntax, argumentList, lambda.ArrowToken, memberAccessExpression);
        }
コード例 #30
0
        private static void Analyze(
            SyntaxNodeAnalysisContext context,
            SyntaxNode declaration,
            ParameterListSyntax parameterList,
            CSharpSyntaxNode bodyOrExpressionBody)
        {
            if (parameterList == null)
            {
                return;
            }

            if (bodyOrExpressionBody == null)
            {
                return;
            }

            if (!parameterList.Parameters.Any())
            {
                return;
            }

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(declaration, cancellationToken);

            SyntaxWalker walker = null;

            foreach (IParameterSymbol parameter in methodSymbol.Parameters)
            {
                cancellationToken.ThrowIfCancellationRequested();

                ITypeSymbol type = parameter.Type;

                if (type.Kind == SymbolKind.ErrorType)
                {
                    continue;
                }

                if (CSharpFacts.IsSimpleType(type.SpecialType))
                {
                    continue;
                }

                if (!type.IsReadOnlyStruct())
                {
                    if (parameter.RefKind == RefKind.In &&
                        type.TypeKind == TypeKind.Struct)
                    {
                        var parameterSyntax = (ParameterSyntax)parameter.GetSyntax(cancellationToken);

                        Debug.Assert(parameterSyntax.Modifiers.Contains(SyntaxKind.InKeyword), "");

                        DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.DoNotPassNonReadOnlyStructByReadOnlyReference, parameterSyntax.Identifier);
                    }

                    continue;
                }

                if (parameter.RefKind != RefKind.None)
                {
                    continue;
                }

                if (walker == null)
                {
                    if (methodSymbol.ImplementsInterfaceMember(allInterfaces: true))
                    {
                        break;
                    }

                    walker = SyntaxWalker.GetInstance();
                }
                else if (walker.Parameters.ContainsKey(parameter.Name))
                {
                    walker.Parameters.Clear();
                    break;
                }

                walker.Parameters.Add(parameter.Name, parameter);
            }

            if (walker == null)
            {
                return;
            }

            if (walker.Parameters.Count > 0)
            {
                walker.SemanticModel     = semanticModel;
                walker.CancellationToken = cancellationToken;

                if (bodyOrExpressionBody is BlockSyntax body)
                {
                    walker.VisitBlock(body);
                }
                else
                {
                    walker.VisitArrowExpressionClause((ArrowExpressionClauseSyntax)bodyOrExpressionBody);
                }

                if (walker.Parameters.Count > 0 &&
                    !IsReferencedAsMethodGroup())
                {
                    foreach (KeyValuePair <string, IParameterSymbol> kvp in walker.Parameters)
                    {
                        if (kvp.Value.GetSyntaxOrDefault(cancellationToken) is ParameterSyntax parameter)
                        {
                            DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.MakeParameterRefReadOnly, parameter.Identifier);
                        }
                    }
                }
            }

            SyntaxWalker.Free(walker);

            bool IsReferencedAsMethodGroup()
            {
                switch (declaration.Kind())
                {
                case SyntaxKind.MethodDeclaration:
                    return(MethodReferencedAsMethodGroupWalker.IsReferencedAsMethodGroup(declaration.Parent, methodSymbol, semanticModel, cancellationToken));

                case SyntaxKind.LocalFunctionStatement:
                    return(MethodReferencedAsMethodGroupWalker.IsReferencedAsMethodGroup(declaration.FirstAncestor <MemberDeclarationSyntax>(), methodSymbol, semanticModel, cancellationToken));

                default:
                    return(false);
                }
            }
        }
コード例 #31
0
 private static ParameterListSyntax RemoveType(ParameterListSyntax parameterList)
 {
     return(parameterList.WithParameters(SyntaxFactory.SeparatedList(parameterList.Parameters.Select(x => RemoveType(x)), parameterList.Parameters.GetSeparators())));
 }
コード例 #32
0
 internal static ParameterListSyntax PrependParameter(this ParameterListSyntax list, ParameterSyntax parameter)
 {
     return(SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(parameter))
            .AddParameters(list.Parameters.ToArray()));
 }
コード例 #33
0
ファイル: Syntax.cs プロジェクト: modulexcite/CSharpSyntax
        public static MethodDeclarationSyntax MethodDeclaration(string returnType = null, string identifier = null, ParameterListSyntax parameterList = null, BlockSyntax body = null)
        {
            var result = new MethodDeclarationSyntax();

            if (returnType != null)
                result.ReturnType = ParseName(returnType);
            result.Identifier = identifier;
            result.ParameterList = parameterList;
            result.Body = body;

            return result;
        }
コード例 #34
0
        private static TypeDeclarationSyntax ParseModel(ClassDeclarationSyntax @class, ParameterListSyntax parameters, Scope scope)
        {
            var init  = new List <ParameterSyntax>();
            var props = new List <PropertyDeclarationSyntax>();

            foreach (var member in @class.Members)
            {
                var field = ParseField(member);
                if (field == null)
                {
                    continue; //error has already been registered
                }
                var type     = field.Declaration.Type;
                var variable = field.Declaration
                               .Variables
                               .Single();


                init.Add(CSharp.Parameter(variable.Identifier)
                         .WithType(type)
                         .WithDefault(CSharp.EqualsValueClause(
                                          variable.Initializer != null
                            ? variable.Initializer.Value
                            : CSharp.DefaultExpression(type))));

                props.Add(ModelProperty.Get <PropertyDeclarationSyntax>(type)
                          .WithIdentifier(variable.Identifier));
            }

            if (!RoslynCompiler.HasVisibilityModifier(@class.Modifiers))
            {
                @class = @class.AddModifiers(CSharp.Token(SyntaxKind.PublicKeyword));
            }

            return(@class
                   .WithMembers(CSharp.List <MemberDeclarationSyntax>(
                                    props.Union(new[] {
                GenerateConstructor(@class, init)
            }))));
        }
コード例 #35
0
 public virtual void VisitParameterList(ParameterListSyntax node)
 {
     DefaultVisit(node);
 }
コード例 #36
0
 public MethodDeclarationParameters(SyntaxList <AttributeListSyntax> attributes, SyntaxTokenList modifiers,
                                    TypeSyntax returnType, TypeParameterListSyntax typeParameters, ParameterListSyntax parameterList,
                                    SyntaxList <TypeParameterConstraintClauseSyntax> constraints,
                                    ArrowExpressionClauseSyntax arrowClause) : base(attributes, modifiers, returnType)
 {
     TypeParameters = typeParameters;
     ParameterList  = parameterList;
     Constraints    = constraints;
     ArrowClause    = arrowClause;
 }
コード例 #37
0
 public ParameterListSyntax TransformToParameters(ParameterListSyntax @params)
 {
     return(@params);
 }
コード例 #38
0
        private static string GetMethodSignature(
            string name, SyntaxList <AttributeListSyntax> attributeLists, TypeSyntax returnType, ParameterListSyntax parameterList)
        {
            StringBuilder ret = new StringBuilder();

            foreach (var list in attributeLists)
            {
                if (list.Target != null && list.Target.Identifier.Text == "return")
                {
                    continue;
                }

                foreach (var attr in list.Attributes)
                {
                    if (attr.ToString().StartsWith("return:"))
                    {
                        continue;
                    }

                    ret.Append($"[{attr}]");
                }
            }

            var retType = GetTypeName(returnType.ToString(), attributeLists);

            if (retType == null)
            {
                retType = returnType.ToString();
            }

            ret.Append(retType);
            ret.Append(' ');
            ret.Append(name);
            ret.Append('(');

            bool firstParam = true;

            foreach (var param in parameterList.Parameters)
            {
                if (firstParam)
                {
                    firstParam = false;
                }
                else
                {
                    ret.Append(',');
                }

                var typeName = GetTypeName(param.Type.ToString(), param.AttributeLists);
                ret.Append(typeName);
                ret.Append(' ');
                ret.Append(param.Identifier.ValueText);
            }

            ret.Append(')');

            return(ret.ToString());
        }
コード例 #39
0
        public static BaseMethodDeclarationSyntax WithParameterList(this BaseMethodDeclarationSyntax method, ParameterListSyntax pls)
        {
            switch (method.Kind())
            {
            case SyntaxKind.OperatorDeclaration:
            case SyntaxKind.ConversionOperatorDeclaration:
                throw new NotImplementedException("Wasabi doesn't have operators");

            case SyntaxKind.MethodDeclaration:
                return(((MethodDeclarationSyntax)method).WithParameterList(pls));

            case SyntaxKind.ConstructorDeclaration:
                return(((ConstructorDeclarationSyntax)method).WithParameterList(pls));

            case SyntaxKind.DestructorDeclaration:
                return(((DestructorDeclarationSyntax)method).WithParameterList(pls));
            }

            throw new NotImplementedException("WithParameterList " + method.Kind().ToString());
        }
コード例 #40
0
 public IEnumerable <Instruction> CreateEntryPointCall(SyntaxNode syntaxNode, ITypeSymbol nodeTypeSymbol,
                                                       ParameterListSyntax parameterList)
 {
     return(CreateFunctionCall(UcfgBuiltInMethodId.EntryPoint, syntaxNode, expressionService.CreateVariable(nodeTypeSymbol),
                               parameterList.Parameters.Select(expressionService.GetExpression).ToArray()));
 }
コード例 #41
0
        private static Task <Document> RefactorAsync(
            Document document,
            ImmutableArray <FieldInfo> fieldInfos,
            TypeDeclarationSyntax typeDeclaration,
            CancellationToken cancellationToken)
        {
            SyntaxList <MemberDeclarationSyntax> members = typeDeclaration.Members;

            HashSet <string> reservedNames = null;

            for (int i = 0; i < members.Count; i++)
            {
                if (!(members[i] is ConstructorDeclarationSyntax constructorDeclaration))
                {
                    continue;
                }

                if (constructorDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword))
                {
                    continue;
                }

                ParameterListSyntax parameterList = constructorDeclaration.ParameterList;

                if (parameterList == null)
                {
                    continue;
                }

                BlockSyntax body = constructorDeclaration.Body;

                if (body == null)
                {
                    continue;
                }

                SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

                reservedNames?.Clear();

                ConstructorInitializerSyntax         initializer  = constructorDeclaration.Initializer;
                ArgumentListSyntax                   argumentList = initializer?.ArgumentList;
                SeparatedSyntaxList <ArgumentSyntax> arguments    = argumentList?.Arguments ?? default;

                bool addToInitializer = initializer?.Kind() == SyntaxKind.ThisConstructorInitializer &&
                                        argumentList != null;

                SyntaxList <StatementSyntax> statements = body.Statements;

                foreach (FieldInfo fieldInfo in fieldInfos)
                {
                    string parameterName = GetParameterName(fieldInfo.NameCamelCase, parameters, ref reservedNames);

                    parameters = parameters.Add(Parameter(fieldInfo.Type.WithoutTrivia(), parameterName));

                    if (addToInitializer)
                    {
                        arguments = arguments.Add(Argument(IdentifierName(parameterName)));
                    }

                    statements = statements.Add(
                        SimpleAssignmentStatement(
                            SimpleMemberAccessExpression(ThisExpression(), IdentifierName(fieldInfo.Name)).WithSimplifierAnnotation(),
                            IdentifierName(parameterName)).WithFormatterAnnotation());
                }

                parameterList = parameterList.WithParameters(parameters).WithFormatterAnnotation();

                if (addToInitializer)
                {
                    initializer = initializer
                                  .WithArgumentList(argumentList.WithArguments(arguments))
                                  .WithFormatterAnnotation();
                }

                body = body.WithStatements(statements);

                constructorDeclaration = constructorDeclaration.Update(
                    constructorDeclaration.AttributeLists,
                    constructorDeclaration.Modifiers,
                    constructorDeclaration.Identifier,
                    parameterList,
                    initializer,
                    body,
                    constructorDeclaration.SemicolonToken);

                members = members.ReplaceAt(i, constructorDeclaration);
            }

            TypeDeclarationSyntax newNode = typeDeclaration.WithMembers(members);

            return(document.ReplaceNodeAsync(typeDeclaration, newNode, cancellationToken));
        }
		public virtual void PostWalkParameterList(ParameterListSyntax parameterListSyntax) { }
コード例 #43
0
 public LocalFunctionStatementSyntaxWrapper WithParameterList(ParameterListSyntax parameterList)
 {
     return(new LocalFunctionStatementSyntaxWrapper(WithParameterListAccessor(this.SyntaxNode, parameterList)));
 }
コード例 #44
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddDocumentationComment) &&
                !Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMethodReturnType) &&
                !Settings.IsCodeFixEnabled(CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType) &&
                !Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddPartialModifier) &&
                !Settings.IsCodeFixEnabled(CodeFixIdentifiers.MakeContainingClassAbstract) &&
                !Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveParametersFromStaticConstructor) &&
                !Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveMemberDeclaration))
            {
                return;
            }

            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberDeclarationSyntax memberDeclaration))
            {
                return;
            }

            foreach (Diagnostic diagnostic in context.Diagnostics)
            {
                switch (diagnostic.Id)
                {
                case CompilerDiagnosticIdentifiers.MissingXmlCommentForPubliclyVisibleTypeOrMember:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddDocumentationComment))
                    {
                        break;
                    }

                    CodeAction codeAction = CodeAction.Create(
                        "Add documentation comment",
                        cancellationToken => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, false, cancellationToken),
                        GetEquivalenceKey(diagnostic));

                    context.RegisterCodeFix(codeAction, diagnostic);

                    CodeAction codeAction2 = CodeAction.Create(
                        "Add documentation comment (copy from base if available)",
                        cancellationToken => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, true, cancellationToken),
                        GetEquivalenceKey(diagnostic, "CopyFromBaseIfAvailable"));

                    context.RegisterCodeFix(codeAction2, diagnostic);
                    break;
                }

                case CompilerDiagnosticIdentifiers.MethodReturnTypeMustMatchOverriddenMethodReturnType:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMethodReturnType))
                    {
                        break;
                    }

                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken);

                    ITypeSymbol typeSymbol = methodSymbol.OverriddenMethod.ReturnType;

                    if (typeSymbol?.IsErrorType() == false)
                    {
                        CodeAction codeAction = CodeAction.Create(
                            $"Change return type to '{SymbolDisplay.GetMinimalString(typeSymbol, semanticModel, memberDeclaration.SpanStart)}'",
                            cancellationToken => MemberTypeMustMatchOverriddenMemberTypeRefactoring.RefactorAsync(context.Document, memberDeclaration, typeSymbol, semanticModel, cancellationToken),
                            GetEquivalenceKey(diagnostic));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }

                case CompilerDiagnosticIdentifiers.PartialMethodsMustHaveVoidReturnType:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMethodReturnType))
                    {
                        break;
                    }

                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration;

                    MethodDeclarationSyntax otherPart = semanticModel.GetOtherPart(methodDeclaration, context.CancellationToken);

                    if (otherPart == null)
                    {
                        break;
                    }

                    CodeAction codeAction = CodeAction.Create(
                        "Change return type to 'void'",
                        cancellationToken =>
                        {
                            return(context.Document.Solution().ReplaceNodesAsync(
                                       new MethodDeclarationSyntax[] { methodDeclaration, otherPart },
                                       (node, rewrittenNode) => node.WithReturnType(CSharpFactory.VoidType().WithTriviaFrom(node.ReturnType)),
                                       cancellationToken));
                        },
                        GetEquivalenceKey(diagnostic));

                    context.RegisterCodeFix(codeAction, diagnostic);
                    break;
                }

                case CompilerDiagnosticIdentifiers.MemberTypeMustMatchOverriddenMemberType:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType))
                    {
                        break;
                    }

                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    ITypeSymbol typeSymbol = null;

                    switch (memberDeclaration.Kind())
                    {
                    case SyntaxKind.PropertyDeclaration:
                    case SyntaxKind.IndexerDeclaration:
                    {
                        var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken);

                        typeSymbol = propertySymbol.OverriddenProperty.Type;
                        break;
                    }

                    case SyntaxKind.EventDeclaration:
                    {
                        var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken);

                        typeSymbol = eventSymbol.OverriddenEvent.Type;
                        break;
                    }

                    case SyntaxKind.EventFieldDeclaration:
                    {
                        VariableDeclaratorSyntax declarator = ((EventFieldDeclarationSyntax)memberDeclaration).Declaration.Variables.First();

                        var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, context.CancellationToken);

                        typeSymbol = eventSymbol.OverriddenEvent.Type;
                        break;
                    }
                    }

                    if (typeSymbol?.IsErrorType() == false)
                    {
                        string title = $"Change type to '{SymbolDisplay.GetMinimalString(typeSymbol, semanticModel, memberDeclaration.SpanStart)}'";

                        CodeAction codeAction = CodeAction.Create(
                            title,
                            cancellationToken => MemberTypeMustMatchOverriddenMemberTypeRefactoring.RefactorAsync(context.Document, memberDeclaration, typeSymbol, semanticModel, cancellationToken),
                            GetEquivalenceKey(diagnostic));

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }

                    break;
                }

                case CompilerDiagnosticIdentifiers.MissingPartialModifier:
                case CompilerDiagnosticIdentifiers.PartialMethodMustBeDeclaredWithinPartialClassOrPartialStruct:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddPartialModifier))
                    {
                        break;
                    }

                    SyntaxNode node = null;

                    switch (memberDeclaration.Kind())
                    {
                    case SyntaxKind.MethodDeclaration:
                    {
                        if (memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
                        {
                            node = memberDeclaration.Parent;
                        }

                        break;
                    }

                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.InterfaceDeclaration:
                    {
                        node = memberDeclaration;
                        break;
                    }
                    }

                    Debug.Assert(node != null, memberDeclaration.ToString());

                    if (node == null)
                    {
                        break;
                    }

                    ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.PartialKeyword);
                    break;
                }

                case CompilerDiagnosticIdentifiers.MemberIsAbstractButItIsContainedInNonAbstractClass:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.MakeContainingClassAbstract))
                    {
                        break;
                    }

                    if (!memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration))
                    {
                        break;
                    }

                    ModifiersCodeFixRegistrator.AddModifier(
                        context,
                        diagnostic,
                        memberDeclaration.Parent,
                        SyntaxKind.AbstractKeyword,
                        title: "Make containing class abstract");

                    break;
                }

                case CompilerDiagnosticIdentifiers.StaticConstructorMustBeParameterless:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveParametersFromStaticConstructor))
                    {
                        break;
                    }

                    var constructorDeclaration = (ConstructorDeclarationSyntax)memberDeclaration;

                    CodeAction codeAction = CodeAction.Create(
                        "Remove parameters",
                        cancellationToken =>
                        {
                            ParameterListSyntax parameterList = constructorDeclaration.ParameterList;

                            ParameterListSyntax newParameterList = parameterList
                                                                   .WithParameters(default(SeparatedSyntaxList <ParameterSyntax>))
                                                                   .WithOpenParenToken(parameterList.OpenParenToken.WithoutTrailingTrivia())
                                                                   .WithCloseParenToken(parameterList.CloseParenToken.WithoutLeadingTrivia());

                            ConstructorDeclarationSyntax newNode = constructorDeclaration.WithParameterList(newParameterList);

                            return(context.Document.ReplaceNodeAsync(constructorDeclaration, newNode, cancellationToken));
                        },
                        GetEquivalenceKey(diagnostic));

                    context.RegisterCodeFix(codeAction, diagnostic);
                    break;
                }

                case CompilerDiagnosticIdentifiers.ExplicitInterfaceDeclarationCanOnlyBeDeclaredInClassOrStruct:
                {
                    if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveMemberDeclaration))
                    {
                        break;
                    }

                    CodeFixRegistrator.RemoveMember(context, diagnostic, memberDeclaration);
                    break;
                }
                }
            }
        }
        private static Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax variableDeclarator,
            TypeDeclarationSyntax typeDeclaration,
            CancellationToken cancellationToken)
        {
            SyntaxList <MemberDeclarationSyntax> members = typeDeclaration.Members;

            string name          = variableDeclarator.Identifier.ValueText;
            string camelCaseName = StringUtility.ToCamelCase(name);

            HashSet <string> reservedNames = null;

            for (int i = 0; i < members.Count; i++)
            {
                if (!(members[i] is ConstructorDeclarationSyntax constructorDeclaration))
                {
                    continue;
                }

                if (constructorDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword))
                {
                    continue;
                }

                ParameterListSyntax parameterList = constructorDeclaration.ParameterList;

                if (parameterList == null)
                {
                    continue;
                }

                BlockSyntax body = constructorDeclaration.Body;

                if (body == null)
                {
                    continue;
                }

                SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters;

                reservedNames?.Clear();

                string parameterName = GetParameterName(camelCaseName, parameters, ref reservedNames);

                ParameterSyntax parameter = Parameter(((VariableDeclarationSyntax)variableDeclarator.Parent).Type.WithoutTrivia(), parameterName);

                parameterList = parameterList.WithParameters(parameters.Add(parameter)).WithFormatterAnnotation();

                ConstructorInitializerSyntax initializer = constructorDeclaration.Initializer;

                if (initializer?.Kind() == SyntaxKind.ThisConstructorInitializer)
                {
                    ArgumentListSyntax argumentList = initializer.ArgumentList;

                    if (argumentList != null)
                    {
                        SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

                        initializer = initializer.WithArgumentList(
                            argumentList.WithArguments(
                                arguments.Add(Argument(IdentifierName(parameterName))))).WithFormatterAnnotation();
                    }
                }

                body = body.WithStatements(
                    body.Statements.Add(
                        SimpleAssignmentStatement(
                            SimpleMemberAccessExpression(ThisExpression(), IdentifierName(name)).WithSimplifierAnnotation(),
                            IdentifierName(parameterName)).WithFormatterAnnotation()));

                constructorDeclaration = constructorDeclaration.Update(
                    constructorDeclaration.AttributeLists,
                    constructorDeclaration.Modifiers,
                    constructorDeclaration.Identifier,
                    parameterList,
                    initializer,
                    body,
                    constructorDeclaration.SemicolonToken);

                members = members.ReplaceAt(i, constructorDeclaration);
            }

            TypeDeclarationSyntax newNode = typeDeclaration.WithMembers(members);

            return(document.ReplaceNodeAsync(typeDeclaration, newNode, cancellationToken));
        }
コード例 #46
0
ファイル: JavaScriptWalker.cs プロジェクト: IgorShare/jinx
        string VisitParameterList(ParameterListSyntax node)
        {
            var @params = new StringBuilder();

            foreach (var param in node.Parameters)
            {
                if (@params.Length != 0)
                    @params.Append(", ");

                @params.Append(param.Identifier.GetText());
            }

            return @params.ToString();
        }
コード例 #47
0
        private static ParameterListSyntax TransformParameterList(ParameterListSyntax list, GeneratorFlags generatorFlags, IReadOnlyDictionary <ParameterSyntax, FriendlyFlags> parametersToFriendlyTransform)
        {
            var resultingList = list.ReplaceNodes(
                WhereIsPointerParameter(list.Parameters),
                (n1, n2) =>
            {
                // Remove all attributes
                n2 = n2.WithAttributeLists(SyntaxFactory.List <AttributeListSyntax>());

                FriendlyFlags friendlyFlags;
                if (generatorFlags.HasFlag(GeneratorFlags.NativePointerToFriendly) && parametersToFriendlyTransform.TryGetValue(n1, out friendlyFlags))
                {
                    var pointerType      = (PointerTypeSyntax)n2.Type;
                    var alteredParameter = n2.WithDefault(null);
                    if (friendlyFlags.HasFlag(FriendlyFlags.Array))
                    {
                        alteredParameter = alteredParameter
                                           .WithType(SyntaxFactory.ArrayType(pointerType.ElementType, OneDimensionalUnspecifiedLengthArray));
                    }
                    else
                    {
                        if (friendlyFlags.HasFlag(FriendlyFlags.Optional))
                        {
                            alteredParameter = alteredParameter
                                               .WithType(SyntaxFactory.NullableType(pointerType.ElementType));
                        }

                        if (friendlyFlags.HasFlag(FriendlyFlags.Out))
                        {
                            SyntaxKind modifier = friendlyFlags.HasFlag(FriendlyFlags.Optional) || friendlyFlags.HasFlag(FriendlyFlags.In)
                                     ? SyntaxKind.RefKeyword
                                     : SyntaxKind.OutKeyword;
                            if (!friendlyFlags.HasFlag(FriendlyFlags.Optional))
                            {
                                alteredParameter = alteredParameter
                                                   .WithType(pointerType.ElementType);
                            }

                            alteredParameter = alteredParameter
                                               .AddModifiers(SyntaxFactory.Token(modifier));
                        }
                        else if (!friendlyFlags.HasFlag(FriendlyFlags.Optional))
                        {
                            alteredParameter = alteredParameter
                                               .WithType(pointerType.ElementType);
                        }
                    }

                    return(alteredParameter);
                }
                else if (generatorFlags.HasFlag(GeneratorFlags.NativePointerToIntPtr))
                {
                    return(n2
                           .WithType(IntPtrTypeSyntax)
                           .WithDefault(null));
                }
                else
                {
                    return(n2);
                }
            });

            return(resultingList);
        }
コード例 #48
0
 public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax?block, ExpressionSyntax?expressionBody)
 => ParenthesizedLambdaExpression(TokenList(asyncKeyword), parameterList, arrowToken, block, expressionBody);
        private static void CheckMethodParameters(SyntaxNodeAnalysisContext context, SyntaxToken identifier, ParameterListSyntax parameterList)
        {
            var methodName = identifier.ToString();

            foreach (var parameter in parameterList.Parameters.Select(p => p.Identifier))
            {
                var parameterName = parameter.ToString();
                if (string.Equals(parameterName, methodName, StringComparison.OrdinalIgnoreCase))
                {
                    context.ReportDiagnosticWhenActive(Diagnostic.Create(rule, parameter.GetLocation(),
                                                                         new[] { identifier.GetLocation() }, parameterName));
                }
            }
        }
コード例 #50
0
 public ParameterListTranslation(ParameterListSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     Parameters = syntax.Parameters.Get <ParameterSyntax, ParameterTranslation>(this);
 }
コード例 #51
0
        private static InvocationExpressionSyntax WithNewParameterNames(InvocationExpressionSyntax invocation, IMethodSymbol method, ParameterListSyntax newParameterList)
        {
            return(invocation.ReplaceNodes(invocation.ArgumentList.Arguments, (argumentNode, _) =>
            {
                if (argumentNode.NameColon == null)
                {
                    return argumentNode;
                }

                var parameterIndex = TryDetermineParameterIndex(argumentNode.NameColon, method);
                if (parameterIndex == -1)
                {
                    return argumentNode;
                }

                var newParameter = newParameterList.Parameters.ElementAtOrDefault(parameterIndex);
                if (newParameter == null || newParameter.Identifier.IsMissing)
                {
                    return argumentNode;
                }

                return argumentNode.WithNameColon(argumentNode.NameColon.WithName(SyntaxFactory.IdentifierName(newParameter.Identifier)));
            }));
        }
コード例 #52
0
        private ImmutableArray<BoundVariableDeclaration> BindParameters(ParameterListSyntax parameterList, Binder invocableBinder, InvocableSymbol invocableSymbol)
        {
            var boundParameters = new List<BoundVariableDeclaration>();
            foreach (var parameterSyntax in parameterList.Parameters)
            {
                var parameterValueType = Bind(parameterSyntax.Type, x => BindType(x, null));
                var parameterDirection = SyntaxFacts.GetParameterDirection(parameterSyntax.Modifiers);

                boundParameters.Add(invocableBinder.Bind(parameterSyntax.Declarator, x => invocableBinder.BindVariableDeclarator(x, parameterValueType.TypeSymbol, (d, t) =>
                    new SourceParameterSymbol(
                        parameterSyntax,
                        invocableSymbol,
                        t,
                        parameterDirection))));
            }

            invocableSymbol.ClearParameters();
            foreach (var parameter in invocableBinder.LocalSymbols.Values.SelectMany(x => x))
                invocableSymbol.AddParameter((ParameterSymbol) parameter);

            return boundParameters.ToImmutableArray();
        }
コード例 #53
0
        public void VisitParameterList(ParameterListSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            if (node.Parameters.Count == 0)
            {
                if (_writer.Configuration.Spaces.BeforeParentheses.MethodDeclarationEmptyParentheses)
                    _writer.WriteSpace();
            }
            else
            {
                if (_writer.Configuration.Spaces.BeforeParentheses.MethodDeclarationParentheses)
                    _writer.WriteSpace();
            }

            _writer.WriteSyntax(Syntax.OpenParen);

            if (_writer.Configuration.Other.AlignMultiLineConstructs.MethodParameters)
                _writer.SetAlignmentBreak(true);

            bool spacesWithin = false;

            if (node.Parent != null)
            {
                switch (node.Parent.SyntaxKind)
                {
                    case SyntaxKind.MethodDeclaration:
                        spacesWithin =
                            node.Parameters.Count > 0
                            ? _writer.Configuration.Spaces.WithinParentheses.MethodDeclarationParentheses
                            : _writer.Configuration.Spaces.WithinParentheses.MethodDeclarationEmptyParentheses;
                        break;
                }
            }

            if (spacesWithin)
                _writer.WriteSpace();

            bool hadOne = false;

            foreach (var parameter in node.Parameters)
            {
                if (hadOne)
                    _writer.WriteListSeparator();
                else
                    hadOne = true;

                parameter.Accept(this);
            }

            if (spacesWithin && node.Parameters.Count > 0)
                _writer.WriteSpace();

            if (_writer.Configuration.Other.AlignMultiLineConstructs.MethodParameters)
                _writer.SetAlignmentBreak(false);

            _writer.WriteSyntax(Syntax.CloseParen);
        }