Ejemplo n.º 1
0
            private bool ConvertToSwitch(ExpressionSyntax expr, SyntaxList <VBSyntax.CaseBlockSyntax> caseBlocks, out SwitchStatementSyntax switchStatement)
            {
                switchStatement = null;

                var sections = new List <SwitchSectionSyntax>();

                foreach (var block in caseBlocks)
                {
                    var labels = new List <SwitchLabelSyntax>();
                    foreach (var c in block.CaseStatement.Cases)
                    {
                        if (c is VBSyntax.SimpleCaseClauseSyntax)
                        {
                            var s = (VBSyntax.SimpleCaseClauseSyntax)c;
                            labels.Add(SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)s.Value.Accept(nodesVisitor)));
                        }
                        else if (c is VBSyntax.ElseCaseClauseSyntax)
                        {
                            labels.Add(SyntaxFactory.DefaultSwitchLabel());
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    var list = SingleStatement(SyntaxFactory.Block(block.Statements.SelectMany(s => s.Accept(this)).Concat(SyntaxFactory.BreakStatement())));
                    sections.Add(SyntaxFactory.SwitchSection(SyntaxFactory.List(labels), list));
                }
                switchStatement = SyntaxFactory.SwitchStatement(expr, SyntaxFactory.List(sections));
                return(true);
            }
        private ExpressionSyntax AddTypeConversion(VBSyntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, TypeConversionKind conversionKind, bool addParenthesisIfNeeded, ITypeSymbol vbType, ITypeSymbol vbConvertedType)
        {
            switch (conversionKind)
            {
            case TypeConversionKind.Unknown:
            case TypeConversionKind.Identity:
                return(addParenthesisIfNeeded ? VbSyntaxNodeExtensions.ParenthesizeIfPrecedenceCouldChange(vbNode, csNode) : csNode);

            case TypeConversionKind.DestructiveCast:
            case TypeConversionKind.NonDestructiveCast:
                return(CreateCast(csNode, vbConvertedType));

            case TypeConversionKind.Conversion:
                return(AddExplicitConvertTo(vbNode, csNode, vbType, vbConvertedType));;

            case TypeConversionKind.NullableBool:
                return(SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, csNode,
                                                      LiteralConversions.GetLiteralExpression(true)));

            case TypeConversionKind.StringToCharArray:
                var memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, csNode, SyntaxFactory.IdentifierName(nameof(string.ToCharArray)));
                return(SyntaxFactory.InvocationExpression(memberAccessExpressionSyntax,
                                                          SyntaxFactory.ArgumentList()));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 3
0
            StatementSyntax ConvertSingleExpression(CSS.ExpressionSyntax node)
            {
                var exprNode = node.Accept(nodesVisitor);

                if (!(exprNode is StatementSyntax))
                {
                    exprNode = SyntaxFactory.ExpressionStatement((ExpressionSyntax)exprNode);
                }

                return((StatementSyntax)exprNode);
            }
        private ExpressionSyntax CreateCast(ExpressionSyntax csNode, ITypeSymbol vbConvertedType)
        {
            var typeName = (TypeSyntax)_csSyntaxGenerator.TypeExpression(vbConvertedType);

            if (csNode is CastExpressionSyntax cast && cast.Type.IsEquivalentTo(typeName))
            {
                return(csNode);
            }

            return(ValidSyntaxFactory.CastExpression(typeName, csNode));
        }
