Ejemplo n.º 1
0
        private static bool NameofHasIssue(SyntaxNode node, SeparatedSyntaxList <ArgumentSyntax> arguments, SemanticModel semanticModel)
        {
            // it might happen that the code is currently being written so there might not yet exist a specific property name
            var a            = arguments.Select(_ => _.Expression).OfType <IdentifierNameSyntax>().FirstOrDefault();
            var propertyName = a.GetName();

            if (propertyName is null)
            {
                return(false);
            }

            var symbol         = node.GetEnclosingSymbol(semanticModel);
            var containingType = symbol?.ContainingType;

            if (containingType is null)
            {
                return(false);
            }

            // verify that nameof uses a property if the type
            var propertySymbols = containingType.GetMembersIncludingInherited <IPropertySymbol>();

            if (propertySymbols.Any(_ => _.Name == propertyName))
            {
                return(false);
            }

            return(true); // report to use nameof instead
        }
Ejemplo n.º 2
0
 private static List <string> GetArgumentTypes(SeparatedSyntaxList <ArgumentSyntax> arguments, SemanticModel model)
 {
     return(arguments
            .Select(argument => model.GetTypeInfo(argument.Expression).Type?.ToString() ?? "object")
            .Select(typeName => typeName == "?" ? "object" : typeName)
            .ToList());
 }
        private static List <SyntaxNodeOrToken> CreateWcfArguments(SeparatedSyntaxList <ParameterSyntax> wcfParameters)
        {
            var arguments = wcfParameters
                            // add arguments using wcf method parameters
                            .Select(parameter =>
            {
                var argument = SyntaxFactory.Argument(SyntaxFactory.IdentifierName(parameter.Identifier));

                // add 'out' keyword if param has it
                var hasOutKeyword = OutKeywordGenerator.HasOutKeyword(parameter);
                argument          = hasOutKeyword
                        ? OutKeywordGenerator.AddOutKeywordToArgument(argument)
                        : argument;

                return(argument);
            })
                            // add commas
                            .SelectMany(param => new SyntaxNodeOrToken[]
            {
                param,
                SyntaxFactory.Token(SyntaxKind.CommaToken)
            })
                            // remove last trailing comma
                            .Take(wcfParameters.Count * 2 - 1)
                            .ToList();

            return(arguments);
        }
Ejemplo n.º 4
0
 private List <SolutionStyleError> InspectMethodParameters(SeparatedSyntaxList <ParameterSyntax> parameters)
 {
     return(parameters
            .Select(InspectMethodParameter)
            .Where(err => err != null)
            .ToList());
 }
        static string GenerateProperty(string typeFullName, string propertyType, string propertyName, bool readOnly, bool bindableReadOnly, Tuple <MemberVisibility, MemberVisibility, bool> overridedPropertyVisibility, SeparatedSyntaxList <ArgumentSyntax> attributes)
        {
            string getterModifier    = overridedPropertyVisibility == null ? "public " : overridedPropertyVisibility.Item2.ToCSharp(MemberVisibility.Private);
            string setterModifier    = overridedPropertyVisibility == null ? (readOnly ? "private " : "") : overridedPropertyVisibility.Item1.ToCSharp(overridedPropertyVisibility.Item2);
            var    nonBrowsable      = overridedPropertyVisibility != null && overridedPropertyVisibility.Item3;
            var    withDXDescription = attributes.Any(x => x.ToString() == "DXDescription");
            string attributesString  =
                (nonBrowsable ? "[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\r\n" : "") +
                (withDXDescription ? $"[DXDescription(\"{typeFullName},{propertyName}\")]\r\n" : "") +
                string.Concat(attributes.Select(attribute => {
                if (attribute.ToString() == "DXDescription")
                {
                    return(null);
                }
                var attributeExpression = attribute.Expression as InvocationExpressionSyntax;
                if (attributeExpression == null)
                {
                    return(null);
                }
                return("[" + attributeExpression.ToString() + "]\r\n");
            }));
            string setterAttributes = bindableReadOnly && !nonBrowsable ? "[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\r\n    " : string.Empty;
            string keySuffix        = readOnly ? "Key" : "";

            return
                ($@"{attributesString}{getterModifier}{propertyType} {propertyName} {{
    get {{ return ({propertyType})GetValue({propertyName}Property); }}
    {setterAttributes}{setterModifier}set {{ SetValue({propertyName}Property{keySuffix}, value); }}
}}
");
        }
 private static SeparatedSyntaxList <ArgumentSyntax> ConvertInitializers(
     SeparatedSyntaxList <AnonymousObjectMemberDeclaratorSyntax> initializers
     ) =>
 SyntaxFactory.SeparatedList(
     initializers.Select(ConvertInitializer),
     initializers.GetSeparators()
     );
 private List <ParameterInformation> GetSimpleParameterInfo(SeparatedSyntaxList <ParameterSyntax> parameters, SemanticModel semanticModel)
 {
     return(parameters.Select(p => new ParameterInformation
     {
         Name = p.Identifier.ValueText,
         SimpleTypeName = p.Type.ToString(),
         Namespaces = this.GetNamespaces(p.Type, semanticModel)
     }).ToList());
 }
