Beispiel #1
0
        protected virtual TypeSymbol BuildReturnType(Signature signature, TypeRef tref, PHPDocBlock phpdocOpt, TypeRefMask rtype)
        {
            if (signature.AliasReturn)
            {
                return(DeclaringCompilation.CoreTypes.PhpAlias);
            }

            // PHP7 return type
            if (tref != null)
            {
                return(DeclaringCompilation.GetTypeFromTypeRef(tref));
            }

            //
            var typeCtx = this.TypeRefContext;

            //
            if (phpdocOpt != null && (DeclaringCompilation.Options.PhpDocTypes & PhpDocTypes.ReturnTypes) != 0)
            {
                var returnTag = phpdocOpt.Returns;
                if (returnTag != null && returnTag.TypeNames.Length != 0)
                {
                    var tmask = PHPDoc.GetTypeMask(typeCtx, returnTag.TypeNamesArray, this.GetNamingContext());
                    if (!tmask.IsVoid && !tmask.IsAnyType)
                    {
                        return(DeclaringCompilation.GetTypeFromTypeRef(typeCtx, tmask));
                    }
                }
            }

            //
            return(DeclaringCompilation.GetTypeFromTypeRef(typeCtx, rtype));
        }
        IEnumerable <Cci.IMethodDefinition> Cci.ITypeDefinition.GetMethods(EmitContext context)
        {
            CheckDefinitionInvariant();

            // All constructors in attributes should be emitted.
            // Don't compute IsAttributeType if IncludePrivateMembers is true, as we'll include it anyway.
            bool alwaysIncludeConstructors = context.IncludePrivateMembers || DeclaringCompilation.IsAttributeType(this);

            foreach (var method in this.GetMethodsToEmit())
            {
                Debug.Assert((object)method != null);
                if ((alwaysIncludeConstructors && method.MethodKind == MethodKind.Constructor) || method.ShouldInclude(context))
                {
                    yield return(method);
                }
            }

            IEnumerable <Cci.IMethodDefinition> generated = ((PEModuleBuilder)context.Module).GetSynthesizedMethods(this);

            if (generated != null)
            {
                foreach (var m in generated)
                {
                    if ((alwaysIncludeConstructors && m.IsConstructor) || m.ShouldInclude(context))
                    {
                        yield return(m);
                    }
                }
            }
        }
Beispiel #3
0
 private void AfterMembersChecks(DiagnosticBag diagnostics)
 {
     if (EmitNullablePublicOnlyAttribute)
     {
         DeclaringCompilation.EnsureNullablePublicOnlyAttributeExists(diagnostics, location: NoLocation.Singleton, modifyCompilation: true);
     }
 }
Beispiel #4
0
        internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder <SynthesizedAttributeData> attributes)
        {
            base.AddSynthesizedAttributes(moduleBuilder, ref attributes);

            var type = this.Type;

            if (type.TypeSymbol.ContainsDynamic())
            {
                AddSynthesizedAttribute(ref attributes,
                                        DeclaringCompilation.SynthesizeDynamicAttribute(type.TypeSymbol, Type.CustomModifiers.Length));
            }

            if (type.TypeSymbol.ContainsTupleNames())
            {
                AddSynthesizedAttribute(ref attributes,
                                        DeclaringCompilation.SynthesizeTupleNamesAttribute(type.TypeSymbol));
            }

            AddSynthesizedNonNullTypesAttributeForMember(ref attributes);

            if (type.ContainsNullableReferenceTypes())
            {
                AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttribute(this, type));
            }
        }
