Пример #1
0
        private BoundExpression BindWithExpression(WithExpressionSyntax syntax, BindingDiagnosticBag diagnostics)
        {
            var receiver     = BindRValueWithoutTargetType(syntax.Expression, diagnostics);
            var receiverType = receiver.Type;

            var  lookupResult = LookupResult.GetInstance();
            bool hasErrors    = false;

            if (receiverType is null || receiverType.IsVoidType())
            {
                diagnostics.Add(ErrorCode.ERR_InvalidWithReceiverType, syntax.Expression.Location);
                receiverType = CreateErrorType();
            }

            MethodSymbol?cloneMethod = null;

            if (receiverType.IsValueType && !receiverType.IsPointerOrFunctionPointer())
            {
                CheckFeatureAvailability(syntax, MessageID.IDS_FeatureWithOnStructs, diagnostics);
            }
            else if (receiverType.IsAnonymousType)
            {
                CheckFeatureAvailability(syntax, MessageID.IDS_FeatureWithOnAnonymousTypes, diagnostics);
            }
            else if (!receiverType.IsErrorType())
            {
                CompoundUseSiteInfo <AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);

                cloneMethod = SynthesizedRecordClone.FindValidCloneMethod(receiverType is TypeParameterSymbol typeParameter ? typeParameter.EffectiveBaseClass(ref useSiteInfo) : receiverType, ref useSiteInfo);
                if (cloneMethod is null)
                {
                    hasErrors = true;
                    diagnostics.Add(ErrorCode.ERR_CannotClone, syntax.Expression.Location, receiverType);
                }
                else
                {
                    cloneMethod.AddUseSiteInfo(ref useSiteInfo);
                }

                diagnostics.Add(syntax.Expression, useSiteInfo);
            }

            var initializer = BindInitializerExpression(
                syntax.Initializer,
                receiverType,
                syntax.Expression,
                isForNewInstance: true,
                diagnostics);

            // N.B. Since we don't parse nested initializers in syntax there should be no extra
            // errors we need to check for here.

            return(new BoundWithExpression(
                       syntax,
                       receiver,
                       cloneMethod,
                       initializer,
                       receiverType,
                       hasErrors: hasErrors));
        }
            private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, DiagnosticBag diagnostics)
            {
                var receiverType = receiver.Type as NamedTypeSymbol;

                if ((object)receiverType == null || !receiverType.IsAnonymousType)
                {
                    // We only construct transparent query variables using anonymous types, so if we're trying to navigate through
                    // some other type, we must have some hinky query API where the types don't match up as expected.
                    // We should report this as an error of some sort.
                    // TODO: DevDiv #737822 - reword error message and add test.
                    var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType);
                    Error(diagnostics, info, node);
                    return(new BoundBadExpression(
                               node,
                               LookupResultKind.Empty,
                               ImmutableArray.Create <Symbol>(receiver.ExpressionSymbol),
                               ImmutableArray.Create <BoundNode>(receiver),
                               new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info)));
                }

                LookupResult             lookupResult       = LookupResult.GetInstance();
                LookupOptions            options            = LookupOptions.MustBeInstance;
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;

                LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteDiagnostics, basesBeingResolved: null, options: options);
                diagnostics.Add(node, useSiteDiagnostics);

                var result = BindMemberOfType(node, node, name, 0, receiver, default(SeparatedSyntaxList <TypeSyntax>), default(ImmutableArray <TypeSymbol>), lookupResult, BoundMethodGroupFlags.None, diagnostics);

                result.WasCompilerGenerated = true;
                lookupResult.Free();
                return(result);
            }
Пример #3
0
        internal override void LookupSymbolsInSingleBinder(LookupResult result, string name, int arity, ConsList <TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo <AssemblySymbol> useSiteInfo)
        {
            bool foundParameter = false;

            if (_withParametersBinder is not null && IsNameofOperator)
            {
                _withParametersBinder.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo);
                if (!result.IsClear)
                {
                    if (result.IsMultiViable)
                    {
                        return;
                    }

                    foundParameter = true;
                }
            }

            if (_withTypeParametersBinder is not null && IsNameofOperator)
            {
                if (foundParameter)
                {
                    var tmp = LookupResult.GetInstance();
                    _withTypeParametersBinder.LookupSymbolsInSingleBinder(tmp, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo);
                    result.MergeEqual(tmp);
                }
                else
                {
                    _withTypeParametersBinder.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo);
                }
            }
        }
            private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, BindingDiagnosticBag diagnostics)
            {
                var receiverType = receiver.Type as NamedTypeSymbol;

                if ((object)receiverType == null || !receiverType.IsAnonymousType)
                {
                    // We only construct transparent query variables using anonymous types, so if we're trying to navigate through
                    // some other type, we must have some query API where the types don't match up as expected.
                    var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType);
                    if (receiver.Type?.IsErrorType() != true)
                    {
                        Error(diagnostics, info, node);
                    }

                    return(new BoundBadExpression(
                               node,
                               LookupResultKind.Empty,
                               ImmutableArray.Create <Symbol>(receiver.ExpressionSymbol),
                               ImmutableArray.Create(BindToTypeForErrorRecovery(receiver)),
                               new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info)));
                }

                LookupResult  lookupResult = LookupResult.GetInstance();
                LookupOptions options      = LookupOptions.MustBeInstance;
                CompoundUseSiteInfo <AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);

                LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteInfo, basesBeingResolved: null, options: options);
                diagnostics.Add(node, useSiteInfo);

                var result = BindMemberOfType(node, node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList <TypeSyntax>), default(ImmutableArray <TypeWithAnnotations>), lookupResult, BoundMethodGroupFlags.None, diagnostics);

                lookupResult.Free();
                return(result);
            }
