Пример #1
0
        internal static DeclarationModifiers CheckModifiers(
            DeclarationModifiers modifiers,
            DeclarationModifiers allowedModifiers,
            Location errorLocation,
            BindingDiagnosticBag diagnostics,
            SyntaxTokenList?modifierTokens,
            out bool modifierErrors
            )
        {
            modifierErrors = false;
            DeclarationModifiers errorModifiers = modifiers & ~allowedModifiers;
            DeclarationModifiers result         = modifiers & allowedModifiers;

            while (errorModifiers != DeclarationModifiers.None)
            {
                DeclarationModifiers oneError = errorModifiers & ~(errorModifiers - 1);
                Debug.Assert(oneError != DeclarationModifiers.None);
                errorModifiers = errorModifiers & ~oneError;

                switch (oneError)
                {
                case DeclarationModifiers.Partial:
                    // Provide a specialized error message in the case of partial.
                    ReportPartialError(errorLocation, diagnostics, modifierTokens);
                    break;

                default:
                    diagnostics.Add(
                        ErrorCode.ERR_BadMemberFlag,
                        errorLocation,
                        ConvertSingleModifierToSyntaxText(oneError)
                        );
                    break;
                }

                modifierErrors = true;
            }

            if ((result & DeclarationModifiers.PrivateProtected) != 0)
            {
                modifierErrors |= !Binder.CheckFeatureAvailability(
                    errorLocation.SourceTree,
                    MessageID.IDS_FeaturePrivateProtected,
                    diagnostics,
                    errorLocation
                    );
            }

            return(result);
        }
Пример #2
0
        protected SourceOrdinaryMethodSymbolBase(
            NamedTypeSymbol containingType,
            string name,
            Location location,
            CSharpSyntaxNode syntax,
            MethodKind methodKind,
            bool isIterator,
            bool isExtensionMethod,
            bool isPartial,
            bool hasBody,
            bool isNullableAnalysisEnabled,
            BindingDiagnosticBag diagnostics) :
            base(containingType,
                 syntax.GetReference(),
                 location,
                 isIterator: isIterator)
        {
            Debug.Assert(diagnostics.DiagnosticBag is object);

            _name = name;

            // The following two values are used to compute and store the initial value of the flags
            // However, these two components are placeholders; the correct value will be
            // computed lazily later and then the flags will be fixed up.
            const bool returnsVoid = false;

            DeclarationModifiers declarationModifiers;

            (declarationModifiers, HasExplicitAccessModifier) = this.MakeModifiers(methodKind, isPartial, hasBody, location, diagnostics);

            var isMetadataVirtualIgnoringModifiers = methodKind == MethodKind.ExplicitInterfaceImplementation; //explicit impls must be marked metadata virtual

            this.MakeFlags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod: isExtensionMethod, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: isMetadataVirtualIgnoringModifiers);

            _typeParameters = MakeTypeParameters(syntax, diagnostics);

            CheckFeatureAvailabilityAndRuntimeSupport(syntax, location, hasBody, diagnostics);

            if (hasBody)
            {
                CheckModifiersForBody(location, diagnostics);
            }

            var info = ModifierUtils.CheckAccessibility(this.DeclarationModifiers, this, isExplicitInterfaceImplementation: methodKind == MethodKind.ExplicitInterfaceImplementation);

            if (info != null)
            {
                diagnostics.Add(info, location);
            }
        }
Пример #3
0
        private NamespaceSymbol ResolveExternAliasTarget(BindingDiagnosticBag diagnostics)
        {
            NamespaceSymbol?target;

            if (!_binder.Compilation.GetExternAliasTarget(_aliasName.ValueText, out target))
            {
                diagnostics.Add(ErrorCode.ERR_BadExternAlias, _aliasName.GetLocation(), _aliasName.ValueText !);
            }

            RoslynDebug.Assert(target is object);
            RoslynDebug.Assert(target.IsGlobalNamespace);

            return(target);
        }