Beispiel #5
0
        private void SetLazyConstantValue(
            ConstantValue value,
            bool earlyDecodingWellKnownAttributes,
            DiagnosticBag diagnostics,
            bool startsCycle)
        {
            Debug.Assert(value != Microsoft.CodeAnalysis.ConstantValue.Unset);
            Debug.Assert((GetLazyConstantValue(earlyDecodingWellKnownAttributes) == Microsoft.CodeAnalysis.ConstantValue.Unset) ||
                         (GetLazyConstantValue(earlyDecodingWellKnownAttributes) == value));

            if (earlyDecodingWellKnownAttributes)
            {
                Interlocked.CompareExchange(ref _lazyConstantEarlyDecodingValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset);
            }
            else
            {
                if (Interlocked.CompareExchange(ref _lazyConstantValue, value, Microsoft.CodeAnalysis.ConstantValue.Unset) == Microsoft.CodeAnalysis.ConstantValue.Unset)
                {
#if REPORT_ALL
                    Console.WriteLine("Thread {0}, Field {1}, StartsCycle {2}", Thread.CurrentThread.ManagedThreadId, this, startsCycle);
#endif
                    this.AddDeclarationDiagnostics(diagnostics);
                    // CompletionPart.ConstantValue is the last part for a field
                    DeclaringCompilation.SymbolDeclaredEvent(this);
                    var wasSetThisThread = this.state.NotePartComplete(CompletionPart.ConstantValue);
                    Debug.Assert(wasSetThisThread);
                }
            }
        }
Beispiel #6
0
        NamedTypeSymbol ResolveBaseType(DiagnosticBag diagnostics)
        {
            NamedTypeSymbol btype;

            if (_syntax.BaseClass != null)
            {
                var baseTypeName = _syntax.BaseClass.ClassName;
                if (baseTypeName == this.MakeQualifiedName())
                {
                    // TODO: Err diagnostics
                    throw new NotImplementedException($"cycle in class hierarchy, {this.MakeQualifiedName()} extends itself.");
                }

                btype = (NamedTypeSymbol)DeclaringCompilation.GetTypeByMetadataName(baseTypeName.ClrName())
                        ?? new MissingMetadataTypeSymbol(baseTypeName.ClrName(), 0, false);

                if (btype.Arity != 0)
                {
                    // TODO: Err diagnostics
                    throw new NotImplementedException($"Class {this.MakeQualifiedName()} extends a generic type {baseTypeName}.");    // generics not supported yet
                }
            }
            else if (!IsStatic && !IsInterface)
            {
                btype = DeclaringCompilation.CoreTypes.Object.Symbol;
            }
            else
            {
                btype = null;
            }

            //
            return(btype);
        }
Beispiel #7
0
        public override ImmutableArray <AttributeData> GetAttributes()
        {
            var attrs = _customAttributes;

            // attributes from syntax node
            if (attrs.IsDefaultOrEmpty)
            {
                attrs = ImmutableArray <AttributeData> .Empty;
            }
            else
            {
                // initialize attribute data if necessary:
                attrs
                .OfType <SourceCustomAttribute>()
                .ForEach(x => x.Bind(this, _containingType.ContainingFile));
            }

            // attributes from PHPDoc
            if (_phpDoc != null)
            {
                var deprecated = _phpDoc.GetElement <PHPDocBlock.DeprecatedTag>();
                if (deprecated != null)
                {
                    // [ObsoleteAttribute(message, false)]
                    attrs = attrs.Add(DeclaringCompilation.CreateObsoleteAttribute(deprecated));
                }

                // ...
            }


            //
            return(attrs);
        }
Beispiel #8
0
 private void CheckUnmanagedConstraint(DiagnosticBag diagnostics)
 {
     if (this.HasUnmanagedTypeConstraint)
     {
         DeclaringCompilation.EnsureIsUnmanagedAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding());
     }
 }
 public override ImmutableArray <AttributeData> GetAttributes()
 {
     // [CompilerGenerated]
     return(ImmutableArray.Create <AttributeData>(
                DeclaringCompilation.CreateCompilerGeneratedAttribute()
                ));
 }
