public CodeGenerationNamedTypeSymbol(
            INamedTypeSymbol containingType,
            IList<AttributeData> attributes,
            Accessibility declaredAccessibility,
            DeclarationModifiers modifiers,
            TypeKind typeKind,
            string name,
            IList<ITypeParameterSymbol> typeParameters,
            INamedTypeSymbol baseType,
            IList<INamedTypeSymbol> interfaces,
            SpecialType specialType,
            IList<ISymbol> members,
            IList<CodeGenerationAbstractNamedTypeSymbol> typeMembers,
            INamedTypeSymbol enumUnderlyingType)
            : base(containingType, attributes, declaredAccessibility, modifiers, name, specialType, typeMembers)
        {
            _typeKind = typeKind;
            _typeParameters = typeParameters ?? SpecializedCollections.EmptyList<ITypeParameterSymbol>();
            _baseType = baseType;
            _interfaces = interfaces ?? SpecializedCollections.EmptyList<INamedTypeSymbol>();
            _members = members ?? SpecializedCollections.EmptyList<ISymbol>();
            _enumUnderlyingType = enumUnderlyingType;

            this.OriginalDefinition = this;
        }
        internal static ulong ConvertEnumUnderlyingTypeToUInt64(object value, SpecialType specialType)
        {
            Contract.Requires(value != null);
            Contract.Requires(value.GetType().GetTypeInfo().IsPrimitive);

            unchecked
            {
                switch (specialType)
                {
                    case SpecialType.System_SByte:
                        return (ulong)(sbyte)value;
                    case SpecialType.System_Int16:
                        return (ulong)(short)value;
                    case SpecialType.System_Int32:
                        return (ulong)(int)value;
                    case SpecialType.System_Int64:
                        return (ulong)(long)value;
                    case SpecialType.System_Byte:
                        return (byte)value;
                    case SpecialType.System_UInt16:
                        return (ushort)value;
                    case SpecialType.System_UInt32:
                        return (uint)value;
                    case SpecialType.System_UInt64:
                        return (ulong)value;

                    default:
                        // not using ExceptionUtilities.UnexpectedValue() because this is used by the Services layer
                        // which doesn't have those utilities.
                        throw new InvalidOperationException($"{specialType} is not a valid underlying type for an enum");
                }
            }
        }
 protected override void AddExplicitlyCastedLiteralValue(INamedTypeSymbol namedType, SpecialType type, object value)
 {
     AddPunctuation(SyntaxKind.OpenParenToken);
     namedType.Accept(this.NotFirstVisitor);
     AddPunctuation(SyntaxKind.CloseParenToken);
     AddLiteralValue(type, value);
 }
 protected CodeGenerationTypeSymbol(
     INamedTypeSymbol containingType,
     IList<AttributeData> attributes,
     Accessibility declaredAccessibility,
     DeclarationModifiers modifiers,
     string name,
     SpecialType specialType)
     : base(containingType, attributes, declaredAccessibility, modifiers, name)
 {
     this.SpecialType = specialType;
 }
        public static bool TryConvertToUInt64(object value, SpecialType specialType, out ulong convertedValue)
        {
            bool success = false;
            convertedValue = 0;
            if (value != null)
            {
                switch (specialType)
                {
                    case SpecialType.System_Int16:
                        convertedValue = unchecked((ulong)((short)value));
                        success = true;
                        break;
                    case SpecialType.System_Int32:
                        convertedValue = unchecked((ulong)((int)value));
                        success = true;
                        break;
                    case SpecialType.System_Int64:
                        convertedValue = unchecked((ulong)((long)value));
                        success = true;
                        break;
                    case SpecialType.System_UInt16:
                        convertedValue = (ushort)value;
                        success = true;
                        break;
                    case SpecialType.System_UInt32:
                        convertedValue = (uint)value;
                        success = true;
                        break;
                    case SpecialType.System_UInt64:
                        convertedValue = (ulong)value;
                        success = true;
                        break;
                    case SpecialType.System_Byte:
                        convertedValue = (byte)value;
                        success = true;
                        break;
                    case SpecialType.System_SByte:
                        convertedValue = unchecked((ulong)((sbyte)value));
                        success = true;
                        break;
                    case SpecialType.System_Char:
                        convertedValue = (char)value;
                        success = true;
                        break;
                    case SpecialType.System_Boolean:
                        convertedValue = (ulong)((bool)value == true ? 1 : 0);
                        success = true;
                        break;
                }
            }

            return success;
        }
Exemplo n.º 6
0
 public void EmitSpecial(SpecialType specialType)
 {
     switch(specialType){
         case SpecialType.one:
             specialOne.UseSpecial();
             break;
         case SpecialType.two:
             specialTwo.UseSpecial();
             break;
         default:
             specialThree.UseSpecial();
             break;
     }
 }
Exemplo n.º 7
0
        protected override SyntaxNode CreateExplicitlyCastedLiteralValue(
            INamedTypeSymbol enumType,
            SpecialType underlyingSpecialType,
            object constantValue)
        {
            var expression = ExpressionGenerator.GenerateNonEnumValueExpression(
                enumType.EnumUnderlyingType, constantValue, canUseFieldReference: true);

            var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType);
            if (constantValueULong == 0)
            {
                // 0 is always convertible to an enum type without needing a cast.
                return expression;
            }

            var factory = new CSharpSyntaxGenerator();
            return factory.CastExpression(enumType, expression);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Helper as VB's CType doesn't work without arithmetic overflow.
 /// </summary>
 public static long Convert(long v, SpecialType type)
 {
     switch (type)
     {
         case SpecialType.System_SByte:
             return unchecked((sbyte)v);
         case SpecialType.System_Byte:
             return unchecked((byte)v);
         case SpecialType.System_Int16:
             return unchecked((short)v);
         case SpecialType.System_UInt16:
             return unchecked((ushort)v);
         case SpecialType.System_Int32:
             return unchecked((int)v);
         case SpecialType.System_UInt32:
             return unchecked((uint)v);
         default:
             return v;
     }
 }
        protected override void AddLiteralValue(SpecialType type, object value)
        {
            Debug.Assert(value.GetType().GetTypeInfo().IsPrimitive || value is string || value is decimal);
            var valueString = SymbolDisplay.FormatPrimitive(value, quoteStrings: true, useHexadecimalNumbers: false);
            Debug.Assert(valueString != null);

            var kind = SymbolDisplayPartKind.NumericLiteral;
            switch (type)
            {
                case SpecialType.System_Boolean:
                    kind = SymbolDisplayPartKind.Keyword;
                    break;

                case SpecialType.System_String:
                case SpecialType.System_Char:
                    kind = SymbolDisplayPartKind.StringLiteral;
                    break;
            }

            this.builder.Add(CreatePart(kind, null, valueString));
        }