Ejemplo n.º 5
0
            string GetPossibleEventName(CSS.ExpressionSyntax expression)
            {
                var ident = expression as CSS.IdentifierNameSyntax;

                if (ident != null)
                {
                    return(ident.Identifier.Text);
                }
                var fre = expression as CSS.MemberAccessExpressionSyntax;

                if (fre != null && fre.Expression.IsKind(CS.SyntaxKind.ThisExpression))
                {
                    return(fre.Name.Identifier.Text);
                }
                return(null);
            }
        private void VisitMethodsCSharp(SyntaxNodeAnalysisContext ctx)
        {
            if (!(ctx.Node is CSharpSyntax.MethodDeclarationSyntax node))
            {
                return;
            }

            //Iterating over the list of annotation for a given method
            foreach (var attribute in node.AttributeLists)
            {
                if (attribute.Attributes.Count == 0)
                {
                    continue; //Bound check .. Unlikely to happens
                }
                var att = attribute.Attributes[0];

                //Extract the annotation identifier
                if (!(att.Name is CSharpSyntax.IdentifierNameSyntax identifier))
                {
                    continue;
                }

                if (identifier.Identifier.Text != "ValidateInput")
                {
                    continue;
                }

                var hasArgumentFalse = false;
                CSharpSyntax.ExpressionSyntax expression = null;
                foreach (var arg in att.ArgumentList.Arguments)
                {
                    var literal = (CSharpSyntax.LiteralExpressionSyntax)arg.Expression;
                    if (literal.Token.ValueText != "false")
                    {
                        continue;
                    }

                    hasArgumentFalse = true;
                    expression       = arg.Expression;
                }

                if (hasArgumentFalse && expression != null)
                {
                    ctx.ReportDiagnostic(Diagnostic.Create(Rule, expression.GetLocation()));
                }
            }
        }
Ejemplo n.º 7
0
        private ExpressionSyntax AddTypeConversion(VBSyntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, TypeConversionKind conversionKind, bool addParenthesisIfNeeded, ITypeSymbol vbType, ITypeSymbol vbConvertedType)
        {
            switch (conversionKind)
            {
            case TypeConversionKind.FractionalNumberRoundThenCast:
                csNode = AddRoundInvocation(vbNode, csNode, vbType, vbConvertedType);
                return(AddTypeConversion(vbNode, csNode, TypeConversionKind.NonDestructiveCast, addParenthesisIfNeeded, vbType, vbConvertedType));

            case TypeConversionKind.EnumConversionThenCast:
                var underlyingType = ((INamedTypeSymbol)vbConvertedType).EnumUnderlyingType;
                csNode = AddTypeConversion(vbNode, csNode, TypeConversionKind.Conversion, addParenthesisIfNeeded, vbType, underlyingType);
                return(AddTypeConversion(vbNode, csNode, TypeConversionKind.NonDestructiveCast, addParenthesisIfNeeded, underlyingType, vbConvertedType));

            case TypeConversionKind.EnumCastThenConversion:
                var enumUnderlyingType = ((INamedTypeSymbol)vbType).EnumUnderlyingType;
                csNode = AddTypeConversion(vbNode, csNode, TypeConversionKind.NonDestructiveCast, addParenthesisIfNeeded, vbType, enumUnderlyingType);
                return(AddTypeConversion(vbNode, csNode, TypeConversionKind.Conversion, addParenthesisIfNeeded, enumUnderlyingType, vbConvertedType));

            case TypeConversionKind.Unknown:
            case TypeConversionKind.Identity:
                return(addParenthesisIfNeeded ? vbNode.ParenthesizeIfPrecedenceCouldChange(csNode) : csNode);

            case TypeConversionKind.DestructiveCast:
            case TypeConversionKind.NonDestructiveCast:
                return(CreateCast(csNode, vbConvertedType));

            case TypeConversionKind.Conversion:
                return(AddExplicitConvertTo(vbNode, csNode, vbType, vbConvertedType));;

            case TypeConversionKind.NullableBool:
                return(SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, csNode,
                                                      LiteralConversions.GetLiteralExpression(true)));

            case TypeConversionKind.StringToCharArray:
                var memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, csNode, SyntaxFactory.IdentifierName(nameof(string.ToCharArray)));
                return(SyntaxFactory.InvocationExpression(memberAccessExpressionSyntax,
                                                          SyntaxFactory.ArgumentList()));

            case TypeConversionKind.DelegateConstructor:
                return(SyntaxFactory.ObjectCreationExpression(GetCommonDelegateTypeOrNull(vbNode, vbConvertedType)).WithArgumentList(new[] { csNode }.CreateCsArgList()));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        /// <summary>
        /// For many types, Conversions.ToString is the same as ToString.
        /// I've done some checks on numeric types, could add more here in future. Any reference types will need a conditional to avoid nullref like Conversions does
        /// </summary>
        private static ExpressionSyntax GetToStringConversionOrNull(ExpressionSyntax csNode, ITypeSymbol currentType, ITypeSymbol targetType)
        {
            if (targetType.SpecialType != SpecialType.System_String)
            {
                return(null);
            }

            const string toStringMethodName = "ToString";

            if (csNode is MemberAccessExpressionSyntax maes && maes.Name.Identifier.Text == toStringMethodName)
            {
                return(csNode);
            }

            if (currentType.IsNumericType())
            {
                var toString = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                    csNode.AddParens(), SyntaxFactory.IdentifierName(toStringMethodName));
                return(SyntaxFactory.InvocationExpression(toString, SyntaxFactory.ArgumentList()));
            }
            return(null);
        }
        public ExpressionSyntax AddExplicitConversion(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, bool addParenthesisIfNeeded = true, bool defaultToCast = false, bool isConst = false, ITypeSymbol forceTargetType = null)
        {
            var conversionKind = AnalyzeConversion(vbNode, defaultToCast, isConst, forceTargetType);

            csNode = addParenthesisIfNeeded && (conversionKind == TypeConversionKind.DestructiveCast || conversionKind == TypeConversionKind.NonDestructiveCast)
                ? VbSyntaxNodeExtensions.ParenthesizeIfPrecedenceCouldChange(vbNode, csNode)
                : csNode;
            return(AddExplicitConversion(vbNode, csNode, conversionKind, addParenthesisIfNeeded, forceTargetType: forceTargetType));
        }