Ejemplo n.º 8
0
 SeparatedSyntaxList <T> FormatList <T>(SeparatedSyntaxList <T> separatedSyntaxList) where T : SyntaxNode
 {
     return(SyntaxFactory.SeparatedList(
                separatedSyntaxList.Select((a, i) => a.WithLeadingTrivia(SyntaxFactory.TriviaList(
                                                                             SyntaxFactory.Whitespace(new string(' ', m_CurrentIndent))))),
                Enumerable.Repeat(
                    SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.LineFeed)),
                    separatedSyntaxList.Count - 1)));
 }
Ejemplo n.º 9
0
        public static Task <Document> RefactorAsync(
            Document document,
            ForStatementSyntax forStatement,
            CancellationToken cancellationToken)
        {
            var statements = new List <StatementSyntax>();

            VariableDeclarationSyntax declaration = forStatement.Declaration;

            if (declaration != null)
            {
                statements.Add(LocalDeclarationStatement(declaration));
            }
            else
            {
                foreach (ExpressionSyntax initializer in forStatement.Initializers)
                {
                    statements.Add(ExpressionStatement(initializer));
                }
            }

            StatementSyntax statement = forStatement.Statement ?? Block();

            SeparatedSyntaxList <ExpressionSyntax> incrementors = forStatement.Incrementors;

            if (incrementors.Any())
            {
                if (!statement.IsKind(SyntaxKind.Block))
                {
                    statement = Block(statement);
                }

                ExpressionStatementSyntax[] incrementorStatements = incrementors
                                                                    .Select(f => ExpressionStatement(f).WithFormatterAnnotation())
                                                                    .ToArray();

                var rewriter = new InsertIncrementorsBeforeContinueRewriter(incrementorStatements);

                statement = (StatementSyntax)rewriter.Visit(statement);

                statement = ((BlockSyntax)statement).AddStatements(incrementorStatements);
            }

            statements.Add(WhileStatement(forStatement.Condition ?? TrueLiteralExpression(), statement));

            statements[0] = statements[0].WithLeadingTrivia(forStatement.GetLeadingTrivia());

            if (forStatement.IsEmbedded())
            {
                return(document.ReplaceNodeAsync(forStatement, Block(statements), cancellationToken));
            }
            else
            {
                return(document.ReplaceNodeAsync(forStatement, statements, cancellationToken));
            }
        }
Ejemplo n.º 10
0
        private static SeparatedSyntaxList <AttributeArgumentSyntax> PermuteAttributeArgumentList(
            Document document,
            ISymbol declarationSymbol,
            SeparatedSyntaxList <AttributeArgumentSyntax> arguments,
            SignatureChange updatedSignature)
        {
            var newArguments        = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature);
            var numSeparatorsToSkip = arguments.Count - newArguments.Count;

            return(SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)));
        }
        private static List <string> GetParameterNames(SeparatedSyntaxList <ParameterSyntax> parameters)
        {
            var names = parameters
                        .Select(parameter =>
            {
                string name = parameter.Identifier.ToFullString();

                return(name);
            })
                        .ToList();

            return(names);
        }