Beispiel #10
0
        internal override ImmutableArray <NamedTypeSymbol> GetDeclaredInterfaces(ConsList <Symbol> basesBeingResolved)
        {
            var ifaces = new HashSet <NamedTypeSymbol>();

            foreach (var i in _syntax.ImplementsList)
            {
                var t = (NamedTypeSymbol)DeclaringCompilation.GetTypeByMetadataName(i.ClassName.ClrName())
                        ?? new MissingMetadataTypeSymbol(i.ClassName.ClrName(), 0, false);

                if (t.Arity != 0)
                {
                    throw new NotImplementedException();    // generics
                }

                ifaces.Add(t);
            }

            // __invoke => IPhpCallable
            if (IsInvokable)
            {
                ifaces.Add(DeclaringCompilation.CoreTypes.IPhpCallable);
            }

            //
            return(ifaces.AsImmutable());
        }
Beispiel #11
0
        public SourceFieldSymbol(
            SourceTypeSymbol type, string name, Location location, Accessibility accessibility,
            PHPDocBlock phpdoc, PhpPropertyKind kind,
            BoundExpression initializer = null,
            ImmutableArray <AttributeData> attributes = default)
        {
            Contract.ThrowIfNull(type);
            Contract.ThrowIfNull(name);

            _containingType = type;
            _fieldName      = name;
            _fieldKind      = kind;
            _accessibility  = accessibility;
            _initializer    = initializer;
            _location       = location;
            _attributes     = attributes.IsDefault ? ImmutableArray <AttributeData> .Empty : attributes;
            PHPDocBlock     = phpdoc;

            // implicit attributes from PHPDoc
            var deprecated = phpdoc?.GetElement <PHPDocBlock.DeprecatedTag>();

            if (deprecated != null)
            {
                // [ObsoleteAttribute(message, false)]
                _attributes = _attributes.Add(DeclaringCompilation.CreateObsoleteAttribute(deprecated));
            }
        }
Beispiel #12
0
 private void CheckNullableAnnotationsInConstraints(DiagnosticBag diagnostics)
 {
     if (ConstraintsNeedNullableAttribute())
     {
         DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding());
     }
 }
        internal override IEnumerable <AttributeData> GetCustomAttributesToEmit(CommonModuleCompilationState compilationState)
        {
            // [param]
            if (IsParams)
            {
                yield return(DeclaringCompilation.CreateParamsAttribute());
            }

            // [Nullable(1)] - does not return null
            if (HasNotNull && Type.IsReferenceType)
            {
                yield return(DeclaringCompilation.CreateNullableAttribute(NullableContextUtils.NotAnnotatedAttributeValue));
            }

            // [DefaultValue]
            if (DefaultValueField != null)
            {
                yield return(DeclaringCompilation.CreateDefaultValueAttribute(ContainingType, DefaultValueField));
            }

            //
            foreach (var attr in GetAttributes())
            {
                yield return(attr);
            }
        }
Beispiel #14
0
        internal void GetDeclarationDiagnostics(DiagnosticBag addTo)
        {
            // Force complete type parameters
            foreach (var typeParam in _typeParameters)
            {
                typeParam.ForceComplete(null, default(CancellationToken));
            }

            // force lazy init
            ComputeParameters();

            foreach (var p in _lazyParameters)
            {
                // Force complete parameters to retrieve all diagnostics
                p.ForceComplete(null, default(CancellationToken));
            }

            ComputeReturnType();

            GetAttributes();
            GetReturnTypeAttributes();

            AsyncMethodChecks(_declarationDiagnostics);

            addTo.AddRange(_declarationDiagnostics);

            if (IsEntryPointCandidate && !IsGenericMethod &&
                ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol &&
                DeclaringCompilation.HasEntryPointSignature(this, new DiagnosticBag()).IsCandidate)
            {
                addTo.Add(ErrorCode.WRN_MainIgnored, Syntax.Identifier.GetLocation(), this);
            }
        }