Ejemplo n.º 10
0
 public static bool IsStaticString(CSharpSyntax.ExpressionSyntax expression)
 {
     return(expression.Kind() == CSharp.SyntaxKind.StringLiteralExpression &&
            expression is CSharpSyntax.LiteralExpressionSyntax);
 }
Ejemplo n.º 11
0
        public ExpressionSyntax AddExplicitConversion(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, TypeConversionKind conversionKind, bool addParenthesisIfNeeded = false, ITypeSymbol forceTargetType = null)
        {
            var vbConvertedType = forceTargetType ?? ModelExtensions.GetTypeInfo(_semanticModel, vbNode).ConvertedType;

            switch (conversionKind)
            {
            case TypeConversionKind.Unknown:
            case TypeConversionKind.Identity:
                return(addParenthesisIfNeeded ? VbSyntaxNodeExtensions.ParenthesizeIfPrecedenceCouldChange(vbNode, csNode) : csNode);

            case TypeConversionKind.DestructiveCast:
            case TypeConversionKind.NonDestructiveCast:
                return(CreateCast(csNode, vbConvertedType));

            case TypeConversionKind.Conversion:
                return(AddExplicitConvertTo(vbNode, csNode, vbConvertedType));

            case TypeConversionKind.ConstConversion:
                return(ConstantFold(vbNode, vbConvertedType));

            case TypeConversionKind.NullableBool:
                return(SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, csNode,
                                                      LiteralConversions.GetLiteralExpression(true)));

            case TypeConversionKind.StringToCharArray:
                var memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, csNode, SyntaxFactory.IdentifierName(nameof(string.ToCharArray)));
                return(SyntaxFactory.InvocationExpression(memberAccessExpressionSyntax,
                                                          SyntaxFactory.ArgumentList()));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 12
0
        public ExpressionSyntax AddExplicitConvertTo(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, ITypeSymbol type)
        {
            var displayType = type.ToMinimalDisplayString(_semanticModel, vbNode.SpanStart);

            if (csNode is InvocationExpressionSyntax invoke &&
                invoke.Expression is MemberAccessExpressionSyntax expr &&
                expr.Expression is IdentifierNameSyntax name && name.Identifier.ValueText == "Conversions" &&
                expr.Name.Identifier.ValueText == $"To{displayType}")
            {
                return(csNode);
            }

            if (!ConversionsTypeFullNames.TryGetValue(type.GetFullMetadataName(), out var methodId))
            {
                return(CreateCast(csNode, type));
            }

            // Need to use Conversions rather than Convert to match what VB does, eg. True -> -1
            _extraUsingDirectives.Add("Microsoft.VisualBasic.CompilerServices");
            var memberAccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                                                    SyntaxFactory.IdentifierName("Conversions"), SyntaxFactory.IdentifierName(methodId.Name));
            var arguments = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(csNode)));

            return(SyntaxFactory.InvocationExpression(memberAccess, arguments));
        }