Пример #5
0
        private TypeSymbol FindPCallDelegateType(IdentifierNameSyntax type)
        {
            if (type == null)
            {
                return(null);
            }
            var lookupResult = LookupResult.GetInstance();

            try
            {
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                LookupOptions            options            = LookupOptions.NamespacesOrTypesOnly;
                this.LookupSymbolsSimpleName(lookupResult, null, type.Identifier.Text, 0, null, options, false, ref useSiteDiagnostics);
                if (lookupResult.IsSingleViable)
                {
                    return(lookupResult.Symbols[0] as TypeSymbol);
                }

                return(null);
            }
            finally
            {
                lookupResult.Free();
            }
        }
Пример #6
0
        /// <summary>
        /// Check for a GetEnumerator method on collectionExprType.  Failing to satisfy the pattern is not an error -
        /// it just means that we have to check for an interface instead.
        /// </summary>
        /// <param name="collectionExprType">Type of the expression over which to iterate.</param>
        /// <param name="diagnostics">Populated with *warnings* if there are near misses.</param>
        /// <param name="builder">Builder to fill in. <see cref="ForEachEnumeratorInfo.Builder.GetEnumeratorMethod"/> set if the pattern in satisfied.</param>
        /// <returns>True if the method was found (still have to verify that the return (i.e. enumerator) type is acceptable).</returns>
        /// <remarks>
        /// Only adds warnings, so does not affect control flow (i.e. no need to check for failure).
        /// </remarks>
        private bool SatisfiesGetEnumeratorPattern(ref ForEachEnumeratorInfo.Builder builder, TypeSymbol collectionExprType, DiagnosticBag diagnostics)
        {
            LookupResult lookupResult        = LookupResult.GetInstance();
            MethodSymbol getEnumeratorMethod = FindForEachPatternMethod(collectionExprType, GetEnumeratorMethodName, lookupResult, warningsOnly: true, diagnostics: diagnostics);

            lookupResult.Free();

            builder.GetEnumeratorMethod = getEnumeratorMethod;
            return((object)getEnumeratorMethod != null);
        }
        private BoundExpression BindWithExpression(WithExpressionSyntax syntax, DiagnosticBag diagnostics)
        {
            var receiver     = BindRValueWithoutTargetType(syntax.Expression, diagnostics);
            var receiverType = receiver.Type;

            var  lookupResult = LookupResult.GetInstance();
            bool hasErrors    = false;

            if (receiverType is null || receiverType.IsVoidType())
            {
                diagnostics.Add(ErrorCode.ERR_InvalidWithReceiverType, syntax.Expression.Location);
                receiverType = CreateErrorType();
            }

            MethodSymbol?cloneMethod = null;

            if (!receiverType.IsErrorType())
            {
                HashSet <DiagnosticInfo>?useSiteDiagnostics = null;

                cloneMethod = SynthesizedRecordClone.FindValidCloneMethod(receiverType is TypeParameterSymbol typeParameter ? typeParameter.EffectiveBaseClass(ref useSiteDiagnostics) : receiverType, ref useSiteDiagnostics);
                if (cloneMethod is null)
                {
                    hasErrors = true;
                    diagnostics.Add(ErrorCode.ERR_NoSingleCloneMethod, syntax.Expression.Location, receiverType);
                }
                else if (cloneMethod.GetUseSiteDiagnostic() is DiagnosticInfo info)
                {
                    (useSiteDiagnostics ??= new HashSet <DiagnosticInfo>()).Add(info);
                }

                diagnostics.Add(syntax.Expression, useSiteDiagnostics);
            }

            var initializer = BindInitializerExpression(
                syntax.Initializer,
                receiverType,
                syntax.Expression,
                isForNewInstance: true,
                diagnostics);

            // N.B. Since we only don't parse nested initializers in syntax there should be no extra
            // errors we need to check for here.

            return(new BoundWithExpression(
                       syntax,
                       receiver,
                       cloneMethod,
                       initializer,
                       receiverType,
                       hasErrors: hasErrors));
        }
Пример #8
0
        /// <summary>
        /// Tries to find candidate operators for a given operator name and
        /// number of parameters in this scope's witnesses.
        /// </summary>
        /// <param name="name">
        /// The special name of the operator to find.
        /// </param>
        /// <param name="numParams">
        /// The number of parameters the operator takes: 1 for unary,
        /// 2 for binary.
        /// </param>
        /// <param name="useSiteDiagnostics">
        /// The set of diagnostics to populate with any use-site diagnostics
        /// coming from this lookup.
        /// </param>
        /// <returns>
        /// An array of possible matches for the given operator.
        /// </returns>
        private ImmutableArray <MethodSymbol> GetWitnessOperators(string name, int numParams, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            var builder = ArrayBuilder <MethodSymbol> .GetInstance();

            var result = LookupResult.GetInstance();

            // @t-mawind
            //   This is a fairly crude, and potentially very incorrect, method
            //   of finding overloads--can it be improved?
            for (var scope = _binder; scope != null; scope = scope.Next)
            {
                scope.LookupConceptMethodsInSingleBinder(result, name, 0, null, LookupOptions.AllMethodsOnArityZero | LookupOptions.AllowSpecialMethods, _binder, true, ref useSiteDiagnostics);
                if (result.IsMultiViable)
                {
                    var haveCandidates = false;

                    foreach (var candidate in result.Symbols)
                    {
                        var meth = candidate as MethodSymbol;
                        if (meth == null)
                        {
                            continue;
                        }
                        if (meth.MethodKind != MethodKind.UserDefinedOperator)
                        {
                            continue;
                        }
                        if (meth.ParameterCount != numParams)
                        {
                            continue;
                        }

                        haveCandidates = true;
                        builder.Add(meth);
                    }

                    // We're currently doing this fairly similarly to the way
                    // normal method lookup works: the moment any scope gives
                    // us at least one possible operator, use only that scope's
                    // results.  I'm not sure whether this is correct, but at
                    // least it's consistent.
                    if (haveCandidates)
                    {
                        return(builder.ToImmutableAndFree());
                    }
                }
            }

            // At this stage, we haven't seen _any_ operators.
            builder.Free();
            return(ImmutableArray <MethodSymbol> .Empty);
        }