Exemplo n.º 10
0
 public static string SpecialTypeToString(SpecialType specialType)
 {
     switch (specialType)
     {
         case SpecialType.System_Boolean:
             return "bool";
         case SpecialType.System_Byte:
             return "byte";
         case SpecialType.System_SByte:
             return "sbyte";
         case SpecialType.System_Int16:
             return "short";
         case SpecialType.System_UInt16:
             return "ushort";
         case SpecialType.System_Int32:
             return "int";
         case SpecialType.System_UInt32:
             return "uint";
         case SpecialType.System_Int64:
             return "long";
         case SpecialType.System_UInt64:
             return "ulong";
         case SpecialType.System_Double:
             return "double";
         case SpecialType.System_Single:
             return "float";
         case SpecialType.System_Decimal:
             return "decimal";
         case SpecialType.System_String:
             return "string";
         case SpecialType.System_Char:
             return "char";
         case SpecialType.System_Void:
             return "void";
         case SpecialType.System_Object:
             return "object";
         default:
             return null;
     }
 }
        /// <summary>
        /// Lookup declaration for predefined CorLib type in this Assembly.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type)
        {
#if DEBUG
            foreach (var module in this.Modules)
            {
                Debug.Assert(module.GetReferencedAssemblies().Length == 0);
            }
#endif

            if (_lazySpecialTypes == null || (object)_lazySpecialTypes[(int)type] == null)
            {
                MetadataTypeName emittedName = MetadataTypeName.FromFullName(type.GetMetadataName(), useCLSCompliantNameArityEncoding: true);
                ModuleSymbol module = this.Modules[0];
                NamedTypeSymbol result = module.LookupTopLevelMetadataType(ref emittedName);
                if (result.Kind != SymbolKind.ErrorType && result.DeclaredAccessibility != Accessibility.Public)
                {
                    result = new MissingMetadataTypeSymbol.TopLevel(module, ref emittedName, type);
                }
                RegisterDeclaredSpecialType(result);
            }

            return _lazySpecialTypes[(int)type];
        }
Exemplo n.º 12
0
        protected override string GetPrimitiveTypeName(SpecialType type)
        {
            switch (type)
            {
                case SpecialType.System_Boolean: return "bool";
                case SpecialType.System_Byte: return "byte";
                case SpecialType.System_Char: return "char";
                case SpecialType.System_Decimal: return "decimal";
                case SpecialType.System_Double: return "double";
                case SpecialType.System_Int16: return "short";
                case SpecialType.System_Int32: return "int";
                case SpecialType.System_Int64: return "long";
                case SpecialType.System_SByte: return "sbyte";
                case SpecialType.System_Single: return "float";
                case SpecialType.System_String: return "string";
                case SpecialType.System_UInt16: return "ushort";
                case SpecialType.System_UInt32: return "uint";
                case SpecialType.System_UInt64: return "ulong";
                case SpecialType.System_Object: return "object";

                default:
                    return null;
            }
        }
 private static object CreateOne(SpecialType specialType)
 {
     switch (specialType)
     {
         case SpecialType.System_SByte:
             return (sbyte)1;
         case SpecialType.System_Byte:
             return (byte)1;
         case SpecialType.System_Int16:
             return (short)1;
         case SpecialType.System_UInt16:
             return (ushort)1;
         case SpecialType.System_Int32:
             return (int)1;
         case SpecialType.System_UInt32:
             return (uint)1;
         case SpecialType.System_Int64:
             return (long)1;
         case SpecialType.System_UInt64:
             return (ulong)1;
         default:
             return 1;
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Lookup declaration for predefined CorLib type in this Assembly. Only should be
        /// called if it is know that this is the Cor Library (mscorlib).
        /// </summary>
        /// <param name="type"></param>
        internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type)
        {
#if DEBUG
            foreach (var module in this.Modules)
            {
                Debug.Assert(module.GetReferencedAssemblies().Length == 0);
            }
#endif

            if (_lazySpecialTypes == null)
            {
                Interlocked.CompareExchange(ref _lazySpecialTypes,
                    new NamedTypeSymbol[(int)SpecialType.Count + 1], null);
            }

            if ((object)_lazySpecialTypes[(int)type] == null)
            {
                MetadataTypeName emittedFullName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding: true);
                NamedTypeSymbol corType = new MissingMetadataTypeSymbol.TopLevel(this.moduleSymbol, ref emittedFullName, type);
                Interlocked.CompareExchange(ref _lazySpecialTypes[(int)type], corType, null);
            }

            return _lazySpecialTypes[(int)type];
        }