Beispiel #15
0
        protected virtual TypeSymbol BuildReturnType(Signature signature, PHPDocBlock phpdocOpt, TypeRefMask return_tmask)
        {
            if (signature.AliasReturn)
            {
                return(DeclaringCompilation.CoreTypes.PhpAlias);
            }

            // TODO: PHP7 return type
            //signature.ReturnTypeHint

            //
            if (phpdocOpt != null)
            {
                var returnTag = phpdocOpt.Returns;
                if (returnTag != null && returnTag.TypeNames.Length != 0)
                {
                    var typeCtx = this.TypeRefContext;
                    var tmask   = PHPDoc.GetTypeMask(typeCtx, returnTag.TypeNamesArray);
                    if (!tmask.IsVoid && !tmask.IsAnyType)
                    {
                        return(DeclaringCompilation.GetTypeFromTypeRef(typeCtx, tmask));
                    }
                }
            }

            //
            return(DeclaringCompilation.GetTypeFromTypeRef(this.TypeRefContext, return_tmask));
        }
Beispiel #16
0
        internal void ComputeReturnType()
        {
            if (!_lazyReturnType.IsDefault)
            {
                return;
            }

            var        diagnostics               = DiagnosticBag.GetInstance();
            TypeSyntax returnTypeSyntax          = _syntax.ReturnType;
            TypeSymbolWithAnnotations returnType = _binder.BindType(returnTypeSyntax.SkipRef(), diagnostics);

            if (this.IsAsync)
            {
                if (this.RefKind != RefKind.None)
                {
                    ReportBadRefToken(returnTypeSyntax, diagnostics);
                }
                else if (returnType.TypeSymbol.IsBadAsyncReturn(this.DeclaringCompilation))
                {
                    diagnostics.Add(ErrorCode.ERR_BadAsyncReturn, this.Locations[0]);
                }
            }

            var location = _syntax.ReturnType.Location;

            if (_refKind == RefKind.RefReadOnly)
            {
                DeclaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: false);
            }

            if (returnType.NeedsNullableAttribute())
            {
                DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: false);
                // Note: we don't need to warn on annotations used without NonNullTypes context for local functions, as this is handled in binding already
            }

            // span-like types are returnable in general
            if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true))
            {
                // Method or delegate cannot return type '{0}'
                diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.TypeSymbol);
            }

            Debug.Assert(_refKind == RefKind.None ||
                         returnType.SpecialType != SpecialType.System_Void ||
                         returnTypeSyntax.HasErrors);

            lock (_declarationDiagnostics)
            {
                if (!_lazyReturnType.IsDefault)
                {
                    diagnostics.Free();
                    return;
                }

                _declarationDiagnostics.AddRangeAndFree(diagnostics);
                _lazyReturnType = returnType;
            }
        }
Beispiel #17
0
        /// <summary>
        /// Emits expression and converts it to required type.
        /// </summary>
        public void EmitConvert(BoundExpression expr, TypeSymbol to)
        {
            Debug.Assert(expr != null);
            Debug.Assert(to != null);

            // pop effectively
            if (to.IsVoid())
            {
                expr.Access = BoundAccess.None;

                if (!expr.IsConstant())
                {
                    // POP LOAD <expr>
                    EmitPop(Emit(expr));
                }

                return;
            }

            // bind target expression type
            expr.Access = expr.Access.WithRead(to);

            if (!expr.Access.IsReadRef)
            {
                // constants
                if (expr.ConstantValue.HasValue && to != null)
                {
                    EmitConvert(EmitLoadConstant(expr.ConstantValue.Value, to), 0, to);
                    return;
                }

                // loads value from place most effectively without runtime type checking
                var place = PlaceOrNull(expr);
                if (place != null && place.Type != to)
                {
                    var type = TryEmitVariableSpecialize(place, expr.TypeRefMask);
                    if (type != null)
                    {
                        EmitConvert(type, 0, to);
                        return;
                    }
                }

                // avoiding of load of full value
                if (place != null && place.HasAddress && place.Type != null && place.Type.IsValueType)
                {
                    var conv = DeclaringCompilation.ClassifyCommonConversion(place.Type, to);
                    if (conv.Exists && conv.IsUserDefined && !conv.MethodSymbol.IsStatic)
                    {
                        // (ADDR expr).Method()
                        this.EmitImplicitConversion(EmitCall(ILOpCode.Call, (MethodSymbol)conv.MethodSymbol, expr, ImmutableArray <BoundArgument> .Empty), to, @checked: true);
                        return;
                    }
                }
            }

            //
            EmitConvert(expr.Emit(this), expr.TypeRefMask, to);
        }
