Example #1
0
        private void ResolveTypesInVariableDeclaration(
            VariableDeclarationStatementSyntax variableDeclaration)
        {
            InferExpressionType(variableDeclaration.Initializer);

            DataType type;

            if (variableDeclaration.TypeExpression != null)
            {
                type = CheckAndEvaluateTypeExpression(variableDeclaration.TypeExpression);
            }
            else if (variableDeclaration.Initializer != null)
            {
                type = variableDeclaration.Initializer.Type;
                // Use the initializer type unless it is constant
                switch (type)
                {
                case IntegerConstantType integerConstant:
                    var value     = integerConstant.Value;
                    var byteCount = value.GetByteCount();
                    type = byteCount <= 4 ? DataType.Int : DataType.Int64;
                    break;

                case StringConstantType stringConstant:
                    throw new NotImplementedException();
                }
            }
            else
            {
                diagnostics.Add(TypeError.NotImplemented(file, variableDeclaration.NameSpan,
                                                         "Inference of local variable types not implemented"));
                type = DataType.Unknown;
            }

            variableDeclaration.Type = type;
            if (variableDeclaration.Initializer != null)
            {
                InsertImplicitConversionIfNeeded(ref variableDeclaration.Initializer, type);
                var initializerType = variableDeclaration.Initializer.Type;
                if (!IsAssignableFrom(type, initializerType))
                {
                    diagnostics.Add(TypeError.CannotConvert(file, variableDeclaration.Initializer, initializerType, type));
                }
            }
        }