Пример #9
0
        internal ImmutableArray <Symbol> BindXmlNameAttribute(
            XmlNameAttributeSyntax syntax,
            ref CompoundUseSiteInfo <AssemblySymbol> useSiteInfo
            )
        {
            var identifier = syntax.Identifier;

            if (identifier.IsMissing)
            {
                return(ImmutableArray <Symbol> .Empty);
            }

            var name = identifier.Identifier.ValueText;

            var lookupResult = LookupResult.GetInstance();

            this.LookupSymbolsWithFallback(
                lookupResult,
                name,
                arity: 0,
                useSiteInfo: ref useSiteInfo
                );

            if (lookupResult.Kind == LookupResultKind.Empty)
            {
                lookupResult.Free();
                return(ImmutableArray <Symbol> .Empty);
            }

            // If we found something, it must be viable, since only parameters or type parameters
            // of the current member are considered.
            Debug.Assert(lookupResult.IsMultiViable);

            ArrayBuilder <Symbol> lookupSymbols = lookupResult.Symbols;

            Debug.Assert(
                lookupSymbols[0].Kind == SymbolKind.TypeParameter ||
                lookupSymbols[0].Kind == SymbolKind.Parameter
                );
            Debug.Assert(lookupSymbols.All(sym => sym.Kind == lookupSymbols[0].Kind));

            // We can sort later when we disambiguate.
            ImmutableArray <Symbol> result = lookupSymbols.ToImmutable();

            lookupResult.Free();

            return(result);
        }