Ejemplo n.º 13
0
        private (TypeSyntax, ExpressionSyntax) AdjustFromName(TypeSyntax rawType,
                                                              ModifiedIdentifierSyntax name, ExpressionSyntax initializer)
        {
            var type = rawType;

            if (!SyntaxTokenExtensions.IsKind(name.Nullable, SyntaxKind.None))
            {
                if (type is ArrayTypeSyntax)
                {
                    type = ((ArrayTypeSyntax)type).WithElementType(
                        SyntaxFactory.NullableType(((ArrayTypeSyntax)type).ElementType));
                    initializer = null;
                }
                else
                {
                    type = SyntaxFactory.NullableType(type);
                }
            }

            var rankSpecifiers = ConvertArrayRankSpecifierSyntaxes(name.ArrayRankSpecifiers, name.ArrayBounds, false);

            if (rankSpecifiers.Count > 0)
            {
                var rankSpecifiersWithSizes = ConvertArrayRankSpecifierSyntaxes(name.ArrayRankSpecifiers,
                                                                                name.ArrayBounds);
                if (!rankSpecifiersWithSizes.SelectMany(ars => ars.Sizes).OfType <OmittedArraySizeExpressionSyntax>().Any())
                {
                    initializer =
                        SyntaxFactory.ArrayCreationExpression(
                            SyntaxFactory.ArrayType(type, rankSpecifiersWithSizes));
                }

                type = SyntaxFactory.ArrayType(type, rankSpecifiers);
            }

            return(type, initializer);
        }
Ejemplo n.º 14
0
 public static CSSyntax.ExpressionSyntax ParenthesizeIfPrecedenceCouldChange(this VBasic.VisualBasicSyntaxNode node, CSSyntax.ExpressionSyntax expression)
 {
     return(PrecedenceCouldChange(node) ? SyntaxFactory.ParenthesizedExpression(expression) : expression);
 }
Ejemplo n.º 15
0
 SyntaxList <StatementSyntax> SingleStatement(ExpressionSyntax expression)
 {
     return(SyntaxFactory.SingletonList <StatementSyntax>(SyntaxFactory.ExpressionStatement(expression)));
 }
 public static ExpressionSyntax ParenthesizeIfPrecedenceCouldChange(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode node, ExpressionSyntax expression)
 {
     return(PrecedenceCouldChange(node) ? SyntaxFactory.ParenthesizedExpression(expression) : expression);
 }
Ejemplo n.º 17
0
            public override SyntaxList <StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node)
            {
                var stmt = node.ForStatement;
                ExpressionSyntax          startValue  = (ExpressionSyntax)stmt.FromValue.Accept(nodesVisitor);
                VariableDeclarationSyntax declaration = null;
                ExpressionSyntax          id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    declaration = SplitVariableDeclarations(v, nodesVisitor, semanticModel).Values.Single();
                    declaration = declaration.WithVariables(SyntaxFactory.SingletonSeparatedList(declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(startValue))));
                    id          = SyntaxFactory.IdentifierName(declaration.Variables[0].Identifier);
                }
                else
                {
                    id = (ExpressionSyntax)stmt.ControlVariable.Accept(nodesVisitor);
                    var symbol = semanticModel.GetSymbolInfo(stmt.ControlVariable).Symbol;
                    if (!semanticModel.LookupSymbols(node.FullSpan.Start, name: symbol.Name).Any())
                    {
                        var variableDeclaratorSyntax = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(symbol.Name), null,
                                                                                        SyntaxFactory.EqualsValueClause(startValue));
                        declaration = SyntaxFactory.VariableDeclaration(
                            SyntaxFactory.IdentifierName("var"),
                            SyntaxFactory.SingletonSeparatedList(variableDeclaratorSyntax));
                    }
                    else
                    {
                        startValue = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, id, startValue);
                    }
                }

                var step = (ExpressionSyntax)stmt.StepClause?.StepValue.Accept(nodesVisitor);
                PrefixUnaryExpressionSyntax value = step.SkipParens() as PrefixUnaryExpressionSyntax;
                ExpressionSyntax            condition;

                if (value == null)
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.LessThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(nodesVisitor));
                }
                else
                {
                    condition = SyntaxFactory.BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, id, (ExpressionSyntax)stmt.ToValue.Accept(nodesVisitor));
                }
                if (step == null)
                {
                    step = SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, id);
                }
                else
                {
                    step = SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, id, step);
                }
                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(this)));

                return(SingleStatement(SyntaxFactory.ForStatement(
                                           declaration,
                                           declaration != null ? SyntaxFactory.SeparatedList <ExpressionSyntax>() : SyntaxFactory.SingletonSeparatedList(startValue),
                                           condition,
                                           SyntaxFactory.SingletonSeparatedList(step),
                                           block.UnpackBlock())));
            }
        public ExpressionSyntax AddExplicitConversion(VBSyntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, bool addParenthesisIfNeeded = true, bool defaultToCast = false, bool isConst = false, ITypeSymbol forceSourceType = null, ITypeSymbol forceTargetType = null)
        {
            if (csNode == null)
            {
                return(null);
            }
            var conversionKind = AnalyzeConversion(vbNode, defaultToCast, isConst, forceSourceType, forceTargetType);

            csNode = addParenthesisIfNeeded && (conversionKind == TypeConversionKind.DestructiveCast || conversionKind == TypeConversionKind.NonDestructiveCast)
                ? VbSyntaxNodeExtensions.ParenthesizeIfPrecedenceCouldChange(vbNode, csNode)
                : csNode;
            return(AddExplicitConversion(vbNode, csNode, conversionKind, addParenthesisIfNeeded, isConst, forceSourceType: forceSourceType, forceTargetType: forceTargetType).Expr);
        }