Exemplo n.º 15
0
 /// <summary>
 /// Lookup declaration for FX type in this Assembly.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 /// <remarks></remarks>
 internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type)
 {
     // Cor library should not have any references and, therefore, should never be
     // wrapped by a RetargetingAssemblySymbol.
     throw ExceptionUtilities.Unreachable;
 }
        internal override int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description)
        {
            if (!IsTargetAttribute(description.Namespace, description.Name))
            {
                return(-1);
            }

            var ctor = this.AttributeConstructor;

            // Ensure that the attribute data really has a constructor before comparing the signature.
            if (ctor is null)
            {
                return(-1);
            }

            // Lazily loaded System.Type type symbol
            TypeSymbol?lazySystemType = null;

            ImmutableArray <ParameterSymbol> parameters = ctor.Parameters;

            for (int signatureIndex = 0; signatureIndex < description.Signatures.Length; signatureIndex++)
            {
                byte[] targetSignature = description.Signatures[signatureIndex];

                if (matches(targetSignature, parameters, ref lazySystemType))
                {
                    return(signatureIndex);
                }
            }

            return(-1);

            bool matches(byte[] targetSignature, ImmutableArray <ParameterSymbol> parameters, ref TypeSymbol?lazySystemType)
            {
                if (targetSignature[0] != (byte)SignatureAttributes.Instance)
                {
                    return(false);
                }

                byte parameterCount = targetSignature[1];

                if (parameterCount != parameters.Length)
                {
                    return(false);
                }

                if ((SignatureTypeCode)targetSignature[2] != SignatureTypeCode.Void)
                {
                    return(false);
                }

                int parameterIndex = 0;

                for (int signatureByteIndex = 3; signatureByteIndex < targetSignature.Length; signatureByteIndex++)
                {
                    if (parameterIndex >= parameters.Length)
                    {
                        return(false);
                    }

                    TypeSymbol  parameterType = parameters[parameterIndex].Type;
                    SpecialType specType      = parameterType.SpecialType;
                    byte        targetType    = targetSignature[signatureByteIndex];

                    if (targetType == (byte)SignatureTypeCode.TypeHandle)
                    {
                        signatureByteIndex++;

                        if (parameterType.Kind != SymbolKind.NamedType && parameterType.Kind != SymbolKind.ErrorType)
                        {
                            return(false);
                        }

                        var namedType = (NamedTypeSymbol)parameterType;
                        AttributeDescription.TypeHandleTargetInfo targetInfo = AttributeDescription.TypeHandleTargets[targetSignature[signatureByteIndex]];

                        // Compare name and containing symbol name. Uses HasNameQualifier
                        // extension method to avoid string allocations.
                        if (!string.Equals(namedType.MetadataName, targetInfo.Name, System.StringComparison.Ordinal) ||
                            !namedType.HasNameQualifier(targetInfo.Namespace))
                        {
                            return(false);
                        }

                        targetType = (byte)targetInfo.Underlying;

                        if (parameterType.IsEnumType())
                        {
                            specType = parameterType.GetEnumUnderlyingType() !.SpecialType;
                        }
                    }
                    else if (targetType != (byte)SignatureTypeCode.SZArray && parameterType.IsArray())
                    {
                        if (targetSignature[signatureByteIndex - 1] != (byte)SignatureTypeCode.SZArray)
                        {
                            return(false);
                        }

                        specType = ((ArrayTypeSymbol)parameterType).ElementType.SpecialType;
                    }

                    switch (targetType)
                    {
                    case (byte)SignatureTypeCode.Boolean:
                        if (specType != SpecialType.System_Boolean)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Char:
                        if (specType != SpecialType.System_Char)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.SByte:
                        if (specType != SpecialType.System_SByte)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Byte:
                        if (specType != SpecialType.System_Byte)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Int16:
                        if (specType != SpecialType.System_Int16)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.UInt16:
                        if (specType != SpecialType.System_UInt16)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Int32:
                        if (specType != SpecialType.System_Int32)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.UInt32:
                        if (specType != SpecialType.System_UInt32)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Int64:
                        if (specType != SpecialType.System_Int64)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.UInt64:
                        if (specType != SpecialType.System_UInt64)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Single:
                        if (specType != SpecialType.System_Single)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Double:
                        if (specType != SpecialType.System_Double)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.String:
                        if (specType != SpecialType.System_String)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.Object:
                        if (specType != SpecialType.System_Object)
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SerializationTypeCode.Type:
                        lazySystemType ??= GetSystemType(targetSymbol);

                        if (!TypeSymbol.Equals(parameterType, lazySystemType, TypeCompareKind.ConsiderEverything))
                        {
                            return(false);
                        }
                        parameterIndex += 1;
                        break;

                    case (byte)SignatureTypeCode.SZArray:
                        // Skip over and check the next byte
                        if (!parameterType.IsArray())
                        {
                            return(false);
                        }
                        break;

                    default:
                        return(false);
                    }
                }

                return(true);
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// Lookup declaration for predefined CorLib type in this Assembly.
 /// </summary>
 /// <returns>The symbol for the pre-defined type or an error type if the type is not defined in the core library.</returns>
 internal abstract NamedTypeSymbol GetDeclaredSpecialType(SpecialType type);
Exemplo n.º 18
0
 /// <summary>
 /// Returns true if the special type is one of the specified special types.
 /// </summary>
 /// <param name="specialType"></param>
 /// <param name="specialType1"></param>
 /// <param name="specialType2"></param>
 /// <param name="specialType3"></param>
 /// <param name="specialType4"></param>
 /// <param name="specialType5"></param>
 internal static bool Is(this SpecialType specialType, SpecialType specialType1, SpecialType specialType2, SpecialType specialType3, SpecialType specialType4, SpecialType specialType5)
 {
     return(specialType == specialType1 ||
            specialType == specialType2 ||
            specialType == specialType3 ||
            specialType == specialType4 ||
            specialType == specialType5);
 }
Exemplo n.º 19
0
 protected void GenerateType(SpecialType specialType)
 {
     GenerateType(SemanticModel.Compilation.GetSpecialType(specialType));
 }
Exemplo n.º 20
0
 protected override void AddExplicitlyCastedLiteralValue(INamedTypeSymbol namedType, SpecialType type, object value)
 {
     _builder.Append(ObjectDisplay.FormatPrimitive(value, ObjectDisplayOptions.None), CodeFileTokenKind.Literal);
 }
Exemplo n.º 21
0
 internal abstract Cci.INamedTypeReference GetSpecialType(SpecialType specialType, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();

            // We need to analyze generated code, but don't intend to report diagnostics for generated code fields.
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);

            context.RegisterCompilationStartAction(
                (compilationContext) =>
            {
                ConcurrentDictionary <IFieldSymbol, UnusedValue> maybeUnreferencedPrivateFields = new ConcurrentDictionary <IFieldSymbol, UnusedValue>();
                ConcurrentDictionary <IFieldSymbol, UnusedValue> referencedPrivateFields        = new ConcurrentDictionary <IFieldSymbol, UnusedValue>();

                ImmutableHashSet <INamedTypeSymbol> specialAttributes = GetSpecialAttributes(compilationContext.Compilation);
                var structLayoutAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesStructLayoutAttribute);

                compilationContext.RegisterSymbolAction(
                    (symbolContext) =>
                {
                    IFieldSymbol field = (IFieldSymbol)symbolContext.Symbol;

                    // Fields of types marked with StructLayoutAttribute with LayoutKind.Sequential should never be flagged as unused as their removal can change the runtime behavior.
                    if (structLayoutAttribute != null && field.ContainingType != null)
                    {
                        foreach (var attribute in field.ContainingType.GetAttributes())
                        {
                            if (structLayoutAttribute.Equals(attribute.AttributeClass.OriginalDefinition) &&
                                attribute.ConstructorArguments.Length == 1)
                            {
                                var argument = attribute.ConstructorArguments[0];
                                if (argument.Type != null)
                                {
                                    SpecialType specialType = argument.Type.TypeKind == TypeKind.Enum ?
                                                              ((INamedTypeSymbol)argument.Type).EnumUnderlyingType.SpecialType :
                                                              argument.Type.SpecialType;

                                    if (DiagnosticHelpers.TryConvertToUInt64(argument.Value, specialType, out ulong convertedLayoutKindValue) &&
                                        convertedLayoutKindValue == (ulong)System.Runtime.InteropServices.LayoutKind.Sequential)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    if (field.DeclaredAccessibility == Accessibility.Private && !referencedPrivateFields.ContainsKey(field))
                    {
                        // Fields with certain special attributes should never be considered unused.
                        if (!specialAttributes.IsEmpty)
                        {
                            foreach (var attribute in field.GetAttributes())
                            {
                                if (specialAttributes.Contains(attribute.AttributeClass.OriginalDefinition))
                                {
                                    return;
                                }
                            }
                        }

                        maybeUnreferencedPrivateFields.TryAdd(field, default);
                    }
                },
                    SymbolKind.Field);

                compilationContext.RegisterOperationAction(
                    (operationContext) =>
                {
                    IFieldSymbol field = ((IFieldReferenceOperation)operationContext.Operation).Field;
                    if (field.DeclaredAccessibility == Accessibility.Private)
                    {
                        referencedPrivateFields.TryAdd(field, default);
                        maybeUnreferencedPrivateFields.TryRemove(field, out _);
                    }
                },
                    OperationKind.FieldReference);

                // Private field reference information reaches a state of consistency as each type symbol completes
                // analysis. Reporting information at the end of each named type provides incremental analysis
                // support inside the IDE.
                compilationContext.RegisterSymbolStartAction(
                    context =>
                {
                    context.RegisterSymbolEndAction(context =>
                    {
                        var namedType = (INamedTypeSymbol)context.Symbol;
                        foreach (var member in namedType.GetMembers())
                        {
                            if (member is not IFieldSymbol field)
                            {
                                continue;
                            }

                            if (!maybeUnreferencedPrivateFields.ContainsKey(field) || referencedPrivateFields.ContainsKey(field))
                            {
                                continue;
                            }

                            context.ReportDiagnostic(field.CreateDiagnostic(Rule, field.Name));
                        }
                    });
                },
                    SymbolKind.NamedType);
            });
        }
Exemplo n.º 23
0
 protected override void AddLiteralValue(SpecialType type, object value)
 {
     _builder.Append(ObjectDisplay.FormatPrimitive(value, ObjectDisplayOptions.None), CodeFileTokenKind.Literal);
 }
Exemplo n.º 24
0
 private void EnsureSpecialType(SpecialType type, DiagnosticBag bag)
 {
     Binder.GetSpecialType(F.Compilation, type, body.Syntax, bag);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Creates a named type symbol that can be used to describe a named type declaration.
        /// </summary>
        public static INamedTypeSymbol CreateNamedTypeSymbol(IList <AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, TypeKind typeKind, string name, IList <ITypeParameterSymbol> typeParameters = null, INamedTypeSymbol baseType = null, IList <INamedTypeSymbol> interfaces = null, SpecialType specialType = SpecialType.None, IList <ISymbol> members = null)
        {
            members = members ?? SpecializedCollections.EmptyList <ISymbol>();

            return(new CodeGenerationNamedTypeSymbol(
                       null, attributes, accessibility, modifiers, typeKind, name,
                       typeParameters, baseType, interfaces, specialType,
                       members.Where(m => !(m is INamedTypeSymbol)).ToList(),
                       members.OfType <INamedTypeSymbol>().Select(n => n.ToCodeGenerationSymbol()).ToList(),
                       enumUnderlyingType: null));
        }
Exemplo n.º 26
0
 protected abstract string GetPrimitiveTypeName(SpecialType type);
Exemplo n.º 27
0
        // process the base list for one part of a partial class, or for the only part of any other type declaration.
        private Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> > MakeOneDeclaredBases(ConsList <TypeSymbol> newBasesBeingResolved, SingleTypeDeclaration decl, DiagnosticBag diagnostics)
        {
            BaseListSyntax bases = GetBaseListOpt(decl);

            if (bases == null)
            {
                return(null);
            }

            NamedTypeSymbol localBase       = null;
            var             localInterfaces = ArrayBuilder <NamedTypeSymbol> .GetInstance();

            var baseBinder = this.DeclaringCompilation.GetBinder(bases);

            // Wrap base binder in a location-specific binder that will avoid generic constraint checks
            // (to avoid cycles if the constraint types are not bound yet). Instead, constraint checks
            // are handled by the caller.
            baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);

            int i = -1;

            foreach (var baseTypeSyntax in bases.Types)
            {
                i++;
                var typeSyntax = baseTypeSyntax.Type;
                if (typeSyntax.Kind() != SyntaxKind.PredefinedType && !SyntaxFacts.IsName(typeSyntax.Kind()))
                {
                    diagnostics.Add(ErrorCode.ERR_BadBaseType, typeSyntax.GetLocation());
                }

                var location = new SourceLocation(typeSyntax);

                TypeSymbol baseType;

                if (i == 0 && TypeKind == TypeKind.Class) // allow class in the first position
                {
                    baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type;

                    SpecialType baseSpecialType = baseType.SpecialType;
                    if (IsRestrictedBaseType(baseSpecialType))
                    {
                        // check for one of the specific exceptions required for compiling mscorlib
                        if (this.SpecialType == SpecialType.System_Enum && baseSpecialType == SpecialType.System_ValueType ||
                            this.SpecialType == SpecialType.System_MulticastDelegate && baseSpecialType == SpecialType.System_Delegate)
                        {
                            // allowed
                        }
                        else if (baseSpecialType == SpecialType.System_Array && this.ContainingAssembly.CorLibrary == this.ContainingAssembly)
                        {
                            // Specific exception for System.ArrayContracts, which is only built when CONTRACTS_FULL is defined.
                            // (See InheritanceResolver::CheckForBaseClassErrors).
                        }
                        else
                        {
                            // '{0}' cannot derive from special class '{1}'
                            diagnostics.Add(ErrorCode.ERR_DeriveFromEnumOrValueType, location, this, baseType);
                            continue;
                        }
                    }

                    if (baseType.IsSealed && !this.IsStatic) // Give precedence to ERR_StaticDerivedFromNonObject
                    {
                        diagnostics.Add(ErrorCode.ERR_CantDeriveFromSealedType, location, this, baseType);
                        continue;
                    }

                    bool baseTypeIsErrorWithoutInterfaceGuess = false;

                    // If baseType is an error symbol and our best guess is that the desired symbol
                    // is an interface, then put baseType in the interfaces list, rather than the
                    // base type slot, to avoid the frustrating scenario where an error message
                    // indicates that the symbol being returned as the base type was elsewhere
                    // interpreted as an interface.
                    if (baseType.TypeKind == TypeKind.Error)
                    {
                        baseTypeIsErrorWithoutInterfaceGuess = true;

                        TypeKind guessTypeKind = baseType.GetNonErrorTypeKindGuess();
                        if (guessTypeKind == TypeKind.Interface)
                        {
                            //base type is an error *with* a guessed interface
                            baseTypeIsErrorWithoutInterfaceGuess = false;
                        }
                    }

                    if ((baseType.TypeKind == TypeKind.Class ||
                         baseType.TypeKind == TypeKind.Delegate ||
                         baseType.TypeKind == TypeKind.Struct ||
                         baseTypeIsErrorWithoutInterfaceGuess) &&
                        ((object)localBase == null))
                    {
                        localBase = (NamedTypeSymbol)baseType;
                        Debug.Assert((object)localBase != null);
                        if (this.IsStatic && localBase.SpecialType != SpecialType.System_Object)
                        {
                            // Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object.
                            var info = diagnostics.Add(ErrorCode.ERR_StaticDerivedFromNonObject, location, this, localBase);
                            localBase = new ExtendedErrorTypeSymbol(localBase, LookupResultKind.NotReferencable, info);
                        }
                        continue;
                    }
                }
                else
                {
                    baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type;
                }

                switch (baseType.TypeKind)
                {
                case TypeKind.Interface:
                    foreach (var t in localInterfaces)
                    {
                        if (TypeSymbol.Equals(t, baseType, TypeCompareKind.ConsiderEverything))
                        {
                            diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceInBaseList, location, baseType);
                            continue;
                        }
                    }

                    if (this.IsStatic)
                    {
                        // '{0}': static classes cannot implement interfaces
                        diagnostics.Add(ErrorCode.ERR_StaticClassInterfaceImpl, location, this, baseType);
                    }

                    if (this.IsRefLikeType)
                    {
                        // '{0}': ref structs cannot implement interfaces
                        diagnostics.Add(ErrorCode.ERR_RefStructInterfaceImpl, location, this, baseType);
                    }

                    if (baseType.ContainsDynamic())
                    {
                        diagnostics.Add(ErrorCode.ERR_DeriveFromConstructedDynamic, location, this, baseType);
                    }

                    localInterfaces.Add((NamedTypeSymbol)baseType);
                    continue;

                case TypeKind.Class:
                    if (TypeKind == TypeKind.Class)
                    {
                        if ((object)localBase == null)
                        {
                            localBase = (NamedTypeSymbol)baseType;
                            diagnostics.Add(ErrorCode.ERR_BaseClassMustBeFirst, location, baseType);
                            continue;
                        }
                        else
                        {
                            diagnostics.Add(ErrorCode.ERR_NoMultipleInheritance, location, this, localBase, baseType);
                            continue;
                        }
                    }
                    goto default;

                case TypeKind.TypeParameter:
                    diagnostics.Add(ErrorCode.ERR_DerivingFromATyVar, location, baseType);
                    continue;

                case TypeKind.Error:
                    // put the error type in the interface list so we don't lose track of it
                    localInterfaces.Add((NamedTypeSymbol)baseType);
                    continue;

                case TypeKind.Dynamic:
                    diagnostics.Add(ErrorCode.ERR_DeriveFromDynamic, location, this);
                    continue;

                case TypeKind.Submission:
                    throw ExceptionUtilities.UnexpectedValue(baseType.TypeKind);

                default:
                    diagnostics.Add(ErrorCode.ERR_NonInterfaceInInterfaceList, location, baseType);
                    continue;
                }
            }

            if (this.SpecialType == SpecialType.System_Object && ((object)localBase != null || localInterfaces.Count != 0))
            {
                var name = GetName(bases.Parent);
                diagnostics.Add(ErrorCode.ERR_ObjectCantHaveBases, new SourceLocation(name));
            }

            return(new Tuple <NamedTypeSymbol, ImmutableArray <NamedTypeSymbol> >(localBase, localInterfaces.ToImmutableAndFree()));
        }
Exemplo n.º 28
0
        public Type Resolve(SpecialType specialType)
        {
            INamedTypeSymbol?typeSymbol = _compilation.GetSpecialType(specialType);

            return(typeSymbol.AsType(this));
        }
        /// <summary>
        /// Get the symbol for the predefined type from the COR Library referenced by this compilation.
        /// </summary>
        internal new NamedTypeSymbol GetSpecialType(SpecialType specialType)
        {
            if (specialType <= SpecialType.None || specialType > SpecialType.Count)
            {
                throw new ArgumentOutOfRangeException("specialType");
            }

            var result = Assembly.GetSpecialType(specialType);
            Debug.Assert(result.SpecialType == specialType);
            return result;
        }
Exemplo n.º 30
0
        private List<Symbol> VerifyEnumsValue(CSharpCompilation comp, string enumName, SpecialType underlyingType, params object[] expectedEnumValues)
        {
            var global = comp.SourceModule.GlobalNamespace;
            var symEnum = GetSymbolByFullName(comp, enumName) as NamedTypeSymbol;
            Assert.NotNull(symEnum);

            var type = symEnum.EnumUnderlyingType;
            Assert.NotNull(type);
            Assert.Equal(underlyingType, type.SpecialType);

            var fields = symEnum.GetMembers().OfType<FieldSymbol>().Cast<Symbol>().ToList();

            Assert.Equal(expectedEnumValues.Length, fields.Count);
            var count = 0;
            foreach (var item in fields)
            {
                var field = item as FieldSymbol;
                Assert.Equal(expectedEnumValues[count++], field.ConstantValue);
            }

            return fields;
        }
Exemplo n.º 31
0
 protected void GenerateNumber(object value, SpecialType specialType)
 {
     GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType));
 }
        private static bool CheckConstantBounds(SpecialType destinationType, double value)
        {
            // Dev10 checks (minValue - 1) < value < (maxValue + 1).
            // See ExpressionBinder::isConstantInRange.
            switch (destinationType)
            {
                case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D);
                case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D);
                case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D);
                case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D);
                case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D);
                case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D);
                case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D);
                case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D);
                // Note: Using <= to compare the min value matches the native compiler.
                case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D);
                case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D);
            }

            return true;
        }