Пример #10
0
        private ImmutableArray <Symbol> ComputeSortedCrefMembers(NamespaceOrTypeSymbol?containerOpt, string memberName, string memberNameText, int arity, bool hasParameterList, CSharpSyntaxNode syntax,
                                                                 BindingDiagnosticBag diagnostics, ref CompoundUseSiteInfo <AssemblySymbol> useSiteInfo)
        {
            // Since we may find symbols without going through the lookup API,
            // expose the symbols via an ArrayBuilder.
            ArrayBuilder <Symbol> builder;

            {
                LookupResult result = LookupResult.GetInstance();
                this.LookupSymbolsOrMembersInternal(
                    result,
                    containerOpt,
                    name: memberName,
                    arity: arity,
                    basesBeingResolved: null,
                    options: LookupOptions.AllMethodsOnArityZero,
                    diagnose: false,
                    useSiteInfo: ref useSiteInfo);

                // CONSIDER: Dev11 also checks for a constructor in the event of an ambiguous result.
                if (result.IsMultiViable)
                {
                    // Dev11 doesn't consider members from System.Object when the container is an interface.
                    // Lookup should already have dropped such members.
                    builder = ArrayBuilder <Symbol> .GetInstance();

                    builder.AddRange(result.Symbols);
                    result.Free();
                }
                else if (memberNameText is "nint" or "nuint" &&
                         containerOpt is null &&
                         arity == 0 &&
                         !hasParameterList)
                {
                    result.Free(); // Won't be using this.
                    Debug.Assert(memberName == memberNameText);
                    CheckFeatureAvailability(syntax, MessageID.IDS_FeatureNativeInt, diagnostics);
                    builder = ArrayBuilder <Symbol> .GetInstance();

                    builder.Add(this.GetSpecialType(memberName == "nint" ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr, diagnostics, syntax).AsNativeInteger());
                }
Пример #11
0
        internal override void LookupSymbolsInSingleBinder(
            LookupResult result, string name, int arity, ConsList <Symbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            if ((options & LookupOptions.NamespaceAliasesOnly) != 0)
            {
                return;
            }

            LookupResult tmp = LookupResult.GetInstance();

            // usings:
            Imports.Empty.LookupSymbolInUsings(ConsolidatedUsings, originalBinder, tmp, name, arity, basesBeingResolved, options, diagnose, ref useSiteDiagnostics);

            // if we found a viable result in imported namespaces, use it instead of unviable symbols found in source:
            if (tmp.IsMultiViable)
            {
                result.MergeEqual(tmp);
            }

            tmp.Free();
        }
        /// <summary>
        /// Tries to find candidate operators for a given operator name and
        /// parameter list in the concepts in scope at this stage.
        /// </summary>
        /// <param name="name">
        /// The special name of the operator to find.
        /// </param>
        /// <param name="args">
        /// The arguments being supplied to the operator.
        /// </param>
        /// <param name="useSiteDiagnostics">
        /// The set of diagnostics to populate with any use-site diagnostics
        /// coming from this lookup.
        /// </param>
        /// <returns>
        /// An array of possible matches for the given operator.
        /// </returns>
        private ImmutableArray <MethodSymbol> GetConceptOperators(string name, ImmutableArray <BoundExpression> args, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            var builder = ArrayBuilder <MethodSymbol> .GetInstance();

            var result = LookupResult.GetInstance();

            // @t-mawind
            //   This is a fairly crude, and potentially very incorrect, method
            //   of finding overloads--can it be improved?
            for (var scope = _binder; scope != null; scope = scope.Next)
            {
                var coptions = Binder.ConceptSearchOptions.SearchUsings |
                               Binder.ConceptSearchOptions.SearchContainers |
                               Binder.ConceptSearchOptions.NoConceptExtensions |
                               Binder.ConceptSearchOptions.AllowStandaloneInstances;
                scope.LookupConceptMethodsInSingleBinder(result, name, 0, null, LookupOptions.AllMethodsOnArityZero | LookupOptions.AllowSpecialMethods, _binder, true, ref useSiteDiagnostics, coptions);
                if (result.IsMultiViable)
                {
                    var haveCandidates = false;

                    foreach (var candidate in result.Symbols)
                    {
                        if (candidate == null)
                        {
                            continue;
                        }
                        if (candidate.Kind != SymbolKind.Method)
                        {
                            continue;
                        }
                        var method = (MethodSymbol)candidate;
                        if (method.MethodKind != MethodKind.UserDefinedOperator)
                        {
                            continue;
                        }
                        if (method.ParameterCount != args.Length)
                        {
                            continue;
                        }

                        // @MattWindsor91 (Concept-C# 2017)
                        //
                        // Unlike normal operator overloads, concept operators
                        // will have missing type parameters: at the very least, the
                        // witness parameter telling us which concept instance to
                        // call into will be unknown.
                        //
                        // In this prototype, we just call a full round of method
                        // type inference, and ignore the method if it doesn't infer.
                        //
                        // This probably doesn't handle nullability correctly.
                        HashSet <DiagnosticInfo> ignore = null;
                        // As with MethodCompiler.BindMethodBody, we need to
                        // pull in the witnesses of a default struct into scope.
                        var mtr = MethodTypeInferrer.Infer(_binder, method.TypeParameters, method.ContainingType, method.ParameterTypes, method.ParameterRefKinds, args, ref ignore);
                        if (!mtr.Success)
                        {
                            continue;
                        }

                        haveCandidates = true;
                        if (method is SynthesizedImplicitConceptMethodSymbol imethod)
                        {
                            builder.Add(imethod.ConstructAndRetarget(mtr.InferredTypeArguments));
                        }
                        else
                        {
                            builder.Add(method.Construct(mtr.InferredTypeArguments));
                        }
                    }

                    // We're currently doing this fairly similarly to the way
                    // normal method lookup works: the moment any scope gives
                    // us at least one possible operator, use only that scope's
                    // results.  I'm not sure whether this is correct, but at
                    // least it's consistent.
                    if (haveCandidates)
                    {
                        return(builder.ToImmutableAndFree());
                    }
                }
            }

            // At this stage, we haven't seen _any_ operators.
            builder.Free();
            return(ImmutableArray <MethodSymbol> .Empty);
        }
Пример #13
0
        /// <summary>
        /// Called after it is determined that the expression being enumerated is of a type that
        /// has a GetEnumerator method.  Checks to see if the return type of the GetEnumerator
        /// method is suitable (i.e. has Current and MoveNext).
        /// </summary>
        /// <param name="builder">Must be non-null and contain a non-null GetEnumeratorMethod.</param>
        /// <param name="diagnostics">Will be populated with pattern diagnostics.</param>
        /// <returns>True if the return type has suitable members.</returns>
        /// <remarks>
        /// It seems that every failure path reports the same diagnostics, so that is left to the caller.
        /// </remarks>
        private bool SatisfiesForEachPattern(ref ForEachEnumeratorInfo.Builder builder, DiagnosticBag diagnostics)
        {
            Debug.Assert((object)builder.GetEnumeratorMethod != null);

            MethodSymbol getEnumeratorMethod = builder.GetEnumeratorMethod;
            TypeSymbol   enumeratorType      = getEnumeratorMethod.ReturnType;

            switch (enumeratorType.TypeKind)
            {
            case TypeKind.Class:
            case TypeKind.Struct:
            case TypeKind.Interface:
            case TypeKind.TypeParameter:   // Not specifically mentioned in the spec, but consistent with Dev10.
            case TypeKind.DynamicType:     // Not specifically mentioned in the spec, but consistent with Dev10.
                break;

            case TypeKind.Submission:
                // submission class is synthesized and should never appear in a foreach:
                throw ExceptionUtilities.UnexpectedValue(enumeratorType.TypeKind);

            default:
                return(false);
            }

            // Use a try-finally since there are many return points
            LookupResult lookupResult = LookupResult.GetInstance();

            try
            {
                // If we searched for the accessor directly, we could reuse FindForEachPatternMethod and we
                // wouldn't have to mangle CurrentPropertyName.  However, Dev10 searches for the property and
                // then extracts the accessor, so we should do the same (in case of accessors with non-standard
                // names).
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                this.LookupMembersInType(
                    lookupResult,
                    enumeratorType,
                    CurrentPropertyName,
                    arity: 0,
                    basesBeingResolved: null,
                    options: LookupOptions.Default, // properties are not invocable - their accessors are
                    originalBinder: this,
                    diagnose: false,
                    useSiteDiagnostics: ref useSiteDiagnostics);

                diagnostics.Add(this.syntax.Expression, useSiteDiagnostics);
                useSiteDiagnostics = null;

                if (!lookupResult.IsSingleViable)
                {
                    ReportPatternMemberLookupDiagnostics(lookupResult, enumeratorType, CurrentPropertyName, warningsOnly: false, diagnostics: diagnostics);
                    return(false);
                }

                // lookupResult.IsSingleViable above guaranteed there is exactly one symbol.
                Symbol lookupSymbol = lookupResult.SingleSymbolOrDefault;
                Debug.Assert((object)lookupSymbol != null);

                if (lookupSymbol.IsStatic || lookupSymbol.DeclaredAccessibility != Accessibility.Public || lookupSymbol.Kind != SymbolKind.Property)
                {
                    return(false);
                }

                // NOTE: accessor can be inherited from overridden property
                MethodSymbol currentPropertyGetterCandidate = ((PropertySymbol)lookupSymbol).GetOwnOrInheritedGetMethod();

                if ((object)currentPropertyGetterCandidate == null)
                {
                    return(false);
                }
                else
                {
                    bool isAccessible = this.IsAccessible(currentPropertyGetterCandidate, ref useSiteDiagnostics);
                    diagnostics.Add(this.syntax.Expression, useSiteDiagnostics);

                    if (!isAccessible)
                    {
                        // NOTE: per Dev10 and the spec, the property has to be public, but the accessor just has to be accessible
                        return(false);
                    }
                }

                builder.CurrentPropertyGetter = currentPropertyGetterCandidate;

                lookupResult.Clear(); // Reuse the same LookupResult

                MethodSymbol moveNextMethodCandidate = FindForEachPatternMethod(enumeratorType, MoveNextMethodName, lookupResult, warningsOnly: false, diagnostics: diagnostics);

                // SPEC VIOLATION: Dev10 checks the return type of the original definition, rather than the return type of the actual method.

                if ((object)moveNextMethodCandidate == null ||
                    moveNextMethodCandidate.IsStatic || moveNextMethodCandidate.DeclaredAccessibility != Accessibility.Public ||
                    ((MethodSymbol)moveNextMethodCandidate.OriginalDefinition).ReturnType.SpecialType != SpecialType.System_Boolean)
                {
                    return(false);
                }

                builder.MoveNextMethod = moveNextMethodCandidate;

                return(true);
            }
            finally
            {
                lookupResult.Free();
            }
        }
Пример #14
0
        internal static bool HandleXSharpImport(UsingDirectiveSyntax usingDirective, Binder usingsBinder,
                                                ArrayBuilder <NamespaceOrTypeAndUsingDirective> usings, PooledHashSet <NamespaceOrTypeSymbol> uniqueUsings,
                                                ConsList <Symbol> basesBeingResolved, CSharpCompilation compilation)
        {
            // The usingDirective name contains spaces when it is nested and the GlobalClassName not , so we must eliminate them here
            // nvk: usingDirective.Name.ToString() ONLY has spaces if it is nested. This is not supposed to be nested, as it is "Functions" even for the non-core dialects !!!
            if (usingDirective.Name.ToString().EndsWith(XSharpSpecialNames.FunctionsClass))
            {
                var                      result             = LookupResult.GetInstance();
                LookupOptions            options            = LookupOptions.AllNamedTypesOnArityZero;
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                usingsBinder.LookupSymbolsSimpleName(result, null, XSharpSpecialNames.FunctionsClass, 0, basesBeingResolved, options, false, useSiteDiagnostics: ref useSiteDiagnostics);
                foreach (var sym in result.Symbols)
                {
                    if (sym.Kind == SymbolKind.NamedType)
                    {
                        var ts = (NamedTypeSymbol)sym;
                        AddNs(usingDirective, ts, usings, uniqueUsings);
                    }
                }
                var opts = ((CSharpSyntaxTree)usingDirective.SyntaxTree).Options;
                if (opts.CommandLineArguments != null)
                {
                    string functionsClass = null;
                    if (compilation.Options.HasRuntime)
                    {
                        functionsClass = Syntax.InternalSyntax.XSharpTreeTransformationRT.VOGlobalClassName(opts);
                    }
                    else
                    {
                        functionsClass = Syntax.InternalSyntax.XSharpTreeTransformationCore.GlobalFunctionClassName(opts.TargetDLL);
                    }
                    if (!string.IsNullOrEmpty(functionsClass))
                    {
                        var declbinder  = usingsBinder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks);
                        var diagnostics = DiagnosticBag.GetInstance();
                        var name        = Syntax.InternalSyntax.XSharpTreeTransformationCore.ExtGenerateQualifiedName(functionsClass);
                        var imported    = declbinder.BindNamespaceOrTypeSymbol(name, diagnostics, basesBeingResolved);
                        if (imported.Kind == SymbolKind.NamedType)
                        {
                            var importedType = (NamedTypeSymbol)imported;
                            AddNs(usingDirective, importedType, usings, uniqueUsings);
                        }
                    }
                }

                if (!compilation.ClassLibraryType().IsErrorType() &&
                    !compilation.ImplicitNamespaceType().IsErrorType())
                {
                    var      declbinder  = usingsBinder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks);
                    var      diagnostics = DiagnosticBag.GetInstance();
                    string[] defNs;
                    if (compilation.Options.XSharpRuntime)
                    {
                        defNs = new string[] { OurNameSpaces.XSharp }
                    }
                    ;
                    else
                    {
                        defNs = new string[] { OurNameSpaces.Vulcan }
                    };

                    foreach (var n in defNs)
                    {
                        var name     = Syntax.InternalSyntax.XSharpTreeTransformationCore.ExtGenerateQualifiedName(n);
                        var imported = declbinder.BindNamespaceOrTypeSymbol(name, diagnostics, basesBeingResolved);
                        if (imported.Kind == SymbolKind.Namespace)
                        {
                            AddNs(usingDirective, imported, usings, uniqueUsings);
                        }
                        else if (imported.Kind == SymbolKind.NamedType)
                        {
                            var importedType = (NamedTypeSymbol)imported;
                            AddNs(usingDirective, importedType, usings, uniqueUsings);
                        }
                    }
                    var vcla   = compilation.ClassLibraryType();
                    var vins   = compilation.ImplicitNamespaceType();
                    var refMan = compilation.GetBoundReferenceManager();
                    foreach (var r in refMan.ReferencedAssemblies)
                    {
                        foreach (var attr in r.GetAttributes())
                        {
                            // Check for VulcanImplicitNameSpace attribute
                            if (attr.AttributeClass.ConstructedFrom == vins && compilation.Options.ImplicitNameSpace)
                            {
                                var args = attr.CommonConstructorArguments;
                                if (args != null && args.Length == 1)
                                {
                                    // only one argument, must be default namespace
                                    var defaultNamespace = args[0].Value.ToString();
                                    if (!string.IsNullOrEmpty(defaultNamespace))
                                    {
                                        var name     = Syntax.InternalSyntax.XSharpTreeTransformationCore.ExtGenerateQualifiedName(defaultNamespace);
                                        var imported = declbinder.BindNamespaceOrTypeSymbol(name, diagnostics, basesBeingResolved);
                                        if (imported.Kind == SymbolKind.Namespace)
                                        {
                                            AddNs(usingDirective, imported, usings, uniqueUsings);
                                        }
                                    }
                                }
                            }
                            // Check for VulcanClasslibrary  attribute
                            else if (attr.AttributeClass.ConstructedFrom == vcla)
                            {
                                var args = attr.CommonConstructorArguments;
                                if (args != null && args.Length == 2)
                                {
                                    // first element is the Functions class
                                    var globalClassName = args[0].Value.ToString();
                                    if (!string.IsNullOrEmpty(globalClassName))
                                    {
                                        var name     = Syntax.InternalSyntax.XSharpTreeTransformationCore.ExtGenerateQualifiedName(globalClassName);
                                        var imported = declbinder.BindNamespaceOrTypeSymbol(name, diagnostics, basesBeingResolved);
                                        if (imported.Kind == SymbolKind.NamedType)
                                        {
                                            var importedType = (NamedTypeSymbol)imported;
                                            AddNs(usingDirective, importedType, usings, uniqueUsings);
                                        }
                                    }
                                    // second element is the default namespace
                                    var defaultNamespace = args[1].Value.ToString();
                                    if (!string.IsNullOrEmpty(defaultNamespace) && compilation.Options.ImplicitNameSpace)
                                    {
                                        var name     = Syntax.InternalSyntax.XSharpTreeTransformationCore.ExtGenerateQualifiedName(defaultNamespace);
                                        var imported = declbinder.BindNamespaceOrTypeSymbol(name, diagnostics, basesBeingResolved);
                                        if (imported.Kind == SymbolKind.Namespace)
                                        {
                                            AddNs(usingDirective, imported, usings, uniqueUsings);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }
            return(false);
        }
    }
Пример #15
0
        private Binder XSLookupSymbolsInternal(
            LookupResult result, string name, int arity, ConsList <Symbol> basesBeingResolved, LookupOptions options, bool diagnose, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            Debug.Assert(result.IsClear);
            Debug.Assert(options.AreValid());

            // X# looks for functions first
            //if (Compilation.Options.HasRuntime)
            {
                // check for function calls method calls outside the current class
                bool check = (options.HasFlag(LookupOptions.MustNotBeInstance) && !options.HasFlag(LookupOptions.MustNotBeMethod));
                if (check)
                {
                    var funcOptions = options;
                    funcOptions |= LookupOptions.MustBeInvocableIfMember;
                    Binder scope = this;
                    while (scope != null)
                    {
                        if (scope is InContainerBinder && scope.ContainingType == null) // at the namespace level, so outside of all types
                        {
                            scope.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, funcOptions, this, diagnose, ref useSiteDiagnostics);
                            FilterResults(result, options);
                            if (!result.IsClear)
                            {
                                break;
                            }
                        }
                        scope = scope.Next;
                    }
                }
            }
            LookupResult functionResults = LookupResult.GetInstance();

            if (!result.IsClear)
            {
                foreach (var symbol in result.Symbols)
                {
                    if (symbol is MethodSymbol)
                    {
                        var ms = symbol as MethodSymbol;
                        if (ms.IsStatic && ms.ContainingType.Name.EndsWith("Functions", XSharpString.Comparison))
                        {
                            SingleLookupResult single = new SingleLookupResult(LookupResultKind.Viable, ms, null);
                            functionResults.MergeEqual(single);
                        }
                    }
                }
                result.Clear();
            }
            Binder binder = null;

            for (var scope = this; scope != null && !result.IsMultiViable; scope = scope.Next)
            {
                if (binder != null)
                {
                    var tmp = LookupResult.GetInstance();
                    scope.LookupSymbolsInSingleBinder(tmp, name, arity, basesBeingResolved, options, this, diagnose, ref useSiteDiagnostics);
                    FilterResults(tmp, options);
                    result.MergeEqual(tmp);
                    tmp.Free();
                }
                else
                {
                    scope.LookupSymbolsInSingleBinder(result, name, arity, basesBeingResolved, options, this, diagnose, ref useSiteDiagnostics);
                    FilterResults(result, options);
                    if (!result.IsClear)
                    {
                        binder = scope;
                    }
                }
            }
            if (!functionResults.IsClear)
            {
                // compare the function results with the overall results found
                // create a list of functions and methods
                // function first and then the methods
                LookupResult mergedResults = LookupResult.GetInstance();
                mergedResults.MergeEqual(functionResults);
                // now add the symbols from result that do not exist
                for (int j = 0; j < result.Symbols.Count; j++)
                {
                    var sym   = result.Symbols[j];
                    var found = false;
                    for (int i = 0; i < mergedResults.Symbols.Count; i++)
                    {
                        if (sym == mergedResults.Symbols[i])
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        SingleLookupResult single = new SingleLookupResult(LookupResultKind.Viable, sym, null);
                        mergedResults.MergeEqual(single);
                    }
                }
                result.Clear();
                result.MergeEqual(mergedResults);
            }
            // C563 Make sure the error is generated for Inaccessible types.
            if (!result.IsClear && result.Kind == LookupResultKind.Inaccessible && result.Error != null)
            {
                // we only want to add this for internal fields (globals)
                if (result.Symbols[0].Kind == SymbolKind.Field)
                {
                    if (useSiteDiagnostics == null)
                    {
                        useSiteDiagnostics = new HashSet <DiagnosticInfo>();
                    }
                    useSiteDiagnostics.Add(result.Error);
                }
            }
            return(binder);
        }
Пример #16
0
        private ImmutableArray <Symbol> ComputeSortedCrefMembers(NamespaceOrTypeSymbol containerOpt, string memberName, int arity, bool hasParameterList, ref HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            // Since we may find symbols without going through the lookup API,
            // expose the symbols via an ArrayBuilder.
            ArrayBuilder <Symbol> builder;

            {
                LookupResult result = LookupResult.GetInstance();
                this.LookupSymbolsOrMembersInternal(
                    result,
                    containerOpt,
                    name: memberName,
                    arity: arity,
                    basesBeingResolved: null,
                    options: LookupOptions.AllMethodsOnArityZero,
                    diagnose: false,
                    useSiteDiagnostics: ref useSiteDiagnostics);

                // CONSIDER: Dev11 also checks for a constructor in the event of an ambiguous result.
                if (result.IsMultiViable)
                {
                    // Dev11 doesn't consider members from System.Object when the container is an interface.
                    // Lookup should already have dropped such members.
                    builder = ArrayBuilder <Symbol> .GetInstance();

                    builder.AddRange(result.Symbols);
                    result.Free();
                }
                else
                {
                    result.Free(); // Won't be using this.

                    // Dev11 has a complicated two-stage process for determining when a cref is really referring to a constructor.
                    // Under two sets of conditions, XmlDocCommentBinder::bindXMLReferenceName will decide that a name refers
                    // to a constructor and under one set of conditions, the calling method, XmlDocCommentBinder::bindXMLReference,
                    // will roll back that decision and return null.

                    // In XmlDocCommentBinder::bindXMLReferenceName:
                    //   1) If an unqualified, non-generic name didn't bind to anything and the name matches the name of the type
                    //      to which the doc comment is applied, then bind to a constructor.
                    //   2) If a qualified, non-generic name didn't bind to anything and the LHS of the qualified name is a type
                    //      with the same name, then bind to a constructor.

                    // Quoted from XmlDocCommentBinder::bindXMLReference:
                    //   Filtering out the case where specifying the name of a generic type without specifying
                    //   any arity returns a constructor. This case shouldn't return anything. Note that
                    //   returning the constructors was a fix for the wonky constructor behavior, but in order
                    //   to not introduce a regression and breaking change we return NULL in this case.
                    //   e.g.
                    //
                    //   /// <see cref="Goo"/>
                    //   class Goo<T> { }
                    //
                    //   This cref used not to bind to anything, because before it was looking for a type and
                    //   since there was no arity, it didn't find Goo<T>. Now however, it finds Goo<T>.ctor,
                    //   which is arguably correct, but would be a breaking change (albeit with minimal impact)
                    //   so we catch this case and chuck out the symbol found.

                    // In Roslyn, we're doing everything in one pass, rather than guessing and rolling back.

                    // As in the native compiler, we treat this as a fallback case - something that actually has the
                    // specified name is preferred.

                    NamedTypeSymbol constructorType = null;

                    if (arity == 0) // Member arity
                    {
                        NamedTypeSymbol containerType = containerOpt as NamedTypeSymbol;
                        if ((object)containerType != null)
                        {
                            // Case 1: If the name is qualified by a type with the same name, then we want a
                            // constructor (unless the type is generic, the cref is on/in the type (but not
                            // on/in a nested type), and there were no parens after the member name).

                            if (containerType.Name == memberName && (hasParameterList || containerType.Arity == 0 || this.ContainingType != containerType.OriginalDefinition))
                            {
                                constructorType = containerType;
                            }
                        }
                        else if ((object)containerOpt == null && hasParameterList)
                        {
                            // Case 2: If the name is not qualified by anything, but we're in the scope
                            // of a type with the same name (regardless of arity), then we want a constructor,
                            // as long as there were parens after the member name.

                            NamedTypeSymbol binderContainingType = this.ContainingType;
                            if ((object)binderContainingType != null && memberName == binderContainingType.Name)
                            {
                                constructorType = binderContainingType;
                            }
                        }
                    }

                    if ((object)constructorType != null)
                    {
                        ImmutableArray <MethodSymbol> instanceConstructors = constructorType.InstanceConstructors;
                        int numInstanceConstructors = instanceConstructors.Length;

                        if (numInstanceConstructors == 0)
                        {
                            return(ImmutableArray <Symbol> .Empty);
                        }

                        builder = ArrayBuilder <Symbol> .GetInstance(numInstanceConstructors);

                        builder.AddRange(instanceConstructors);
                    }
                    else
                    {
                        return(ImmutableArray <Symbol> .Empty);
                    }
                }
            }

            Debug.Assert(builder != null);

            // Since we resolve ambiguities by just picking the first symbol we encounter,
            // the order of the symbols matters for repeatability.
            if (builder.Count > 1)
            {
                builder.Sort(ConsistentSymbolOrder.Instance);
            }

            return(builder.ToImmutableAndFree());
        }
Пример #17
0
        private void BindPCallAndDelegate(InvocationExpressionSyntax node, ArrayBuilder <BoundExpression> args,
                                          DiagnosticBag diagnostics, TypeSyntax type)
        {
            var    XNode  = node.XNode as XP.MethodCallContext;
            string method = XNode?.Expr.GetText();

            if (string.IsNullOrEmpty(method))
            {
                method = "PCALL";
            }
            if (!ValidatePCallArguments(node, args, diagnostics, method))
            {
                return;
            }
            var kind = args[0].Kind;

            if (kind != BoundKind.Local && kind != BoundKind.FieldAccess)
            {
                Error(diagnostics, ErrorCode.ERR_PCallFirstArgument, node, method, "typed function pointer");
                return;
            }
            string methodName = null;
            // Note that this does not get the syntax of the argument itself
            // but the syntax of the place where the symbol (Global, Field or Local) that the argument points to was defined
            SyntaxReference syntaxref = null;

            if (kind == BoundKind.FieldAccess)
            {
                var bfa = args[0] as BoundFieldAccess;  // Global or Field
                if (bfa != null && bfa.ExpressionSymbol.DeclaringSyntaxReferences.Length > 0)
                {
                    syntaxref = bfa.ExpressionSymbol.DeclaringSyntaxReferences[0] as SyntaxReference;
                }
            }
            else if (kind == BoundKind.Local)
            {
                var bl = args[0] as BoundLocal;         // Local
                if (bl != null && bl.LocalSymbol?.DeclaringSyntaxReferences.Length > 0)
                {
                    syntaxref = bl.LocalSymbol.DeclaringSyntaxReferences[0] as SyntaxReference;
                }
            }
            if (syntaxref != null)
            {
                CSharpSyntaxNode syntaxnode = syntaxref.GetSyntax() as CSharpSyntaxNode;
                var xNode = syntaxnode?.XNode;
                methodName = GetTypedPtrName(xNode);
            }

            if (methodName == null)
            {
                // first argument for pcall must be typed ptr
                Error(diagnostics, ErrorCode.ERR_PCallFirstArgument, node, method, "typed function pointer");
                return;
            }
            var lookupResult = LookupResult.GetInstance();
            HashSet <DiagnosticInfo> useSiteDiagnostics = null;
            LookupOptions            options            = LookupOptions.AllMethodsOnArityZero;

            options |= LookupOptions.MustNotBeInstance;
            this.LookupSymbolsWithFallback(lookupResult, methodName, arity: 0, useSiteDiagnostics: ref useSiteDiagnostics, options: options);
            SourceMethodSymbol methodSym = null;

            if (lookupResult.IsClear)
            {
                // Cannot locate types pointer for pcall
                Error(diagnostics, ErrorCode.ERR_PCallTypedPointerName, node, method, methodName);
                methodSym = null;
            }
            else if (lookupResult.IsMultiViable)
            {
                foreach (var symbol in lookupResult.Symbols)
                {
                    if (symbol.DeclaringCompilation == this.Compilation && symbol is SourceMethodSymbol)
                    {
                        methodSym = (SourceMethodSymbol)symbol;
                        break;
                    }
                }
            }
            else
            {
                methodSym = (SourceMethodSymbol)lookupResult.Symbols[0];
            }
            if (methodSym != null)
            {
                lookupResult.Clear();
                var ts = FindPCallDelegateType(type as IdentifierNameSyntax);
                if (ts != null && ts.IsDelegateType())
                {
                    SourceDelegateMethodSymbol delmeth = ts.DelegateInvokeMethod() as SourceDelegateMethodSymbol;
                    // clone the parameters from the methodSym
                    var builder = ArrayBuilder <ParameterSymbol> .GetInstance();

                    foreach (var par in methodSym.Parameters)
                    {
                        var parameter = new SourceSimpleParameterSymbol(
                            delmeth,
                            par.Type,
                            par.Ordinal,
                            par.RefKind,
                            par.Name,
                            par.Locations);
                        builder.Add(parameter);
                    }
                    delmeth.InitializeParameters(builder.ToImmutableAndFree());
                    delmeth.SetReturnType(methodSym.ReturnType);
                }
                else
                {
                    Error(diagnostics, ErrorCode.ERR_PCallResolveGeneratedDelegate, node, method, type.ToString());
                }
            }
            return;
        }
Пример #18
0
        private BoundExpression BindWithExpression(WithExpressionSyntax syntax, DiagnosticBag diagnostics)
        {
            var receiver     = BindRValueWithoutTargetType(syntax.Expression, diagnostics);
            var receiverType = receiver.Type;

            var  lookupResult = LookupResult.GetInstance();
            bool hasErrors    = false;

            if (receiverType is null || receiverType.IsVoidType())
            {
                diagnostics.Add(ErrorCode.ERR_InvalidWithReceiverType, syntax.Expression.Location);
                receiverType = CreateErrorType();
            }

            MethodSymbol?cloneMethod = null;

            if (!receiverType.IsErrorType())
            {
                HashSet <DiagnosticInfo>?useSiteDiagnostics = null;

                LookupMembersInType(
                    lookupResult,
                    receiverType,
                    WellKnownMemberNames.CloneMethodName,
                    arity: 0,
                    ConsList <TypeSymbol> .Empty,
                    LookupOptions.MustBeInstance | LookupOptions.MustBeInvocableIfMember,
                    this,
                    diagnose: false,
                    ref useSiteDiagnostics);

                if (lookupResult.IsMultiViable)
                {
                    foreach (var symbol in lookupResult.Symbols)
                    {
                        if (symbol is MethodSymbol {
                            ParameterCount: 0
                        } m)
                        {
                            cloneMethod = m;
                            break;
                        }
                    }
                }

                lookupResult.Clear();

                if (cloneMethod is null ||
                    !receiverType.IsEqualToOrDerivedFrom(
                        cloneMethod.ReturnType,
                        TypeCompareKind.ConsiderEverything,
                        ref useSiteDiagnostics))
                {
                    hasErrors = true;
                    diagnostics.Add(ErrorCode.ERR_NoSingleCloneMethod, syntax.Expression.Location, receiverType);
                }

                diagnostics.Add(syntax.Expression, useSiteDiagnostics);
            }

            var initializer = BindInitializerExpression(
                syntax.Initializer,
                receiverType,
                syntax.Expression,
                diagnostics);

            // N.B. Since we only don't parse nested initializers in syntax there should be no extra
            // errors we need to check for here.

            return(new BoundWithExpression(
                       syntax,
                       receiver,
                       cloneMethod,
                       initializer,
                       receiverType,
                       hasErrors: hasErrors));
        }