Ejemplo n.º 12
0
                static string _Function(SeparatedSyntaxList <ParameterSyntax> a)
                {
                    int n = a.Count; if (n == 0)

                    {
                        return(null);
                    }

                    if (n == 1)
                    {
                        return(a[0].Type.ToString());
                    }
                    return(string.Join(", ", a.Select(o => o.Type)));
                }
Ejemplo n.º 13
0
        private static SeparatedSyntaxList <AttributeArgumentSyntax> PermuteAttributeArgumentList(
            Document document,
            ISymbol declarationSymbol,
            SeparatedSyntaxList <AttributeArgumentSyntax> arguments,
            SignatureChange updatedSignature)
        {
            var newArguments        = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature);
            var numSeparatorsToSkip = arguments.Count - newArguments.Count;

            // copy whitespace trivia from original position
            var newArgumentsWithTrivia = TransferLeadingWhitespaceTrivia(
                newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), arguments);

            return(SyntaxFactory.SeparatedList(newArgumentsWithTrivia, GetSeparators(arguments, numSeparatorsToSkip)));
        }
        private static string GetNames(LocalDeclarationStatementSyntax localDeclaration)
        {
            VariableDeclarationSyntax declaration = localDeclaration.Declaration;

            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables;

            if (variables.Count == 1)
            {
                return($"'{variables[0].Identifier.ValueText}'");
            }
            else
            {
                return(string.Join(", ", variables.Select(f => $"'{f.Identifier.ValueText}'")));
            }
        }
        public static string ConvertSeparatedSyntaxList <T>(
            this SeparatedSyntaxList <T> source,
            Func <T, string> itemConverter = null,
            string separatorForced         = null
            ) where T : SyntaxNode
        {
            var separator = separatorForced ??
                            BuilderStatic.SyntaxTokenConvert(source.GetSeparators().FirstOrDefault());

            if (itemConverter == null)
            {
                itemConverter = BuilderStatic.SyntaxNode;
            }

            return(string.Join(separator, source.Select(itemConverter)));
        }
Ejemplo n.º 16
0
        public static List <NetEnumValue> GetNetEnumValues(SeparatedSyntaxList <EnumMemberDeclarationSyntax> enumMembers)
        {
            return(enumMembers.Select(m =>
            {
                var v = new NetEnumValue
                {
                    Name = m.Identifier.ToString()
                };

                int evi;
                if (m.EqualsValue?.Value != null && int.TryParse(m.EqualsValue.Value.ToString(), out evi))
                {
                    v.EnumValue = evi;
                }
                return v;
            }).ToList());
        }