Пример #4
0
        protected void ReportModifiersDiagnostics(BindingDiagnosticBag diagnostics)
        {
            if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected())
            {
                diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(containingType), ErrorLocation, this);
            }
            else if (IsVolatile && IsReadOnly)
            {
                diagnostics.Add(ErrorCode.ERR_VolatileAndReadonly, ErrorLocation, this);
            }
            else if (containingType.IsStatic && !IsStatic)
            {
                diagnostics.Add(ErrorCode.ERR_InstanceMemberInStaticClass, ErrorLocation, this);
            }
            else if (!IsStatic && !IsReadOnly && containingType.IsReadOnly)
            {
                diagnostics.Add(ErrorCode.ERR_FieldsInRoStruct, ErrorLocation);
            }

            // TODO: Consider checking presence of core type System.Runtime.CompilerServices.IsVolatile
            // if there is a volatile modifier. Perhaps an appropriate error should be reported if the
            // type isn't available.
        }
Пример #5
0
        internal SourceCustomEventAccessorSymbol(
            SourceEventSymbol @event,
            AccessorDeclarationSyntax syntax,
            EventSymbol explicitlyImplementedEventOpt,
            string aliasQualifierOpt,
            bool isNullableAnalysisEnabled,
            BindingDiagnosticBag diagnostics)
            : base(@event,
                   syntax.GetReference(),
                   ImmutableArray.Create(syntax.Keyword.GetLocation()), explicitlyImplementedEventOpt, aliasQualifierOpt,
                   isAdder: syntax.Kind() == SyntaxKind.AddAccessorDeclaration,
                   isIterator: SyntaxFacts.HasYieldOperations(syntax.Body),
                   isNullableAnalysisEnabled: isNullableAnalysisEnabled)
        {
            Debug.Assert(syntax != null);
            Debug.Assert(syntax.Kind() == SyntaxKind.AddAccessorDeclaration || syntax.Kind() == SyntaxKind.RemoveAccessorDeclaration);

            CheckFeatureAvailabilityAndRuntimeSupport(syntax, this.Location, hasBody: true, diagnostics: diagnostics);

            if (syntax.Body != null || syntax.ExpressionBody != null)
            {
                if (IsExtern && !IsAbstract)
                {
                    diagnostics.Add(ErrorCode.ERR_ExternHasBody, this.Location, this);
                }
                // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only
                // in that case ("member cannot be both extern and abstract").
            }

            if (syntax.Modifiers.Count > 0)
            {
                diagnostics.Add(ErrorCode.ERR_NoModifiersOnAccessor, syntax.Modifiers[0].GetLocation());
            }

            CheckForBlockAndExpressionBody(
                syntax.Body, syntax.ExpressionBody, syntax, diagnostics);
        }
Пример #6
0
        internal static void ReportDefaultInterfaceImplementationModifiers(
            bool hasBody,
            DeclarationModifiers modifiers,
            DeclarationModifiers defaultInterfaceImplementationModifiers,
            Location errorLocation,
            BindingDiagnosticBag diagnostics)
        {
            if ((modifiers & defaultInterfaceImplementationModifiers) != 0)
            {
                LanguageVersion availableVersion = ((CSharpParseOptions)errorLocation.SourceTree.Options).LanguageVersion;
                LanguageVersion requiredVersion;

                if ((modifiers & defaultInterfaceImplementationModifiers & DeclarationModifiers.Static) != 0 &&
                    (modifiers & defaultInterfaceImplementationModifiers & (DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Virtual)) != 0)
                {
                    var reportModifiers = DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Virtual;
                    if ((modifiers & defaultInterfaceImplementationModifiers & DeclarationModifiers.Sealed) != 0 &&
                        (modifiers & defaultInterfaceImplementationModifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual)) != 0)
                    {
                        diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, ConvertSingleModifierToSyntaxText(DeclarationModifiers.Sealed));
                        reportModifiers &= ~DeclarationModifiers.Sealed;
                    }

                    requiredVersion = MessageID.IDS_FeatureStaticAbstractMembersInInterfaces.RequiredVersion();
                    if (availableVersion < requiredVersion)
                    {
                        ReportUnsupportedModifiersForLanguageVersion(modifiers, reportModifiers, errorLocation, diagnostics, availableVersion, requiredVersion);
                    }

                    return; // below we will either ask for an earlier version of the language, or will not report anything
                }

                if (hasBody)
                {
                    if ((modifiers & defaultInterfaceImplementationModifiers & DeclarationModifiers.Static) != 0)
                    {
                        Binder.CheckFeatureAvailability(errorLocation.SourceTree, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, errorLocation);
                    }
                }
                else
                {
                    requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion();
                    if (availableVersion < requiredVersion)
                    {
                        ReportUnsupportedModifiersForLanguageVersion(modifiers, defaultInterfaceImplementationModifiers, errorLocation, diagnostics, availableVersion, requiredVersion);
                    }
                }
            }
        }