Exemplo n.º 33
0
 /// <summary>
 /// Gets the symbol for the pre-defined type from core library associated with this assembly.
 /// </summary>
 /// <returns>The symbol for the pre-defined type or an error type if the type is not defined in the core library.</returns>
 internal NamedTypeSymbol GetSpecialType(SpecialType type)
 {
     return(CorLibrary.GetDeclaredSpecialType(type));
 }
        private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value)
        {
            // Note that we keep "single" floats as doubles internally to maintain higher precision. However,
            // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose 
            // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on
            // the double values.
            //
            // An example will help. Suppose we have:
            //
            // const float cf1 = 1.0f;
            // const float cf2 = 1.0e-15f;
            // const double cd3 = cf1 - cf2;
            //
            // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats,
            // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction
            // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we
            // do it in doubles and get 0.99999999999999.
            //
            // Similarly, if we have
            //
            // const int i4 = int.MaxValue; // 2147483647
            // const float cf5 = int.MaxValue; //  2147483648.0
            // const double cd6 = cf5; // 2147483648.0
            //
            // The int is converted to float and stored internally as the double 214783648, even though the
            // fully precise int would fit into a double.

            unchecked
            {
                switch (value.Discriminator)
                {
                    case ConstantValueTypeDiscriminator.Byte:
                        byte byteValue = value.ByteValue;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)byteValue;
                            case SpecialType.System_Char: return (char)byteValue;
                            case SpecialType.System_UInt16: return (ushort)byteValue;
                            case SpecialType.System_UInt32: return (uint)byteValue;
                            case SpecialType.System_UInt64: return (ulong)byteValue;
                            case SpecialType.System_SByte: return (sbyte)byteValue;
                            case SpecialType.System_Int16: return (short)byteValue;
                            case SpecialType.System_Int32: return (int)byteValue;
                            case SpecialType.System_Int64: return (long)byteValue;
                            case SpecialType.System_Single:
                            case SpecialType.System_Double: return (double)byteValue;
                            case SpecialType.System_Decimal: return (decimal)byteValue;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.Char:
                        char charValue = value.CharValue;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)charValue;
                            case SpecialType.System_Char: return (char)charValue;
                            case SpecialType.System_UInt16: return (ushort)charValue;
                            case SpecialType.System_UInt32: return (uint)charValue;
                            case SpecialType.System_UInt64: return (ulong)charValue;
                            case SpecialType.System_SByte: return (sbyte)charValue;
                            case SpecialType.System_Int16: return (short)charValue;
                            case SpecialType.System_Int32: return (int)charValue;
                            case SpecialType.System_Int64: return (long)charValue;
                            case SpecialType.System_Single:
                            case SpecialType.System_Double: return (double)charValue;
                            case SpecialType.System_Decimal: return (decimal)charValue;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.UInt16:
                        ushort uint16Value = value.UInt16Value;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)uint16Value;
                            case SpecialType.System_Char: return (char)uint16Value;
                            case SpecialType.System_UInt16: return (ushort)uint16Value;
                            case SpecialType.System_UInt32: return (uint)uint16Value;
                            case SpecialType.System_UInt64: return (ulong)uint16Value;
                            case SpecialType.System_SByte: return (sbyte)uint16Value;
                            case SpecialType.System_Int16: return (short)uint16Value;
                            case SpecialType.System_Int32: return (int)uint16Value;
                            case SpecialType.System_Int64: return (long)uint16Value;
                            case SpecialType.System_Single:
                            case SpecialType.System_Double: return (double)uint16Value;
                            case SpecialType.System_Decimal: return (decimal)uint16Value;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.UInt32:
                        uint uint32Value = value.UInt32Value;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)uint32Value;
                            case SpecialType.System_Char: return (char)uint32Value;
                            case SpecialType.System_UInt16: return (ushort)uint32Value;
                            case SpecialType.System_UInt32: return (uint)uint32Value;
                            case SpecialType.System_UInt64: return (ulong)uint32Value;
                            case SpecialType.System_SByte: return (sbyte)uint32Value;
                            case SpecialType.System_Int16: return (short)uint32Value;
                            case SpecialType.System_Int32: return (int)uint32Value;
                            case SpecialType.System_Int64: return (long)uint32Value;
                            case SpecialType.System_Single: return (double)(float)uint32Value;
                            case SpecialType.System_Double: return (double)uint32Value;
                            case SpecialType.System_Decimal: return (decimal)uint32Value;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.UInt64:
                        ulong uint64Value = value.UInt64Value;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)uint64Value;
                            case SpecialType.System_Char: return (char)uint64Value;
                            case SpecialType.System_UInt16: return (ushort)uint64Value;
                            case SpecialType.System_UInt32: return (uint)uint64Value;
                            case SpecialType.System_UInt64: return (ulong)uint64Value;
                            case SpecialType.System_SByte: return (sbyte)uint64Value;
                            case SpecialType.System_Int16: return (short)uint64Value;
                            case SpecialType.System_Int32: return (int)uint64Value;
                            case SpecialType.System_Int64: return (long)uint64Value;
                            case SpecialType.System_Single: return (double)(float)uint64Value;
                            case SpecialType.System_Double: return (double)uint64Value;
                            case SpecialType.System_Decimal: return (decimal)uint64Value;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.SByte:
                        sbyte sbyteValue = value.SByteValue;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)sbyteValue;
                            case SpecialType.System_Char: return (char)sbyteValue;
                            case SpecialType.System_UInt16: return (ushort)sbyteValue;
                            case SpecialType.System_UInt32: return (uint)sbyteValue;
                            case SpecialType.System_UInt64: return (ulong)sbyteValue;
                            case SpecialType.System_SByte: return (sbyte)sbyteValue;
                            case SpecialType.System_Int16: return (short)sbyteValue;
                            case SpecialType.System_Int32: return (int)sbyteValue;
                            case SpecialType.System_Int64: return (long)sbyteValue;
                            case SpecialType.System_Single:
                            case SpecialType.System_Double: return (double)sbyteValue;
                            case SpecialType.System_Decimal: return (decimal)sbyteValue;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.Int16:
                        short int16Value = value.Int16Value;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)int16Value;
                            case SpecialType.System_Char: return (char)int16Value;
                            case SpecialType.System_UInt16: return (ushort)int16Value;
                            case SpecialType.System_UInt32: return (uint)int16Value;
                            case SpecialType.System_UInt64: return (ulong)int16Value;
                            case SpecialType.System_SByte: return (sbyte)int16Value;
                            case SpecialType.System_Int16: return (short)int16Value;
                            case SpecialType.System_Int32: return (int)int16Value;
                            case SpecialType.System_Int64: return (long)int16Value;
                            case SpecialType.System_Single:
                            case SpecialType.System_Double: return (double)int16Value;
                            case SpecialType.System_Decimal: return (decimal)int16Value;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.Int32:
                        int int32Value = value.Int32Value;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)int32Value;
                            case SpecialType.System_Char: return (char)int32Value;
                            case SpecialType.System_UInt16: return (ushort)int32Value;
                            case SpecialType.System_UInt32: return (uint)int32Value;
                            case SpecialType.System_UInt64: return (ulong)int32Value;
                            case SpecialType.System_SByte: return (sbyte)int32Value;
                            case SpecialType.System_Int16: return (short)int32Value;
                            case SpecialType.System_Int32: return (int)int32Value;
                            case SpecialType.System_Int64: return (long)int32Value;
                            case SpecialType.System_Single: return (double)(float)int32Value;
                            case SpecialType.System_Double: return (double)int32Value;
                            case SpecialType.System_Decimal: return (decimal)int32Value;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.Int64:
                        long int64Value = value.Int64Value;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)int64Value;
                            case SpecialType.System_Char: return (char)int64Value;
                            case SpecialType.System_UInt16: return (ushort)int64Value;
                            case SpecialType.System_UInt32: return (uint)int64Value;
                            case SpecialType.System_UInt64: return (ulong)int64Value;
                            case SpecialType.System_SByte: return (sbyte)int64Value;
                            case SpecialType.System_Int16: return (short)int64Value;
                            case SpecialType.System_Int32: return (int)int64Value;
                            case SpecialType.System_Int64: return (long)int64Value;
                            case SpecialType.System_Single: return (double)(float)int64Value;
                            case SpecialType.System_Double: return (double)int64Value;
                            case SpecialType.System_Decimal: return (decimal)int64Value;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.Single:
                    case ConstantValueTypeDiscriminator.Double:
                        double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue) ? value.DoubleValue : 0D;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)doubleValue;
                            case SpecialType.System_Char: return (char)doubleValue;
                            case SpecialType.System_UInt16: return (ushort)doubleValue;
                            case SpecialType.System_UInt32: return (uint)doubleValue;
                            case SpecialType.System_UInt64: return (ulong)doubleValue;
                            case SpecialType.System_SByte: return (sbyte)doubleValue;
                            case SpecialType.System_Int16: return (short)doubleValue;
                            case SpecialType.System_Int32: return (int)doubleValue;
                            case SpecialType.System_Int64: return (long)doubleValue;
                            case SpecialType.System_Single: return (double)(float)doubleValue;
                            case SpecialType.System_Double: return (double)doubleValue;
                            case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue;
                        }
                        break;
                    case ConstantValueTypeDiscriminator.Decimal:
                        decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue) ? value.DecimalValue : 0m;
                        switch (destinationType)
                        {
                            case SpecialType.System_Byte: return (byte)decimalValue;
                            case SpecialType.System_Char: return (char)decimalValue;
                            case SpecialType.System_UInt16: return (ushort)decimalValue;
                            case SpecialType.System_UInt32: return (uint)decimalValue;
                            case SpecialType.System_UInt64: return (ulong)decimalValue;
                            case SpecialType.System_SByte: return (sbyte)decimalValue;
                            case SpecialType.System_Int16: return (short)decimalValue;
                            case SpecialType.System_Int32: return (int)decimalValue;
                            case SpecialType.System_Int64: return (long)decimalValue;
                            case SpecialType.System_Single: return (double)(float)decimalValue;
                            case SpecialType.System_Double: return (double)decimalValue;
                            case SpecialType.System_Decimal: return (decimal)decimalValue;
                        }
                        break;
                }
            }

            Debug.Assert(false, "Unexpected case in constant folding");
            return value.Value;
        }