Ejemplo n.º 17
0
        internal void ReportIncorrectlyOrderedParameters(SyntaxNodeAnalysisContext analysisContext,
                                                         AbstractMethodParameterLookup <TArgumentSyntax> methodParameterLookup, SeparatedSyntaxList <TArgumentSyntax> argumentList,
                                                         Func <Location> getLocationToReport)
        {
            var argumentParameterMappings = methodParameterLookup.GetAllArgumentParameterMappings()
                                            .ToDictionary(pair => pair.SyntaxNode, pair => pair.Symbol);

            var methodSymbol = methodParameterLookup.MethodSymbol;

            if (methodSymbol == null)
            {
                return;
            }

            var parameterNames = argumentParameterMappings.Values
                                 .Select(symbol => symbol.Name)
                                 .Distinct()
                                 .ToList();

            var argumentIdentifiers = argumentList
                                      .Select(argument => ConvertToArgumentIdentifier(argument))
                                      .ToList();
            var identifierNames = argumentIdentifiers
                                  .Select(p => p.IdentifierName)
                                  .ToList();

            if (parameterNames.Intersect(identifierNames).Any() &&
                HasIncorrectlyOrderedParameters(argumentIdentifiers, argumentParameterMappings, parameterNames, identifierNames,
                                                analysisContext.SemanticModel))
            {
                // for VB the symbol does not contain the method syntax reference
                var secondaryLocations = methodSymbol.DeclaringSyntaxReferences
                                         .Select(s => GetMethodDeclarationIdentifierLocation(s.GetSyntax()))
                                         .WhereNotNull();

                analysisContext.ReportDiagnosticWhenActive(Diagnostic.Create(SupportedDiagnostics[0], getLocationToReport(),
                                                                             additionalLocations: secondaryLocations,
                                                                             messageArgs: methodSymbol.Name));
            }
        }
 private static bool HasAnyExcludedArgumentKind(SeparatedSyntaxList <ArgumentSyntax> arguments) =>
 arguments.Select(a => a.Expression).Any(e =>
                                         e.IsKind(SyntaxKind.PostIncrementExpression) ||
                                         e.IsKind(SyntaxKind.PostDecrementExpression) ||
                                         e.IsKind(SyntaxKind.PreIncrementExpression) ||
                                         e.IsKind(SyntaxKind.PreDecrementExpression));
Ejemplo n.º 19
0
        /// <summary>
        /// Generates a single proxy constructor.
        /// </summary>
        /// <param name="sourceClassDeclaration">The source class declaration.</param>
        /// <param name="constructorDeclarationSyntax">An optional existing constructor on the base class.</param>
        /// <returns>A member declaration.</returns>
        private MemberDeclarationSyntax GenerateProxyConstructor(
            ClassDeclarationSyntax sourceClassDeclaration,
            ConstructorDeclarationSyntax constructorDeclarationSyntax = null)
        {
            SeparatedSyntaxList <ParameterSyntax> parameters =
                constructorDeclarationSyntax?.ParameterList?.Parameters
                ?? default(SeparatedSyntaxList <ParameterSyntax>);

            string arguments   = parameters.Any() ? parameters.ToFullString() : string.Empty;
            var    constructor = $@"
                /// <summary>
                /// Initializes a new instance of the <see cref=""Proxy{sourceClassDeclaration.Identifier}""/> class.
                /// </summary>
                public Proxy{sourceClassDeclaration.Identifier}({arguments}) : base({string.Join(",", parameters.Select(x => x.Identifier))})
                {{
                }}
            ";

            return(ParseMemberDeclaration(constructor)
                   .NormalizeWhitespace());
        }