Пример #7
0
 protected static void ReportBadRefToken(
     TypeSyntax returnTypeSyntax,
     BindingDiagnosticBag diagnostics
     )
 {
     if (!returnTypeSyntax.HasErrors)
     {
         var refKeyword = returnTypeSyntax.GetFirstToken();
         diagnostics.Add(
             ErrorCode.ERR_UnexpectedToken,
             refKeyword.GetLocation(),
             refKeyword.ToString()
             );
     }
 }
        private void CheckShiftSignature(BindingDiagnosticBag diagnostics)
        {
            // SPEC: A binary << or >> operator must take two parameters, the first
            // SPEC: of which must have type T or T? and the second of which must
            // SPEC: have type int or int?, and can return any type.

            if (
                !MatchesContainingType(this.GetParameterType(0).StrippedType()) ||
                this.GetParameterType(1).StrippedType().SpecialType != SpecialType.System_Int32
                )
            {
                // CS0546: The first operand of an overloaded shift operator must have the
                //         same type as the containing type, and the type of the second
                //         operand must be int
                diagnostics.Add(ErrorCode.ERR_BadShiftOperatorSignature, this.Locations[0]);
            }

            if (this.ReturnsVoid)
            {
                // The Roslyn parser does not detect this error.
                // CS0590: User-defined operators cannot return void
                diagnostics.Add(ErrorCode.ERR_OperatorCantReturnVoid, this.Locations[0]);
            }
        }
Пример #9
0
            internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
            {
                var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics);

                try
                {
                    F.CurrentFunction = this;
                    F.CloseMethod(F.Block(F.Return(F.Typeof(ContainingType))));
                }
                catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
                {
                    diagnostics.Add(ex.Diagnostic);
                    F.CloseMethod(F.ThrowNull());
                }
            }
Пример #10
0
 private static void ReportErrorOnWellKnownMember(Symbol symbol, WellKnownMember member, BindingDiagnosticBag diagnostics, ref bool hasError)
 {
     if ((object)symbol == null)
     {
         MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member);
         diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, NoLocation.Singleton,
                         memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name);
         hasError = true;
     }
     else
     {
         ReportErrorOnSymbol(symbol, diagnostics, ref hasError);
         ReportErrorOnSymbol(symbol.ContainingType, diagnostics, ref hasError);
     }
 }
Пример #11
0
            internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null)
            {
                if (this.IsConst && inProgress == this)
                {
                    if (diagnostics != null)
                    {
                        diagnostics.Add(ErrorCode.ERR_CircConstValue, node.GetLocation(), this);
                    }

                    return(Microsoft.CodeAnalysis.ConstantValue.Bad);
                }

                MakeConstantTuple(inProgress, boundInitValue: null);
                return(_constantTuple == null ? null : _constantTuple.Value);
            }
Пример #12
0
 internal static void CheckUnsafeModifier(
     this Symbol symbol,
     DeclarationModifiers modifiers,
     Location errorLocation,
     BindingDiagnosticBag diagnostics
     )
 {
     if (
         ((modifiers & DeclarationModifiers.Unsafe) == DeclarationModifiers.Unsafe) &&
         !symbol.CompilationAllowsUnsafe()
         )
     {
         RoslynDebug.Assert(errorLocation != null);
         diagnostics.Add(ErrorCode.ERR_IllegalUnsafe, errorLocation);
     }
 }