Beispiel #18
0
 internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics)
 {
     var location = ErrorLocation;
     if (this.Type.NeedsNullableAttribute())
     {
         DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
     }
 }
Beispiel #19
0
 private void CheckNullableAnnotationsInConstraints(DiagnosticBag diagnostics)
 {
     if ((this.HasReferenceTypeConstraint && this.ReferenceTypeConstraintIsNullable != null) ||
         this.ConstraintTypesNoUseSiteDiagnostics.Any(c => c.NeedsNullableAttribute()))
     {
         DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding());
     }
 }
        TypeSymbol ResolveType()
        {
            if (IsThis)
            {
                // <this> parameter
                if (_routine is SourceGlobalMethodSymbol)
                {
                    // "AnyType" in case of $this in global scope
                    return(DeclaringCompilation.CoreTypes.PhpValue);
                }

                return(ContainingType);
            }

            //return DeclaringCompilation.GetTypeFromTypeRef(_routine, _routine.ControlFlowGraph.GetParamTypeMask(this));

            // determine parameter type from the signature:

            // aliased parameter:
            if (_syntax.IsOut || _syntax.PassedByRef)
            {
                return(DeclaringCompilation.CoreTypes.PhpAlias);
            }

            // 1. specified type hint
            var typehint = new Utilities.TypeHintValue(_syntax.TypeHint);
            var result   = typehint.AsTypeSymbol(DeclaringCompilation);

            // 2. optionally type specified in PHPDoc
            if (result == null && _ptagOpt != null && _ptagOpt.TypeNamesArray.Length != 0)
            {
                var typectx = _routine.TypeRefContext;
                var tmask   = FlowAnalysis.PHPDoc.GetTypeMask(typectx, _ptagOpt.TypeNamesArray);
                if (!tmask.IsVoid && !tmask.IsAnyType)
                {
                    result = DeclaringCompilation.GetTypeFromTypeRef(typectx, tmask);
                }
            }

            // 3 default:
            if (result == null)
            {
                // TODO: use type from overriden method

                result = DeclaringCompilation.CoreTypes.PhpValue;
            }

            // variadic (result[])
            if (_syntax.IsVariadic)
            {
                // result = ArraySZSymbol.FromElement(result);
                throw new NotImplementedException();
            }

            //
            return(result);
        }
        public override ImmutableArray <AttributeData> GetAttributes()
        {
            // [CompilerGenerated]
            var compilergenerated = (MethodSymbol)DeclaringCompilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor);

            return(base.GetAttributes().Add(
                       new SynthesizedAttributeData(compilergenerated, ImmutableArray <TypedConstant> .Empty, ImmutableArray <KeyValuePair <string, TypedConstant> > .Empty)
                       ));
        }