Ejemplo n.º 20
0
 public SeparatedSyntaxListTranslation(SeparatedSyntaxList <T> separatedSyntaxList, SyntaxTranslation parent) : base(parent)
 {
     this.separatedSyntaxList = separatedSyntaxList;
     this.Parent      = parent;
     SyntaxCollection = separatedSyntaxList.Select(f => f.Get <SyntaxTranslation>(this)).ToList();
 }
        private void AddController(
            string serviceNamespace,
            string newNamespace,
            string controllerName,
            string serviceType,
            string serviceParameterName,
            string serviceName,
            string methodName,
            string inboundParameterType,
            string calledMethodName,
            string path)
        {
            var controllerPath = path + @"\Controllers\" + controllerName + ".cs";

            var templateControllerFile = File.ReadAllText(Directory.GetCurrentDirectory() + @"\Refactorings\Concrete\TemplateController.txt");

            var methodCall = "";

            var list = inboundParameterType.Replace("(", "").Replace(")", "").Replace(", ", ",").Split(',');

            for (int i = 0; i < list.Count(); i++)
            {
                var item = list.ElementAt(i);

                if (i == (list.Count() - 1))
                {
                    requestData += $"\t\tpublic {item} {{ get; set; }}";
                    methodCall  += "requestData." + item.Split(' ').ElementAt(1);
                }
                else
                {
                    requestData += $"\t\tpublic {item} {{ get; set; }}\n";
                    methodCall  += "requestData." + item.Split(' ').ElementAt(1) + ", ";
                }
            }

            requestDataCallObject = "var requestData = new RequestData() {\n";

            var arguments = invokedMethodArguments.Select(x => x.Expression.ToString());

            for (int i = 0; i < list.Count(); i++)
            {
                var item = list.ElementAt(i);

                if (i == (list.Count() - 1))
                {
                    requestDataCallObject += "\t\t\t\t" + item.Split(' ').LastOrDefault() + " = " + invokedMethodArguments[i] + "\n";
                    requestDataCallObject += "\t\t\t};\n";
                }
                else
                {
                    requestDataCallObject += "\t\t\t\t" + item.Split(' ').LastOrDefault() + " = " + invokedMethodArguments[i] + ",\n";
                }
            }

            var controllerFile = templateControllerFile
                                 .Replace("{serviceNamespace}", serviceNamespace)
                                 .Replace("{newNamespace}", newNamespace)
                                 .Replace("{controllerName}", controllerName)
                                 .Replace("{serviceType}", serviceType)
                                 .Replace("{serviceParameterName}", serviceParameterName)
                                 .Replace("{serviceName}", serviceName)
                                 .Replace("{methodName}", methodName)
                                 .Replace("{inboundParameters}", inboundParameterType)
                                 .Replace("{calledMethodName}", calledMethodName)
                                 .Replace("{parameters}", requestData)
                                 .Replace("{inboundParameterName}", methodCall);

            if (File.Exists(controllerPath))
            {
                File.WriteAllText(controllerPath, string.Empty);
            }

            File.AppendAllText(controllerPath, controllerFile);
        }
        private static void WriteArguments(OutputWriter writer, InvocationExpressionSyntax invocationExpression,
            SeparatedSyntaxList<ArgumentSyntax> arguments, bool firstParameter, bool inParams, IMethodSymbol methodSymbol, bool foundParamsArray,
            ITypeSymbol typeSymbol, bool isOverloaded, ISymbol symbol, string instanceName=null)
        {
            foreach (var arg in arguments.Select(o => new TransformedArgument(o)))
            {
                if (firstParameter)
                    firstParameter = false;
                else
                    writer.Write(", ");

                var argumentType = TypeProcessor.GetTypeInfo(arg.ArgumentOpt.Expression);

                if (!inParams && IsParamsArgument(invocationExpression, arg.ArgumentOpt, methodSymbol))
                {
                    foundParamsArray = true;
                    typeSymbol = TypeProcessor.GetTypeInfo(arg.ArgumentOpt.Expression).ConvertedType;

                    if (
                        !TypeProcessor.ConvertType(typeSymbol)
                            .StartsWith("Array_T"))
                    {
                        inParams = true;

                        var s = TypeProcessor.ConvertType(typeSymbol);
                        writer.Write("__ARRAY!(" + s + ")([");
                    }
                }

                var isValueType = argumentType.Type != null && argumentType.Type.IsValueType;
                ProcessArgument(writer, arg.ArgumentOpt,
                    isOverloaded && isValueType &&
                    (arg.ArgumentOpt.RefOrOutKeyword.RawKind == (decimal) SyntaxKind.None));
            }

            if (inParams)
                writer.Write("])");

            if (!foundParamsArray && methodSymbol.Parameters.Any() && methodSymbol.Parameters.Last().IsParams)
            {
                // if (typeSymbol != null)
                //{
                if (!firstParameter)
                    writer.Write(",");
                var s = TypeProcessor.ConvertType(((IArrayTypeSymbol) methodSymbol.Parameters.Last().Type).ElementType);
                    writer.Write("__ARRAY!(" + s + ")([])");
                //}
               /* else
                {
                    if (!firstParameter)
                        writer.Write(",");
                    writer.Write("null"); //params method called without any params argument.  Send null.
                }*/
            }

            if (instanceName != null)
            {
                if (!firstParameter)
                    writer.Write(",");
                writer.Write(instanceName);
                firstParameter = false;
            }
            else
            if (symbol.ContainingType.TypeKind == TypeKind.Interface) // Need it as specialized as possible
            {
                if (!firstParameter)
                    writer.Write(",");
                writer.Write("cast({0}) null", TypeProcessor.ConvertType(symbol.ContainingType));
            }

            writer.Write(")");
        }