Пример #13
0
        internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
        {
            var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);

            try
            {
                // => !(r1 == r2);
                F.CloseMethod(F.Block(F.Return(F.Not(F.Call(receiver: null, ContainingType.GetMembers(WellKnownMemberNames.EqualityOperatorName).OfType <SynthesizedRecordEqualityOperator>().Single(),
                                                            F.Parameter(Parameters[0]), F.Parameter(Parameters[1]))))));
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
                F.CloseMethod(F.ThrowNull());
            }
        }
        /// <summary>
        /// Given a SynthesizedSealedPropertyAccessor (an accessor with a reference to the accessor it overrides),
        /// construct a BoundBlock body.
        /// </summary>
        internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
        {
            SyntheticBoundNodeFactory F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics);

            F.CurrentFunction = (MethodSymbol)this.OriginalDefinition;

            try
            {
                F.CloseMethod(MethodBodySynthesizer.ConstructSingleInvocationMethodBody(F, this.OverriddenAccessor, useBaseReference: true));
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
                F.CloseMethod(F.ThrowNull());
            }
        }
Пример #15
0
        internal SynthesizedSubmissionConstructor(NamedTypeSymbol containingType, BindingDiagnosticBag diagnostics)
            : base(containingType)
        {
            Debug.Assert(containingType.TypeKind == TypeKind.Submission);
            Debug.Assert(diagnostics != null);

            var compilation = containingType.DeclaringCompilation;

            var submissionArrayType = compilation.CreateArrayTypeSymbol(compilation.GetSpecialType(SpecialType.System_Object));
            var useSiteInfo         = submissionArrayType.GetUseSiteInfo();

            diagnostics.Add(useSiteInfo, NoLocation.Singleton);

            _parameters = ImmutableArray.Create <ParameterSymbol>(
                SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(submissionArrayType), 0, RefKind.None, "submissionArray"));
        }
Пример #16
0
        internal override void GenerateMethodBody(
            TypeCompilationState compilationState,
            BindingDiagnosticBag diagnostics
            )
        {
            var F = new SyntheticBoundNodeFactory(
                this,
                this.SyntaxNode,
                compilationState,
                diagnostics
                );

            try
            {
                var paramAccess = F.Parameter(Parameters[0]);

                BoundExpression expression;
                if (ContainingType.IsStructType())
                {
                    throw ExceptionUtilities.Unreachable;
                }
                else
                {
                    if (_typedRecordEquals.ReturnType.SpecialType != SpecialType.System_Boolean)
                    {
                        // There is a signature mismatch, an error was reported elsewhere
                        F.CloseMethod(F.ThrowNull());
                        return;
                    }

                    // For classes:
                    //      return this.Equals(param as ContainingType);
                    expression = F.Call(
                        F.This(),
                        _typedRecordEquals,
                        F.As(paramAccess, ContainingType)
                        );
                }

                F.CloseMethod(F.Block(ImmutableArray.Create <BoundStatement>(F.Return(expression))));
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
                F.CloseMethod(F.ThrowNull());
            }
        }