Exemplo n.º 35
0
 private static bool IsBaseNumberType(this SpecialType specialType)
 {
     return(specialType >= SpecialType.System_Char && specialType <= SpecialType.System_Double);
 }
 /// <summary>
 /// Returns the predefined keyword kind for a given specialtype.
 /// </summary>
 /// <param name="specialType">The specialtype of this type.</param>
 /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns>
 public static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType)
 {
     switch (specialType)
     {
         case SpecialType.System_Boolean:
             return SyntaxKind.BoolKeyword;
         case SpecialType.System_Byte:
             return SyntaxKind.ByteKeyword;
         case SpecialType.System_SByte:
             return SyntaxKind.SByteKeyword;
         case SpecialType.System_Int32:
             return SyntaxKind.IntKeyword;
         case SpecialType.System_UInt32:
             return SyntaxKind.UIntKeyword;
         case SpecialType.System_Int16:
             return SyntaxKind.ShortKeyword;
         case SpecialType.System_UInt16:
             return SyntaxKind.UShortKeyword;
         case SpecialType.System_Int64:
             return SyntaxKind.LongKeyword;
         case SpecialType.System_UInt64:
             return SyntaxKind.ULongKeyword;
         case SpecialType.System_Single:
             return SyntaxKind.FloatKeyword;
         case SpecialType.System_Double:
             return SyntaxKind.DoubleKeyword;
         case SpecialType.System_Decimal:
             return SyntaxKind.DecimalKeyword;
         case SpecialType.System_String:
             return SyntaxKind.StringKeyword;
         case SpecialType.System_Char:
             return SyntaxKind.CharKeyword;
         case SpecialType.System_Object:
             return SyntaxKind.ObjectKeyword;
         case SpecialType.System_Void:
             return SyntaxKind.VoidKeyword;
         default:
             return SyntaxKind.None;
     }
 }