Ejemplo n.º 23
0
 public static List <glsl.ArgumentSyntax> Translate(this SeparatedSyntaxList <cs.ArgumentSyntax> node)
 {
     return(node.Select(a => a.Translate()).ToList());
 }
        private static SeparatedSyntaxList <ExpressionSyntax> CreateSingleLineLambdaExpressions(SeparatedSyntaxList <ExpressionSyntax> expressions)
        {
            var singleLineLambdaExpressionSyntaxes = expressions.Select <ExpressionSyntax, ExpressionSyntax>(CreateSingleLineLambdaExpression);

            return(SeparatedList(singleLineLambdaExpressionSyntaxes));
        }
Ejemplo n.º 25
0
        private static void WriteArguments(OutputWriter writer, InvocationExpressionSyntax invocationExpression,
                                           SeparatedSyntaxList <ArgumentSyntax> arguments, bool firstParameter, bool inParams, IMethodSymbol methodSymbol, bool foundParamsArray,
                                           ITypeSymbol typeSymbol, bool isOverloaded, ISymbol symbol, string instanceName = null)
        {
            foreach (var arg in arguments.Select(o => new TransformedArgument(o)))
            {
                if (firstParameter)
                {
                    firstParameter = false;
                }
                else
                {
                    writer.Write(", ");
                }

                var argumentType = TypeProcessor.GetTypeInfo(arg.ArgumentOpt.Expression);

                if (!inParams && IsParamsArgument(invocationExpression, arg.ArgumentOpt, methodSymbol))
                {
                    foundParamsArray = true;
                    typeSymbol       = TypeProcessor.GetTypeInfo(arg.ArgumentOpt.Expression).ConvertedType;

                    if (
                        !TypeProcessor.ConvertType(typeSymbol)
                        .StartsWith("Array_T"))
                    {
                        inParams = true;

                        var s = TypeProcessor.ConvertType(typeSymbol);
                        writer.Write("__ARRAY!(" + s + ")([");
                    }
                }

                var isValueType = argumentType.Type != null && argumentType.Type.IsValueType;
                ProcessArgument(writer, arg.ArgumentOpt,
                                isOverloaded && isValueType &&
                                (arg.ArgumentOpt.RefOrOutKeyword.RawKind == (decimal)SyntaxKind.None));
            }

            if (inParams)
            {
                writer.Write("])");
            }

            if (!foundParamsArray && methodSymbol.Parameters.Any() && methodSymbol.Parameters.Last().IsParams)
            {
                // if (typeSymbol != null)
                //{
                if (!firstParameter)
                {
                    writer.Write(",");
                }
                var s = TypeProcessor.ConvertType(((IArrayTypeSymbol)methodSymbol.Parameters.Last().Type).ElementType);
                writer.Write("__ARRAY!(" + s + ")([])");
                //}

                /* else
                 * {
                 *   if (!firstParameter)
                 *       writer.Write(",");
                 *   writer.Write("null"); //params method called without any params argument.  Send null.
                 * }*/
            }

            if (instanceName != null)
            {
                if (!firstParameter)
                {
                    writer.Write(",");
                }
                writer.Write(instanceName);
                firstParameter = false;
            }
            else
            if (symbol.ContainingType.TypeKind == TypeKind.Interface) // Need it as specialized as possible
            {
                if (!firstParameter)
                {
                    writer.Write(",");
                }
                writer.Write("cast({0}) null", TypeProcessor.ConvertType(symbol.ContainingType));
            }

            writer.Write(")");
        }