Ejemplo n.º 19
0
 public virtual void VisitInvocationAndCreation(CSharpSyntax.ExpressionSyntax node,
                                                CSharpSyntax.ArgumentListSyntax argList,
                                                ExecutionState state,
                                                Configuration projectConfiguration)
 {
 }
        public (ExpressionSyntax Expr, bool IsConst) AddExplicitConversion(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, TypeConversionKind conversionKind, bool addParenthesisIfNeeded = false, bool requiresConst = false, ITypeSymbol forceSourceType = null, ITypeSymbol forceTargetType = null)
        {
            var  typeInfo        = ModelExtensions.GetTypeInfo(_semanticModel, vbNode);
            var  vbType          = forceSourceType ?? typeInfo.Type;
            var  vbConvertedType = forceTargetType ?? typeInfo.ConvertedType;
            bool resultConst     = false;

            if (requiresConst)
            {
                var(constExpression, isCorrectType) = _expressionEvaluator.GetConstantOrNull(vbNode, vbConvertedType, conversionKind, csNode);
                if (isCorrectType)
                {
                    return(constExpression, true);
                }
                if (constExpression != null)
                {
                    csNode      = constExpression ?? csNode;
                    resultConst = true;
                }
            }

            var typeConvertedResult = AddTypeConversion(vbNode, csNode, conversionKind, addParenthesisIfNeeded, vbType, vbConvertedType);

            return(typeConvertedResult, resultConst);
        }
        public (ExpressionSyntax Expr, bool IsConst) AddExplicitConversion(VBSyntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, TypeConversionKind conversionKind, bool addParenthesisIfNeeded = false, bool requiresConst = false, ITypeSymbol forceSourceType = null, ITypeSymbol forceTargetType = null)
        {
            var(vbType, vbConvertedType) = GetTypeInfo(vbNode, forceSourceType, forceTargetType);
            bool resultConst = false;

            if (requiresConst)
            {
                var(constExpression, isCorrectType) = _expressionEvaluator.GetConstantOrNull(vbNode, vbConvertedType, conversionKind, csNode);
                if (isCorrectType)
                {
                    return(constExpression, true);
                }
                if (constExpression != null)
                {
                    csNode      = constExpression ?? csNode;
                    resultConst = true;
                }
            }

            var typeConvertedResult = AddTypeConversion(vbNode, csNode, conversionKind, addParenthesisIfNeeded, vbType, vbConvertedType);

            return(typeConvertedResult, resultConst);
        }
Ejemplo n.º 22
0
 public static glsl.ExpressionSyntax Translate(this cs.ExpressionSyntax node)
 {
     return(Translate(node as CSharpSyntaxNode) as glsl.ExpressionSyntax);
 }