Exemplo n.º 37
0
        private static string DisplayUnsignedEnumConstant(TypedConstant constant, SpecialType specialType, ulong constantToDecode, string typeName)
        {
            Debug.Assert(constant.Kind == TypedConstantKind.Enum);

            // Specified valueConstant might have an exact matching enum field
            // or it might be a bitwise Or of multiple enum fields.
            // For the later case, we keep track of the current value of
            // bitwise Or of possible enum fields.
            ulong curValue = 0;

            // Initialize the value string to empty
            PooledStringBuilder?pooledBuilder      = null;
            StringBuilder?      valueStringBuilder = null;

            // Iterate through all the constant members in the enum type
            var members = constant.Type !.GetMembers();

            foreach (var member in members)
            {
                var field = member as IFieldSymbol;

                if (field is object && field.HasConstantValue)
                {
                    ConstantValue memberConstant = ConstantValue.Create(field.ConstantValue !, specialType); // use MemberNotNull when available https://github.com/dotnet/roslyn/issues/41964
                    ulong         memberValue    = memberConstant.UInt64Value;

                    // Do we have an exact matching enum field
                    if (memberValue == constantToDecode)
                    {
                        if (pooledBuilder != null)
                        {
                            pooledBuilder.Free();
                        }

                        return(typeName + "." + field.Name);
                    }

                    // specifiedValue might be a bitwise Or of multiple enum fields
                    // Is the current member included in the specified value?
                    if ((memberValue & constantToDecode) == memberValue)
                    {
                        // update the current value
                        curValue = curValue | memberValue;

                        if (valueStringBuilder == null)
                        {
                            pooledBuilder      = PooledStringBuilder.GetInstance();
                            valueStringBuilder = pooledBuilder.Builder;
                        }
                        else
                        {
                            valueStringBuilder.Append(" | ");
                        }

                        valueStringBuilder.Append(typeName);
                        valueStringBuilder.Append(".");
                        valueStringBuilder.Append(field.Name);
                    }
                }
            }

            if (pooledBuilder != null)
            {
                if (curValue == constantToDecode)
                {
                    // return decoded enum constant
                    return(pooledBuilder.ToStringAndFree());
                }

                // Unable to decode the enum constant
                pooledBuilder.Free();
            }

            // Unable to decode the enum constant, just display the integral value
            Debug.Assert(constant.ValueInternal is object);
            var result = constant.ValueInternal.ToString();

            Debug.Assert(result is object);
            return(result);
        }