Пример #17
0
        public static ImmutableArray <FunctionPointerParameterSymbol> MakeFunctionPointerParameters(
            Binder binder,
            FunctionPointerMethodSymbol owner,
            SeparatedSyntaxList <FunctionPointerParameterSyntax> parametersList,
            BindingDiagnosticBag diagnostics,
            bool suppressUseSiteDiagnostics)
        {
            return(MakeParameters <FunctionPointerParameterSyntax, FunctionPointerParameterSymbol, FunctionPointerMethodSymbol>(
                       binder,
                       owner,
                       parametersList,
                       out _,
                       diagnostics,
                       allowRefOrOut: true,
                       allowThis: false,
                       addRefReadOnlyModifier: true,
                       suppressUseSiteDiagnostics,
                       parametersList.Count - 2,
                       parameterCreationFunc: (Binder binder, FunctionPointerMethodSymbol owner, TypeWithAnnotations parameterType,
                                               FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal,
                                               SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier,
                                               DeclarationScope scope,
                                               BindingDiagnosticBag diagnostics) =>
            {
                // Non-function pointer locations have other locations to encode in/ref readonly/outness. For function pointers,
                // these modreqs are the only locations where this can be encoded. If that changes, we should update this.
                Debug.Assert(addRefReadOnlyModifier, "If addReadonlyRef isn't true, we must have found a different location to encode the readonlyness of a function pointer");
                ImmutableArray <CustomModifier> customModifiers = refKind switch
                {
                    RefKind.In => CreateInModifiers(binder, diagnostics, syntax),
                    RefKind.Out => CreateOutModifiers(binder, diagnostics, syntax),
                    _ => ImmutableArray <CustomModifier> .Empty
                };

                if (parameterType.IsVoidType())
                {
                    diagnostics.Add(ErrorCode.ERR_NoVoidParameter, syntax.Type.Location);
                }

                return new FunctionPointerParameterSymbol(
                    parameterType,
                    refKind,
                    ordinal,
                    owner,
                    customModifiers);
            },
Пример #18
0
        internal static void ReportUnsupportedModifiersForLanguageVersion(DeclarationModifiers modifiers, DeclarationModifiers unsupportedModifiers, Location errorLocation, BindingDiagnosticBag diagnostics, LanguageVersion availableVersion, LanguageVersion requiredVersion)
        {
            DeclarationModifiers errorModifiers = modifiers & unsupportedModifiers;
            var requiredVersionArgument         = new CSharpRequiredLanguageVersion(requiredVersion);
            var availableVersionArgument        = availableVersion.ToDisplayString();

            while (errorModifiers != DeclarationModifiers.None)
            {
                DeclarationModifiers oneError = errorModifiers & ~(errorModifiers - 1);
                Debug.Assert(oneError != DeclarationModifiers.None);
                errorModifiers = errorModifiers & ~oneError;
                diagnostics.Add(ErrorCode.ERR_InvalidModifierForLanguageVersion, errorLocation,
                                ConvertSingleModifierToSyntaxText(oneError),
                                availableVersionArgument,
                                requiredVersionArgument);
            }
        }
Пример #19
0
        /// <summary>
        /// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen.
        /// </summary>
        /// <remarks>
        /// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument.
        /// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute.
        /// It involves following steps:
        ///  1) Verifying that the specified file name resolves to a valid path.
        ///  2) Reading the contents of the file into a byte array.
        ///  3) Convert each byte in the file content into two bytes containing hexadecimal characters.
        ///  4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above.
        ///
        /// Step 1) is performed in this method, i.e. during binding.
        /// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass.
        /// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps.
        /// </remarks>
        /// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns>
        private string?DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax?nodeOpt, BindingDiagnosticBag diagnostics)
        {
            Debug.Assert(!this.HasErrors);

            string?resolvedFilePath = null;
            var    namedArgs        = this.CommonNamedArguments;

            if (namedArgs.Length == 1)
            {
                var namedArg = namedArgs[0];
                Debug.Assert(AttributeClass is object);
                NamedTypeSymbol attrType     = this.AttributeClass;
                string          filePropName = PermissionSetAttributeWithFileReference.FilePropertyName;
                string          hexPropName  = PermissionSetAttributeWithFileReference.HexPropertyName;

                if (namedArg.Key == filePropName &&
                    PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName))
                {
                    // resolve file prop path
                    var fileName = (string?)namedArg.Value.ValueInternal;
                    var resolver = compilation.Options.XmlReferenceResolver;

                    resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null;

                    if (resolvedFilePath == null)
                    {
                        // CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute
                        Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton;
                        diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName);
                    }
                    else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName))
                    {
                        // PermissionSetAttribute was defined in user source, but doesn't have the required Hex property.
                        // Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception.
                        // We instead skip the fixup and emit the file property.

                        // CONSIDER: We may want to consider taking a breaking change and generating an error here.

                        return(null);
                    }
                }
            }

            return(resolvedFilePath);
        }
