Exemplo n.º 1
0
    public (ExpressionSyntax Expr, bool IsCorrectType) GetConstantOrNull(VBSyntax.ExpressionSyntax vbNode, ITypeSymbol type, TypeConversionAnalyzer.TypeConversionKind analyzedConversionKind, ExpressionSyntax csNode)
    {
        var vbOperation = _semanticModel.GetOperation(vbNode).SkipParens(true);

        // Guideline tradeoff: Usually would aim for erring on the side of correct runtime behaviour. But making lots of simple constants unreadable for the sake of an edge case that will turn into an easily fixed compile error seems overkill.
        // See https://github.com/icsharpcode/CodeConverter/blob/master/.github/CONTRIBUTING.md#deciding-what-the-output-should-be
        bool isExactType = analyzedConversionKind == TypeConversionAnalyzer.TypeConversionKind.Identity;

        if ((isExactType || analyzedConversionKind == TypeConversionAnalyzer.TypeConversionKind.NonDestructiveCast) &&
            IsProbablyConstExpression(vbOperation))
        {
            return(csNode, isExactType);
        }

        if (TryCompileTimeEvaluate(vbOperation, out var result))
        {
            if (type.Name == "Char" && result is int resultInt)
            {
                result = Strings.ChrW(resultInt);
            }
            else if (ConversionsTypeFullNames.TryGetValue(type.GetFullMetadataName(), out var method))
            {
                result = method.Invoke(null, new[] { result });
            }
            return(LiteralConversions.GetLiteralExpression(result, convertedType: type), true);
        }

        return(null, false);
    }
Exemplo n.º 2
0
        public ExpressionSyntax GetConstantOrNull(VBSyntax.ExpressionSyntax vbNode, ITypeSymbol type, ExpressionSyntax csNode)
        {
            var vbOperation = _semanticModel.GetOperation(vbNode).SkipParens(true);

            // Guideline tradeoff: Usually would aim for erring on the side of correct runtime behaviour. But making lots of simple constants unreadable for the sake of an edge case that will turn into an easily fixed compile error seems overkill.
            // See https://github.com/icsharpcode/CodeConverter/blob/master/.github/CONTRIBUTING.md#deciding-what-the-output-should-be
            if (Equals(vbOperation.Type, type) && IsProbablyConstExpression(vbOperation))
            {
                return(csNode);
            }

            if (TryCompileTimeEvaluate(vbOperation, out var result) && ConversionsTypeFullNames.TryGetValue(type.GetFullMetadataName(), out var method))
            {
                result = method.Invoke(null, new[] { result });
                return(LiteralConversions.GetLiteralExpression(result, convertedType: type));
            }

            return(null);
        }