Exemplo n.º 38
0
        internal static SpecialType GetEnumPromotedType(SpecialType underlyingType)
        {
            switch (underlyingType)
            {
                case SpecialType.System_Byte:
                case SpecialType.System_SByte:
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                    return SpecialType.System_Int32;

                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                    return underlyingType;

                default:
                    throw ExceptionUtilities.UnexpectedValue(underlyingType);
            }
        }
Exemplo n.º 39
0
 public SpecialCard(SpecialType type, SpecialEffect effect)
 {
     Type   = type;
     Effect = effect;
 }
Exemplo n.º 40
0
        // Returns null if the operator can't be evaluated at compile time.
        private ConstantValue FoldBinaryOperator(
            CSharpSyntaxNode syntax,
            BinaryOperatorKind kind,
            BoundExpression left,
            BoundExpression right,
            SpecialType resultType,
            DiagnosticBag diagnostics,
            ref int compoundStringLength)
        {
            Debug.Assert(left != null);
            Debug.Assert(right != null);

            if (left.HasAnyErrors || right.HasAnyErrors)
            {
                return null;
            }

            // SPEC VIOLATION: see method definition for details
            ConstantValue nullableEqualityResult = TryFoldingNullableEquality(kind, left, right);
            if (nullableEqualityResult != null)
            {
                return nullableEqualityResult;
            }

            var valueLeft = left.ConstantValue;
            var valueRight = right.ConstantValue;
            if (valueLeft == null || valueRight == null)
            {
                return null;
            }

            if (valueLeft.IsBad || valueRight.IsBad)
            {
                return ConstantValue.Bad;
            }

            if (kind.IsEnum() && !kind.IsLifted())
            {
                return FoldEnumBinaryOperator(syntax, kind, left, right, diagnostics);
            }

            // Divisions by zero on integral types and decimal always fail even in an unchecked context.
            if (IsDivisionByZero(kind, valueRight))
            {
                Error(diagnostics, ErrorCode.ERR_IntDivByZero, syntax);
                return ConstantValue.Bad;
            }

            object newValue = null;

            // Certain binary operations never fail; bool & bool, for example. If we are in one of those
            // cases, simply fold the operation and return.
            //
            // Although remainder and division always overflow at runtime with arguments int.MinValue/long.MinValue and -1 
            // (regardless of checked context) the constant folding behavior is different. 
            // Remainder never overflows at compile time while division does.
            newValue = FoldNeverOverflowBinaryOperators(kind, valueLeft, valueRight);
            if (newValue != null)
            {
                return ConstantValue.Create(newValue, resultType);
            }

            ConstantValue concatResult = FoldStringConcatenation(kind, valueLeft, valueRight, ref compoundStringLength);
            if (concatResult != null)
            {
                if (concatResult.IsBad)
                {
                    Error(diagnostics, ErrorCode.ERR_ConstantStringTooLong, syntax);
                }

                return concatResult;
            }

            // Certain binary operations always fail if they overflow even when in an unchecked context;
            // decimal + decimal, for example. If we are in one of those cases, make the attempt. If it
            // succeeds, return the result. If not, give a compile-time error regardless of context.
            try
            {
                newValue = FoldDecimalBinaryOperators(kind, valueLeft, valueRight);
            }
            catch (OverflowException)
            {
                Error(diagnostics, ErrorCode.ERR_DecConstError, syntax);
                return ConstantValue.Bad;
            }

            if (newValue != null)
            {
                return ConstantValue.Create(newValue, resultType);
            }

            if (CheckOverflowAtCompileTime)
            {
                try
                {
                    newValue = FoldCheckedIntegralBinaryOperator(kind, valueLeft, valueRight);
                }
                catch (OverflowException)
                {
                    Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax);
                    return ConstantValue.Bad;
                }
            }
            else
            {
                newValue = FoldUncheckedIntegralBinaryOperator(kind, valueLeft, valueRight);
            }

            if (newValue != null)
            {
                return ConstantValue.Create(newValue, resultType);
            }

            return null;
        }
 public static int FixedBufferElementSizeInBytes(this SpecialType specialType)
 {
     // SizeInBytes() handles decimal (contrary to the language spec).  But decimal is not allowed
     // as a fixed buffer element type.
     return(specialType == SpecialType.System_Decimal ? 0 : specialType.SizeInBytes());
 }
Exemplo n.º 42
0
        private static string DisplayUnsignedEnumConstant(TypedConstant constant, SpecialType specialType, ulong constantToDecode, string typeName)
        {
            // Specified valueConstant might have an exact matching enum field
            // or it might be a bitwise Or of multiple enum fields.
            // For the later case, we keep track of the current value of
            // bitwise Or of possible enum fields.
            ulong curValue = 0;

            // Initialize the value string to empty
            PooledStringBuilder pooledBuilder      = null;
            StringBuilder       valueStringBuilder = null;

            // Iterate through all the constant members in the enum type
            var members = constant.Type.GetMembers();

            foreach (var member in members)
            {
                var field = member as IFieldSymbol;

                if ((object)field != null && field.HasConstantValue)
                {
                    ConstantValue memberConstant = ConstantValue.Create(field.ConstantValue, specialType);
                    ulong         memberValue    = memberConstant.UInt64Value;

                    // Do we have an exact matching enum field
                    if (memberValue == constantToDecode)
                    {
                        if (pooledBuilder != null)
                        {
                            pooledBuilder.Free();
                        }

                        return(typeName + "." + field.Name);
                    }

                    // specifiedValue might be a bitwise Or of multiple enum fields
                    // Is the current member included in the specified value?
                    if ((memberValue & constantToDecode) == memberValue)
                    {
                        // update the current value
                        curValue = curValue | memberValue;

                        if (valueStringBuilder == null)
                        {
                            pooledBuilder      = PooledStringBuilder.GetInstance();
                            valueStringBuilder = pooledBuilder.Builder;
                        }
                        else
                        {
                            valueStringBuilder.Append(" | ");
                        }

                        valueStringBuilder.Append(typeName);
                        valueStringBuilder.Append(".");
                        valueStringBuilder.Append(field.Name);
                    }
                }
            }

            if (pooledBuilder != null)
            {
                if (curValue == constantToDecode)
                {
                    // return decoded enum constant
                    return(pooledBuilder.ToStringAndFree());
                }

                // Unable to decode the enum constant
                pooledBuilder.Free();
            }

            // Unable to decode the enum constant, just display the integral value
            return(constant.Value.ToString());
        }
 private static Func<Symbol, bool> IsPropertyWithSingleParameter(SpecialType paramSpecialType, bool isArrayType = false)
 {
     return s =>
     {
         if (s.Kind != SymbolKind.Property)
         {
             return false;
         }
         var paramType = s.GetParameters().Single().Type;
         var comparisonType = isArrayType ? ((ArrayTypeSymbol)paramType).ElementType : paramType;
         return comparisonType.SpecialType == paramSpecialType;
     };
 }