Пример #20
0
        internal void GetDeclarationDiagnostics(BindingDiagnosticBag 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, allowMismatchInDependencyAccumulation: true);

            var diagnostics = BindingDiagnosticBag.GetInstance(
                withDiagnostics: false,
                withDependencies: addTo.AccumulatesDependencies
                );

            if (
                IsEntryPointCandidate &&
                !IsGenericMethod &&
                ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol &&
                DeclaringCompilation.HasEntryPointSignature(this, diagnostics).IsCandidate
                )
            {
                addTo.Add(ErrorCode.WRN_MainIgnored, Syntax.Identifier.GetLocation(), this);
            }

            addTo.AddRangeAndFree(diagnostics);
        }
Пример #21
0
        internal string DecodeGuidAttribute(AttributeSyntax?nodeOpt, BindingDiagnosticBag diagnostics)
        {
            Debug.Assert(!this.HasErrors);

            var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal;

            // Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens)
            Guid guid;

            if (!Guid.TryParseExact(guidString, "D", out guid))
            {
                // CS0591: Invalid value for argument to '{0}' attribute
                Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt);
                diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "");
                guidString = String.Empty;
            }

            return(guidString !);
        }
Пример #22
0
        internal TypeParameterSymbol MakeSymbol(int ordinal, IList <TypeParameterBuilder> builders, BindingDiagnosticBag diagnostics)
        {
            var syntaxNode = (TypeParameterSyntax)_syntaxRef.GetSyntax();
            var result     = new SourceTypeParameterSymbol(
                _owner,
                syntaxNode.Identifier.ValueText,
                ordinal,
                syntaxNode.VarianceKeyword.VarianceKindFromToken(),
                ToLocations(builders),
                ToSyntaxRefs(builders));

            // SPEC: A type parameter [of a type] cannot have the same name as the type itself.
            if (result.Name == result.ContainingSymbol.Name)
            {
                diagnostics.Add(ErrorCode.ERR_TypeVariableSameAsParent, result.Locations[0], result.Name);
            }

            return(result);
        }
Пример #23
0
        private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax?nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics)
        {
            Debug.Assert((object)targetSymbol != null);
            Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method);
            Debug.Assert(this.IsSecurityAttribute(compilation));

            var ctorArgs = this.CommonConstructorArguments;

            if (!ctorArgs.Any())
            {
                // NOTE:    Security custom attributes must have a valid SecurityAction as its first argument, we have none here.
                // NOTE:    Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case.
                // NOTE:    However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses
                // NOTE:    SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case.

                // BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments,
                //                  it doesn't quite do this correctly

                // The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first
                // attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute.
                // We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior.

                if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute))
                {
                    hasErrors = false;
                    return(DeclarativeSecurityAction.LinkDemand);
                }
            }
            else
            {
                TypedConstant firstArg     = ctorArgs.First();
                var           firstArgType = (TypeSymbol?)firstArg.TypeInternal;
                if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction)))
                {
                    return(DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors));
                }
            }

            // CS7048: First argument to a security attribute must be a valid SecurityAction
            diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton);
            hasErrors = true;
            return(DeclarativeSecurityAction.None);
        }