Beispiel #22
0
            public SyntaxTree AddSource(GeneratedSourceText sourceText)
            {
                var compilation = DeclaringCompilation as CSharpCompilation ?? throw new NotSupportedException("Non C# compilation is not supported");
                var syntax      = CSharpSyntaxTree.ParseText(sourceText.SourceText, new CSharpParseOptions(compilation.LanguageVersion), cancellationToken: Parent._context.OnOperationCanceled);

                DeclaringCompilation = DeclaringCompilation.AddSyntaxTrees(syntax);
                GeneratedSourceTexts.Add(sourceText);
                return(syntax);
            }
        void EmitToString(Emit.PEModuleBuilder module)
        {
            if (this.IsInterface || this.IsTrait)
            {
                return;
            }

            var __tostring = this.GetMembersByPhpName(SpecialMethodNames.Tostring.Value).OfType <MethodSymbol>().FirstOrDefault();

            if (__tostring != null)    // implement ToString if: there is __toString() function
            {
                // lookup base string ToString()
                var overriden = this.LookupMember <MethodSymbol>(
                    WellKnownMemberNames.ObjectToString,
                    m => OverrideHelper.SignaturesMatch(m, (MethodSymbol)DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString)));

                Debug.Assert(overriden != null);

                if (overriden == null || overriden.IsSealed || overriden.ContainingType == this)
                {
                    // cannot be overriden
                    return;
                }

                // public sealed override string ToString()
                var tostring = new SynthesizedMethodSymbol(this, WellKnownMemberNames.ObjectToString, false, true, DeclaringCompilation.CoreTypes.String, Accessibility.Public, isfinal: false, phphidden: true)
                {
                    ExplicitOverride = overriden,
                    ForwardedCall    = __tostring,
                };

                module.SetMethodBody(tostring, MethodGenerator.GenerateMethodBody(module, tostring, il =>
                {
                    var thisPlace = new ArgPlace(this, 0);
                    var cg        = new CodeGenerator(il, module, DiagnosticBag.GetInstance(), module.Compilation.Options.OptimizationLevel, false, this, new FieldPlace(thisPlace, this.ContextStore, module), thisPlace);

                    if (__tostring != null)
                    {
                        // __tostring().ToString()
                        cg.EmitConvert(cg.EmitForwardCall(__tostring, tostring, callvirt: true), 0, tostring.ReturnType);
                    }
                    else
                    {
                        // PhpException.ObjectToStringNotSupported(this)
                        cg.EmitThis();
                        cg.EmitPop(cg.EmitCall(ILOpCode.Call, cg.CoreTypes.PhpException.Method("ObjectToStringNotSupported", cg.CoreTypes.Object)));

                        // return ""
                        cg.Builder.EmitStringConstant(string.Empty);
                    }
                    cg.EmitRet(tostring.ReturnType);
                }, null, DiagnosticBag.GetInstance(), false));
                module.SynthesizedManager.AddMethod(this, tostring);
            }
        }
        internal override IEnumerable <AttributeData> GetCustomAttributesToEmit(CommonModuleCompilationState compilationState)
        {
            if (IsParams)
            {
                yield return(new SynthesizedAttributeData(
                                 (MethodSymbol)DeclaringCompilation.GetWellKnownTypeMember(WellKnownMember.System_ParamArrayAttribute__ctor),
                                 ImmutableArray <TypedConstant> .Empty, ImmutableArray <KeyValuePair <string, TypedConstant> > .Empty));
            }

            yield break;
        }