Exemplo n.º 44
0
 private KnownType(string typeName)
 {
     TypeName      = typeName;
     specialType   = SpecialType.None;
     isSpecialType = false;
 }
        public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value)
        {
            if (value.IsBad)
            {
                //assume that the constant was intended to be in bounds
                return true;
            }

            // Compute whether the value fits into the bounds of the given destination type without
            // error. We know that the constant will fit into either a double or a decimal, so
            // convert it to one of those and then check the bounds on that.
            var canonicalValue = CanonicalizeConstant(value);
            return canonicalValue is decimal ?
                CheckConstantBounds(destinationType, (decimal)canonicalValue) :
                CheckConstantBounds(destinationType, (double)canonicalValue);
        }
Exemplo n.º 46
0
 private KnownType(SpecialType specialType, string typeName)
 {
     TypeName         = typeName;
     this.specialType = specialType;
     isSpecialType    = true;
 }
        private static bool CheckConstantBounds(SpecialType destinationType, decimal value)
        {
            // Dev10 checks (minValue - 1) < value < (MaxValue + 1) + 1).
            // See ExpressionBinder::isConstantInRange.
            switch (destinationType)
            {
                case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M);
                case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M);
                case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M);
                case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M);
                case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M);
                case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M);
                case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M);
                case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M);
                case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M);
            }

            return true;
        }
Exemplo n.º 48
0
 internal bool Matches(SpecialType type)
 {
     return(isSpecialType && specialType == type);
 }
Exemplo n.º 49
0
 public NamedTypeSymbol SpecialType(SpecialType st)
 {
     NamedTypeSymbol specialType = Compilation.GetSpecialType(st);
     Binder.ReportUseSiteDiagnostics(specialType, Diagnostics, Syntax);
     return specialType;
 }
Exemplo n.º 50
0
        // http://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table
        public static bool IsImplicitNumericConversion(SpecialType from, SpecialType to)
        {
            switch (from)
            {
            case SpecialType.System_Char:
            {
                switch (to)
                {
                case SpecialType.System_UInt16:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_SByte:
            {
                switch (to)
                {
                case SpecialType.System_Int16:
                case SpecialType.System_Int32:
                case SpecialType.System_Int64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_Byte:
            {
                switch (to)
                {
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_Int16:
            {
                switch (to)
                {
                case SpecialType.System_Int32:
                case SpecialType.System_Int64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_UInt16:
            {
                switch (to)
                {
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_Int32:
            {
                switch (to)
                {
                case SpecialType.System_Int64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_UInt32:
            {
                switch (to)
                {
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_Int64:
            case SpecialType.System_UInt64:
            {
                switch (to)
                {
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                case SpecialType.System_Decimal:
                    return(true);
                }

                break;
            }

            case SpecialType.System_Single:
            {
                switch (to)
                {
                case SpecialType.System_Double:
                    return(true);
                }

                break;
            }
            }

            return(false);
        }
Exemplo n.º 51
0
 public abstract string GetPrimitiveTypeName(SpecialType type);
Exemplo n.º 52
0
 CoreType Create(SpecialType type) => CreateFromFullName(SpecialTypes.GetMetadataName(type));
Exemplo n.º 53
0
 // Returns null if the operator can't be evaluated at compile time.
 private ConstantValue FoldBinaryOperator(
     CSharpSyntaxNode syntax,
     BinaryOperatorKind kind,
     BoundExpression left,
     BoundExpression right,
     SpecialType resultType,
     DiagnosticBag diagnostics)
 {
     int compoundStringLength = 0;
     return FoldBinaryOperator(syntax, kind, left, right, resultType, diagnostics, ref compoundStringLength);
 }
Exemplo n.º 54
0
        public static ConstantValue CreateSizeOf(SpecialType st)
        {
            int size = st.SizeInBytes();

            return((size == 0) ? ConstantValue.NotAvailable : ConstantValue.Create(size));
        }
Exemplo n.º 55
0
        private ConstantValue FoldUnaryOperator(
            CSharpSyntaxNode syntax,
            UnaryOperatorKind kind,
            BoundExpression operand,
            SpecialType resultType,
            DiagnosticBag diagnostics)
        {
            Debug.Assert(operand != null);
            // UNDONE: report errors when in a checked context.

            if (operand.HasAnyErrors)
            {
                return null;
            }

            var value = operand.ConstantValue;
            if (value == null || value.IsBad)
            {
                return value;
            }

            if (kind.IsEnum() && !kind.IsLifted())
            {
                return FoldEnumUnaryOperator(syntax, kind, operand, diagnostics);
            }

            var newValue = FoldNeverOverflowUnaryOperator(kind, value);
            if (newValue != null)
            {
                return ConstantValue.Create(newValue, resultType);
            }

            if (CheckOverflowAtCompileTime)
            {
                try
                {
                    newValue = FoldCheckedIntegralUnaryOperator(kind, value);
                }
                catch (OverflowException)
                {
                    Error(diagnostics, ErrorCode.ERR_CheckedOverflow, syntax);
                    return ConstantValue.Bad;
                }
            }
            else
            {
                newValue = FoldUncheckedIntegralUnaryOperator(kind, value);
            }

            if (newValue != null)
            {
                return ConstantValue.Create(newValue, resultType);
            }

            return null;
        }
 protected override void AddExplicitlyCastedLiteralValue(INamedTypeSymbol namedType, SpecialType type, object value)
 {
     AddPunctuation(SyntaxKind.OpenParenToken);
     namedType.Accept(this.NotFirstVisitor);
     AddPunctuation(SyntaxKind.CloseParenToken);
     AddLiteralValue(type, value);
 }
Exemplo n.º 57
0
 private static bool IsZeroValueConstant(object value, SpecialType specialType)
 {
     ulong convertedValue;
     return DiagnosticHelpers.TryConvertToUInt64(value, specialType, out convertedValue) && convertedValue == 0;
 }
Exemplo n.º 58
0
 /// <summary>
 /// Get the symbol for the predefined type from the Cor Library referenced by this
 /// compilation.
 /// </summary>
 internal new NamedTypeSymbol GetSpecialType(SpecialType specialType)
 {
     return((NamedTypeSymbol)CommonGetSpecialType(specialType));
 }
 protected override INamedTypeSymbol CommonGetSpecialType(SpecialType specialType)
 {
     return this.GetSpecialType(specialType);
 }
Exemplo n.º 60
0
 /// <summary>
 /// Returns true if the special type is one of the specified special types.
 /// </summary>
 /// <param name="specialType"></param>
 /// <param name="specialType1"></param>
 /// <param name="specialType2"></param>
 internal static bool Is(this SpecialType specialType, SpecialType specialType1, SpecialType specialType2)
 {
     return(specialType == specialType1 ||
            specialType == specialType2);
 }