Пример #24
0
            /// <summary>
            /// Given a SynthesizedSealedPropertyAccessor (an accessor with a reference to the accessor it overrides),
            /// construct a BoundBlock body.
            /// </summary>
            internal override void GenerateMethodBody(
                TypeCompilationState compilationState,
                BindingDiagnosticBag diagnostics
                )
            {
                SyntheticBoundNodeFactory F = new SyntheticBoundNodeFactory(
                    this,
                    this.GetNonNullSyntaxNode(),
                    compilationState,
                    diagnostics
                    );

                F.CurrentFunction = this.OriginalDefinition;

                try
                {
                    MethodSymbol methodBeingWrapped = this.BaseMethod;

                    if (this.Arity > 0)
                    {
                        Debug.Assert(this.Arity == methodBeingWrapped.Arity);
                        methodBeingWrapped = methodBeingWrapped.ConstructedFrom.Construct(
                            StaticCast <TypeSymbol> .From(this.TypeParameters)
                            );
                    }

                    BoundBlock body = MethodBodySynthesizer.ConstructSingleInvocationMethodBody(
                        F,
                        methodBeingWrapped,
                        useBaseReference: true
                        );
                    if (body.Kind != BoundKind.Block)
                    {
                        body = F.Block(body);
                    }
                    F.CompilationState.AddMethodWrapper(methodBeingWrapped, this, body);
                }
                catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
                {
                    diagnostics.Add(ex.Diagnostic);
                }
            }
Пример #25
0
        private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, MethodKind methodKind, bool hasBody, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors)
        {
            var defaultAccess = (methodKind == MethodKind.StaticConstructor) ? DeclarationModifiers.None : DeclarationModifiers.Private;

            // Check that the set of modifiers is allowed
            const DeclarationModifiers allowedModifiers =
                DeclarationModifiers.AccessibilityMask |
                DeclarationModifiers.Static |
                DeclarationModifiers.Extern |
                DeclarationModifiers.Unsafe;

            bool isInterface = ContainingType.IsInterface;
            var  mods        = ModifierUtils.MakeAndCheckNontypeMemberModifiers(isOrdinaryMethod: false, isForInterfaceMember: isInterface, modifiers, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors);

            this.CheckUnsafeModifier(mods, diagnostics);

            if (methodKind == MethodKind.StaticConstructor)
            {
                // Don't report ERR_StaticConstructorWithAccessModifiers if the ctor symbol name doesn't match the containing type name.
                // This avoids extra unnecessary errors.
                // There will already be a diagnostic saying Method must have a return type.
                if ((mods & DeclarationModifiers.AccessibilityMask) != 0 &&
                    ContainingType.Name == ((ConstructorDeclarationSyntax)this.SyntaxNode).Identifier.ValueText)
                {
                    diagnostics.Add(ErrorCode.ERR_StaticConstructorWithAccessModifiers, location, this);
                    mods           = mods & ~DeclarationModifiers.AccessibilityMask;
                    modifierErrors = true;
                }

                mods |= DeclarationModifiers.Private; // we mark static constructors private in the symbol table

                if (isInterface)
                {
                    ModifierUtils.ReportDefaultInterfaceImplementationModifiers(hasBody, mods,
                                                                                DeclarationModifiers.Extern,
                                                                                location, diagnostics);
                }
            }

            return(mods);
        }
Пример #26
0
        internal void DecodeInterfaceTypeAttribute(
            AttributeSyntax node,
            BindingDiagnosticBag diagnostics
            )
        {
            Debug.Assert(!this.HasErrors);

            TypedConstant ctorArgument = this.CommonConstructorArguments[0];

            Debug.Assert(
                ctorArgument.Kind == TypedConstantKind.Enum ||
                ctorArgument.Kind == TypedConstantKind.Primitive
                );

            ComInterfaceType interfaceType =
                ctorArgument.Kind == TypedConstantKind.Enum
                    ? ctorArgument.DecodeValue <ComInterfaceType>(SpecialType.System_Enum)
                    : (ComInterfaceType)ctorArgument.DecodeValue <short>(SpecialType.System_Int16);

            switch (interfaceType)
            {
            case Cci.Constants.ComInterfaceType_InterfaceIsDual:
            case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch:
            case ComInterfaceType.InterfaceIsIInspectable:
            case ComInterfaceType.InterfaceIsIUnknown:
                break;

            default:
                // CS0591: Invalid value for argument to '{0}' attribute
                CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(
                    0,
                    node
                    );
                diagnostics.Add(
                    ErrorCode.ERR_InvalidAttributeArgument,
                    attributeArgumentSyntax.Location,
                    node.GetErrorDisplayName()
                    );
                break;
            }
        }