Beispiel #25
0
 private void EnsureAttributesFromConstraints(DiagnosticBag diagnostics)
 {
     if (ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger()))
     {
         DeclaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding());
     }
     if (ConstraintsNeedNullableAttribute())
     {
         DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding());
     }
     Location getLocation() => this.GetNonNullSyntaxNode().Location;
 }
        internal SynthesizedAttributeData GetVoStructAttributeData()
        {
            var syntax               = ((CSharpSyntaxNode)declaration.SyntaxReferences.FirstOrDefault()?.GetSyntax());
            var attributeType        = DeclaringCompilation.VOStructAttributeType();
            var int32type            = DeclaringCompilation.GetSpecialType(SpecialType.System_Int32);
            var attributeConstructor = attributeType.GetMembers(".ctor").FirstOrDefault() as MethodSymbol;
            var constructorArguments = ArrayBuilder <TypedConstant> .GetInstance();

            constructorArguments.Add(new TypedConstant(int32type, TypedConstantKind.Primitive, VoStructSize));
            constructorArguments.Add(new TypedConstant(int32type, TypedConstantKind.Primitive, VoStructElementSize));
            return(new SynthesizedAttributeData(attributeConstructor, constructorArguments.ToImmutableAndFree(), ImmutableArray <KeyValuePair <string, TypedConstant> > .Empty));
        }
        /// <summary>
        /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol.
        /// </summary>
        /// <remarks>
        /// Forces binding and decoding of attributes.
        /// </remarks>
        private CustomAttributesBag <CSharpAttributeData> GetAttributesBag()
        {
            if ((_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) &&
                LoadAndValidateAttributes(OneOrMany.Create(this.AttributeDeclarationSyntaxList), ref _lazyCustomAttributesBag))
            {
                DeclaringCompilation.SymbolDeclaredEvent(this);
                var wasCompletedThisThread = state.NotePartComplete(CompletionPart.Attributes);
                Debug.Assert(wasCompletedThisThread);
            }

            return(_lazyCustomAttributesBag);
        }
        /// <summary>
        /// Emits conversion to <c>System.DateTime</c>.
        /// </summary>
        /// <param name="from">Value on stack to be converted.</param>
        private void EmitConvertToDateTime(TypeSymbol from)
        {
            // PhpValue
            EmitConvertToPhpValue(from, 0);

            // Convert.ToDateTime( STACK ) : DateTime
            var datetime = DeclaringCompilation.GetSpecialType(SpecialType.System_DateTime);
            var method   = CoreTypes.Convert.Method("ToDateTime", CoreTypes.PhpValue);

            EmitCall(ILOpCode.Call, method)
            .Expect(datetime);
        }
            internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics)
            {
                base.AfterAddingTypeMembersChecks(conversions, diagnostics);

                if (_refKind == RefKind.RefReadOnly)
                {
                    var syntax = (DelegateDeclarationSyntax)SyntaxRef.GetSyntax();
                    DeclaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, syntax.ReturnType.GetLocation(), modifyCompilationForRefReadOnly: true);
                }

                ParameterHelpers.EnsureIsReadOnlyAttributeExists(Parameters, diagnostics, modifyCompilationForRefReadOnly: true);
            }
Beispiel #30
0
        internal void ComputeReturnType()
        {
            if (!_lazyReturnType.IsNull)
            {
                return;
            }

            var        diagnostics               = DiagnosticBag.GetInstance();
            TypeSyntax returnTypeSyntax          = _syntax.ReturnType;
            TypeSymbolWithAnnotations returnType = _binder.BindType(returnTypeSyntax.SkipRef(), diagnostics);

            if (this.IsAsync)
            {
                if (this.RefKind != RefKind.None)
                {
                    ReportBadRefToken(returnTypeSyntax, diagnostics);
                }
                else if (returnType.TypeSymbol.IsBadAsyncReturn(this.DeclaringCompilation))
                {
                    diagnostics.Add(ErrorCode.ERR_BadAsyncReturn, this.Locations[0]);
                }
            }

            var location = _syntax.ReturnType.Location;

            if (_refKind == RefKind.RefReadOnly)
            {
                DeclaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: false);
            }

            if (returnType.ContainsNullableReferenceTypes())
            {
                DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: false);
                // Note: we don't need to warn on annotations used without NonNullTypes context for local functions, as this is handled in binding already
            }

            Debug.Assert(_refKind == RefKind.None ||
                         returnType.SpecialType != SpecialType.System_Void ||
                         returnTypeSyntax.HasErrors);

            lock (_declarationDiagnostics)
            {
                if (!_lazyReturnType.IsNull)
                {
                    diagnostics.Free();
                    return;
                }

                _declarationDiagnostics.AddRangeAndFree(diagnostics);
                _lazyReturnType = returnType;
            }
        }