Пример #27
0
        internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
        {
            var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);

            try
            {
                // => (object)left == right || ((object)left != null && left.Equals(right));
                MethodSymbol?equals = null;
                foreach (var member in ContainingType.GetMembers(WellKnownMemberNames.ObjectEquals))
                {
                    if (member is MethodSymbol candidate && candidate.ParameterCount == 1 && candidate.Parameters[0].RefKind == RefKind.None &&
                        candidate.ReturnType.SpecialType == SpecialType.System_Boolean && !candidate.IsStatic &&
                        candidate.Parameters[0].Type.Equals(ContainingType, TypeCompareKind.AllIgnoreOptions))
                    {
                        equals = candidate;
                        break;
                    }
                }

                if (equals is null)
                {
                    // Unable to locate expected method, an error was reported elsewhere
                    F.CloseMethod(F.ThrowNull());
                    return;
                }

                var left  = F.Parameter(Parameters[0]);
                var right = F.Parameter(Parameters[1]);

                BoundExpression objectEqual  = F.ObjectEqual(left, right);
                BoundExpression recordEquals = F.LogicalAnd(F.ObjectNotEqual(left, F.Null(F.SpecialType(SpecialType.System_Object))),
                                                            F.Call(left, equals, right));

                F.CloseMethod(F.Block(F.Return(F.LogicalOr(objectEqual, recordEquals))));
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
                F.CloseMethod(F.ThrowNull());
            }
        }
        /// <summary>
        /// Given a SynthesizedExplicitImplementationMethod (effectively a tuple (interface method, implementing method, implementing type)),
        /// construct a BoundBlock body.  Consider the tuple (Interface.Goo, Base.Goo, Derived).  The generated method will look like:
        ///
        /// R Interface.Goo&lt;T1, T2, ...&gt;(A1 a1, A2 a2, ...)
        /// {
        ///     //don't return the output if the return type is void
        ///     return this.Goo&lt;T1, T2, ...&gt;(a1, a2, ...);
        /// }
        /// </summary>
        internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
        {
            SyntheticBoundNodeFactory F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics);

            F.CurrentFunction = (MethodSymbol)this.OriginalDefinition;

            try
            {
                MethodSymbol methodToInvoke =
                    this.IsGenericMethod ?
                    this.ImplementingMethod.Construct(this.TypeParameters.Cast <TypeParameterSymbol, TypeSymbol>()) :
                    this.ImplementingMethod;

                F.CloseMethod(MethodBodySynthesizer.ConstructSingleInvocationMethodBody(F, methodToInvoke, useBaseReference: false));
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
                F.CloseMethod(F.ThrowNull());
            }
        }
Пример #29
0
        private void CheckForFieldTargetedAttribute(BindingDiagnosticBag diagnostics)
        {
            var languageVersion = this.DeclaringCompilation.LanguageVersion;

            if (languageVersion.AllowAttributesOnBackingFields())
            {
                return;
            }

            foreach (var attribute in AttributeDeclarationSyntaxList)
            {
                if (attribute.Target?.GetAttributeLocation() == AttributeLocation.Field)
                {
                    diagnostics.Add(
                        new CSDiagnosticInfo(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable,
                                             languageVersion.ToDisplayString(),
                                             new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion())),
                        attribute.Target.Location);
                }
            }
        }
Пример #30
0
 protected SourceEnumConstantSymbol(
     SourceMemberContainerTypeSymbol containingEnum,
     EnumMemberDeclarationSyntax syntax,
     BindingDiagnosticBag diagnostics
     )
     : base(
         containingEnum,
         syntax.Identifier.ValueText,
         syntax.GetReference(),
         syntax.Identifier.GetLocation()
         )
 {
     if (this.Name == WellKnownMemberNames.EnumBackingFieldName)
     {
         diagnostics.Add(
             ErrorCode.ERR_ReservedEnumerator,
             this.ErrorLocation,
             WellKnownMemberNames.EnumBackingFieldName
             );
     }
 }